339 lines
14 KiB
TypeScript
339 lines
14 KiB
TypeScript
import { Link } from '@inertiajs/react';
|
|
import { useRef, useState } from 'react';
|
|
import { Frame, input, button, card } from './shared';
|
|
import {
|
|
ClassificationEditor,
|
|
ClassificationSummary,
|
|
classificationStates,
|
|
type ClassificationRelation,
|
|
type ClassificationOptions,
|
|
type PublicClassification,
|
|
} from '@/components/opportunity-classification';
|
|
|
|
type ReviewRow = {
|
|
hash: string;
|
|
relation: ClassificationRelation;
|
|
state: string;
|
|
dimension: string;
|
|
can_review: boolean;
|
|
history: { state: string; at: string; reason: string }[];
|
|
};
|
|
type Supplement = {
|
|
id: string;
|
|
title: string;
|
|
status: string;
|
|
version_no: number;
|
|
rows: ReviewRow[];
|
|
publication: PublicClassification[];
|
|
preview: PublicClassification[];
|
|
publication_version: number | null;
|
|
can_prepare: boolean;
|
|
can_disclose: boolean;
|
|
options: ClassificationOptions;
|
|
authorities: { id: string; label_pt_mz: string }[];
|
|
documents: {
|
|
id: string;
|
|
payload: { title?: string };
|
|
file: { file_name: string };
|
|
}[];
|
|
};
|
|
|
|
export default function BusinessClassification({
|
|
supplement,
|
|
}: {
|
|
supplement: Supplement;
|
|
}) {
|
|
const [current, setCurrent] = useState(supplement);
|
|
const [rows, setRows] = useState(supplement.rows.map((r) => r.relation));
|
|
const [reason, setReason] = useState('');
|
|
const [error, setError] = useState('');
|
|
const [errors, setErrors] = useState<Record<string, string>>({});
|
|
const [message, setMessage] = useState('');
|
|
const [busy, setBusy] = useState(false);
|
|
const [preview, setPreview] = useState(false);
|
|
const alert = useRef<HTMLDivElement>(null);
|
|
const dirty =
|
|
JSON.stringify(rows) !==
|
|
JSON.stringify(current.rows.map((r) => r.relation));
|
|
async function act(action: string, fields: Record<string, unknown> = {}) {
|
|
setBusy(true);
|
|
setError('');
|
|
setErrors({});
|
|
setMessage('');
|
|
try {
|
|
const token = decodeURIComponent(
|
|
document.cookie
|
|
.split('; ')
|
|
.find((v) => v.startsWith('XSRF-TOKEN='))
|
|
?.slice(11) ?? '',
|
|
);
|
|
const response = await fetch(
|
|
`/api/v1/existing-business/listings/${current.id}/classification`,
|
|
{
|
|
method: 'POST',
|
|
credentials: 'same-origin',
|
|
headers: {
|
|
Accept: 'application/json',
|
|
'Content-Type': 'application/json',
|
|
'X-XSRF-TOKEN': token,
|
|
},
|
|
body: JSON.stringify({
|
|
action,
|
|
version_no: current.version_no,
|
|
reason,
|
|
...fields,
|
|
}),
|
|
},
|
|
);
|
|
const result = await response.json();
|
|
if (!response.ok) {
|
|
const details = Object.fromEntries(
|
|
Object.entries(result.errors ?? {}).map(([key, value]) => [
|
|
key,
|
|
(value as string[]).join(' '),
|
|
]),
|
|
);
|
|
setErrors(details);
|
|
throw new Error(
|
|
Object.values(details)[0] ||
|
|
result.message ||
|
|
'Não foi possível concluir. Os valores preparados permanecem no formulário.',
|
|
);
|
|
}
|
|
setCurrent(result.supplement);
|
|
setRows(result.supplement.rows.map((r: ReviewRow) => r.relation));
|
|
setPreview(false);
|
|
setMessage(
|
|
action === 'prepare'
|
|
? 'Classificação guardada e recuperada. A publicação anterior mantém-se.'
|
|
: action === 'review'
|
|
? 'Decisão registada. A divulgação continua separada.'
|
|
: action === 'withdraw'
|
|
? 'Projeção da classificação retirada; anúncio preservado.'
|
|
: 'Nova fotografia da classificação divulgada; anúncio preservado.',
|
|
);
|
|
} catch (e) {
|
|
setError(
|
|
e instanceof Error
|
|
? e.message
|
|
: 'Não foi possível concluir. Preserve os valores e atualize a página.',
|
|
);
|
|
requestAnimationFrame(() => alert.current?.focus());
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
const previewRows = current.preview;
|
|
return (
|
|
<Frame title="Classificação do anúncio">
|
|
<div className="mx-auto max-w-5xl space-y-5">
|
|
<Link
|
|
className="underline"
|
|
href={`/investidor/negocios/${current.id}`}
|
|
>
|
|
Voltar ao mesmo anúncio
|
|
</Link>
|
|
<h1 className="text-2xl font-bold">{current.title}</h1>
|
|
<p>
|
|
Anúncio{' '}
|
|
{current.status === 'published'
|
|
? 'publicado'
|
|
: 'em preparação'}{' '}
|
|
· versão {current.version_no}
|
|
</p>
|
|
<p>
|
|
Este suplemento altera apenas a classificação. Conteúdo,
|
|
confidencialidade e workflow do anúncio mantêm-se. Guardar
|
|
ou confirmar uma relação não a divulga.
|
|
</p>
|
|
{error && (
|
|
<div
|
|
ref={alert}
|
|
tabIndex={-1}
|
|
role="alert"
|
|
className="rounded border border-red-600 p-3"
|
|
>
|
|
{error}
|
|
</div>
|
|
)}
|
|
{message && <p role="status">{message}</p>}
|
|
{current.can_prepare && (
|
|
<section className={card}>
|
|
<ClassificationEditor
|
|
rows={rows}
|
|
onChange={setRows}
|
|
options={current.options}
|
|
documents={current.documents}
|
|
authorities={current.authorities}
|
|
errors={errors}
|
|
/>
|
|
</section>
|
|
)}
|
|
<label className="grid gap-1">
|
|
Fundamento da ação{' '}
|
|
<textarea
|
|
className={input}
|
|
value={reason}
|
|
onChange={(e) => setReason(e.target.value)}
|
|
minLength={20}
|
|
maxLength={1000}
|
|
/>
|
|
</label>
|
|
<p className="text-sm">
|
|
Indique o fundamento da operação, com pelo menos 20
|
|
caracteres. A nota permanece privada.
|
|
</p>
|
|
{current.can_prepare && (
|
|
<button
|
|
className={button}
|
|
disabled={busy}
|
|
onClick={() => void act('prepare', { rows })}
|
|
>
|
|
Guardar classificação privada
|
|
</button>
|
|
)}
|
|
<section
|
|
className="space-y-4"
|
|
aria-label="Decisões por relação"
|
|
>
|
|
<h2 className="text-xl font-bold">
|
|
Relações guardadas e decisões
|
|
</h2>
|
|
{!current.rows.length && (
|
|
<p>Ainda não existem relações guardadas.</p>
|
|
)}
|
|
{current.rows.map((r) => (
|
|
<article key={r.hash} className={card}>
|
|
<h3 className="font-bold">
|
|
{current.options.targets[
|
|
r.relation.classification!.target_type
|
|
]?.find(
|
|
(t) =>
|
|
String(t.id) === r.relation.related_id,
|
|
)?.label ?? 'Referência indisponível'}
|
|
</h3>
|
|
<p>
|
|
{current.options.dimensions[r.dimension]} ·{' '}
|
|
{
|
|
current.options.purposes[
|
|
r.relation.classification!.purpose
|
|
]
|
|
}{' '}
|
|
· {classificationStates[r.state]}
|
|
</p>
|
|
<p>
|
|
Fonte:{' '}
|
|
{r.relation.classification!.source_reference ||
|
|
'Por indicar'}{' '}
|
|
·{' '}
|
|
{r.relation.classification!.citation ||
|
|
'Citação por indicar'}
|
|
</p>
|
|
<p>
|
|
Fundamento:{' '}
|
|
{r.relation.classification!.justification ||
|
|
'Por indicar'}
|
|
</p>
|
|
{r.can_review ? (
|
|
<div className="flex flex-wrap gap-2">
|
|
{[
|
|
'confirmed',
|
|
'in_validation',
|
|
'rejected',
|
|
'revoked',
|
|
'archived',
|
|
].map((state) => (
|
|
<button
|
|
key={state}
|
|
className={button}
|
|
disabled={busy || dirty}
|
|
onClick={() =>
|
|
void act('review', {
|
|
hash: r.hash,
|
|
state,
|
|
})
|
|
}
|
|
>
|
|
{classificationStates[state]}
|
|
</button>
|
|
))}
|
|
</div>
|
|
) : (
|
|
<p>
|
|
Decisão indisponível nesta sessão: requer
|
|
Validador independente, âmbito,
|
|
responsabilidade e MFA aplicáveis.
|
|
</p>
|
|
)}
|
|
{!!r.history.length && (
|
|
<details>
|
|
<summary>Histórico de decisões</summary>
|
|
<ul>
|
|
{r.history.map((h, i) => (
|
|
<li key={i}>
|
|
{h.at} ·{' '}
|
|
{classificationStates[h.state]}{' '}
|
|
· {h.reason}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</details>
|
|
)}
|
|
</article>
|
|
))}
|
|
</section>
|
|
<section className={card} aria-label="Fotografia pública atual">
|
|
<h2 className="text-xl font-bold">
|
|
Fotografia pública atual
|
|
</h2>
|
|
<p>
|
|
{current.publication_version
|
|
? `Divulgada na versão ${current.publication_version}.`
|
|
: 'Sem classificação divulgada; o teaser anterior mantém-se.'}
|
|
</p>
|
|
<ClassificationSummary rows={current.publication} />
|
|
</section>
|
|
{current.can_disclose && (
|
|
<section className={`${card} space-y-3`}>
|
|
<h2 className="text-xl font-bold">
|
|
Divulgação expressa da classificação
|
|
</h2>
|
|
<p>
|
|
Apenas as relações guardadas com intenção de
|
|
divulgação pública integram a fotografia. Notas,
|
|
contactos, critérios privados e ficheiros de suporte
|
|
permanecem privados.
|
|
</p>
|
|
<button
|
|
className={button}
|
|
disabled={busy || dirty}
|
|
onClick={() => setPreview(!preview)}
|
|
>
|
|
Conferir nova fotografia pública
|
|
</button>
|
|
{preview && (
|
|
<div>
|
|
<ClassificationSummary rows={previewRows} />
|
|
<button
|
|
className={button}
|
|
disabled={busy || dirty}
|
|
onClick={() => void act('disclose')}
|
|
>
|
|
Divulgar esta classificação
|
|
</button>
|
|
</div>
|
|
)}
|
|
<button
|
|
className={button}
|
|
disabled={busy}
|
|
onClick={() => void act('withdraw')}
|
|
>
|
|
Retirar apenas a classificação pública
|
|
</button>
|
|
</section>
|
|
)}
|
|
</div>
|
|
</Frame>
|
|
);
|
|
}
|