Complete APIEX documentary preparation and private contextual SWOT in existing dossiers

This commit is contained in:
2026-11-10 18:00:06 +02:00
parent 7476dc3430
commit 37854d0231
17 changed files with 2982 additions and 24 deletions
+143
View File
@@ -0,0 +1,143 @@
import { createOperationKey } from './operation-key.ts';
export const swotDimensions = {
strength: 'Forças — internas ao objecto',
weakness: 'Fraquezas — internas ao objecto',
opportunity: 'Oportunidades — externas ao objecto',
threat: 'Ameaças — externas ao objecto',
} as const;
export type SwotRow = {
id: string;
dimension: keyof typeof swotDimensions;
text: string;
reference: string;
source_key: string | null;
date: string | null;
classification: 'documented_fact' | 'hypothesis' | 'unconfirmed';
};
export type SwotDraft = {
sources_snapshot?: unknown;
snapshot_fingerprint?: string;
object_key: string;
scope: string | null;
rows: SwotRow[];
source_fingerprint: string;
review?: { reason: string; at: string } | null;
actions: {
id: string;
title: string;
kind: string;
href: string;
review_version: number;
}[];
};
export type Workspace = {
historical?: boolean;
initial_scope?: boolean;
saved_scopes?: { key: string; label: string; href: string }[];
case: { id: string; title: string; closed: boolean };
opportunity: string | null;
opportunity_label?: string | null;
version: number;
apiex: {
note: string | null;
additional_documents: string[];
review: { reason: string; at: string; fingerprint: string } | null;
exports: { id: string; at: string; context_revision: number }[];
external: {
id: string;
kind: string;
date: string;
reference: string;
proof_document: string;
related_id?: string;
export_id: string;
outcome?: string;
}[];
};
swot: SwotDraft;
api_state: string;
api_issues: string[];
api_fingerprint: string;
swot_fingerprint: string;
swot_review_required: boolean;
can_write: boolean;
can_review: boolean;
links: Record<string, string>;
objects: { key: string; label: string; kind: string }[];
sources: {
key: string;
label: string;
consulted?: unknown;
current?: unknown;
notice?: string;
}[];
reused?: Record<string, unknown>;
context: { revision: number; fields: Record<string, unknown> };
assessment: {
requirements: {
key: string;
label: string;
state: string;
required: boolean;
available: boolean;
reason: string;
document_id: string | null;
source: { reference: string; url: string };
}[];
};
documents: {
id: string;
document_id: string;
file_name: string;
available: boolean;
version_no: number;
}[];
history_next?: number | null;
history: {
version: number;
action: string;
at: string;
actor: number;
operation_key?: string;
}[];
};
/** A lost response retains the exact intent; editing fields never mutates a retry. */
export class PreparationAttempt {
private value: Record<string, unknown> | null = null;
start(
version: number,
opportunity: string | null,
action: string,
data: Record<string, unknown>,
reason: string,
) {
if (this.value)
throw Error('Resolva a tentativa anterior antes de iniciar outra.');
this.value = JSON.parse(
JSON.stringify({
...data,
version,
opportunity,
action,
reason,
operation_key: createOperationKey(),
}),
) as Record<string, unknown>;
return this.current()!;
}
current() {
return this.value ? structuredClone(this.value) : null;
}
complete() {
this.value = null;
}
canAdopt(view: Pick<Workspace, 'version' | 'history'>) {
return (
!this.value ||
view.version > Number(this.value.version) ||
view.history.some(
(h) => h.operation_key === this.value?.operation_key,
)
);
}
}
+2
View File
@@ -3,6 +3,7 @@ export class ProfileValidationError extends Error {
message: string,
public readonly fields: Record<string, string>,
public readonly reauthenticate = false,
public readonly status: number | null = null,
) {
super(message);
}
@@ -67,6 +68,7 @@ export async function profileJson(
]),
),
reauthenticate,
response.status,
);
return result;
}
File diff suppressed because it is too large Load Diff
+67 -11
View File
@@ -39,6 +39,13 @@ type Step = {
source_paragraph: number;
};
type Path = {
preparation_action?: {
id: string;
title: string;
kind: string;
case_id: string;
opportunity: string | null;
} | null;
context_opportunity: string | null;
opportunity_options: NonNullable<DossierContext['opportunity_choices']>;
private_investment?: Preparation | null;
@@ -193,7 +200,11 @@ function Stage({ step, path }: { step: Step; path: Path }) {
className={`space-y-3 rounded-xl border p-4 ${licensing ? 'md:col-span-2' : ''}`}
>
<Heading
className={licensing ? 'text-lg font-semibold' : 'cursor-pointer font-semibold'}
className={
licensing
? 'text-lg font-semibold'
: 'cursor-pointer font-semibold'
}
>
{step.title} · {pathStates[step.state]}
</Heading>
@@ -270,7 +281,11 @@ function Stage({ step, path }: { step: Step; path: Path }) {
</p>
))}
<Reference className="text-xs">
<ReferenceHeading className={licensing ? 'font-semibold' : 'cursor-pointer underline'}>
<ReferenceHeading
className={
licensing ? 'font-semibold' : 'cursor-pointer underline'
}
>
Fonte e referência desta etapa
</ReferenceHeading>
<p>
@@ -285,9 +300,17 @@ function Stage({ step, path }: { step: Step; path: Path }) {
</Reference>
{step.preparation_allowed && (path.canWrite || path.canReview) && (
<Record
aria-label={licensing ? 'Registar licenciamento' : undefined}
aria-label={
licensing ? 'Registar licenciamento' : undefined
}
>
<RecordHeading className={licensing ? 'font-semibold' : 'cursor-pointer underline'}>
<RecordHeading
className={
licensing
? 'font-semibold'
: 'cursor-pointer underline'
}
>
Registar avanço ou pendência
</RecordHeading>
<form
@@ -437,9 +460,11 @@ function Stage({ step, path }: { step: Step; path: Path }) {
))}
<button
disabled={form.processing}
className={licensing
? 'rounded bg-emerald-800 px-4 py-3 font-semibold text-white disabled:opacity-50'
: 'rounded border p-2'}
className={
licensing
? 'rounded bg-emerald-800 px-4 py-3 font-semibold text-white disabled:opacity-50'
: 'rounded border p-2'
}
>
Guardar registo
</button>
@@ -456,7 +481,11 @@ export default function InvestmentPath(path: Path) {
useEffect(() => {
const reveal = () => {
if (root.current) {
revealPathStage(root.current, window.location.hash, stageCodes.split(','));
revealPathStage(
root.current,
window.location.hash,
stageCodes.split(','),
);
}
};
reveal();
@@ -467,6 +496,15 @@ export default function InvestmentPath(path: Path) {
auth: { user: { id: number } };
flash: { success?: string };
}>().props;
useEffect(() => {
if (path.preparation_action && window.location.hash === '#tarefas') {
const target = document.getElementById('tarefas');
if (target instanceof HTMLDetailsElement) {
target.open = true;
target.scrollIntoView({ block: 'start' });
}
}
}, [path.preparation_action]);
const facts = useForm({
version: path.case.version,
context_opportunity: path.context_opportunity,
@@ -476,7 +514,9 @@ export default function InvestmentPath(path: Path) {
const task = useForm({
version: path.case.version,
code: 'S02',
title: '',
title: path.preparation_action?.title ?? '',
preparation_action: path.preparation_action?.id ?? null,
opportunity: path.preparation_action?.opportunity ?? null,
due_at: '',
consent: false,
});
@@ -498,7 +538,10 @@ export default function InvestmentPath(path: Path) {
);
}
return (
<main ref={root} className="mx-auto max-w-6xl min-w-0 space-y-6 p-4 [overflow-wrap:anywhere] md:p-8 [&_input]:max-w-full [&_input]:min-w-0 [&_label]:min-w-0 [&_select]:max-w-full [&_select]:min-w-0">
<main
ref={root}
className="mx-auto max-w-6xl min-w-0 space-y-6 p-4 [overflow-wrap:anywhere] md:p-8 [&_input]:max-w-full [&_input]:min-w-0 [&_label]:min-w-0 [&_select]:max-w-full [&_select]:min-w-0"
>
<Head title={path.case.title} />
<Link className="underline" href="/investimentos">
Os meus investimentos
@@ -732,6 +775,7 @@ export default function InvestmentPath(path: Path) {
{
(
{
preparation: 'Preparação APIEX e SWOT',
simulator: 'Plano e simulador',
desk: 'Balcão e histórico',
library: 'Biblioteca',
@@ -975,6 +1019,11 @@ export default function InvestmentPath(path: Path) {
>
Preparar os dados para a constituição da empresa
</Link>
{path.tools.preparation && (
<Link className="underline" href={path.tools.preparation}>
Preparação APIEX e análise SWOT deste investimento
</Link>
)}
{path.tools.company && (
<Link className="underline" href={path.tools.company}>
Comparar formas jurídicas para este investimento
@@ -997,10 +1046,17 @@ export default function InvestmentPath(path: Path) {
Anexar ou conferir no Balcão
</Link>
</section>
<details className="space-y-3 rounded-xl border p-4">
<details id="tarefas" className="space-y-3 rounded-xl border p-4">
<summary className="cursor-pointer text-lg font-semibold">
Acompanhamento interno
</summary>
{path.preparation_action && (
<p role="status">
Acção ligada à SWOT deste dossier:{' '}
{path.preparation_action.title}. Confira a etapa e a
data antes de assumir a tarefa.
</p>
)}
{path.canWrite && (
<form
className="grid min-w-0 gap-3 [&_input]:max-w-full [&_input]:min-w-0 [&_label]:min-w-0 [&_select]:max-w-full [&_select]:min-w-0"
@@ -0,0 +1,20 @@
<!doctype html>
<html lang="pt"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Preparação documental — {{ $workspace['case']['title'] }}</title><style>body{font:16px sans-serif;max-width:70rem;margin:2rem auto;padding:1rem;color:#17202a}table{border-collapse:collapse;width:100%}td,th{padding:.6rem;border:1px solid #aaa;text-align:left;vertical-align:top}pre{white-space:pre-wrap;overflow-wrap:anywhere}h1,h2{break-after:avoid}</style></head><body>
<h1>Preparação documental APIEX</h1>
<p>{{ $workspace['case']['title'] }} · Dossier {{ $workspace['case']['id'] }} · Oportunidade {{ $workspace['opportunity'] ?? 'contexto único do dossier' }} · Revisão de contexto {{ $workspace['context']['revision'] }}</p>
<p>Preparação para entrega externa. Não é formulário oficial, submissão electrónica nem aprovação. Os modelos existentes só integram o pacote quando associados como documentos. Não foi criada uma interface de recepção APIEX.</p>
<h2>Índice e requisitos aplicáveis</h2><table><thead><tr><th>Requisito</th><th>Situação</th><th>Fundamento</th><th>Documento/versão</th></tr></thead><tbody>
@foreach($workspace['assessment']['requirements'] as $requirement)
<tr><td>{{ $requirement['label'] }}</td><td>{{ $requirement['state'] === 'not_applicable' ? 'Não aplicável' : ($requirement['available'] ? 'Disponível' : ($requirement['state'] === 'indeterminate' ? 'Por determinar' : 'Em falta/indisponível')) }}</td><td>{{ $requirement['reason'] }} {{ $requirement['source']['reference'] }} · {{ $requirement['source']['url'] }}</td><td>{{ $requirement['document']['file_name'] ?? '—' }} · {{ $requirement['document']['version_no'] ?? '—' }}</td></tr>
@endforeach
</tbody></table>
<h2>Anexos organizados</h2><ol>
@foreach($workspace['selected_documents'] as $n => $document)
<li>@if($manifest)<a href="{{ 'anexos/'.sprintf('%02d-', $n + 1).preg_replace('/[^\pL\pN._-]+/u', '-', basename($document['file_name'])) }}">{{ $document['file_name'] }}</a>@else{{ $document['file_name'] }}@endif · versão {{ $document['version_no'] }} · SHA256 {{ $document['sha256'] }}</li>
@endforeach
</ol>
<h2>Investidor e empresa reutilizados</h2><pre>{{ json_encode($workspace['reused'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) }}</pre><h2>Dados reutilizados do contexto</h2><pre>{{ json_encode($workspace['context']['fields'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) }}</pre>
<p>{{ $workspace['apiex']['note'] }}</p>
<h2>Revisão</h2><p>{{ $workspace['apiex']['review']['reason'] ?? 'Por conferir' }} · {{ $workspace['apiex']['review']['at'] ?? '' }}</p>
@if($manifest)<h2>Identificação da exportação</h2><p>{{ $manifest['export']['id'] }} · {{ $manifest['export']['at'] }} · {{ $manifest['export']['fingerprint'] }}</p>@endif
</body></html>