feat: consolidar desenvolvimentos do portal InvestMoz

This commit is contained in:
2026-11-03 23:32:32 +02:00
parent 1da273f1f3
commit 36c8cadb49
345 changed files with 110714 additions and 2799 deletions
@@ -6,6 +6,11 @@ import {
type TerritoryOption,
} from '@/components/investment-territory';
import { businessModalities } from './business-types';
import {
BusinessDistance,
GeographicCoverage,
type BusinessGeographicCoverage,
} from '@/components/similar-businesses';
import {
ClassificationSummary,
type PublicClassification,
@@ -25,6 +30,10 @@ type PublicBusiness = {
currency?: string | null;
sector?: { name: string; slug: string } | null;
province?: string | null;
distance_km?: number | null;
location_recorded_at?: string | null;
location_source_reference?: string | null;
location_source_date?: string | null;
};
type PaginationLink = { url: string | null; label: string; active: boolean };
type Props = {
@@ -52,6 +61,7 @@ type Props = {
locality_id?: string;
};
territorySelection?: TerritoryOption[];
geographicCoverage?: BusinessGeographicCoverage | null;
};
export default function BusinessMarketplace({
@@ -60,7 +70,20 @@ export default function BusinessMarketplace({
territorySelection = [],
classificationOptions,
authorities = [],
geographicCoverage,
}: Props) {
const [radiusSelection, setRadiusSelection] = useState({
origin: filters.near_business,
value: filters.radius_km ?? '',
});
const radius =
radiusSelection.origin === filters.near_business
? radiusSelection.value
: (filters.radius_km ?? '');
const proximity =
filters.near_business && radius
? { near_business: filters.near_business, radius_km: radius }
: {};
const [classification, setClassification] = useState<
Record<string, string>
>(() =>
@@ -85,12 +108,15 @@ export default function BusinessMarketplace({
admin_post_id: filters.admin_post_id ?? '',
locality_id: filters.locality_id ?? '',
});
const returnQuery = new URLSearchParams({
...(query ? { q: query } : {}),
...(modality ? { modality } : {}),
...territory,
...classification,
}).toString();
// Detail links describe the results actually retrieved, even while the next search is being edited.
const returnQuery = new URLSearchParams(
Object.fromEntries(
Object.entries(filters).filter(
(entry): entry is [string, string] =>
entry[1] !== undefined && entry[1] !== '',
),
),
).toString();
const paginationLinks =
results.meta?.links ??
(Array.isArray(results.links) ? results.links : []);
@@ -111,11 +137,44 @@ export default function BusinessMarketplace({
modality: modality || undefined,
...territory,
...classification,
...proximity,
},
{ preserveState: true, preserveScroll: true },
);
}}
>
{filters.near_business && (
<fieldset className="w-full rounded border p-3">
<legend>
Distância a partir da ficha de referência
</legend>
<label>
Raio em km (0,1 a 2000)
<input
className={input}
type="number"
min="0.1"
max="2000"
step="any"
value={radius}
onChange={(event) =>
setRadiusSelection({
origin: filters.near_business,
value: event.target.value,
})
}
/>
</label>
<p className="text-sm">
Referência:{' '}
{geographicCoverage?.origin_title ??
'ficha pública seleccionada'}
. Limpar o raio retira o filtro de distância na
próxima pesquisa. Um filtro territorial adicional
restringe também os resultados.
</p>
</fieldset>
)}
<label className="sr-only" htmlFor="business-search">
Pesquisar negócios
</label>
@@ -290,6 +349,16 @@ export default function BusinessMarketplace({
)}
<button className={button}>Pesquisar</button>
</form>
{geographicCoverage && (
<GeographicCoverage coverage={geographicCoverage} />
)}
{results.data.length === 0 && (
<p>
Não foram encontradas fichas públicas com estes critérios. A
cobertura do catálogo não demonstra ausência de negócios no
mercado.
</p>
)}
<ul className="grid gap-4 md:grid-cols-2">
{results.data.map((record) => (
<li className={card} key={record.id}>
@@ -297,6 +366,7 @@ export default function BusinessMarketplace({
{businessModalities[record.modality] ??
'Modalidade por indicar'}
</p>
<BusinessDistance record={record} />
<h2 className="text-xl font-bold">
<Link
className="underline"
@@ -2,7 +2,9 @@ import { Link } from '@inertiajs/react';
import { Frame, button, card } from './shared';
import { businessModalities } from './business-types';
import PartnershipSourceLinks from '@/components/partnership-source-links';
import SimilarBusinesses from '@/components/similar-businesses';
import SimilarBusinesses, {
BusinessLocationSource,
} from '@/components/similar-businesses';
import { downloadPublicBusinessOffline } from '@/lib/public-business-offline';
import { useState } from 'react';
import {
@@ -28,6 +30,9 @@ type Business = {
locality?: string | null;
sector?: { name: string; slug: string } | null;
published_at?: string | null;
location_recorded_at?: string | null;
location_source_reference?: string | null;
location_source_date?: string | null;
};
export default function BusinessOpportunity({
@@ -35,11 +40,13 @@ export default function BusinessOpportunity({
returnUrl = '/negocios',
interestUrl = `/negocios/${record.slug}/manifestar-interesse`,
similarCatalogueUrl,
similarRadiusAvailable = false,
}: {
record: Business;
returnUrl?: string;
interestUrl?: string;
similarCatalogueUrl?: string;
similarRadiusAvailable?: boolean;
}) {
const [offlineMessage, setOfflineMessage] = useState('');
return (
@@ -71,6 +78,7 @@ export default function BusinessOpportunity({
.join(', ')}
</p>
)}
<BusinessLocationSource record={record} showRecorded />
{(record.amount_min || record.amount_max) && (
<p>
Montante indicativo: {record.amount_min ?? '—'} –{' '}
@@ -128,16 +136,19 @@ export default function BusinessOpportunity({
currentId={record.id}
classifications={record.multidimensional}
catalogueUrl={similarCatalogueUrl}
criteria={[
businessModalities[record.modality] ?? record.modality,
...(record.sector ? [record.sector.name] : []),
...(record.province &&
radiusAvailable={similarRadiusAvailable}
areaLabel={
record.province &&
new URL(
similarCatalogueUrl,
'https://portal.invalid',
).searchParams.has('province_id')
? [record.province]
: []),
? record.province
: undefined
}
criteria={[
businessModalities[record.modality] ?? record.modality,
...(record.sector ? [record.sector.name] : []),
]}
/>
)}
@@ -6,6 +6,9 @@ import type { Business } from './business-types';
import { businessModalities } from './business-types';
import BusinessObjects from './business-objects';
import type { BusinessObject } from './business-objects';
import BusinessPointSummary, {
type RegisteredBusinessLocation,
} from '@/components/business-point-summary';
import {
decodeBusinessLocations,
emptyBusinessLocation,
@@ -13,6 +16,8 @@ import {
hasDuplicateBusinessLocationPath,
locationPathFromPayload,
updateBusinessLocation,
businessPointTerritoryKey,
businessPointRequiredFields,
} from '../../lib/business-locations';
export type FormSchema = Record<
@@ -36,6 +41,8 @@ type Props = {
objects: BusinessObject[];
objectKinds: string[];
sectors: { id: number; name: string }[];
registeredLocation?: RegisteredBusinessLocation | null;
pointPublicationAvailable?: boolean;
};
const steps = [
['Proponente', 'Applicant'],
@@ -185,6 +192,8 @@ export default function BusinessWizard({
objects,
objectKinds,
sectors,
registeredLocation,
pointPublicationAvailable,
}: Props) {
const [english, setEnglish] = useState(false);
const t = (pt: string, en: string) => (english ? en : pt);
@@ -206,6 +215,7 @@ export default function BusinessWizard({
return initial;
});
const modality = record.modality;
const pointRequired = businessPointRequiredFields(payload);
const [sectorId, setSectorId] = useState(record.sector_id ?? null);
const [sectorSearch, setSectorSearch] = useState('');
const [publicTitle, setPublicTitle] = useState(record.public_title ?? '');
@@ -530,6 +540,13 @@ export default function BusinessWizard({
<p>
{record.code} · {t('Versão', 'Version')} {version}
</p>
{[5, 7, 8].includes(step) && (
<BusinessPointSummary
payload={payload}
registered={registeredLocation}
available={pointPublicationAvailable}
/>
)}
<p>
{t(
'Área privada. Guardar ou submeter não publica a oportunidade nem confirma a titularidade ou a transmissibilidade.',
@@ -720,7 +737,7 @@ export default function BusinessWizard({
label={
field.type === 'checkbox'
? ''
: `${english ? field.en : field.pt}${requiredFields.has(key) || ((key === 'mandate_reference' || key === 'mandate_document_reference' || key === 'disclosure_scope') && payload.acting_capacity === 'representative') || (key === 'project_stage_other' && payload.project_stage === 'other') || (key === 'available_from' && payload.availability === 'from_date') || (key === 'province_id' && payload.geography_scope === 'specific') || (key === 'locations_json' && payload.geography_scope === 'multiple') || (['value_meaning', 'currency', 'asking_value'].includes(key) && ['defined', 'indicative'].includes(payload.value_status ?? '')) || (key === 'investment_total' && payload.opportunity_type === 'investment_project') || (key === 'asset_deal_kind' && ['company_sale', 'asset_sale'].includes(payload.opportunity_type ?? '')) || (key === 'partnership_contribution' && payload.opportunity_type === 'business_partnership') || (key === 'amount_sought' && payload.opportunity_type === 'financing_request') || (key === 'asset_modality' && payload.opportunity_type === 'asset_sale') || (['concession_entity', 'concession_reference'].includes(key) && payload.opportunity_type === 'concession_opportunity') || (key === 'supply_description' && payload.opportunity_type === 'supply_opportunity') ? ' *' : ''}`
: `${english ? field.en : field.pt}${pointRequired.has(key) || requiredFields.has(key) || ((key === 'mandate_reference' || key === 'mandate_document_reference' || key === 'disclosure_scope') && payload.acting_capacity === 'representative') || (key === 'project_stage_other' && payload.project_stage === 'other') || (key === 'available_from' && payload.availability === 'from_date') || (key === 'province_id' && payload.geography_scope === 'specific') || (key === 'locations_json' && payload.geography_scope === 'multiple') || (['value_meaning', 'currency', 'asking_value'].includes(key) && ['defined', 'indicative'].includes(payload.value_status ?? '')) || (key === 'investment_total' && payload.opportunity_type === 'investment_project') || (key === 'asset_deal_kind' && ['company_sale', 'asset_sale'].includes(payload.opportunity_type ?? '')) || (key === 'partnership_contribution' && payload.opportunity_type === 'business_partnership') || (key === 'amount_sought' && payload.opportunity_type === 'financing_request') || (key === 'asset_modality' && payload.opportunity_type === 'asset_sale') || (['concession_entity', 'concession_reference'].includes(key) && payload.opportunity_type === 'concession_opportunity') || (key === 'supply_description' && payload.opportunity_type === 'supply_opportunity') ? ' *' : ''}`
}
>
{field.type === 'checkbox' ? (
@@ -775,6 +792,71 @@ export default function BusinessWizard({
update(key, value)
}
/>
) : field.type === 'point_territory' ? (
<select
className={input}
value={payload[key] ?? ''}
onChange={(event) =>
update(key, event.target.value)
}
>
<option value="">
{t(
'Seleccionar uma localização declarada',
'Select a declared location',
)}
</option>
{payload[key] &&
!locationRows.some(
(row) =>
businessPointTerritoryKey(
row,
) === payload[key],
) && (
<option
value={payload[key]}
>
{t(
'Selecção guardada fora das localizações actuais; reconcilie antes de submeter',
'Saved selection is outside the current locations; reconcile before submitting',
)}
</option>
)}
{locationRows
.map((row, index) => ({
row,
index,
}))
.filter(
({ row }) =>
row.province_id,
)
.map(({ row, index }) => (
<option
key={businessPointTerritoryKey(
row,
)}
value={businessPointTerritoryKey(
row,
)}
>
{t(
'Localização',
'Location',
)}{' '}
{index + 1}
{payload.locations_json ===
resolvedLocationJson &&
territoryPaths[index]
?.length
? ` — ${territoryPaths[index].join(' / ')}`
: t(
' (declarada nesta etapa)',
' (declared in this step)',
)}
</option>
))}
</select>
) : field.type === 'select' ? (
<select
className={input}
@@ -846,8 +928,8 @@ export default function BusinessWizard({
</h3>
<p className="text-sm">
{t(
'Indique pelo menos duas localizações distintas. Não são recolhidas coordenadas neste formulário.',
'Enter at least two distinct locations. This form does not collect coordinates.',
'Indique pelo menos duas localizações distintas. Se preparar um ponto exacto, escolha acima a localização a que pertence. Não é escolhido automaticamente o primeiro território.',
'Enter at least two distinct locations. If preparing an exact point, select its location above. The first territory is not selected automatically.',
)}
</p>
{locationRows.map((row, index) => (
+30 -1
View File
@@ -10,6 +10,10 @@ import type { BusinessVerification } from './business-verifications';
import BusinessWizard from './business-wizard';
import type { FormSchema } from './business-wizard';
import type { Country } from '@/components/country-select';
import BusinessPointSummary, {
type RegisteredBusinessLocation,
} from '@/components/business-point-summary';
import { businessPointTerritoryLabel } from '@/lib/business-locations';
type Props = {
countries: Country[];
@@ -18,6 +22,8 @@ type Props = {
sectors: { id: number; name: string }[];
record: Business;
canEdit: boolean;
registeredLocation?: RegisteredBusinessLocation | null;
pointPublicationAvailable?: boolean;
owner: boolean;
canReview: boolean;
canTriage: boolean;
@@ -68,6 +74,8 @@ function Editor({
verifications,
formSchema,
sectors,
registeredLocation,
pointPublicationAvailable,
}: Props) {
const [payload, setPayload] = useState(record.payload);
const [modality, setModality] = useState(record.modality);
@@ -131,6 +139,16 @@ function Editor({
{businessStates[record.status]} · versão {record.version_no} ·
informação reservada
</p>
<BusinessPointSummary
payload={record.payload}
registered={registeredLocation}
available={pointPublicationAvailable}
published={record.status === 'published'}
territoryLabel={businessPointTerritoryLabel(
record.payload,
record.territory_paths,
)}
/>
<p>
Informação declarada, pendente de validação. Não constitui
anúncio público, certificação, avaliação ou autorização de
@@ -148,7 +166,18 @@ function Editor({
</div>
{Object.entries(formSchema)
.filter(
([key]) =>
([key, field]) =>
!key.startsWith('location_point_') &&
![
'location_latitude',
'location_longitude',
].includes(key) &&
Object.entries(field.when ?? {}).every(
([dependency, values]) =>
values.includes(
record.payload[dependency] ?? '',
),
) &&
![
'title',
'description',
@@ -0,0 +1,386 @@
import { useRef, useState } from 'react';
import { Link, router } from '@inertiajs/react';
import { Frame, card, input, button } from './shared';
import { profileJson } from '@/lib/profile-json';
import { createOperationKey } from '@/lib/operation-key';
import {
companyComparisonUrl,
type CompanyAnswers,
} from '@/lib/company-comparison';
type Question = { label: string; options: Record<string, string> };
type Result = {
engine_version: string;
source: {
title: string;
edition: string;
issued_on: string;
consulted_on: string;
url: string;
};
questions: Record<string, Question>;
active: string[];
pending: string[];
route: string;
scope: string;
preparation: string[];
forms: {
code: string;
title: string;
description: string;
articles: string;
source_href: string;
constraints: string[];
notes: string[];
selected: boolean;
}[];
};
type Props = {
definition: { version: string; questions: Record<string, Question> };
case: { id: string; title: string; version: number } | null;
canWrite: boolean;
answers: CompanyAnswers;
result: Result;
saved: { revision: number; at: string; result: Result } | null;
history: {
id: string;
revision: number;
at: string;
engine_version: string;
}[];
historyNext: number | null;
historical: boolean;
workingCopy: boolean;
};
export default function CompanyComparison(props: Props) {
return (
<Comparator
key={JSON.stringify([
props.case?.id,
props.answers,
props.result.engine_version,
props.historical,
])}
{...props}
/>
);
}
function Comparator(props: Props) {
const { definition, result, saved, history, historical, workingCopy } =
props;
const dossier = props.case;
const [answers, setAnswers] = useState(props.answers);
const [dirty, setDirty] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const formRef = useRef<HTMLFormElement>(null);
const operation = useRef(createOperationKey());
const base = dossier
? `/investimentos/${dossier.id}/forma-juridica`
: '/formas-juridicas';
const oldDefinition =
!workingCopy && saved && result.engine_version !== definition.version;
const readOnly = historical || !!oldDefinition;
const active = ['representation', 'cooperation'].includes(answers.purpose)
? ['purpose', 'regulated']
: Object.keys(definition.questions);
const currentValues = (): CompanyAnswers => {
const data = new FormData(formRef.current!);
return Object.fromEntries(
Object.keys(definition.questions).map((key) => {
const value = data.get(`answers[${key}]`);
return [
key,
typeof value === 'string'
? value
: (answers[key] ?? 'unknown'),
];
}),
);
};
async function save() {
if (!dossier || busy) return;
setBusy(true);
setError('');
try {
await profileJson(base, {
version: dossier.version,
operation_key: operation.current,
answers: currentValues(),
});
router.visit(base, { preserveState: false });
} catch (e) {
setError(
e instanceof Error
? e.message
: 'Não foi possível guardar. As respostas continuam no formulário.',
);
} finally {
setBusy(false);
}
}
return (
<Frame title="Comparar formas jurídicas">
{dossier && (
<p>
Dossier:{' '}
<Link
className="underline"
href={`/investimentos/${dossier.id}`}
>
{dossier.title}
</Link>
</p>
)}
<p>
Compare a estrutura pretendida e os pontos a esclarecer antes de
preparar o acto constitutivo.
</p>
{saved && (
<p>
{historical
? 'Revisão histórica'
: 'Última comparação guardada'}
: {saved.revision} · {saved.at}.{' '}
{workingCopy &&
'As respostas desta consulta ainda não substituem a edição guardada.'}
</p>
)}
{readOnly ? (
<section className={card}>
<h2 className="text-lg font-semibold">
Respostas conservadas
</h2>
<dl>
{result.active.map((key) => (
<div key={key}>
<dt>{result.questions[key]?.label ?? key}</dt>
<dd>
{result.questions[key]?.options[
answers[key]
] ?? answers[key]}
</dd>
</div>
))}
</dl>
<Link
className="underline"
href={companyComparisonUrl(base, answers)}
>
Preparar nova comparação com estas respostas
</Link>
</section>
) : (
<form ref={formRef} action={base} method="get" className={card}>
<div className="grid gap-4 md:grid-cols-2">
{Object.entries(definition.questions).map(
([key, question]) =>
active.includes(key) ? (
<label key={key} className="grid gap-1">
{question.label}
<select
className={input}
name={`answers[${key}]`}
value={answers[key] ?? 'unknown'}
disabled={busy}
onChange={(e) => {
setAnswers({
...answers,
[key]: e.target.value,
});
setDirty(true);
operation.current =
createOperationKey();
}}
>
{Object.entries(
question.options,
).map(([code, label]) => (
<option key={code} value={code}>
{label}
</option>
))}
</select>
</label>
) : (
<input
key={key}
type="hidden"
name={`answers[${key}]`}
value={answers[key] ?? 'unknown'}
/>
),
)}
</div>
<div className="mt-4 flex flex-wrap gap-3">
<button className={button} disabled={busy}>
Actualizar comparação
</button>
{dossier ? (
props.canWrite && (
<button
type="button"
className={button}
disabled={busy}
onClick={save}
>
{busy ? 'A guardar…' : 'Guardar no dossier'}
</button>
)
) : (
<button
type="button"
className={button}
onClick={() =>
router.visit(
companyComparisonUrl(
'/investimentos',
currentValues(),
'company_comparison',
),
)
}
>
Escolher dossier para guardar
</button>
)}
</div>
{dirty && (
<p role="status">
Actualize a comparação para reflectir as alterações.
Guardar utiliza as respostas actuais.
</p>
)}
{dossier && !props.canWrite && (
<p>
Consulta do dossier. A edição depende do acesso
actual e de o dossier estar aberto.
</p>
)}
{error && (
<div role="alert">
<p>{error}</p>
<p>
As respostas continuam no formulário. Reabra a
comparação com estes valores para recuperar a
sessão ou a versão actual do dossier.
</p>
<button
className={button}
type="submit"
disabled={busy}
>
Reabrir com estas respostas
</button>
</div>
)}
</form>
)}
<section className={card} aria-label="Resultado da comparação">
<h2 className="text-lg font-semibold">
Alternativas e pontos a conferir
</h2>
<p>{result.route}</p>
{result.pending.length > 0 && (
<p>
Por esclarecer:{' '}
{result.pending
.map((key) => result.questions[key]?.label ?? key)
.join(' · ')}
</p>
)}
<div className="grid gap-4 md:grid-cols-2">
{result.forms.map((item) => (
<article
key={item.code}
className="space-y-2 rounded border p-4"
>
<h3 className="font-semibold">
{item.title}
{item.selected
? ' · Preferência para aprofundar'
: ''}
</h3>
<p>{item.description}</p>
{item.constraints.map((text) => (
<p key={text}>
Incompatibilidade a resolver: {text}
</p>
))}
{item.notes.map((text) => (
<p key={text}>{text}</p>
))}
<a
className="underline"
href={item.source_href}
target="_blank"
rel="noopener noreferrer"
>
{item.articles} · consultar fonte
</a>
</article>
))}
</div>
<h3 className="mt-4 font-semibold">
Preparar a próxima conversa
</h3>
<ul className="list-disc pl-5">
{result.preparation.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
<p>{result.scope}</p>
</section>
<section className={card}>
<h2 className="text-lg font-semibold">
Fonte e edição consultadas
</h2>
<a
className="underline"
href={result.source.url}
target="_blank"
rel="noopener noreferrer"
>
{result.source.title}
</a>
<p>
{result.source.edition}. Publicação:{' '}
{result.source.issued_on}. Consulta desta edição:{' '}
{result.source.consulted_on}.
</p>
</section>
{dossier && (
<section className={card}>
<h2 className="text-lg font-semibold">
Comparações guardadas
</h2>
<ul>
{history.map((item) => (
<li key={item.id}>
<Link
className="underline"
href={`${base}?revision=${item.id}`}
>
Revisão {item.revision} · {item.at}
</Link>
</li>
))}
</ul>
{props.historyNext && (
<Link
className="underline"
href={`${base}?history_before=${props.historyNext}`}
>
Comparações anteriores
</Link>
)}
{historical && (
<Link className="underline" href={base}>
Voltar à comparação actual
</Link>
)}
</section>
)}
</Frame>
);
}
@@ -0,0 +1,790 @@
import { useRef, useState } from 'react';
import { Link, router } from '@inertiajs/react';
import { Frame, card, input, button } from './shared';
import { profileJson, ProfileValidationError } from '@/lib/profile-json';
import { createOperationKey } from '@/lib/operation-key';
import {
preparationValues,
type CompanyFacts,
type Party,
} from '@/lib/company-preparation';
type Review = {
issues: string[];
totals: Record<string, string | null> | null;
note: string;
};
type Props = {
case: { id: string; title: string; version: number };
canWrite: boolean;
historical: boolean;
definition: {
version: string;
forms: Record<string, { title: string }>;
roles: Record<string, string>;
template_notice: string;
source: { title: string; edition: string; url: string };
};
facts: CompanyFacts;
review: Review;
saved: { revision: number; at: string } | null;
sources: Record<
string,
{ name: string; kind: 'person' | 'entity'; origin: string }
>;
history: { id: string; revision: number; at: string }[];
historyNext: number | null;
};
export default function CompanyPreparation(props: Props) {
return (
<Preparation
key={`${props.case.id}:${props.saved?.revision}:${props.historical}`}
{...props}
/>
);
}
function Preparation(props: Props) {
const [facts, setFacts] = useState(props.facts);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [fields, setFields] = useState<Record<string, string>>({});
const [recovery, setRecovery] = useState<Props | null>(null);
const [version, setVersion] = useState(props.case.version);
const [dirty, setDirty] = useState(false);
const form = useRef<HTMLFormElement>(null);
const operation = useRef(createOperationKey());
const base = `/investimentos/${props.case.id}/preparar-empresa`;
const readOnly = !props.canWrite || props.historical;
const corporate = !!facts.form && facts.form !== 'individual';
const shares = ['anonymous', 'simplified'].includes(facts.form ?? '');
function update(key: keyof CompanyFacts, value: string) {
setFacts((old) => ({ ...old, [key]: value || null }));
}
function party(id: string, changes: Partial<Party>) {
setFacts((old) => ({
...old,
parties: old.parties.map((p) =>
p.id === id ? { ...p, ...changes } : p,
),
}));
}
function text(
key: Exclude<keyof CompanyFacts, 'parties'>,
label: string,
multiline = false,
) {
return (
<label className="block" key={key}>
{label}
{multiline ? (
<textarea
className={input}
name={key}
value={facts[key] ?? ''}
onChange={(e) => update(key, e.target.value)}
maxLength={2000}
/>
) : (
<input
className={input}
name={key}
value={facts[key] ?? ''}
onChange={(e) => update(key, e.target.value)}
maxLength={
key === 'proposed_name'
? 250
: key === 'currency'
? 3
: 25
}
/>
)}
</label>
);
}
function partyText(
p: Party,
key:
| 'name'
| 'cash'
| 'in_kind'
| 'paid'
| 'share_count'
| 'work'
| 'commitment',
label: string,
) {
return (
<label className="block" key={key}>
{label}
<input
className={input}
name={`${p.id}.${key}`}
value={p[key] ?? ''}
readOnly={key === 'name' && !!p.source}
onChange={(e) =>
party(p.id, { [key]: e.target.value || null })
}
maxLength={
['work', 'commitment'].includes(key)
? 2000
: key === 'name'
? 250
: 25
}
/>
</label>
);
}
async function save() {
if (busy || readOnly) return;
setBusy(true);
setError('');
setFields({});
const values = preparationValues(form.current!, facts);
setFacts(values);
try {
await profileJson(base, {
version,
operation_key: operation.current,
facts: values,
});
router.visit(base, { preserveState: false });
} catch (e) {
setError(
e instanceof Error
? e.message
: 'Não foi possível guardar. Os dados continuam no formulário.',
);
if (e instanceof ProfileValidationError) setFields(e.fields);
} finally {
setBusy(false);
}
}
async function recover() {
setBusy(true);
try {
setRecovery(await profileJson(base, {}, 'GET'));
} catch (e) {
setError(
e instanceof Error
? e.message
: 'Não foi possível consultar o dossier.',
);
} finally {
setBusy(false);
}
}
return (
<Frame title="Preparar a constituição da empresa">
<p>
<Link
className="underline"
href={`/investimentos/${props.case.id}`}
>
{props.case.title}
</Link>{' '}
·{' '}
<Link
className="underline"
href={`/investimentos/${props.case.id}/forma-juridica`}
>
Comparar formas jurídicas
</Link>
</p>
<p>{props.definition.template_notice}</p>
<p>
Guarde mesmo que faltem dados. Só se pedem informações desta
preparação; valores indicados como realizados são declarações,
não comprovativos de pagamento.
</p>
{props.saved && (
<p>
{props.historical
? 'Revisão histórica'
: 'Última ficha guardada'}
: {props.saved.revision} · {props.saved.at}.{' '}
<Link className="underline" href={base}>
Abrir a preparação actual
</Link>
</p>
)}
{dirty && (
<p role="status">
Alterações por guardar. Os totais e as questões serão
conferidos quando guardar esta ficha.
</p>
)}
{error && (
<div role="alert" className={card}>
<p>{error}</p>
<ul>
{Object.entries(fields).map(([key, message]) => (
<li key={key}>{message}</li>
))}
</ul>
<button
type="button"
className={button}
disabled={busy}
onClick={recover}
>
Conferir edição actual sem perder estes dados
</button>
</div>
)}
{recovery && (
<section className={card}>
<h2 className="font-semibold">
Edição actualmente guardada no dossier
</h2>
<p>
Versão {recovery.case.version}. Compare os dados antes
de voltar a guardar; a nova gravação conserva esta
edição no histórico.
</p>
<SavedFacts
facts={recovery.facts}
definition={recovery.definition}
/>
{recovery.canWrite && (
<button
className={button}
type="button"
onClick={() => {
setVersion(recovery.case.version);
operation.current = createOperationKey();
setRecovery(null);
setError('');
}}
>
Conferi: manter os meus dados para uma nova revisão
</button>
)}
</section>
)}
<form
ref={form}
onChange={() => setDirty(true)}
onSubmit={(e) => {
e.preventDefault();
void save();
}}
className="space-y-5"
>
<fieldset disabled={readOnly || busy} className="space-y-5">
<section className={card}>
<h2 className="text-lg font-semibold">
1. Forma jurídica
</h2>
<label className="block">
Alternativa a preparar
<select
className={input}
name="form"
value={facts.form ?? ''}
onChange={(e) => update('form', e.target.value)}
>
<option value="">Ainda por definir</option>
{Object.entries(props.definition.forms).map(
([code, f]) => (
<option key={code} value={code}>
{f.title}
</option>
),
)}
</select>
</label>
</section>
<section className={card}>
<h2 className="text-lg font-semibold">
2. Intervenientes e papéis
</h2>
<p>
A mesma pessoa pode acumular papéis. Ter uma
participação não atribui automaticamente
administração, representação ou qualidade de
beneficiário efectivo.
</p>
{facts.parties.map((p, index) => (
<fieldset
key={p.id}
className="my-4 space-y-2 rounded border p-3"
>
<legend>Interveniente {index + 1}</legend>
<label className="block">
Origem do nome
<select
className={input}
value={p.source ?? ''}
onChange={(e) => {
const s =
props.sources[e.target.value];
party(p.id, {
source: e.target.value || null,
source_snapshot: undefined,
...(s
? {
name: s.name,
kind: s.kind,
}
: {}),
});
}}
>
<option value="">
Informação nova desta preparação
</option>
{Object.entries(props.sources).map(
([key, source]) => (
<option key={key} value={key}>
{source.origin} ·{' '}
{source.name}
</option>
),
)}
</select>
</label>
{p.source_snapshot && (
<p>
Versão utilizada:{' '}
{p.source_snapshot.version ??
'não indicada'}{' '}
· {p.source_snapshot.origin}. Conservada
nesta ficha; mudanças no cadastro não a
substituem.
</p>
)}
{partyText(
p,
'name',
'Nome da pessoa ou entidade',
)}
<label className="block">
Natureza
<select
className={input}
value={p.kind}
disabled={!!p.source}
onChange={(e) =>
party(p.id, {
kind: e.target
.value as Party['kind'],
})
}
>
<option value="person">
Pessoa singular
</option>
<option value="entity">Entidade</option>
</select>
</label>
{Object.entries(props.definition.roles).map(
([code, label]) => (
<label key={code} className="block">
<input
type="checkbox"
checked={p.roles.includes(code)}
onChange={(e) =>
party(p.id, {
roles: e.target.checked
? [...p.roles, code]
: p.roles.filter(
(r) =>
r !==
code,
),
})
}
/>{' '}
{label}
</label>
),
)}
{p.roles.includes('representative') && (
<label className="block">
Quem representa?
<select
className={input}
value={p.represented_id ?? ''}
onChange={(e) =>
party(p.id, {
represented_id:
e.target.value || null,
})
}
>
<option value="">
Ainda por identificar
</option>
{facts.parties
.filter(
(other) =>
other.id !== p.id,
)
.map((other, i) => (
<option
key={other.id}
value={other.id}
>
{other.name ||
`Interveniente ${i + 1}`}
</option>
))}
</select>
</label>
)}
<button
type="button"
className="underline"
onClick={() => {
setDirty(true);
setFacts((old) => ({
...old,
parties: old.parties.filter(
(other) => other.id !== p.id,
),
}));
}}
>
Retirar da preparação actual
</button>
</fieldset>
))}
<button
className={button}
type="button"
onClick={() => {
setDirty(true);
setFacts((old) => ({
...old,
parties: [
...old.parties,
{
id: createOperationKey(),
name: null,
kind: 'person',
source: null,
roles: [],
represented_id: null,
cash: null,
in_kind: null,
paid: null,
share_count: null,
work: null,
commitment: null,
},
],
}));
}}
>
Adicionar interveniente
</button>
</section>
<section className={card}>
<h2 className="text-lg font-semibold">
3. Nome e sede propostos
</h2>
{text('proposed_name', 'Denominação proposta')}
{text(
'seat',
'Sede proposta (distinta da morada pessoal)',
true,
)}
</section>
<section className={card}>
<h2 className="text-lg font-semibold">
4. Actividades
</h2>
{text(
'activities',
'Actividades a incluir no objecto',
true,
)}
<label className="block">
Existem regras sectoriais ou profissionais próprias?
<select
className={input}
name="regulated"
value={facts.regulated}
onChange={(e) =>
update('regulated', e.target.value)
}
>
<option value="unknown">
Ainda não confirmei
</option>
<option value="yes">Sim</option>
<option value="no">Não identifiquei</option>
</select>
</label>
<p>
Descrever o objecto não concede licença para exercer
a actividade.
</p>
</section>
{corporate && (
<section className={card}>
<h2 className="text-lg font-semibold">
5. Capital e participações
</h2>
<p>
Indique zero apenas quando confirmado; deixe em
branco o que desconhece. Todos os valores
monetários desta ficha usam a mesma moeda, sem
conversão.
</p>
{text(
'currency',
'Código da moeda (três letras, por exemplo MZN)',
)}
{text('capital', 'Capital declarado')}
{shares &&
text(
'nominal_value',
'Valor nominal de cada acção',
)}
{facts.parties
.filter((p) => p.roles.includes('subscriber'))
.map((p) => (
<fieldset
key={p.id}
className="my-4 border p-3"
>
<legend>
{p.name ||
'Participante ainda sem nome'}
</legend>
{partyText(
p,
'cash',
'Entrada subscrita em dinheiro',
)}
{partyText(
p,
'in_kind',
'Entrada subscrita em espécie (valor declarado)',
)}
{partyText(
p,
'paid',
'Total já realizado (declaração)',
)}
{shares &&
partyText(
p,
'share_count',
'Número de acções',
)}
{partyText(
p,
'work',
'Contribuição em trabalho, se pretendida; não somada ao capital',
)}
{partyText(
p,
'commitment',
'Condições e prazos ainda por cumprir, se definidos',
)}
</fieldset>
))}
</section>
)}
<section className={card}>
<h2 className="text-lg font-semibold">
6. Administração e forma de obrigar
</h2>
{text(
'management',
'Estrutura, nomeações e poderes pretendidos',
true,
)}
{text(
'binding',
'Quem poderá vincular a entidade e em que condições?',
true,
)}
</section>
<section className={card}>
<h2 className="text-lg font-semibold">
7. Conferência e preparação para revisão
</h2>
{text(
'notes',
'Questões a esclarecer nesta preparação',
true,
)}
<button type="submit" className={button}>
Guardar ficha no dossier
</button>
</section>
</fieldset>
</form>
<section className={card}>
<h2 className="text-lg font-semibold">
{props.saved
? 'Conferência da ficha guardada'
: 'Pontos a preparar'}
</h2>
<p>{props.review.note}</p>
{props.review.totals && (
<dl>
{Object.entries(props.review.totals).map(
([key, value]) => (
<div key={key}>
<dt>
{{
currency: 'Moeda',
subscribed: 'Total subscrito',
paid: 'Realizado declarado',
unpaid: 'Por realizar declarado',
shares_nominal:
'Valor nominal total das acções',
}[key] ?? key}
</dt>
<dd>{value ?? 'Por determinar'}</dd>
</div>
),
)}
</dl>
)}
<ul>
{props.review.issues.map((issue) => (
<li key={issue}>{issue}</li>
))}
</ul>
<p>
<a
className="underline"
href={props.definition.source.url}
target="_blank"
rel="noopener noreferrer"
>
{props.definition.source.title}
</a>{' '}
· {props.definition.source.edition}
</p>
</section>
<section className={card}>
<h2 className="text-lg font-semibold">Histórico</h2>
<ul>
{props.history.map((h) => (
<li key={h.id}>
<Link
className="underline"
href={`${base}?revision=${h.id}`}
>
Revisão {h.revision} · {h.at}
</Link>
</li>
))}
</ul>
{props.historyNext && (
<Link
className="underline"
href={`${base}?history_before=${props.historyNext}`}
>
Edições anteriores
</Link>
)}
</section>
</Frame>
);
}
function SavedFacts({
facts,
definition,
}: Pick<Props, 'facts' | 'definition'>) {
const labels: {
key: Exclude<keyof CompanyFacts, 'parties'>;
label: string;
}[] = [
{ key: 'form', label: 'Forma jurídica' },
{ key: 'proposed_name', label: 'Denominação proposta' },
{ key: 'seat', label: 'Sede proposta' },
{ key: 'activities', label: 'Actividades' },
{
key: 'regulated',
label: 'Regras sectoriais ou profissionais identificadas',
},
{ key: 'currency', label: 'Moeda' },
{ key: 'capital', label: 'Capital declarado' },
{ key: 'nominal_value', label: 'Valor nominal por acção' },
{ key: 'management', label: 'Administração pretendida' },
{ key: 'binding', label: 'Forma de obrigar pretendida' },
{ key: 'notes', label: 'Questões a esclarecer' },
];
return (
<div className="max-h-96 space-y-3 overflow-auto">
<dl>
{labels.map(({ key, label }) => (
<div key={key}>
<dt className="font-medium">{label}</dt>
<dd className="whitespace-pre-wrap">
{key === 'form'
? (definition.forms[facts.form ?? '']?.title ??
'Por definir')
: key === 'regulated'
? ({
yes: 'Sim',
no: 'Não identificadas',
unknown: 'Por confirmar',
}[facts.regulated] ?? 'Por confirmar')
: (facts[key] ?? 'Por definir')}
</dd>
</div>
))}
</dl>
{facts.parties.map((p, index) => (
<section key={p.id} className="rounded border p-3">
<h3 className="font-semibold">
Interveniente {index + 1}:{' '}
{p.name ?? 'Nome por definir'}
</h3>
<p>
{p.kind === 'entity' ? 'Entidade' : 'Pessoa singular'} ·{' '}
{p.roles
.map((role) => definition.roles[role] ?? role)
.join(', ') || 'Papéis por definir'}
</p>
{p.source_snapshot && (
<p>
{p.source_snapshot.origin} · versão{' '}
{p.source_snapshot.version ?? 'não indicada'}
</p>
)}
{p.roles.includes('representative') && (
<p>
Representa:{' '}
{facts.parties.find(
(other) => other.id === p.represented_id,
)?.name ?? 'Por identificar'}
</p>
)}
<dl>
{(
[
['cash', 'Entrada em dinheiro'],
['in_kind', 'Entrada em espécie'],
['paid', 'Realização declarada'],
['share_count', 'Número de acções'],
['work', 'Contribuição em trabalho'],
['commitment', 'Condições e prazos'],
] as const
).map(([key, label]) => (
<div key={key}>
<dt>{label}</dt>
<dd className="whitespace-pre-wrap">
{p[key] ?? 'Por definir'}
</dd>
</div>
))}
</dl>
</section>
))}
</div>
);
}
+676
View File
@@ -0,0 +1,676 @@
import { useRef, useState } from 'react';
import { Link, router } from '@inertiajs/react';
import { Frame, card, input, button } from './shared';
import { profileJson, ProfileValidationError } from '@/lib/profile-json';
import { createOperationKey } from '@/lib/operation-key';
import { guideChoices, guideUrl } from '@/lib/investment-guides';
type Guide = {
slug: string;
version: string;
sha256: string;
title: string;
reviewed_on: string;
scope: string;
selection_label?: string;
selection_hint?: string;
cards_title?: string;
eligibility_title?: string;
preparation_title?: string;
requirements?: GuideRequirement[];
documents?: {
id: string;
title: string;
text: string;
paths: string[];
citations: GuideCitation[];
}[];
handoffs?: { title: string; url: string; note: string }[];
instruments: Record<
string,
{
title: string;
description: string;
risks: string[];
prepare: string[];
sources: string[];
requirements?: GuideRequirement[];
}
>;
sources: Record<
string,
{
title: string;
url: string;
edition: string;
locator: string;
consulted_on: string;
sha256: string | null;
valid_until?: string;
}
>;
eligibility: {
text: string;
sources: string[];
citations?: GuideCitation[];
}[];
preparation: {
title: string;
text: string;
sources: string[];
responsible?: string;
citations?: GuideCitation[];
}[];
next: string[];
limits: string[];
};
type GuideCitation = { source: string; reference: string; page: number };
type GuideRequirement = {
id: string;
text: string;
kind: 'requirement' | 'exception' | 'gap';
citations: GuideCitation[];
};
type Props = {
guide: Guide;
instruments: string[];
note: string;
case: { id: string; title: string; version: number } | null;
saved: {
revision: number;
at: string;
note: string;
instruments: string[];
guide: Guide;
context: { revision: number };
} | null;
canWrite: boolean;
historical: boolean;
olderEdition: boolean;
currentAvailable: boolean;
workingCopy: boolean;
contextChanged: boolean;
unavailableInstruments: string[];
history: { id: string; revision: number; at: string; edition: string }[];
historyNext: number | null;
};
export default function InvestmentGuide(props: Props) {
return (
<GuideView
key={`${props.case?.id}:${props.guide.sha256}:${props.saved?.revision}:${props.historical}:${props.workingCopy}:${props.instruments.join(',')}`}
{...props}
/>
);
}
function GuideView(props: Props) {
const { guide, saved, historical, olderEdition } = props;
const dossier = props.case;
const [selected, setSelected] = useState(props.instruments);
const [note, setNote] = useState(props.note);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [recovery, setRecovery] = useState<Props | null>(null);
const [version, setVersion] = useState(dossier?.version ?? 0);
const form = useRef<HTMLFormElement>(null);
const operation = useRef(createOperationKey());
const base = dossier
? `/investimentos/${dossier.id}/guias/${guide.slug}`
: `/guias-investimento/${guide.slug}`;
const readOnly =
historical || olderEdition || (!!dossier && !props.canWrite);
const visible = selected.length ? selected : Object.keys(guide.instruments);
function sourceLinks(keys: string[]) {
return (
<p className="text-sm">
Fontes:{' '}
{keys.map((key) => (
<span key={key}>
<a className="mr-3 underline" href={`#source-${key}`}>
{guide.sources[key]?.title ?? key}
</a>
</span>
))}
</p>
);
}
function citations(items: GuideCitation[] = []) {
return (
<ul className="text-sm">
{items.map((item) => (
<li key={`${item.source}:${item.reference}:${item.page}`}>
<a
className="underline"
href={`${guide.sources[item.source].url}#page=${item.page}`}
target="_blank"
rel="noopener noreferrer"
>
{guide.sources[item.source].title} ·{' '}
{item.reference} · p. {item.page} do PDF
</a>
</li>
))}
</ul>
);
}
function requirements(items: GuideRequirement[] = []) {
return (
<ul className="space-y-3">
{items.map((item) => (
<li key={item.id} className="rounded border p-3">
<p>
<strong>
{
{
gap: 'Por esclarecer',
exception:
'Regra com dispensa ou condição específica',
requirement: 'Conferir requisito',
}[item.kind]
}
:
</strong>{' '}
{item.text}
</p>
{citations(item.citations)}
</li>
))}
</ul>
);
}
function choose() {
router.visit(
guideUrl(
'/investimentos',
{
slug: guide.slug,
sha256: guide.sha256,
instruments: guideChoices(form.current!),
},
true,
),
);
}
async function save() {
if (!dossier || busy || readOnly) return;
setBusy(true);
setError('');
const values = new FormData(form.current!);
const currentNote = values.get('note');
const chosen = guideChoices(form.current!);
const text = typeof currentNote === 'string' ? currentNote : note;
setNote(text);
setSelected(chosen);
try {
await profileJson(base, {
version,
operation_key: operation.current,
sha256: guide.sha256,
instruments: chosen,
note: text,
});
router.visit(base, { preserveState: false });
} catch (e) {
setError(
e instanceof Error
? e.message
: 'Não foi possível guardar. A nota continua nesta página.',
);
if (
e instanceof ProfileValidationError &&
Object.values(e.fields).length
)
setError(Object.values(e.fields).join(' '));
} finally {
setBusy(false);
}
}
async function recover() {
setBusy(true);
try {
setRecovery(await profileJson(base, {}, 'GET'));
} catch (e) {
setError(
e instanceof Error
? e.message
: 'Não foi possível consultar o dossier.',
);
} finally {
setBusy(false);
}
}
return (
<Frame title={guide.title}>
{dossier && (
<p>
Dossier:{' '}
<Link
className="underline"
href={`/investimentos/${dossier.id}`}
>
{dossier.title}
</Link>
</p>
)}
<p>{guide.scope}</p>
<p>
Edição {guide.version} · Conteúdo conferido em{' '}
{guide.reviewed_on}.
</p>
{saved && (
<p>
{historical
? 'Referência histórica'
: 'Última referência guardada'}
: revisão {saved.revision} · {saved.at} · contexto{' '}
{saved.context.revision}.
{props.workingCopy &&
' Esta preparação ainda não substitui a referência guardada.'}
</p>
)}
{props.contextChanged && (
<p>
Os dados de contexto disponíveis nesta consulta diferem dos
utilizados na referência. Confira a sua pertinência; a
edição guardada conserva o contexto anterior.
</p>
)}
{props.unavailableInstruments.length > 0 && (
<p>
Esta edição deixou de incluir:{' '}
{props.unavailableInstruments.join(', ')}. A selecção e o
conteúdo anteriores continuam na referência guardada e no
histórico.
</p>
)}
{(historical || olderEdition) && (
<p>
Consulta preservada da edição utilizada.{' '}
{props.currentAvailable ? (
<Link className="underline" href={`${base}?current=1`}>
Preparar uma nova referência com o guia actual
</Link>
) : (
'O guia foi retirado da consulta actual; esta referência continua disponível.'
)}
</p>
)}
<form
ref={form}
onSubmit={(e) => {
e.preventDefault();
if (dossier) void save();
else choose();
}}
className={card}
>
<fieldset disabled={busy || readOnly} className="space-y-3">
<legend className="font-semibold">
{guide.selection_label ??
'Que instrumentos pretende aprofundar?'}
</legend>
<p>
{guide.selection_hint ??
'Sem selecção, consulte o conjunto. Pode combinar instrumentos; a selecção organiza a consulta e não é uma recomendação.'}
</p>
{Object.entries(guide.instruments).map(([code, item]) => (
<label key={code} className="block">
<input
type="checkbox"
name="instruments[]"
value={code}
checked={selected.includes(code)}
onChange={(e) =>
setSelected((old) =>
e.target.checked
? [...old, code]
: old.filter((v) => v !== code),
)
}
/>{' '}
{item.title}
</label>
))}
{dossier && (
<label className="block">
Questões a discutir nesta preparação (opcional)
<textarea
className={input}
name="note"
value={note}
maxLength={3000}
onChange={(e) => setNote(e.target.value)}
/>
<span className="text-sm">
A nota fica privada no dossier; reutilize os
dados e documentos já registados.
</span>
</label>
)}
<button type="submit" className={button}>
{dossier
? 'Guardar referência no dossier'
: 'Escolher dossier para preparar'}
</button>
</fieldset>
</form>
{error && (
<div role="alert" className={card}>
<p>{error}</p>
<button
className={button}
type="button"
disabled={busy}
onClick={recover}
>
Conferir a referência actual sem perder a nota
</button>
</div>
)}
{recovery && (
<section className={card}>
<h2 className="font-semibold">
Referência actualmente guardada
</h2>
<p>
Dossier: {recovery.case?.title} · Edição{' '}
{recovery.guide.version} · revisão{' '}
{recovery.saved?.revision ?? 'ainda não guardada'}
</p>
<p>
{recovery.instruments
.map(
(code) =>
recovery.guide.instruments[code]?.title ??
code,
)
.join(', ') || 'Consulta do conjunto'}
</p>
<p className="whitespace-pre-wrap">
{recovery.note || 'Sem nota'}
</p>
{recovery.canWrite &&
recovery.case &&
recovery.currentAvailable &&
!recovery.olderEdition &&
recovery.guide.sha256 === guide.sha256 && (
<button
className={button}
type="button"
onClick={() => {
setVersion(recovery.case!.version);
operation.current = createOperationKey();
setRecovery(null);
setError('');
}}
>
Conferi: manter a minha preparação numa nova
revisão
</button>
)}
{(recovery.guide.sha256 !== guide.sha256 ||
recovery.olderEdition ||
!recovery.currentAvailable) && (
<p>
O guia utilizado foi alterado. Conserve a nota e
abra o guia actual numa nova página para comparar as
edições.
</p>
)}
</section>
)}
<section className={card}>
<h2 className="text-lg font-semibold">
{guide.cards_title ?? 'Instrumentos, riscos e preparação'}
</h2>
{guide.requirements && (
<div className="my-4">
<h3 className="font-semibold">
Conferência comum aos percursos deste guião
</h3>
{requirements(guide.requirements)}
</div>
)}
<div className="grid gap-4 md:grid-cols-2">
{visible.map((code) => {
const item = guide.instruments[code];
return (
item && (
<article
className="space-y-2 rounded border p-3"
key={code}
>
<h3 className="font-semibold">
{item.title}
</h3>
<p>{item.description}</p>
<h4 className="font-medium">
Riscos e pontos a conferir
</h4>
<ul className="list-disc pl-5">
{item.risks.map((text) => (
<li key={text}>{text}</li>
))}
</ul>
{item.prepare.length > 0 && (
<>
<h4 className="font-medium">
Preparar para discussão
</h4>
<ul className="list-disc pl-5">
{item.prepare.map((text) => (
<li key={text}>{text}</li>
))}
</ul>
</>
)}
{sourceLinks(item.sources)}
{requirements(item.requirements)}
</article>
)
);
})}
</div>
</section>
{guide.documents && (
<section className={card}>
<h2 className="text-lg font-semibold">
Documentos dos percursos seleccionados
</h2>
<p>
Os documentos comuns aparecem uma vez; as condições
específicas de cada segmento devem ser conservadas.
Reutilize os documentos do dossier e confira a sua
actualidade com o operador.
</p>
{guide.documents
.filter((doc) =>
doc.paths.some((code) => visible.includes(code)),
)
.map((doc) => (
<article key={doc.id} className="my-4">
<h3 className="font-semibold">{doc.title}</h3>
<p>{doc.text}</p>
<p className="text-sm">
Percursos:{' '}
{doc.paths
.filter((code) =>
visible.includes(code),
)
.map(
(code) =>
guide.instruments[code].title,
)
.join(' · ')}
</p>
{citations(doc.citations)}
</article>
))}
</section>
)}
<section className={card}>
<h2 className="text-lg font-semibold">
{guide.eligibility_title ??
'Elegibilidade: confirmar com a entidade'}
</h2>
{guide.eligibility.map((item) => (
<div key={item.text}>
<p>{item.text}</p>
{sourceLinks(item.sources)}
{citations(item.citations)}
</div>
))}
</section>
<section className={card}>
<h2 className="text-lg font-semibold">
{guide.preparation_title ?? 'Dados e documentos a preparar'}
</h2>
<p>
Referência de preparação; a lista exigida em cada operação é
definida pela entidade destinatária.
</p>
{guide.preparation.map((item) => (
<article className="my-3" key={item.title}>
<h3 className="font-semibold">{item.title}</h3>
<p>{item.text}</p>
{item.responsible && (
<p>Intervenientes: {item.responsible}</p>
)}
{sourceLinks(item.sources)}
{citations(item.citations)}
</article>
))}
{dossier && (
<Link
className="underline"
href={`/balcao-virtual/dossiers/${dossier.id}`}
>
Reutilizar ou anexar documentos neste dossier
</Link>
)}
</section>
<section className={card}>
<h2 className="text-lg font-semibold">Próximos passos</h2>
<ol className="list-decimal pl-5">
{guide.next.map((text) => (
<li key={text}>{text}</li>
))}
</ol>
<ul className="mt-4 list-disc pl-5">
{guide.limits.map((text) => (
<li key={text}>{text}</li>
))}
</ul>
{guide.handoffs?.map((handoff) => (
<p key={handoff.url} className="my-3">
<a
className="underline"
href={handoff.url}
target="_blank"
rel="noopener noreferrer"
>
{handoff.title}
</a>{' '}
· {handoff.note}
</p>
))}
<p>
<Link
className="underline"
href={
dossier
? `/investimentos/${dossier.id}/guias/${guide.slug === 'bolsa' ? 'capitalizacao' : 'bolsa'}`
: `/guias-investimento/${guide.slug === 'bolsa' ? 'capitalizacao' : 'bolsa'}`
}
>
{guide.slug === 'bolsa'
? 'Consultar a preparação de capitalização'
: 'Consultar o guião de admissão à Bolsa'}
</Link>
</p>
<Link
className="underline"
href={
dossier
? `/investimentos/${dossier.id}`
: '/investimentos'
}
>
Continuar a preparação no percurso existente
</Link>
</section>
<section className={card}>
<h2 className="text-lg font-semibold">
Fontes e edição consultada
</h2>
{Object.entries(guide.sources).map(([key, source]) => (
<article className="my-3" key={key} id={`source-${key}`}>
<h3>
<a
className="underline"
href={source.url}
target="_blank"
rel="noopener noreferrer"
>
{source.title}
</a>
</h3>
<p>
{source.edition} · {source.locator} · consulta{' '}
{source.consulted_on}
</p>
{source.valid_until && (
<p>
Período indicado até {source.valid_until}; fonte
histórica, sem aplicação como mínimo actual.
</p>
)}
{source.sha256 && (
<details>
<summary>
Identificação do exemplar consultado
</summary>
<p className="break-all">
SHA256: {source.sha256}
</p>
<p>
A fonte externa pode ser actualizada; a
referência guardada conserva os dados da
edição utilizada.
</p>
</details>
)}
</article>
))}
</section>
{dossier && (
<section className={card}>
<h2 className="text-lg font-semibold">
Histórico de referências
</h2>
<ul>
{props.history.map((h) => (
<li key={h.id}>
<Link
className="underline"
href={`${base}?revision=${h.id}`}
>
Revisão {h.revision} · {h.edition} · {h.at}
</Link>
</li>
))}
</ul>
{props.historyNext && (
<Link
className="underline"
href={`${base}?history_before=${props.historyNext}`}
>
Referências anteriores
</Link>
)}
</section>
)}
</Frame>
);
}
+55 -238
View File
@@ -1,8 +1,11 @@
import { Link, router, useForm } from '@inertiajs/react';
import { Frame, Field, input, button, card } from './shared';
import { Link, router } from '@inertiajs/react';
import { Frame, button, card } from './shared';
import PartnershipSourceLinks from '@/components/partnership-source-links';
import CountrySelect, { type Country } from '@/components/country-select';
import { useEffect, useId } from 'react';
import { type Country } from '@/components/country-select';
import { useCallback, useState } from 'react';
import Editor from '@/components/investment-profile-editor';
import OrganizationEditor from '@/components/organization-country-editor';
import { usePagePreparationGuard } from '@/lib/page-preparation-guard';
type RecordData = { version: number; payload: Record<string, string> };
type Company = RecordData & {
@@ -37,19 +40,38 @@ const labels: Record<string, string> = {
export default function Profile({
account,
actorId,
companies,
countries,
organizations = [],
organizationCountryAvailable = false,
}: {
account: RecordData;
actorId: number;
companies: Company[];
countries: Country[];
organizations?: Organization[];
organizationCountryAvailable?: boolean;
}) {
const [preparations, setPreparations] = useState<Record<string, boolean>>(
{},
);
const reportDirty = useCallback(
(id: string, dirty: boolean) =>
setPreparations((prior) =>
prior[id] === dirty ? prior : { ...prior, [id]: dirty },
),
[],
);
usePagePreparationGuard(
Object.values(preparations).some(Boolean),
'Existem dados por guardar nesta página. Sair e perder a preparação?',
);
return (
<Frame title="Perfil de investimento e empresas">
<Link className="underline" href="/formas-juridicas">
Comparar formas jurídicas antes de constituir uma entidade
</Link>
<Link href="/investidor/manifestacoes" className="underline">
Voltar à área do investidor
</Link>
@@ -62,7 +84,11 @@ export default function Profile({
.
</p>
<Editor
key={'account-' + account.version}
key={'account-' + actorId}
actorId={actorId}
editorId="account"
labels={labels}
reportDirty={reportDirty}
record={account}
countries={countries}
fields={[
@@ -102,8 +128,13 @@ export default function Profile({
</p>
)}
<Editor
key={company.version}
key={company.id + '-' + actorId}
actorId={actorId}
editorId={company.id}
labels={labels}
reportDirty={reportDirty}
record={company}
organizations={organizations}
countries={countries}
fields={[
'name',
@@ -114,42 +145,20 @@ export default function Profile({
'description',
]}
/>
{organizations
.filter((o) => o.country)
.map((org) => (
<div key={org.id} className="mt-3 space-y-2">
<p>
País mestre de {org.name}: {org.country}. A
reutilização altera somente esta declaração;
manifestações anteriores conservam o seu
valor.
</p>
<button
className={button}
onClick={() =>
router.post(
`/investidor/companies/${company.id}/organization-country`,
{
version: company.version,
organization_id: org.id,
organization_version:
org.version,
},
{ preserveScroll: true },
)
}
>
Reutilizar país de {org.name}
</button>
</div>
))}
<button
className={button + ' mt-4'}
onClick={() =>
onClick={() => {
if (
Object.values(preparations).some(Boolean) &&
!window.confirm(
'Existem dados por guardar nesta página. Sair e perder a preparação?',
)
)
return;
router.post('/investidor/manifestacoes', {
company_id: company.id,
})
}
});
}}
>
Preparar manifestação desta empresa
</button>
@@ -159,7 +168,11 @@ export default function Profile({
<section className={card}>
<h3 className="text-xl font-bold">Acrescentar empresa</h3>
<Editor
key={'new-' + companies.length}
key={'new-' + actorId}
actorId={actorId}
editorId="new-company"
labels={labels}
reportDirty={reportDirty}
record={{ version: 0, payload: {} }}
company
countries={countries}
@@ -195,7 +208,9 @@ export default function Profile({
)}
{organizations.map((org) => (
<OrganizationEditor
key={org.id + org.version}
key={org.id + '-' + actorId}
actorId={actorId}
reportDirty={reportDirty}
organization={org}
countries={countries}
/>
@@ -203,201 +218,3 @@ export default function Profile({
</Frame>
);
}
function OrganizationEditor({
organization,
countries,
}: {
organization: Organization;
countries: Country[];
}) {
const form = useForm({
version: organization.version,
country: organization.country ?? '',
source_reference: organization.provenance?.reference ?? '',
});
const id = useId();
useEffect(() => {
if (Object.keys(form.errors).length)
document
.getElementById(id)
?.querySelector<HTMLElement>('[aria-invalid="true"]')
?.focus();
}, [form.errors, id]);
return (
<section
className={card}
aria-label={`Cadastro mestre: ${organization.name}`}
>
<h3 className="text-xl font-bold">{organization.name}</h3>
<p>
Versão {organization.version}; origem do país:{' '}
{organization.provenance?.kind === 'representative_declaration'
? 'declaração do representante'
: 'não informada'}
.
</p>
<form
className="mt-4 space-y-4"
id={id}
onSubmit={(event) => {
event.preventDefault();
form.put(
`/investidor/organizations/${organization.id}/country`,
{ preserveScroll: true },
);
}}
>
<Field label="País de constituição da organização">
<CountrySelect
id={id + '-country'}
label="País de constituição da organização"
countries={countries}
value={form.data.country}
disabled={!organization.canEdit}
error={form.errors.country}
onChange={(country) => form.setData('country', country)}
/>
</Field>
<label className="block" htmlFor={id + '-source'}>
Fonte ou referência deste país
</label>
<textarea
id={id + '-source'}
className={input}
value={form.data.source_reference}
disabled={!organization.canEdit}
maxLength={2000}
aria-invalid={!!form.errors.source_reference}
aria-describedby={
form.errors.source_reference
? id + '-source-error'
: undefined
}
onChange={(event) =>
form.setData('source_reference', event.target.value)
}
/>
{form.errors.source_reference && (
<p id={id + '-source-error'} role="alert">
{form.errors.source_reference}
</p>
)}
{form.errors.version && (
<p role="alert">{form.errors.version}</p>
)}
<button
className={button}
disabled={!organization.canEdit || form.processing}
>
Guardar país da organização
</button>
</form>
</section>
);
}
function Editor({
record,
fields,
company = false,
countries,
}: {
record: RecordData & { id?: string };
fields: string[];
company?: boolean;
countries: Country[];
}) {
const isCompany = company || !!record.id;
const form = useForm({
version: record.version,
payload: Object.fromEntries(
[...fields, 'country'].map((key) => [
key,
record.payload[key] ?? '',
]),
),
});
return (
<form
className="mt-4 space-y-4"
onSubmit={(e) => {
e.preventDefault();
const options = { preserveScroll: true };
if (isCompany)
form.post(
'/investidor/companies' +
(record.id ? '/' + record.id : ''),
options,
);
else form.put('/investidor/profile', options);
}}
>
<div className="grid gap-4 md:grid-cols-2">
{record.payload.country && (
<p>
País anteriormente registado: {record.payload.country}.
Conservado sem atribuir automaticamente residência,
constituição ou origem da solicitação.
</p>
)}
{fields.map((key) => (
<Field key={key} label={labels[key]}>
{key.endsWith('_country_code') ? (
<CountrySelect
id={key + (record.id ?? 'account')}
countries={countries}
label={labels[key]}
error={form.errors[`payload.${key}`]}
value={form.data.payload[key]}
onChange={(value) =>
form.setData('payload', {
...form.data.payload,
[key]: value,
})
}
/>
) : (
<input
className={input}
value={form.data.payload[key]}
required={
isCompany &&
['name', 'country', 'role'].includes(key)
}
maxLength={
key === 'description' ||
key === 'experience'
? 2000
: key === 'investment_capacity'
? 1000
: 200
}
onChange={(e) =>
form.setData('payload', {
...form.data.payload,
[key]: e.target.value,
})
}
/>
)}
{!key.endsWith('_country_code') &&
form.errors[`payload.${key}`] && (
<p role="alert" className="text-red-700">
{form.errors[`payload.${key}`]}
</p>
)}
</Field>
))}
</div>
{Object.entries(form.errors).map(([key, value]) => (
<p role="alert" key={key} className="text-red-700">
{value}
</p>
))}
<button className={button} disabled={form.processing}>
{isCompany
? 'Guardar declaração da empresa'
: 'Guardar perfil de investimento'}
</button>
</form>
);
}
@@ -287,12 +287,22 @@ export default function ZoneAttachments({
type="button"
className={button}
disabled={busy}
onClick={() =>
void send(
onClick={() => {
setBusy(true);
setError('');
router.post(
`/management/documents/${item.document_id}/malware/retry`,
{},
)
}
{
preserveScroll: true,
onError: () =>
setError(
'Não foi possível pedir a análise. Actualize o estado antes de repetir.',
),
onFinish: () => setBusy(false),
},
);
}}
>
Tentar análise novamente
</button>