Files
Investidor-V2/resources/js/components/investment-promoter.tsx
T
2026-11-15 18:56:39 +02:00

215 lines
9.7 KiB
TypeScript

import { useRef, useState } from 'react';
import { Link, router } from '@inertiajs/react';
import CatalogueChoiceSelect from './catalogue-choice-select';
import { contextApi, type PromoterEntity } from '@/lib/investor-context';
import { createOperationKey } from '@/lib/operation-key';
type Options = {
version: number;
selected: PromoterEntity;
can_write: boolean;
companies: { id: string; name: string; version: number }[];
organizations: { id: string; name: string; version: number }[];
};
const valueOf = (entity?: PromoterEntity) =>
entity && ['company', 'organization'].includes(entity.kind)
? entity.kind + ':' + entity.id
: (entity?.kind ?? 'undetermined');
export default function InvestmentPromoter({
caseId,
selected,
canEdit,
}: {
caseId: string;
selected?: PromoterEntity;
canEdit: boolean;
}) {
const [options, setOptions] = useState<Options | null>(null);
const [choice, setChoice] = useState(valueOf(selected));
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [uncertain, setUncertain] = useState(false);
const command = useRef<Record<string, unknown> | null>(null);
const current = options?.selected ?? selected;
const url = `/investimentos/${caseId}/contexto/entidade`;
const recover = async () => {
setBusy(true);
setError('');
try {
setOptions(await contextApi<Options>(url));
command.current = null;
setUncertain(false);
} catch (error) {
setError(
error instanceof Error
? error.message
: 'Não foi possível consultar a associação.',
);
} finally {
setBusy(false);
}
};
return (
<section
id="entidade-promotora"
className="space-y-3 rounded border p-4"
>
<h2 className="font-semibold">Entidade promotora</h2>
<p>
{current?.snapshot?.name ||
(current?.kind === 'being_formed'
? 'Entidade por constituir'
: 'Entidade por definir')}
</p>
<p>
{current?.kind === 'company' || current?.kind === 'organization'
? 'Cadastro associado no portal. A associação não comprova constituição legal nem altera a propriedade ou o acesso ao dossier.'
: 'Pode continuar a ideia e a viabilidade. Os actos que dependam da entidade serão identificados na respectiva etapa.'}
</p>
<nav className="flex flex-wrap gap-3">
{canEdit && (
<Link
className="underline"
href={`/simulador-fiscal?context=${caseId}`}
>
Continuar a viabilidade
</Link>
)}
{current?.kind === 'being_formed' && (
<Link
className="underline"
href={`/investimentos/${caseId}/preparar-empresa`}
>
Continuar a preparação da empresa
</Link>
)}
{current?.kind !== 'company' &&
current?.kind !== 'organization' && (
<Link
className="underline"
href={`/investimentos/${caseId}/forma-juridica`}
>
Comparar formas jurídicas, se precisar
</Link>
)}
</nav>
{canEdit && (
<details
onToggle={(event) => {
if (event.currentTarget.open && !options && !busy)
void recover();
}}
>
<summary>Associar ou alterar a entidade promotora</summary>
{options && (
<div className="mt-3 grid gap-3">
<CatalogueChoiceSelect
label="Entidade para este investimento"
value={choice}
disabled={
busy || uncertain || !options.can_write
}
options={[
{
value: 'undetermined',
label: 'Continuar com entidade por definir',
},
{
value: 'being_formed',
label: 'Preparar uma entidade por constituir',
},
...options.companies.map((company) => ({
value: 'company:' + company.id,
label:
company.name +
' — empresa declarada',
})),
...options.organizations.map(
(organization) => ({
value:
'organization:' +
organization.id,
label:
organization.name +
' — organização com acesso autorizado',
}),
),
]}
onChange={(value) => {
setChoice(value || 'undetermined');
command.current = null;
}}
/>
<Link
className="underline"
href={`/investidor/profile?dossier=${caseId}`}
>
Registar uma empresa existente no cadastro
habitual e regressar
</Link>
<button
type="button"
className="min-h-11 rounded border p-2"
disabled={
busy || uncertain || !options.can_write
}
onClick={async () => {
setBusy(true);
setError('');
const [kind, id] = choice.split(':');
const source = (
kind === 'company'
? options.companies
: options.organizations
).find((source) => source.id === id);
command.current ??= {
version: options.version,
operation_key: createOperationKey(),
kind,
...(id
? {
id,
source_version:
source?.version,
}
: {}),
};
try {
const result = await contextApi<{
continue: string;
}>(url, command.current);
command.current = null;
router.visit(result.continue);
} catch (error) {
setUncertain(true);
setError(
error instanceof Error
? error.message
: 'Não foi possível confirmar a associação.',
);
} finally {
setBusy(false);
}
}}
>
Guardar associação e continuar
</button>
</div>
)}
{error && <p role="alert">{error}</p>}
{(error || uncertain) && (
<button
type="button"
className="underline"
disabled={busy}
onClick={() => void recover()}
>
Recuperar associação guardada sem perder a escolha
</button>
)}
</details>
)}
</section>
);
}