feat: implement F22 period financing and asset agendas in isolated QA
This commit is contained in:
@@ -10,6 +10,11 @@ import {
|
||||
isDayTerms,
|
||||
type DayTerms,
|
||||
} from './financial-day-terms.ts';
|
||||
import {
|
||||
buildPeriodInvestments,
|
||||
isPeriodInvestments,
|
||||
type PeriodInvestments,
|
||||
} from './period-investments.ts';
|
||||
import { csvCell } from './csv.js';
|
||||
import { calculateStartupAssetRequirements } from './startup-asset-requirements.ts';
|
||||
|
||||
@@ -95,6 +100,7 @@ function validCurrency(value: string): boolean {
|
||||
}
|
||||
|
||||
export type BusinessFinancialPlanInput = {
|
||||
periodInvestments?: PeriodInvestments;
|
||||
/** Explicit opt-in. Missing keeps all historical calculations unchanged. */
|
||||
dayTerms?: DayTerms;
|
||||
supplierAdvances?: SupplierAdvances;
|
||||
@@ -219,29 +225,31 @@ export function serializeBusinessPlanSnapshot(
|
||||
): string {
|
||||
const snapshot = JSON.stringify({
|
||||
version:
|
||||
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.periodInvestments !== undefined
|
||||
? 23
|
||||
: 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
|
||||
@@ -328,21 +336,30 @@ export function restoreBusinessPlanSnapshot(
|
||||
decoded.version !== 19 &&
|
||||
decoded.version !== 20 &&
|
||||
decoded.version !== 21 &&
|
||||
decoded.version !== 22) ||
|
||||
decoded.version !== 22 &&
|
||||
decoded.version !== 23) ||
|
||||
!decoded.plan ||
|
||||
typeof decoded.plan !== 'object'
|
||||
)
|
||||
return null;
|
||||
const plan = decoded.plan as Record<string, unknown>;
|
||||
if (decoded.version === 23 && plan.periodInvestments === undefined)
|
||||
return null;
|
||||
if (
|
||||
plan.periodInvestments !== undefined &&
|
||||
(decoded.version !== 23 ||
|
||||
!isPeriodInvestments(plan.periodInvestments))
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
plan.dayTerms !== undefined &&
|
||||
(![20, 21, 22].includes(decoded.version) ||
|
||||
(![20, 21, 22, 23].includes(decoded.version) ||
|
||||
!isDayTerms(plan.dayTerms))
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
plan.supplierAdvances !== undefined &&
|
||||
(![21, 22].includes(decoded.version) ||
|
||||
(![21, 22, 23].includes(decoded.version) ||
|
||||
!isSupplierAdvances(plan.supplierAdvances))
|
||||
)
|
||||
return null;
|
||||
@@ -360,7 +377,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
return null;
|
||||
if (
|
||||
plan.accountingRegime !== undefined &&
|
||||
(decoded.version !== 22 ||
|
||||
(![22, 23].includes(decoded.version!) ||
|
||||
typeof plan.accountingRegime !== 'string' ||
|
||||
!['PGC-PE', 'PGC-NIRF'].includes(plan.accountingRegime))
|
||||
)
|
||||
@@ -374,7 +391,8 @@ export function restoreBusinessPlanSnapshot(
|
||||
const advances = plan.supplierAdvances as SupplierAdvances | undefined;
|
||||
if (
|
||||
advances?.regime === 'PGC-NIRF' &&
|
||||
(decoded.version !== 22 || plan.accountingRegime !== 'PGC-NIRF')
|
||||
(![22, 23].includes(decoded.version!) ||
|
||||
plan.accountingRegime !== 'PGC-NIRF')
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
@@ -503,7 +521,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
[12, 13, 14, 15, 16, 17, 20, 21, 22].includes(
|
||||
[12, 13, 14, 15, 16, 17, 20, 21, 22, 23].includes(
|
||||
Number(decoded.version),
|
||||
) &&
|
||||
(!Object.hasOwn(plan, 'inventoryPurchaseSchedule') ||
|
||||
@@ -516,7 +534,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
plan.inventoryPurchaseSchedule !== null
|
||||
) {
|
||||
if (
|
||||
![12, 13, 14, 15, 16, 17, 20, 21, 22].includes(
|
||||
![12, 13, 14, 15, 16, 17, 20, 21, 22, 23].includes(
|
||||
Number(decoded.version),
|
||||
) ||
|
||||
!Array.isArray(plan.inventoryPurchaseSchedule) ||
|
||||
@@ -541,7 +559,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
[13, 14, 15, 16, 17, 20, 21, 22].includes(
|
||||
[13, 14, 15, 16, 17, 20, 21, 22, 23].includes(
|
||||
Number(decoded.version),
|
||||
) &&
|
||||
!Object.hasOwn(plan, 'monthlyVariableCostPaymentsByPeriod')
|
||||
@@ -550,7 +568,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
if (
|
||||
plan.monthlyVariableCostPaymentsByPeriod !== undefined &&
|
||||
plan.monthlyVariableCostPaymentsByPeriod !== null &&
|
||||
(![13, 14, 15, 16, 17, 20, 21, 22].includes(
|
||||
(![13, 14, 15, 16, 17, 20, 21, 22, 23].includes(
|
||||
Number(decoded.version),
|
||||
) ||
|
||||
!Array.isArray(plan.monthlyVariableCostPaymentsByPeriod) ||
|
||||
@@ -617,7 +635,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, 22].includes(
|
||||
[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23].includes(
|
||||
Number(decoded.version),
|
||||
)
|
||||
) {
|
||||
@@ -690,7 +708,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22].includes(
|
||||
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23].includes(
|
||||
Number(decoded.version),
|
||||
)
|
||||
) {
|
||||
@@ -729,7 +747,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
const schedule = plan[field];
|
||||
if (
|
||||
schedule !== undefined &&
|
||||
(![11, 12, 13, 14, 15, 16, 17, 20, 21, 22].includes(
|
||||
(![11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23].includes(
|
||||
Number(decoded.version),
|
||||
) ||
|
||||
!Array.isArray(schedule) ||
|
||||
@@ -819,7 +837,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
const costSchedule = productData.unitVariableCostByPeriod;
|
||||
const validMoneySchedule = (values: unknown) =>
|
||||
values === undefined ||
|
||||
([10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22].includes(
|
||||
([10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23].includes(
|
||||
Number(decoded.version),
|
||||
) &&
|
||||
Array.isArray(values) &&
|
||||
@@ -867,7 +885,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
entry.paymentLagMonths < 0 ||
|
||||
entry.paymentLagMonths > 12)) ||
|
||||
(entry.paymentInstallments !== undefined &&
|
||||
(![16, 17, 20, 21, 22].includes(
|
||||
(![16, 17, 20, 21, 22, 23].includes(
|
||||
Number(decoded.version),
|
||||
) ||
|
||||
!Array.isArray(
|
||||
@@ -988,7 +1006,9 @@ export function restoreBusinessPlanSnapshot(
|
||||
: null,
|
||||
} as unknown as BusinessFinancialPlanInput;
|
||||
if (
|
||||
(restored.dayTerms || restored.supplierAdvances) &&
|
||||
(restored.dayTerms ||
|
||||
restored.supplierAdvances ||
|
||||
restored.periodInvestments) &&
|
||||
!options.editable
|
||||
)
|
||||
forecastBusinessPlan(restored);
|
||||
@@ -1549,6 +1569,20 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
throw new Error('Prazos em dias: estrutura inválida.');
|
||||
if (advances !== undefined && !isSupplierAdvances(advances))
|
||||
throw new Error('Adiantamentos: estrutura inválida.');
|
||||
if (
|
||||
input.periodInvestments !== undefined &&
|
||||
!isPeriodInvestments(input.periodInvestments)
|
||||
)
|
||||
throw Error('Movimentos por período: estrutura inválida.');
|
||||
const movements = input.periodInvestments?.enabled
|
||||
? buildPeriodInvestments(
|
||||
input.periodInvestments,
|
||||
input.accountingRegime,
|
||||
Number(input.reportAssumptions?.startYear),
|
||||
input.periods ?? 12,
|
||||
cents,
|
||||
)
|
||||
: undefined;
|
||||
const useAdvances = advances && (advances.purchases || advances.services);
|
||||
// A category has exactly one cash agenda. Inactive day/manual inputs remain saved.
|
||||
const activeDays = config
|
||||
@@ -1561,7 +1595,8 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
const useDays =
|
||||
activeDays &&
|
||||
(activeDays.sales || activeDays.purchases || activeDays.services);
|
||||
if (!useDays && !useAdvances) return forecastBusinessPlanBase(input);
|
||||
if (!useDays && !useAdvances)
|
||||
return forecastBusinessPlanBase(input, undefined, undefined, movements);
|
||||
const economic = forecastBusinessPlanBase(input);
|
||||
const year = Number(input.reportAssumptions?.startYear);
|
||||
const recognized = {
|
||||
@@ -1599,7 +1634,7 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
config: advances,
|
||||
}
|
||||
: undefined;
|
||||
return forecastBusinessPlanBase(input, day, advance);
|
||||
return forecastBusinessPlanBase(input, day, advance, movements);
|
||||
}
|
||||
|
||||
function forecastBusinessPlanBase(
|
||||
@@ -1608,6 +1643,7 @@ function forecastBusinessPlanBase(
|
||||
advance?: ReturnType<typeof buildSupplierAdvances> & {
|
||||
config: SupplierAdvances;
|
||||
},
|
||||
movements?: ReturnType<typeof buildPeriodInvestments>,
|
||||
) {
|
||||
if (input.startupAssetRequirements) {
|
||||
const needs = calculateStartupAssetRequirements(input);
|
||||
@@ -2526,7 +2562,17 @@ function forecastBusinessPlanBase(
|
||||
totalInventoryShortfall += inventoryShortfall;
|
||||
}
|
||||
}
|
||||
const depreciation =
|
||||
const movement = movements?.monthly[month - 1];
|
||||
const periodInterestExpense =
|
||||
interestExpense +
|
||||
cents(movement?.interestExpense ?? '0', 'Novos juros reconhecidos');
|
||||
const periodInterestPayment =
|
||||
interestPayment +
|
||||
cents(movement?.interestPaid ?? '0', 'Novos juros pagos');
|
||||
const periodPrincipal =
|
||||
principalRepayment +
|
||||
cents(movement?.principal ?? '0', 'Novo principal reembolsado');
|
||||
const legacyDepreciation =
|
||||
month < input.depreciationLifeMonths
|
||||
? monthlyDepreciation
|
||||
: month === input.depreciationLifeMonths
|
||||
@@ -2534,13 +2580,19 @@ function forecastBusinessPlanBase(
|
||||
monthlyDepreciation *
|
||||
BigInt(input.depreciationLifeMonths - 1)
|
||||
: 0n;
|
||||
const depreciation =
|
||||
legacyDepreciation +
|
||||
cents(
|
||||
movement?.depreciation ?? '0',
|
||||
'Depreciação dos novos activos',
|
||||
);
|
||||
const operatingResult =
|
||||
revenue -
|
||||
costOfSales -
|
||||
periodOperatingExpense -
|
||||
periodPayrollExpense -
|
||||
depreciation;
|
||||
const profitBeforeTax = operatingResult - interestExpense;
|
||||
const profitBeforeTax = operatingResult - periodInterestExpense;
|
||||
let salesCollections: bigint | null = null;
|
||||
let salesScheduledCollections: bigint | null = null;
|
||||
let salesRecoveryCollections: bigint | null = null;
|
||||
@@ -2624,11 +2676,15 @@ function forecastBusinessPlanBase(
|
||||
periodVariableCostPayment +
|
||||
periodOperatingPayment +
|
||||
periodPayrollPayment +
|
||||
interestPayment +
|
||||
principalRepayment +
|
||||
periodInterestPayment +
|
||||
periodPrincipal +
|
||||
openingPayablesPayments +
|
||||
dividends[month - 1];
|
||||
const netCashFlow = allCollections - totalPayments;
|
||||
dividends[month - 1] +
|
||||
cents(movement?.acquisitions ?? '0', 'Aquisições posteriores');
|
||||
const netCashFlow =
|
||||
allCollections +
|
||||
cents(movement?.borrowings ?? '0', 'Novos desembolsos') -
|
||||
totalPayments;
|
||||
cash += netCashFlow;
|
||||
totalProfitBeforeTax += profitBeforeTax;
|
||||
totalCashCollections += allCollections;
|
||||
@@ -2685,17 +2741,27 @@ function forecastBusinessPlanBase(
|
||||
operatingExpenses: format(periodOperatingExpense),
|
||||
payrollExpense: format(periodPayrollExpense),
|
||||
depreciation: format(depreciation),
|
||||
interestExpense: format(interestExpense),
|
||||
interestExpense: format(periodInterestExpense),
|
||||
operatingResult: format(operatingResult),
|
||||
profitBeforeTax: format(profitBeforeTax),
|
||||
variableCostPayments: format(periodVariableCostPayment),
|
||||
operatingPayments: format(periodOperatingPayment),
|
||||
payrollPayments: format(periodPayrollPayment),
|
||||
interestPayment: format(interestPayment),
|
||||
principalRepayment: format(principalRepayment),
|
||||
interestPayment: format(periodInterestPayment),
|
||||
principalRepayment: format(periodPrincipal),
|
||||
dividends: format(dividends[month - 1]),
|
||||
netCashFlow: format(netCashFlow),
|
||||
closingCash: format(cash),
|
||||
...(movement
|
||||
? {
|
||||
newBorrowings: movement.borrowings,
|
||||
assetAcquisitions: movement.acquisitions,
|
||||
newPrincipalRepayment: movement.principal,
|
||||
newInterestExpense: movement.interestExpense,
|
||||
newInterestPayment: movement.interestPaid,
|
||||
newDepreciation: movement.depreciation,
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3160,6 +3226,7 @@ function forecastBusinessPlanBase(
|
||||
};
|
||||
return {
|
||||
...output,
|
||||
...(movements ? { periodInvestmentLedger: movements } : {}),
|
||||
...(advance
|
||||
? {
|
||||
supplierAdvanceLedger: {
|
||||
@@ -3734,6 +3801,56 @@ export function exportBusinessPlanCsv(
|
||||
'Estimativa sem aconselhamento fiscal, parâmetros legais, sazonalidade, inflação ou validação contabilística. Moeda original preservada.',
|
||||
],
|
||||
];
|
||||
if (result.periodInvestmentLedger) {
|
||||
rows.push(
|
||||
[],
|
||||
['Novos movimentos — regime', result.periodInvestmentLedger.regime],
|
||||
[
|
||||
'Financiamento',
|
||||
'Tipo',
|
||||
'Mês',
|
||||
'Desembolso',
|
||||
'Principal',
|
||||
'Juros reconhecidos',
|
||||
'Juros pagos',
|
||||
'Saldo de capital',
|
||||
],
|
||||
...result.periodInvestmentLedger.financings.flatMap((f) =>
|
||||
f.monthly.map((r) => [
|
||||
f.id,
|
||||
f.kind,
|
||||
r.month,
|
||||
r.borrowings,
|
||||
r.principal,
|
||||
r.interestExpense,
|
||||
r.interestPaid,
|
||||
r.balance,
|
||||
]),
|
||||
),
|
||||
[
|
||||
'Activo',
|
||||
'Mês',
|
||||
'Aquisição',
|
||||
'Depreciação',
|
||||
'Depreciação acumulada',
|
||||
'Valor líquido',
|
||||
],
|
||||
...result.periodInvestmentLedger.assets.flatMap((a) =>
|
||||
a.monthly.map((r) => [
|
||||
a.id,
|
||||
r.month,
|
||||
r.acquisition,
|
||||
r.depreciation,
|
||||
r.accumulated,
|
||||
r.net,
|
||||
]),
|
||||
),
|
||||
[
|
||||
'Rastreabilidade dos movimentos por período',
|
||||
JSON.stringify(result.periodInvestmentLedger),
|
||||
],
|
||||
);
|
||||
}
|
||||
if (result.dayTermEvents) {
|
||||
rows.push(
|
||||
[],
|
||||
|
||||
Reference in New Issue
Block a user