feat(qa): consolidate eleven financial report tables pending private visual acceptance

This commit is contained in:
2026-11-20 13:31:47 +02:00
parent 2e5b7f973c
commit 93fc837a47
12 changed files with 674 additions and 68 deletions
@@ -0,0 +1,47 @@
import type { DossierReportModel } from '@/lib/project-dossier-report';
import { InvestmentReportTables } from './investment-report-tables';
export function DossierReportPreview({
report,
}: {
report: DossierReportModel;
}) {
return (
<article
aria-label="Pré-visualização do relatório"
className="min-w-0 space-y-3 rounded border p-3"
>
<h3 className="font-semibold">{report.title}</h3>
<p className="text-sm">{report.version}</p>
{report.sections.map((section, i) => (
<section
key={`${section.id}-${i}`}
className="min-w-0 space-y-2"
>
<h4 className="font-medium">{section.title}</h4>
{section.paragraphs.map((p, j) => (
<p key={j}>{p}</p>
))}
<dl className="space-y-2">
{section.rows.map((r, j) => (
<div className="break-words" key={j}>
<dt className="font-medium">{r.field}</dt>
<dd>{r.value}</dd>
<dd className="text-sm">
{r.classification} · {r.origin}
</dd>
</div>
))}
</dl>
{section.tables && (
<InvestmentReportTables tables={section.tables} />
)}
</section>
))}
{report.limitations.map((p, i) => (
<p className="text-sm" key={i}>
{p}
</p>
))}
</article>
);
}
@@ -1,9 +1,10 @@
import { useEffect, useState } from 'react';
import { InvestmentReportTables } from './investment-report-tables';
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 {
@@ -32,6 +33,7 @@ function InvestorDossierReportsContent({
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;
@@ -45,13 +47,44 @@ function InvestorDossierReportsContent({
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 {
const model = stage
? createInvestorStageReport(dossier, stage)
: createInvestorDossierReport(dossier);
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)
@@ -116,13 +149,69 @@ function InvestorDossierReportsContent({
))}
</select>
</label>
{stage && (
<StageReportPreview dossier={dossier} stage={stage} />
{(!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}
disabled={busy || financialChoiceRequired}
onClick={() => exportReport('word')}
>
Preparar{' '}
@@ -133,7 +222,7 @@ function InvestorDossierReportsContent({
</button>
<button
className="rounded border px-3 py-2"
disabled={busy}
disabled={busy || financialChoiceRequired}
onClick={() => exportReport('html')}
>
Preparar versão para impressão/PDF
@@ -227,49 +316,3 @@ function InvestorDossierReportsContent({
</section>
);
}
function StageReportPreview({
dossier,
stage,
}: {
dossier: InvestorDossierReportInput;
stage: string;
}) {
const report = createInvestorStageReport(dossier, stage);
return (
<article
className="space-y-3 rounded border p-3"
aria-label={`Relatório da etapa ${stage}`}
>
<h3 className="font-semibold">{report.title}</h3>
<p className="text-sm">{report.version}</p>
{report.sections.map((section) => (
<section key={section.id} className="space-y-2">
<h4 className="font-medium">{section.title}</h4>
{section.paragraphs.map((text) => (
<p key={text}>{text}</p>
))}
<dl className="space-y-2">
{section.rows.map((row, index) => (
<div key={index} className="break-words">
<dt className="font-medium">{row.field}</dt>
<dd>{row.value}</dd>
<dd className="text-sm">
{row.classification} · {row.origin}
</dd>
</div>
))}
</dl>
{section.tables && (
<InvestmentReportTables tables={section.tables} />
)}
</section>
))}
{report.limitations.map((text) => (
<p className="text-sm" key={text}>
{text}
</p>
))}
</article>
);
}
@@ -1,4 +1,5 @@
import { useMemo, useRef, useState } from 'react';
import { DossierReportPreview } from './dossier-report-preview';
import {
DossierExportGate,
dossierExportFailure,
@@ -7,6 +8,7 @@ import {
import {
createProjectDossierPrintHtml,
createProjectDossierReport,
createIntegralFinancialReport,
dossierReportSections,
generateProjectDossierDocx,
generateProjectDossierPackage,
@@ -58,6 +60,7 @@ export function ProjectDossierExport({
currentCalculation = null,
}: Props) {
const [selectedSections, setSelectedSections] = useState(defaultSections);
const [reportMode, setReportMode] = useState('dossier');
const [attachments, setAttachments] = useState<DossierAttachment[]>([]);
const [error, setError] = useState('');
const [busy, setBusy] = useState('');
@@ -127,13 +130,31 @@ export function ProjectDossierExport({
);
}
function model() {
return createProjectDossierReport(draft, {
selectedSections: selectedSectionSet,
const report = useMemo(
() =>
reportMode === 'financial'
? createIntegralFinancialReport(draft, {
version,
references,
currentCalculation,
})
: createProjectDossierReport(draft, {
selectedSections: selectedSectionSet,
version,
references,
currentCalculation,
}),
[
draft,
reportMode,
version,
references,
currentCalculation,
});
selectedSectionSet,
],
);
function model() {
return report;
}
async function exportWord(): Promise<void> {
@@ -272,7 +293,10 @@ export function ProjectDossierExport({
</p>
</div>
<fieldset className="space-y-2">
<fieldset
className="space-y-2"
disabled={reportMode === 'financial'}
>
<legend className="font-medium">
Escolha as secções a incluir
</legend>
@@ -400,6 +424,26 @@ export function ProjectDossierExport({
em zero. O relatório identifica pressupostos, estimativas e
referências sem as apresentar como resultados confirmados.
</p>
<label className="grid min-w-0 gap-1">
Conteúdo do relatório
<select
className="w-full min-w-0 rounded border p-2"
value={reportMode}
onChange={(e) => setReportMode(e.target.value)}
disabled={Boolean(busy)}
>
<option value="dossier">
Dossier e contexto — secções seleccionadas
</option>
<option value="financial">
Relatório financeiro integral — onze tabelas
</option>
</select>
</label>
<details className="rounded border p-3">
<summary>Conferir o relatório antes de exportar</summary>
<DossierReportPreview report={report} />
</details>
{notice && (
<p role="status" className="text-sm">
{notice}
@@ -414,7 +458,11 @@ export function ProjectDossierExport({
<button
type="button"
className="rounded bg-emerald-800 px-4 py-2 font-semibold text-white disabled:opacity-50"
disabled={Boolean(busy) || selectedSections.size === 0}
disabled={
Boolean(busy) ||
(reportMode === 'dossier' &&
selectedSections.size === 0)
}
onClick={() => void exportWord()}
>
{busy === 'word'
@@ -424,7 +472,11 @@ export function ProjectDossierExport({
<button
type="button"
className="rounded border px-4 py-2 disabled:opacity-50"
disabled={Boolean(busy) || selectedSections.size === 0}
disabled={
Boolean(busy) ||
(reportMode === 'dossier' &&
selectedSections.size === 0)
}
onClick={() => void exportPdf()}
>
{busy === 'pdf'
+68 -2
View File
@@ -8,6 +8,7 @@ import type {
DossierReportModel,
DossierReportRow,
} from './project-dossier-report.ts';
import { createIntegralFinancialReport } from './project-dossier-report.ts';
export type PreparationReport = {
case_id: string;
@@ -337,11 +338,71 @@ export function investorDossierReportIndex(
return entries.sort((a, b) => a.stage.localeCompare(b.stage));
}
export function investorFinancialReportChoices(
input: InvestorDossierReportInput,
) {
return input.results.filter(
(r) =>
(r.context_opportunity ?? null) === input.context_opportunity &&
typeof r.preparation_snapshot?.business_plan_snapshot ===
'string' &&
r.preparation_snapshot.business_plan_snapshot.trim() !== '',
);
}
export function createInvestorDossierReport(
input: InvestorDossierReportInput,
generatedAt = new Date().toISOString(),
options: {
financialResultId?: string;
omitIntegralFinancial?: boolean;
} = {},
): DossierReportModel {
const index = investorDossierReportIndex(input);
const choices = options.omitIntegralFinancial
? []
: investorFinancialReportChoices(input);
if (
options.financialResultId &&
!choices.some((r) => r.id === options.financialResultId)
)
throw Error(
'O plano financeiro escolhido não pertence a este contexto ou não foi preservado nesta versão.',
);
if (choices.length > 1 && !options.financialResultId)
throw Error(
'Escolha a versão financeira a incluir; os valores de versões diferentes não são misturados.',
);
const chosen = options.financialResultId
? choices.find((r) => r.id === options.financialResultId)
: choices.length === 1
? choices[0]
: undefined;
const integral = chosen
? createIntegralFinancialReport(
{
...chosen.preparation_snapshot,
currency: chosen.currency ?? '',
project_title: input.case.title,
},
{
generatedAt,
version: `Plano guardado v${chosen.draft_version} · contexto v${chosen.context_revision ?? 'por identificar'}`,
},
)
: null;
if (integral && chosen) {
integral.sections[0].paragraphs.unshift(
`Plano preservado em ${chosen.recorded_at}, rascunho v${chosen.draft_version}. As onze tabelas desta secção correspondem apenas à versão escolhida; os outros registos financeiros do dossier mantêm a sua origem e não são somados a este plano.`,
);
if (
chosen.context_revision !== input.investment_context?.revision ||
chosen.context_state === 'review_required'
)
integral.sections[0].paragraphs.unshift(
'Versão histórica: o contexto mudou. Os valores foram preservados e exigem conferência antes de utilização.',
);
}
const supply = input.supply_aggregates?.at(-1);
const row = (
field: string,
@@ -552,6 +613,7 @@ export function createInvestorDossierReport(
'O índice referencia os originais; não incorpora automaticamente os seus anexos nem envia dados a entidades externas.',
],
sections: [
...(integral?.sections ?? []),
{
id: 'supply',
title: 'Actividades existentes — análise agregada',
@@ -764,17 +826,21 @@ export function createInvestorStageReport(
input: InvestorDossierReportInput,
stageCode: string,
generatedAt = new Date().toISOString(),
financialResultId?: string,
): DossierReportModel {
const step = input.steps.find((item) => item.code === stageCode);
if (!step) throw new Error('Etapa não encontrada neste dossier.');
const report = createInvestorDossierReport(input, generatedAt);
const report = createInvestorDossierReport(input, generatedAt, {
financialResultId: stageCode === 'S03' ? financialResultId : undefined,
omitIntegralFinancial: stageCode !== 'S03',
});
const entries = investorDossierReportIndex(input).filter((entry) =>
entry.stage.split(', ').includes(stageCode),
);
const origins = new Set(entries.map((entry) => entry.href));
const specificSections = new Set([
...(stageCode === 'S02' ? ['market'] : []),
...(stageCode === 'S03' ? ['finance'] : []),
...(stageCode === 'S03' ? ['finance', 'financial-report'] : []),
...(['S06', 'S07'].includes(stageCode) ? ['sources'] : []),
]);
return {
+12 -1
View File
@@ -629,6 +629,17 @@ export async function createProjectDossierPrintHtml(
content.push(`<section><h2>${escapeHtml(section.title)}</h2>`);
for (const paragraph of section.paragraphs)
content.push(`<p>${escapeHtml(paragraph)}</p>`);
if (section.id === 'financial-report' && section.rows.length)
content.push(
htmlTable(
['Campo', 'Conteúdo', 'Classificação / origem'],
section.rows.map((row) => [
row.field,
row.value,
`${row.classification}. ${row.origin}`,
]),
),
);
for (const entry of section.tables ?? []) {
content.push(`<h3>${escapeHtml(entry.title)}</h3>`);
for (const note of [...entry.issues, ...entry.notes])
@@ -636,7 +647,7 @@ export async function createProjectDossierPrintHtml(
for (const slice of investmentReportTableSlices(entry))
content.push(htmlTable(slice.headers, slice.rows));
}
if (section.rows.length)
if (section.rows.length && section.id !== 'financial-report')
content.push(
htmlTable(
['Campo', 'Conteúdo', 'Classificação / origem'],
@@ -43,6 +43,7 @@ export const dossierReportSections = [
export type DossierReportSectionId =
| (typeof dossierReportSections)[number]['id']
| 'financial-report'
| 'supply';
export type DossierReference = {
version: number;
@@ -860,6 +861,80 @@ export function createProjectDossierReport(
};
}
export const integralFinancialTableIds = [
'startup',
'market-analysis',
'sales',
'milestones',
'personnel',
'funding',
'break-even',
'profit-loss',
'cashflow',
'balance',
'ratios',
] as const;
/** One saved scenario, one report; existing statement builders remain the source. */
export function createIntegralFinancialReport(
draft: Record<string, string | string[]>,
options: Omit<
Parameters<typeof createProjectDossierReport>[1],
'selectedSections'
> = {},
): DossierReportModel {
const report = createProjectDossierReport(draft, {
...options,
selectedSections: new Set(['market', 'finance', 'team', 'execution']),
});
const tables = report.sections.flatMap((s) => s.tables ?? []);
const finance = report.sections.find((s) => s.id === 'finance');
const planCurrency = restoreBusinessPlanSnapshot(
text(draft, 'business_plan_snapshot'),
)?.currency;
const declaredCurrency = text(draft, 'currency');
const summary = new Set([
'Moeda do plano',
'Horizonte',
'Facturação no horizonte',
'Cobranças no horizonte',
'Pagamentos no horizonte',
'Resultado antes de impostos',
'Caixa final projectada',
'Reconciliação do financiamento',
'Diferença entre usos e fontes',
'Resultado líquido no horizonte',
]);
const ordered = integralFinancialTableIds.flatMap((id) => {
const t = tables.find((t) => t.id === id);
return t ? [t] : [];
});
return {
...report,
sections: [
{
id: 'financial-report',
title: 'Relatório financeiro integral',
private: true,
paragraphs: [
...(planCurrency &&
declaredCurrency &&
planCurrency !== declaredCurrency
? [
`Moedas diferentes: o plano financeiro mantém ${planCurrency}; o projecto declara ${declaredCurrency}. Confira os dados complementares antes de comparar montantes. Não foi feita conversão.`,
]
: []),
`Tabelas incluídas: ${ordered.length} de 11. Os valores provêm do mesmo plano e dos dados complementares guardados.`,
'Projecções para avaliar o investimento; não são contas realizadas nem confirmação de financiamento. Campos em falta e indicadores indeterminados mantêm-se identificados.',
],
rows:
finance?.rows.filter((row) => summary.has(row.field)) ?? [],
tables: ordered,
},
],
};
}
export function classifyDossierAttachment(
file: Pick<File, 'name' | 'type' | 'size'>,
): DossierAttachmentKind {