feat(qa): consolidate eleven financial report tables pending private visual acceptance
This commit is contained in:
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user