336 lines
15 KiB
TypeScript
336 lines
15 KiB
TypeScript
import { BusinessPlanWarnings } from './business-plan-warnings';
|
|
import { useEffect, useMemo, useState } from 'react';
|
|
import { DossierReportPreview } from './dossier-report-preview';
|
|
import {
|
|
createInvestorDossierReport,
|
|
createInvestorStageReport,
|
|
investorDossierReportIndex,
|
|
investorFinancialReportChoices,
|
|
type InvestorDossierReportInput,
|
|
} from '@/lib/investor-dossier-report';
|
|
import {
|
|
createProjectDossierPrintHtml,
|
|
generateProjectDossierDocx,
|
|
} from '@/lib/project-dossier-report';
|
|
|
|
export function InvestorDossierReports({
|
|
dossier,
|
|
}: {
|
|
dossier: InvestorDossierReportInput;
|
|
}) {
|
|
return (
|
|
<InvestorDossierReportsContent
|
|
key={`${dossier.case.id}:${dossier.case.version}:${dossier.context_opportunity ?? ''}`}
|
|
dossier={dossier}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function InvestorDossierReportsContent({
|
|
dossier,
|
|
}: {
|
|
dossier: InvestorDossierReportInput;
|
|
}) {
|
|
const [busy, setBusy] = useState(false);
|
|
const [error, setError] = useState('');
|
|
const [stage, setStage] = useState('');
|
|
const [financialResultId, setFinancialResultId] = useState('');
|
|
const [download, setDownload] = useState<{
|
|
url: string;
|
|
name: string;
|
|
} | null>(null);
|
|
useEffect(
|
|
() => () => {
|
|
if (download) URL.revokeObjectURL(download.url);
|
|
},
|
|
[download],
|
|
);
|
|
const requiresChoice =
|
|
dossier.opportunity_options.length > 1 && !dossier.context_opportunity;
|
|
const entries = requiresChoice ? [] : investorDossierReportIndex(dossier);
|
|
const financialChoices = requiresChoice
|
|
? []
|
|
: investorFinancialReportChoices(dossier);
|
|
const financialChoiceRequired =
|
|
(!stage || stage === 'S03') &&
|
|
financialChoices.length > 1 &&
|
|
!financialResultId;
|
|
const report = useMemo(
|
|
() =>
|
|
requiresChoice || financialChoiceRequired
|
|
? null
|
|
: stage
|
|
? createInvestorStageReport(
|
|
dossier,
|
|
stage,
|
|
undefined,
|
|
financialResultId || undefined,
|
|
)
|
|
: createInvestorDossierReport(dossier, undefined, {
|
|
financialResultId: financialResultId || undefined,
|
|
}),
|
|
[
|
|
dossier,
|
|
stage,
|
|
financialResultId,
|
|
requiresChoice,
|
|
financialChoiceRequired,
|
|
],
|
|
);
|
|
async function exportReport(format: 'word' | 'html') {
|
|
setBusy(true);
|
|
setError('');
|
|
try {
|
|
if (!report)
|
|
throw Error(
|
|
'Escolha o contexto e a versão financeira antes de exportar.',
|
|
);
|
|
const model = report;
|
|
const blob =
|
|
format === 'word'
|
|
? await generateProjectDossierDocx(model, [], true)
|
|
: new Blob(
|
|
[
|
|
await createProjectDossierPrintHtml(
|
|
model,
|
|
[],
|
|
true,
|
|
),
|
|
],
|
|
{ type: 'text/html;charset=utf-8' },
|
|
);
|
|
const url = URL.createObjectURL(blob);
|
|
const name = `dossier-${dossier.case.id}-v${dossier.case.version}-${dossier.context_opportunity ? encodeURIComponent(dossier.context_opportunity) : 'comum'}${stage ? `-${stage}` : ''}.${format === 'word' ? 'docx' : 'html'}`;
|
|
setDownload({ url, name });
|
|
} catch (cause) {
|
|
setError(
|
|
cause instanceof Error
|
|
? cause.message
|
|
: 'Não foi possível preparar o relatório. Os registos foram preservados.',
|
|
);
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
return (
|
|
<section id="relatorios" className="space-y-4 rounded-xl border p-4">
|
|
<h2 className="text-lg font-semibold">Relatórios deste dossier</h2>
|
|
{!requiresChoice && (
|
|
<BusinessPlanWarnings
|
|
metrics={{
|
|
optionalTexts: [
|
|
{
|
|
label: 'SWOT',
|
|
value: dossier.preparation_report?.swot.rows.some(
|
|
(row) => row.text.trim(),
|
|
)
|
|
? 'preenchido'
|
|
: '',
|
|
},
|
|
],
|
|
}}
|
|
/>
|
|
)}
|
|
<p>
|
|
Dossier {dossier.case.title} · versão {dossier.case.version} ·
|
|
oportunidade {dossier.context_opportunity ?? 'contexto comum'}.
|
|
</p>
|
|
<p>
|
|
Reúna as etapas, a viabilidade, a análise SWOT e a preparação
|
|
APIEX. O relatório mantém os estados e as pendências; os
|
|
originais continuam nas respectivas versões.
|
|
</p>
|
|
{requiresChoice ? (
|
|
<p role="status">
|
|
Seleccione a oportunidade em tratamento para reunir os seus
|
|
relatórios sem misturar contextos.
|
|
</p>
|
|
) : (
|
|
<>
|
|
<label className="block">
|
|
Relatório a consultar e descarregar
|
|
<select
|
|
className="mt-1 block w-full rounded border p-2"
|
|
value={stage}
|
|
disabled={busy}
|
|
onChange={(event) => {
|
|
setStage(event.target.value);
|
|
setDownload(null);
|
|
}}
|
|
>
|
|
<option value="">Dossier completo</option>
|
|
{dossier.steps.map((step) => (
|
|
<option key={step.code} value={step.code}>
|
|
{step.code} — {step.title}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
{(!stage || stage === 'S03') &&
|
|
financialChoices.length > 0 && (
|
|
<label className="grid min-w-0 gap-1">
|
|
Plano financeiro a incluir
|
|
<select
|
|
className="w-full min-w-0 rounded border p-2"
|
|
value={financialResultId}
|
|
disabled={busy}
|
|
onChange={(e) => {
|
|
setFinancialResultId(e.target.value);
|
|
setDownload(null);
|
|
}}
|
|
>
|
|
<option value="">
|
|
{financialChoices.length === 1
|
|
? 'Única versão preservada neste contexto'
|
|
: 'Escolha uma versão — os valores não serão misturados'}
|
|
</option>
|
|
{financialChoices.map((r) => (
|
|
<option key={r.id} value={r.id}>
|
|
Rascunho v{r.draft_version} ·{' '}
|
|
{r.recorded_at} · contexto v
|
|
{r.context_revision ??
|
|
'por identificar'}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
)}
|
|
{financialChoiceRequired && (
|
|
<p role="status">
|
|
Escolha a versão financeira a incluir. As restantes
|
|
versões permanecem no histórico.
|
|
</p>
|
|
)}
|
|
{!financialChoices.length &&
|
|
dossier.results.some(
|
|
(r) =>
|
|
(r.context_opportunity ?? null) ===
|
|
dossier.context_opportunity,
|
|
) && (
|
|
<p className="text-sm">
|
|
As versões antigas não contêm todos os dados do
|
|
relatório integral. Os originais permanecem
|
|
disponíveis; use uma versão completa guardada
|
|
para reunir as onze tabelas.
|
|
</p>
|
|
)}
|
|
{report && (
|
|
<details
|
|
className="rounded border p-3"
|
|
open={Boolean(stage)}
|
|
>
|
|
<summary>
|
|
Conferir o relatório antes de exportar
|
|
</summary>
|
|
<DossierReportPreview report={report} />
|
|
</details>
|
|
)}
|
|
<div className="flex flex-wrap gap-3">
|
|
<button
|
|
className="rounded border px-3 py-2"
|
|
disabled={busy || financialChoiceRequired}
|
|
onClick={() => exportReport('word')}
|
|
>
|
|
Preparar{' '}
|
|
{stage
|
|
? `relatório ${stage}`
|
|
: 'relatório consolidado'}{' '}
|
|
(Word)
|
|
</button>
|
|
<button
|
|
className="rounded border px-3 py-2"
|
|
disabled={busy || financialChoiceRequired}
|
|
onClick={() => exportReport('html')}
|
|
>
|
|
Preparar versão para impressão/PDF
|
|
</button>
|
|
</div>
|
|
{busy && <p role="status">A preparar o ficheiro…</p>}
|
|
{download && (
|
|
<p role="status">
|
|
Ficheiro pronto.{' '}
|
|
<a
|
|
className="font-medium underline"
|
|
href={download.url}
|
|
download={download.name}
|
|
>
|
|
Descarregar {download.name}
|
|
</a>
|
|
</p>
|
|
)}
|
|
<p className="text-sm">
|
|
A versão HTML pode ser aberta e impressa ou guardada
|
|
como PDF. As descargas são privadas; não enviam
|
|
processos ou mensagens a entidades externas.
|
|
</p>
|
|
{!!entries.length && (
|
|
<div className="overflow-x-auto">
|
|
<table className="w-full min-w-[48rem] text-left text-sm">
|
|
<caption className="sr-only">
|
|
Índice por etapa, versão e data
|
|
</caption>
|
|
<thead>
|
|
<tr>
|
|
<th className="p-2">Etapa</th>
|
|
<th className="p-2">
|
|
Relatório ou documento
|
|
</th>
|
|
<th className="p-2">Versão e data</th>
|
|
<th className="p-2">Estado</th>
|
|
<th className="p-2">Consultar</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{entries.map((entry) => (
|
|
<tr key={entry.id} className="border-t">
|
|
<td className="p-2">
|
|
{entry.stage}
|
|
</td>
|
|
<td className="p-2">
|
|
{entry.title}
|
|
</td>
|
|
<td className="max-w-56 p-2 break-words">
|
|
{entry.version} ·{' '}
|
|
{entry.date ||
|
|
'Data não registada'}
|
|
</td>
|
|
<td className="p-2">
|
|
{entry.state}
|
|
</td>
|
|
<td className="p-2">
|
|
<a
|
|
className="underline"
|
|
href={entry.href}
|
|
>
|
|
{entry.action}
|
|
</a>
|
|
</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
)}
|
|
{!entries.length && (
|
|
<p>
|
|
Nenhum relatório ou documento produzido e autorizado
|
|
neste âmbito. O relatório consolidado identifica as
|
|
etapas e as pendências existentes.
|
|
</p>
|
|
)}
|
|
<p className="text-sm">
|
|
Os relatórios financeiros são apresentados apenas ao
|
|
titular autorizado do rascunho. Consulte os documentos
|
|
de cada acto antes de executar o investimento.
|
|
</p>
|
|
</>
|
|
)}
|
|
{error && (
|
|
<p role="alert" className="text-red-700">
|
|
{error}
|
|
</p>
|
|
)}
|
|
</section>
|
|
);
|
|
}
|