feat(finance): add explicit plan regime and PGC-NIRF advance basis in QA

This commit is contained in:
2026-11-21 11:20:07 +02:00
parent 7f2f034980
commit 8867b3fdbc
21 changed files with 3516 additions and 71 deletions
+129 -37
View File
@@ -3,6 +3,7 @@ import {
buildSupplierAdvances,
isSupplierAdvances,
type SupplierAdvances,
type AccountingRegime,
} from './supplier-advances.ts';
import {
buildDayTermSchedule,
@@ -97,6 +98,7 @@ export type BusinessFinancialPlanInput = {
/** Explicit opt-in. Missing keeps all historical calculations unchanged. */
dayTerms?: DayTerms;
supplierAdvances?: SupplierAdvances;
accountingRegime?: AccountingRegime;
economicClassification?: {
code: string;
revision: string;
@@ -217,27 +219,29 @@ export function serializeBusinessPlanSnapshot(
): string {
const snapshot = JSON.stringify({
version:
plan.supplierAdvances !== undefined
? 21
: plan.dayTerms !== undefined
? 20
: plan.startupAssetRequirements
? 19
: [
'applyAnnualGrowth',
'creditTermDays',
'dividendsByPeriod',
'operatingExpenseLines',
'fundingBreakdown',
'reportSource',
].some(
(key) =>
plan[
key as keyof BusinessFinancialPlanInput
] !== undefined,
)
? 18
: 17,
plan.accountingRegime !== undefined
? 22
: plan.supplierAdvances !== undefined
? 21
: plan.dayTerms !== undefined
? 20
: plan.startupAssetRequirements
? 19
: [
'applyAnnualGrowth',
'creditTermDays',
'dividendsByPeriod',
'operatingExpenseLines',
'fundingBreakdown',
'reportSource',
].some(
(key) =>
plan[
key as keyof BusinessFinancialPlanInput
] !== undefined,
)
? 18
: 17,
plan: {
...plan,
...(plan.useSupplierPaymentTerms === true
@@ -323,7 +327,8 @@ export function restoreBusinessPlanSnapshot(
decoded.version !== 18 &&
decoded.version !== 19 &&
decoded.version !== 20 &&
decoded.version !== 21) ||
decoded.version !== 21 &&
decoded.version !== 22) ||
!decoded.plan ||
typeof decoded.plan !== 'object'
)
@@ -331,12 +336,13 @@ export function restoreBusinessPlanSnapshot(
const plan = decoded.plan as Record<string, unknown>;
if (
plan.dayTerms !== undefined &&
(![20, 21].includes(decoded.version) || !isDayTerms(plan.dayTerms))
(![20, 21, 22].includes(decoded.version) ||
!isDayTerms(plan.dayTerms))
)
return null;
if (
plan.supplierAdvances !== undefined &&
(decoded.version !== 21 ||
(![21, 22].includes(decoded.version) ||
!isSupplierAdvances(plan.supplierAdvances))
)
return null;
@@ -352,6 +358,31 @@ export function restoreBusinessPlanSnapshot(
].some((key) => plan[key] !== undefined)
)
return null;
if (
plan.accountingRegime !== undefined &&
(decoded.version !== 22 ||
typeof plan.accountingRegime !== 'string' ||
!['PGC-PE', 'PGC-NIRF'].includes(plan.accountingRegime))
)
return null;
if (
decoded.version === 22 &&
(typeof plan.accountingRegime !== 'string' ||
!['PGC-PE', 'PGC-NIRF'].includes(plan.accountingRegime))
)
return null;
const advances = plan.supplierAdvances as SupplierAdvances | undefined;
if (
advances?.regime === 'PGC-NIRF' &&
(decoded.version !== 22 || plan.accountingRegime !== 'PGC-NIRF')
)
return null;
if (
plan.accountingRegime &&
advances?.regime &&
plan.accountingRegime !== advances.regime
)
return null;
const shortText = (v: unknown) =>
typeof v === 'string' && v.length <= 160;
if (plan.startupAssetRequirements !== undefined) {
@@ -472,7 +503,7 @@ export function restoreBusinessPlanSnapshot(
)
return null;
if (
[12, 13, 14, 15, 16, 17, 20, 21].includes(
[12, 13, 14, 15, 16, 17, 20, 21, 22].includes(
Number(decoded.version),
) &&
(!Object.hasOwn(plan, 'inventoryPurchaseSchedule') ||
@@ -485,7 +516,7 @@ export function restoreBusinessPlanSnapshot(
plan.inventoryPurchaseSchedule !== null
) {
if (
![12, 13, 14, 15, 16, 17, 20, 21].includes(
![12, 13, 14, 15, 16, 17, 20, 21, 22].includes(
Number(decoded.version),
) ||
!Array.isArray(plan.inventoryPurchaseSchedule) ||
@@ -510,14 +541,18 @@ export function restoreBusinessPlanSnapshot(
)
return null;
if (
[13, 14, 15, 16, 17, 20, 21].includes(Number(decoded.version)) &&
[13, 14, 15, 16, 17, 20, 21, 22].includes(
Number(decoded.version),
) &&
!Object.hasOwn(plan, 'monthlyVariableCostPaymentsByPeriod')
)
return null;
if (
plan.monthlyVariableCostPaymentsByPeriod !== undefined &&
plan.monthlyVariableCostPaymentsByPeriod !== null &&
(![13, 14, 15, 16, 17, 20, 21].includes(Number(decoded.version)) ||
(![13, 14, 15, 16, 17, 20, 21, 22].includes(
Number(decoded.version),
) ||
!Array.isArray(plan.monthlyVariableCostPaymentsByPeriod) ||
plan.monthlyVariableCostPaymentsByPeriod.length <
Number(plan.periods) ||
@@ -582,7 +617,7 @@ export function restoreBusinessPlanSnapshot(
if (openingCollectionRate < 0n || openingCollectionRate > 100_000_000n)
return null;
if (
[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22].includes(
Number(decoded.version),
)
) {
@@ -655,7 +690,7 @@ export function restoreBusinessPlanSnapshot(
)
return null;
if (
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22].includes(
Number(decoded.version),
)
) {
@@ -694,7 +729,7 @@ export function restoreBusinessPlanSnapshot(
const schedule = plan[field];
if (
schedule !== undefined &&
(![11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
(![11, 12, 13, 14, 15, 16, 17, 20, 21, 22].includes(
Number(decoded.version),
) ||
!Array.isArray(schedule) ||
@@ -784,7 +819,7 @@ export function restoreBusinessPlanSnapshot(
const costSchedule = productData.unitVariableCostByPeriod;
const validMoneySchedule = (values: unknown) =>
values === undefined ||
([10, 11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
([10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22].includes(
Number(decoded.version),
) &&
Array.isArray(values) &&
@@ -793,9 +828,9 @@ export function restoreBusinessPlanSnapshot(
values.every((value) => typeof value === 'string'));
return (
(schedule !== undefined &&
(![9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
Number(decoded.version),
) ||
(![
9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22,
].includes(Number(decoded.version)) ||
!Array.isArray(schedule) ||
schedule.length < Number(plan.periods) ||
schedule.length > 60 ||
@@ -832,7 +867,7 @@ export function restoreBusinessPlanSnapshot(
entry.paymentLagMonths < 0 ||
entry.paymentLagMonths > 12)) ||
(entry.paymentInstallments !== undefined &&
(![16, 17, 20, 21].includes(
(![16, 17, 20, 21, 22].includes(
Number(decoded.version),
) ||
!Array.isArray(
@@ -1489,6 +1524,27 @@ type ActiveDayTerms = ReturnType<typeof buildDayTermSchedule> & {
export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
const config = input.dayTerms;
const advances = input.supplierAdvances;
if (
input.accountingRegime !== undefined &&
!['PGC-PE', 'PGC-NIRF'].includes(input.accountingRegime)
)
throw Error('Seleccione PGC-PE ou PGC-NIRF no plano.');
if (
advances?.regime === 'PGC-NIRF' &&
input.accountingRegime !== 'PGC-NIRF'
)
throw Error(
'Adiantamentos PGC-NIRF exigem identificação explícita do regime no plano.',
);
if (
input.accountingRegime &&
advances?.regime &&
input.accountingRegime !== advances.regime
)
throw Error(
'O regime do plano diverge da agenda de adiantamentos. Confirme a mudança de regime antes de recalcular.',
);
if (config !== undefined && !isDayTerms(config))
throw new Error('Prazos em dias: estrutura inválida.');
if (advances !== undefined && !isSupplierAdvances(advances))
@@ -3710,11 +3766,19 @@ export function exportBusinessPlanCsv(
]),
);
}
if (input.accountingRegime)
rows.push(
[],
[
'Regime contabilístico declarado no plano',
input.accountingRegime,
],
);
if (result.supplierAdvanceLedger) {
rows.push(
[],
[
'Adiantamentos por operação — PGC-PE; projecções sem IVA, câmbio, perdas ou penalizações',
`Adiantamentos por operação — ${result.supplierAdvanceLedger.regime}; projecções sem IVA, câmbio, perdas ou penalizações`,
],
[
'Operação',
@@ -3760,6 +3824,34 @@ export function exportBusinessPlanCsv(
]),
),
);
if (result.supplierAdvanceLedger.regime === 'PGC-NIRF')
rows.push(
[],
[
'Operação',
'Parcela',
'Acordo formal',
'Data do acordo',
'Aplicação',
'Fundamento',
'Referência',
],
...result.supplierAdvanceLedger.operations.flatMap((o) =>
o.events
.filter((e) => e.kind === 'apply')
.map((e) => [
o.originId,
o.parcelId,
o.formalAgreement?.reference ?? '',
o.formalAgreement?.date ?? '',
e.date,
e.applicationBasis?.kind === 'formal_agreement'
? 'Acordo formal'
: 'Factura',
e.applicationBasis?.reference ?? '',
]),
),
);
}
return `\uFEFF${rows
.map((row) => row.map(csvCell).join(','))
+28 -3
View File
@@ -4,7 +4,10 @@ import {
type BusinessFinancialPlanInput,
} from './business-financial-plan.ts';
import { calculateStartupAssetRequirements } from './startup-asset-requirements.ts';
import { advanceEventLabels } from './supplier-advances.ts';
import {
advanceEventLabels,
advanceDocumentLabel,
} from './supplier-advances.ts';
export type InvestmentReportTable = {
id: string;
@@ -712,6 +715,10 @@ export function buildIntegralFinancialTables(
label,
ledger.map((row) => row[key]),
);
if (plan.accountingRegime)
table('balance').notes.push(
`Regime contabilístico declarado no plano: ${plan.accountingRegime}. Tratamentos limitados ao âmbito implementado; não equivale a certificação integral do regime.`,
);
if (result.supplierAdvanceLedger) {
stocks(
'balance',
@@ -739,16 +746,34 @@ export function buildIntegralFinancialTables(
),
);
table('balance').notes.push(
'PGC-PE: adiantamentos identificados apresentados no activo, separados das obrigações brutas. Líquido por liquidar é calculado por operação/parcela, sem compensação entre operações. Devoluções não são receita; aplicações não movimentam caixa.',
`${result.supplierAdvanceLedger.regime}: adiantamentos identificados apresentados no activo, separados das obrigações brutas. Líquido por liquidar é calculado por operação/parcela, sem compensação entre operações. Devoluções não são receita; aplicações não movimentam caixa.`,
);
table('cashflow').notes.push(
'Adiantamentos, aplicações, devoluções e remanescentes são projecções discriminadas, já incluídas nos totais de caixa quando aplicável; não somar novamente. Sem automatização de IVA, câmbio, perdas, penalizações ou contratos especiais.',
...result.supplierAdvanceLedger.operations.map(
(o) =>
`${o.originId}/${o.parcelId} — ${o.supplier}: reconhecimento ${o.recognitionDate || 'por confirmar'}; factura ${o.invoiceDate || 'por confirmar'}. ${o.events.map((e) => `${advanceEventLabels[e.kind]}: ${e.date}, ${e.amount} ${plan.currency}${e.outsideHorizon ? ' (fora do horizonte)' : ''}`).join('; ')}.`,
`${o.originId}/${o.parcelId} — ${o.supplier}: reconhecimento ${o.recognitionDate || 'por confirmar'}; factura ${o.invoiceDate || 'por confirmar'}. ${o.formalAgreement ? `Acordo formal ${o.formalAgreement.reference}, ${o.formalAgreement.date}. ` : ''}${o.events.map((e) => `${advanceEventLabels[e.kind]}: ${e.date}, ${e.amount} ${plan.currency}${e.outsideHorizon ? ' (fora do horizonte)' : ''}`).join('; ')}.`,
),
);
}
if (result.supplierAdvanceLedger?.regime === 'PGC-NIRF')
table('balance').notes.push(
...result.supplierAdvanceLedger.operations.map(
(o) =>
`${o.originId}/${o.parcelId}: ${o.monthly.map((m) => `mês ${m.month}, ${advanceDocumentLabel(m.documentaryStatus ?? '')}`).join('; ')}.`,
),
);
if (result.supplierAdvanceLedger?.regime === 'PGC-NIRF')
table('cashflow').notes.push(
...result.supplierAdvanceLedger.operations.flatMap((o) =>
o.events
.filter((e) => e.applicationBasis)
.map(
(e) =>
`${o.originId}/${o.parcelId}: aplicação ${e.date}, fundamento ${e.applicationBasis!.kind === 'formal_agreement' ? 'acordo formal' : 'factura'}, referência ${e.applicationBasis!.reference}, data ${e.applicationBasis!.date}.`,
),
),
);
table('balance').rows.push([
'Existências',
...ledger.map((row) =>
+83 -6
View File
@@ -1,5 +1,6 @@
export type AdvanceKind = 'purchases' | 'services';
export type AdvanceEventKind = 'advance' | 'apply' | 'refund' | 'settle';
export type AccountingRegime = 'PGC-PE' | 'PGC-NIRF';
export type SupplierAdvanceOperation = {
originId: string;
parcelId: string;
@@ -8,6 +9,7 @@ export type SupplierAdvanceOperation = {
amount: string;
recognitionDate: string;
invoiceDate: string;
formalAgreement?: { date: string; reference: string };
ordinaryContract: boolean;
events: {
id: string;
@@ -17,7 +19,7 @@ export type SupplierAdvanceOperation = {
}[];
};
export type SupplierAdvances = {
regime: '' | 'PGC-PE';
regime: '' | AccountingRegime;
purchases: boolean;
services: boolean;
operations: SupplierAdvanceOperation[];
@@ -32,12 +34,22 @@ export const advanceEventLabels = {
refund: 'Devolução do adiantamento',
settle: 'Pagamento do remanescente',
};
export function advanceDocumentLabel(status: string) {
const labels: Record<string, string> = {
not_recognized: 'Ainda não reconhecido',
invoice: 'Fornecimento facturado',
formal_agreement: 'Fornecimento formalmente acordado',
pending_documentation:
'Fornecimento reconhecido, documentação por confirmar',
};
return labels[status] ?? 'Por confirmar';
}
const text = (v: unknown) => typeof v === 'string' && v.length <= 160;
export function isSupplierAdvances(v: unknown): v is SupplierAdvances {
if (!v || typeof v !== 'object') return false;
const c = v as SupplierAdvances;
return (
['', 'PGC-PE'].includes(c.regime) &&
['', 'PGC-PE', 'PGC-NIRF'].includes(c.regime) &&
typeof c.purchases === 'boolean' &&
typeof c.services === 'boolean' &&
Array.isArray(c.operations) &&
@@ -47,6 +59,10 @@ export function isSupplierAdvances(v: unknown): v is SupplierAdvances {
o &&
['purchases', 'services'].includes(o.kind) &&
typeof o.ordinaryContract === 'boolean' &&
(o.formalAgreement === undefined ||
(o.formalAgreement &&
text(o.formalAgreement.date) &&
text(o.formalAgreement.reference))) &&
[
'originId',
'parcelId',
@@ -89,9 +105,9 @@ export function buildSupplierAdvances(
) {
if (!isSupplierAdvances(config))
throw Error('Adiantamentos: estrutura inválida.');
if (config.regime !== 'PGC-PE')
if (!['PGC-PE', 'PGC-NIRF'].includes(config.regime))
throw Error(
'Adiantamentos: seleccione explicitamente PGC-PE. Outros regimes não estão automatizados.',
'Adiantamentos: seleccione explicitamente PGC-PE ou PGC-NIRF.',
);
if (!Number.isSafeInteger(year) || year < 1900 || year > 9993)
throw Error(
@@ -145,6 +161,12 @@ export function buildSupplierAdvances(
o.supplier.trim(),
o.recognitionDate,
o.invoiceDate,
...(config.regime === 'PGC-NIRF'
? [
o.formalAgreement?.date ?? '',
o.formalAgreement?.reference.trim() ?? '',
]
: []),
]);
if (origins.has(originKey) && origins.get(originKey) !== identity)
fail(
@@ -158,6 +180,18 @@ export function buildSupplierAdvances(
? date(o.recognitionDate)
: null;
const invoice = o.invoiceDate ? date(o.invoiceDate) : null;
const agreement =
config.regime === 'PGC-NIRF' && o.formalAgreement
? date(o.formalAgreement.date)
: null;
if (
config.regime === 'PGC-NIRF' &&
o.formalAgreement &&
(!agreement || !o.formalAgreement.reference.trim())
)
fail(
'acordo formal exige data válida e referência identificada da mesma operação; não basta orçamento ou encomenda.',
);
if (o.recognitionDate && !recognition)
fail('data de reconhecimento inválida.');
if (o.invoiceDate && !invoice) fail('data de factura inválida.');
@@ -204,6 +238,11 @@ export function buildSupplierAdvances(
advance: string;
obligation: string;
netDue: string;
applicationBasis?: {
kind: 'invoice' | 'formal_agreement';
date: string;
reference: string;
};
}[] = [];
const process = (e: (typeof events)[number]) => {
if (!isRecognized && recognition && recognition <= e.when) {
@@ -212,6 +251,13 @@ export function buildSupplierAdvances(
}
const m = index(e.when);
const inside = m >= 0 && m < periods;
let applicationBasis:
| {
kind: 'invoice' | 'formal_agreement';
date: string;
reference: string;
}
| undefined;
if (e.kind === 'advance') {
if (isRecognized)
fail(
@@ -223,10 +269,26 @@ export function buildSupplierAdvances(
paid[m] += e.value;
}
} else if (e.kind === 'apply') {
if (!isRecognized || !invoice || invoice > e.when)
const hasInvoice = !!invoice && invoice <= e.when;
const hasAgreement = !!agreement && agreement <= e.when;
if (!isRecognized || (!hasInvoice && !hasAgreement))
fail(
'aplicação exige reconhecimento e factura correspondente, sem antecipar datas.',
config.regime === 'PGC-NIRF'
? 'aplicação exige reconhecimento e factura ou acordo formal correspondente já datado e identificado, sem antecipar datas.'
: 'aplicação exige reconhecimento e factura correspondente, sem antecipar datas.',
);
if (config.regime === 'PGC-NIRF')
applicationBasis = hasInvoice
? {
kind: 'invoice',
date: o.invoiceDate,
reference: o.originId + '/' + o.parcelId,
}
: {
kind: 'formal_agreement',
date: o.formalAgreement!.date,
reference: o.formalAgreement!.reference,
};
if (e.value > advance || e.value > obligation)
fail(
'aplicação excede o saldo da mesma parcela ou a obrigação reconhecida.',
@@ -269,6 +331,7 @@ export function buildSupplierAdvances(
netDue: money(
obligation > advance ? obligation - advance : 0n,
),
...(applicationBasis ? { applicationBasis } : {}),
});
};
const monthly = [];
@@ -293,6 +356,17 @@ export function buildSupplierAdvances(
obligation: money(obligation),
netDue: money(netDue),
recognized: isRecognized,
...(config.regime === 'PGC-NIRF'
? {
documentaryStatus: !isRecognized
? 'not_recognized'
: invoice && invoice < boundary
? 'invoice'
: agreement && agreement < boundary
? 'formal_agreement'
: 'pending_documentation',
}
: {}),
});
}
// Validate future events as well; they never leak into the last month of cash.
@@ -305,6 +379,9 @@ export function buildSupplierAdvances(
amount: money(amount),
recognitionDate: o.recognitionDate,
invoiceDate: o.invoiceDate,
...(config.regime === 'PGC-NIRF' && o.formalAgreement
? { formalAgreement: o.formalAgreement }
: {}),
recognitionOutsideHorizon: !recognition || recognition >= end,
monthly,
events: audit,