Files
Investidor-V2/resources/js/pages/investment/company-preparation.tsx
T

791 lines
34 KiB
TypeScript

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>
);
}