feat(finance): project PGC-PE supplier advances by operation in QA
This commit is contained in:
@@ -1,3 +1,9 @@
|
||||
import {
|
||||
advanceEventLabels,
|
||||
buildSupplierAdvances,
|
||||
isSupplierAdvances,
|
||||
type SupplierAdvances,
|
||||
} from './supplier-advances.ts';
|
||||
import {
|
||||
buildDayTermSchedule,
|
||||
isDayTerms,
|
||||
@@ -90,6 +96,7 @@ function validCurrency(value: string): boolean {
|
||||
export type BusinessFinancialPlanInput = {
|
||||
/** Explicit opt-in. Missing keeps all historical calculations unchanged. */
|
||||
dayTerms?: DayTerms;
|
||||
supplierAdvances?: SupplierAdvances;
|
||||
economicClassification?: {
|
||||
code: string;
|
||||
revision: string;
|
||||
@@ -210,24 +217,27 @@ export function serializeBusinessPlanSnapshot(
|
||||
): string {
|
||||
const snapshot = JSON.stringify({
|
||||
version:
|
||||
plan.dayTerms !== undefined
|
||||
? 20
|
||||
: plan.startupAssetRequirements
|
||||
? 19
|
||||
: [
|
||||
'applyAnnualGrowth',
|
||||
'creditTermDays',
|
||||
'dividendsByPeriod',
|
||||
'operatingExpenseLines',
|
||||
'fundingBreakdown',
|
||||
'reportSource',
|
||||
].some(
|
||||
(key) =>
|
||||
plan[key as keyof BusinessFinancialPlanInput] !==
|
||||
undefined,
|
||||
)
|
||||
? 18
|
||||
: 17,
|
||||
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
|
||||
@@ -312,7 +322,8 @@ export function restoreBusinessPlanSnapshot(
|
||||
decoded.version !== 17 &&
|
||||
decoded.version !== 18 &&
|
||||
decoded.version !== 19 &&
|
||||
decoded.version !== 20) ||
|
||||
decoded.version !== 20 &&
|
||||
decoded.version !== 21) ||
|
||||
!decoded.plan ||
|
||||
typeof decoded.plan !== 'object'
|
||||
)
|
||||
@@ -320,7 +331,13 @@ export function restoreBusinessPlanSnapshot(
|
||||
const plan = decoded.plan as Record<string, unknown>;
|
||||
if (
|
||||
plan.dayTerms !== undefined &&
|
||||
(decoded.version !== 20 || !isDayTerms(plan.dayTerms))
|
||||
(![20, 21].includes(decoded.version) || !isDayTerms(plan.dayTerms))
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
plan.supplierAdvances !== undefined &&
|
||||
(decoded.version !== 21 ||
|
||||
!isSupplierAdvances(plan.supplierAdvances))
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
@@ -455,7 +472,9 @@ export function restoreBusinessPlanSnapshot(
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
[12, 13, 14, 15, 16, 17, 20].includes(Number(decoded.version)) &&
|
||||
[12, 13, 14, 15, 16, 17, 20, 21].includes(
|
||||
Number(decoded.version),
|
||||
) &&
|
||||
(!Object.hasOwn(plan, 'inventoryPurchaseSchedule') ||
|
||||
!Object.hasOwn(plan, 'useInventoryPurchaseSchedule') ||
|
||||
typeof plan.useInventoryPurchaseSchedule !== 'boolean')
|
||||
@@ -466,7 +485,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
plan.inventoryPurchaseSchedule !== null
|
||||
) {
|
||||
if (
|
||||
![12, 13, 14, 15, 16, 17, 20].includes(
|
||||
![12, 13, 14, 15, 16, 17, 20, 21].includes(
|
||||
Number(decoded.version),
|
||||
) ||
|
||||
!Array.isArray(plan.inventoryPurchaseSchedule) ||
|
||||
@@ -491,14 +510,14 @@ export function restoreBusinessPlanSnapshot(
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
[13, 14, 15, 16, 17, 20].includes(Number(decoded.version)) &&
|
||||
[13, 14, 15, 16, 17, 20, 21].includes(Number(decoded.version)) &&
|
||||
!Object.hasOwn(plan, 'monthlyVariableCostPaymentsByPeriod')
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
plan.monthlyVariableCostPaymentsByPeriod !== undefined &&
|
||||
plan.monthlyVariableCostPaymentsByPeriod !== null &&
|
||||
(![13, 14, 15, 16, 17, 20].includes(Number(decoded.version)) ||
|
||||
(![13, 14, 15, 16, 17, 20, 21].includes(Number(decoded.version)) ||
|
||||
!Array.isArray(plan.monthlyVariableCostPaymentsByPeriod) ||
|
||||
plan.monthlyVariableCostPaymentsByPeriod.length <
|
||||
Number(plan.periods) ||
|
||||
@@ -563,7 +582,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].includes(
|
||||
[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
|
||||
Number(decoded.version),
|
||||
)
|
||||
) {
|
||||
@@ -636,7 +655,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20].includes(
|
||||
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
|
||||
Number(decoded.version),
|
||||
)
|
||||
) {
|
||||
@@ -675,7 +694,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
const schedule = plan[field];
|
||||
if (
|
||||
schedule !== undefined &&
|
||||
(![11, 12, 13, 14, 15, 16, 17, 20].includes(
|
||||
(![11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
|
||||
Number(decoded.version),
|
||||
) ||
|
||||
!Array.isArray(schedule) ||
|
||||
@@ -765,7 +784,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
const costSchedule = productData.unitVariableCostByPeriod;
|
||||
const validMoneySchedule = (values: unknown) =>
|
||||
values === undefined ||
|
||||
([10, 11, 12, 13, 14, 15, 16, 17, 20].includes(
|
||||
([10, 11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
|
||||
Number(decoded.version),
|
||||
) &&
|
||||
Array.isArray(values) &&
|
||||
@@ -774,7 +793,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
values.every((value) => typeof value === 'string'));
|
||||
return (
|
||||
(schedule !== undefined &&
|
||||
(![9, 10, 11, 12, 13, 14, 15, 16, 17, 20].includes(
|
||||
(![9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
|
||||
Number(decoded.version),
|
||||
) ||
|
||||
!Array.isArray(schedule) ||
|
||||
@@ -813,7 +832,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
entry.paymentLagMonths < 0 ||
|
||||
entry.paymentLagMonths > 12)) ||
|
||||
(entry.paymentInstallments !== undefined &&
|
||||
(![16, 17, 20].includes(
|
||||
(![16, 17, 20, 21].includes(
|
||||
Number(decoded.version),
|
||||
) ||
|
||||
!Array.isArray(
|
||||
@@ -933,7 +952,10 @@ export function restoreBusinessPlanSnapshot(
|
||||
? plan.monthlyVariableCostPaymentsByPeriod.map(String)
|
||||
: null,
|
||||
} as unknown as BusinessFinancialPlanInput;
|
||||
if (restored.dayTerms && !options.editable)
|
||||
if (
|
||||
(restored.dayTerms || restored.supplierAdvances) &&
|
||||
!options.editable
|
||||
)
|
||||
forecastBusinessPlan(restored);
|
||||
return restored;
|
||||
} catch {
|
||||
@@ -1466,40 +1488,70 @@ type ActiveDayTerms = ReturnType<typeof buildDayTermSchedule> & {
|
||||
|
||||
export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
const config = input.dayTerms;
|
||||
const advances = input.supplierAdvances;
|
||||
if (config !== undefined && !isDayTerms(config))
|
||||
throw new Error('Prazos em dias: estrutura inválida.');
|
||||
if (!config || !(config.sales || config.purchases || config.services))
|
||||
return forecastBusinessPlanBase(input);
|
||||
// First pass obtains economic recognition from the unchanged calculator. The second
|
||||
// replaces only opted-in cash schedules. Neither pass mutates stored/manual inputs.
|
||||
if (advances !== undefined && !isSupplierAdvances(advances))
|
||||
throw new Error('Adiantamentos: estrutura inválida.');
|
||||
const useAdvances = advances && (advances.purchases || advances.services);
|
||||
// A category has exactly one cash agenda. Inactive day/manual inputs remain saved.
|
||||
const activeDays = config
|
||||
? {
|
||||
...config,
|
||||
purchases: config.purchases && !advances?.purchases,
|
||||
services: config.services && !advances?.services,
|
||||
}
|
||||
: undefined;
|
||||
const useDays =
|
||||
activeDays &&
|
||||
(activeDays.sales || activeDays.purchases || activeDays.services);
|
||||
if (!useDays && !useAdvances) return forecastBusinessPlanBase(input);
|
||||
const economic = forecastBusinessPlanBase(input);
|
||||
if (!input.reportAssumptions?.startYear?.trim())
|
||||
throw new Error(
|
||||
'Prazos em dias — Ano inicial: preencha o ano do relatório.',
|
||||
);
|
||||
const day = buildDayTermSchedule(
|
||||
config,
|
||||
Number(input.reportAssumptions.startYear),
|
||||
economic.rows.length,
|
||||
{
|
||||
sales: economic.rows.map((r) => cents(r.revenue, 'Vendas')),
|
||||
purchases: economic.rows.map((r) =>
|
||||
r.inventoryReceipts === null
|
||||
? null
|
||||
: cents(r.inventoryReceipts, 'Recepções'),
|
||||
),
|
||||
services: economic.rows.map((r) =>
|
||||
cents(r.operatingExpenses, 'Serviços reconhecidos'),
|
||||
),
|
||||
},
|
||||
cents,
|
||||
);
|
||||
return forecastBusinessPlanBase(input, { ...day, config });
|
||||
const year = Number(input.reportAssumptions?.startYear);
|
||||
const recognized = {
|
||||
sales: economic.rows.map((r) => cents(r.revenue, 'Vendas')),
|
||||
purchases: economic.rows.map((r) =>
|
||||
r.inventoryReceipts === null
|
||||
? null
|
||||
: cents(r.inventoryReceipts, 'Recepções'),
|
||||
),
|
||||
services: economic.rows.map((r) =>
|
||||
cents(r.operatingExpenses, 'Serviços reconhecidos'),
|
||||
),
|
||||
};
|
||||
const day = useDays
|
||||
? {
|
||||
...buildDayTermSchedule(
|
||||
activeDays,
|
||||
year,
|
||||
economic.rows.length,
|
||||
recognized,
|
||||
cents,
|
||||
),
|
||||
config: activeDays,
|
||||
}
|
||||
: undefined;
|
||||
const advance = useAdvances
|
||||
? {
|
||||
...buildSupplierAdvances(
|
||||
advances,
|
||||
year,
|
||||
economic.rows.length,
|
||||
recognized,
|
||||
cents,
|
||||
),
|
||||
config: advances,
|
||||
}
|
||||
: undefined;
|
||||
return forecastBusinessPlanBase(input, day, advance);
|
||||
}
|
||||
|
||||
function forecastBusinessPlanBase(
|
||||
input: BusinessFinancialPlanInput,
|
||||
day?: ActiveDayTerms,
|
||||
advance?: ReturnType<typeof buildSupplierAdvances> & {
|
||||
config: SupplierAdvances;
|
||||
},
|
||||
) {
|
||||
if (input.startupAssetRequirements) {
|
||||
const needs = calculateStartupAssetRequirements(input);
|
||||
@@ -2304,13 +2356,17 @@ function forecastBusinessPlanBase(
|
||||
const rows = [];
|
||||
|
||||
for (let month = 1; month <= periods; month++) {
|
||||
const periodVariableCostPayment = day?.config.purchases
|
||||
? day.schedules.purchases[month - 1]
|
||||
: variableCostPaymentsByPeriod[month - 1];
|
||||
const periodVariableCostPayment = advance?.config.purchases
|
||||
? advance.payments.purchases[month - 1]
|
||||
: day?.config.purchases
|
||||
? day.schedules.purchases[month - 1]
|
||||
: variableCostPaymentsByPeriod[month - 1];
|
||||
const periodOperatingExpense = operatingExpenseByPeriod[month - 1];
|
||||
const periodOperatingPayment = day?.config.services
|
||||
? day.schedules.services[month - 1]
|
||||
: operatingPaymentsByPeriod[month - 1];
|
||||
const periodOperatingPayment = advance?.config.services
|
||||
? advance.payments.services[month - 1]
|
||||
: day?.config.services
|
||||
? day.schedules.services[month - 1]
|
||||
: operatingPaymentsByPeriod[month - 1];
|
||||
const periodPayrollExpense = payrollExpenseByPeriod[month - 1];
|
||||
const periodPayrollPayment = payrollPaymentsByPeriod[month - 1];
|
||||
const revenue = revenueByPeriod[month - 1];
|
||||
@@ -2504,7 +2560,10 @@ function forecastBusinessPlanBase(
|
||||
const openingPayablesPayments =
|
||||
openingPayablesInstallmentSchedule.get(month) ?? 0n;
|
||||
openingPayablesBalance -= openingPayablesPayments;
|
||||
const allCollections = totalCollections + openingReceivablesCollections;
|
||||
const allCollections =
|
||||
totalCollections +
|
||||
openingReceivablesCollections +
|
||||
(advance?.refunds[month - 1] ?? 0n);
|
||||
const totalPayments =
|
||||
periodVariableCostPayment +
|
||||
periodOperatingPayment +
|
||||
@@ -2752,15 +2811,28 @@ function forecastBusinessPlanBase(
|
||||
? null
|
||||
: salesCollectionPercent,
|
||||
totalPayments: format(totalOperatingPayments),
|
||||
supplierPaymentsOutstandingAtEnd: day?.config.purchases
|
||||
supplierPaymentsOutstandingAtEnd: advance?.config.purchases
|
||||
? format(
|
||||
day.events
|
||||
.filter((e) => e.kind === 'purchases' && e.outsideHorizon)
|
||||
.reduce((sum, e) => sum + BigInt(e.amount), 0n),
|
||||
advance.operations
|
||||
.filter((o) => o.kind === 'purchases')
|
||||
.reduce(
|
||||
(sum, o) =>
|
||||
sum +
|
||||
cents(o.monthly.at(-1)!.obligation, 'Obrigação'),
|
||||
0n,
|
||||
),
|
||||
)
|
||||
: useSupplierPaymentTerms
|
||||
? format(supplierPaymentsOutstanding)
|
||||
: null,
|
||||
: day?.config.purchases
|
||||
? format(
|
||||
day.events
|
||||
.filter(
|
||||
(e) => e.kind === 'purchases' && e.outsideHorizon,
|
||||
)
|
||||
.reduce((sum, e) => sum + BigInt(e.amount), 0n),
|
||||
)
|
||||
: useSupplierPaymentTerms
|
||||
? format(supplierPaymentsOutstanding)
|
||||
: null,
|
||||
totalProfitBeforeTax: format(totalProfitBeforeTax),
|
||||
endingCash: format(cash),
|
||||
inventoryProjection,
|
||||
@@ -3032,6 +3104,15 @@ function forecastBusinessPlanBase(
|
||||
};
|
||||
return {
|
||||
...output,
|
||||
...(advance
|
||||
? {
|
||||
supplierAdvanceLedger: {
|
||||
regime: advance.config.regime,
|
||||
monthly: advance.monthly,
|
||||
operations: advance.operations,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
presentationCurrency,
|
||||
conversion,
|
||||
...(day
|
||||
@@ -3629,6 +3710,57 @@ export function exportBusinessPlanCsv(
|
||||
]),
|
||||
);
|
||||
}
|
||||
if (result.supplierAdvanceLedger) {
|
||||
rows.push(
|
||||
[],
|
||||
[
|
||||
'Adiantamentos por operação — PGC-PE; projecções sem IVA, câmbio, perdas ou penalizações',
|
||||
],
|
||||
[
|
||||
'Operação',
|
||||
'Parcela',
|
||||
'Fornecedor',
|
||||
'Reconhecimento',
|
||||
'Factura',
|
||||
'Mês',
|
||||
'Obrigação bruta',
|
||||
'Adiantamento activo',
|
||||
'Líquido por liquidar',
|
||||
],
|
||||
...result.supplierAdvanceLedger.operations.flatMap((o) =>
|
||||
o.monthly.map((m) => [
|
||||
o.originId,
|
||||
o.parcelId,
|
||||
o.supplier,
|
||||
o.recognitionDate || 'Por confirmar',
|
||||
o.invoiceDate || 'Por confirmar',
|
||||
m.month,
|
||||
m.obligation,
|
||||
m.advance,
|
||||
m.netDue,
|
||||
]),
|
||||
),
|
||||
[],
|
||||
[
|
||||
'Operação',
|
||||
'Parcela',
|
||||
'Movimento',
|
||||
'Data',
|
||||
'Montante',
|
||||
'Horizonte',
|
||||
],
|
||||
...result.supplierAdvanceLedger.operations.flatMap((o) =>
|
||||
o.events.map((e) => [
|
||||
o.originId,
|
||||
o.parcelId,
|
||||
advanceEventLabels[e.kind],
|
||||
e.date,
|
||||
e.amount,
|
||||
e.outsideHorizon ? 'Fora do horizonte' : 'No horizonte',
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
return `\uFEFF${rows
|
||||
.map((row) => row.map(csvCell).join(','))
|
||||
.join('\r\n')}`;
|
||||
|
||||
Reference in New Issue
Block a user