387 lines
15 KiB
TypeScript
387 lines
15 KiB
TypeScript
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>
|
|
);
|
|
}
|