feat(finance): validate opt-in day terms without supplier advances

This commit is contained in:
2026-11-21 10:21:15 +02:00
parent be7196d246
commit 1f44a63caf
23 changed files with 1268 additions and 46 deletions
@@ -0,0 +1,364 @@
import {
forecastBusinessPlan,
type BusinessFinancialPlanInput,
} from '@/lib/business-financial-plan';
import {
dayTermLabels,
type DayTermKind,
type DayTermOperation,
type DayTerms,
} from '@/lib/financial-day-terms';
const kinds = Object.keys(dayTermLabels) as DayTermKind[];
const empty = (): DayTerms => ({
sales: false,
purchases: false,
services: false,
operations: [],
});
export function FinancialDayTerms({
plan,
onChange,
}: {
plan: BusinessFinancialPlanInput;
onChange: (plan: BusinessFinancialPlanInput) => void;
}) {
const config = plan.dayTerms ?? empty();
const save = (next: DayTerms) => onChange({ ...plan, dayTerms: next });
const update = (index: number, patch: Partial<DayTermOperation>) =>
save({
...config,
operations: config.operations.map((o, i) =>
i === index ? { ...o, ...patch } : o,
),
});
let economic: ReturnType<typeof forecastBusinessPlan> | undefined;
let calculated: ReturnType<typeof forecastBusinessPlan> | undefined;
try {
economic = forecastBusinessPlan({ ...plan, dayTerms: undefined });
} catch {
/* Existing diagnostics remain in the report. */
}
try {
calculated = forecastBusinessPlan(plan);
} catch {
/* One existing report diagnostic, no duplicate here. */
}
const prepare = (kind: DayTermKind) => {
if (
!economic ||
config[kind] ||
config.operations.some((o) => o.kind === kind)
)
return;
const operations: DayTermOperation[] = [];
for (const row of economic.rows) {
const amount =
kind === 'sales'
? row.revenue
: kind === 'purchases'
? row.inventoryReceipts
: row.operatingExpenses;
if (amount === null || Number(amount) === 0) continue;
operations.push({
kind,
month: row.month,
amount,
originId: `${kind}-${row.month}`,
parcelId: '1',
recognitionBasis: 'monthly',
recognitionDate: '',
originBasis: 'recognition',
originDate: '',
termDays: '',
});
}
save({ ...config, operations: [...config.operations, ...operations] });
};
return (
<details className="my-3 min-w-0 space-y-3 rounded border p-3">
<summary className="font-semibold">
Prazos em dias — operações sem adiantamentos
</summary>
<p>
Adesão opcional por agenda. A agenda em dias substitui
integralmente a agenda de caixa correspondente, incluindo
cobranças mensais e recuperações de vendas do período. Os
valores manuais correspondentes ficam guardados, inactivos;
outras receitas explicitamente classificadas mantêm-se activas.
Os saldos de abertura mantêm as agendas próprias. Para misturar
operações datadas e coortes, distribua o total reconhecido entre
parcelas sem repetir montantes.
</p>
<p>
Mercadorias: só após recepção reconhecida. Serviços adquiridos:
este modo abrange a totalidade das despesas operacionais
declaradas; use-o apenas se todas corresponderem a serviços
elegíveis. Não inclui salários, impostos, juros, empréstimos ou
novos activos. Antecipações e datas insuficientes bloqueiam o
cálculo automático, sem conversão para pagamentos normais.
</p>
<p>
Sem data individual, escolha explicitamente «Último dia do mês
(aproximação)». O vencimento também será aproximado. A origem
dos pagamentos é o evento contratual indicado; não se presume
que factura e recepção coincidam. O prazo em dias deste editor é
independente do campo histórico usado nos avisos de crédito.
</p>
<p>
Ano inicial:{' '}
{plan.reportAssumptions?.startYear ||
'preencha o ano no relatório financeiro integral'}
. Horizonte: {plan.periods} meses. Os vencimentos posteriores
ficam identificados fora do horizonte.
</p>
{kinds.map((kind) => (
<fieldset
key={kind}
className="min-w-0 space-y-2 rounded border p-3"
>
<legend className="font-medium">
{dayTermLabels[kind]}
</legend>
<label className="grid gap-1">
Modo de {dayTermLabels[kind]}
<select
className="w-full rounded border p-2"
value={config[kind] ? 'days' : 'manual'}
onChange={(e) => {
if (
e.target.value === 'days' &&
!window.confirm(
`Activar prazos em dias para ${dayTermLabels[kind]}? A agenda em dias substitui toda a agenda de caixa desta categoria. Os valores anteriores ficam guardados e não serão somados. Confira primeiro as parcelas e as datas.`,
)
)
return;
save({
...config,
[kind]: e.target.value === 'days',
});
}}
>
<option value="manual">
Agenda anterior/manual preservada
</option>
<option value="days">
Prazos em dias (adesão explícita)
</option>
</select>
</label>
<button
type="button"
className="rounded border px-3 py-2"
disabled={
!economic ||
config[kind] ||
config.operations.some((o) => o.kind === kind)
}
onClick={() => prepare(kind)}
>
Preparar coortes mensais de {dayTermLabels[kind]}
</button>
<p className="text-sm">
Preparar coortes não activa o modo. Revise os valores,
indique o prazo de cada parcela e só depois escolha o
modo em dias.
</p>
{config.operations.map((o, index) =>
o.kind !== kind ? null : (
<div
key={index}
className="grid min-w-0 gap-2 rounded border p-3 sm:grid-cols-2 lg:grid-cols-3"
aria-label={`Parcela ${index + 1} de ${dayTermLabels[kind]}`}
>
{(
[
['Origem', 'originId'],
['Parcela', 'parcelId'],
['Montante', 'amount'],
['Prazo (dias)', 'termDays'],
] as const
).map(([label, key]) => (
<label
key={key}
className="grid min-w-0 gap-1"
>
{label}
<input
className="w-full min-w-0 rounded border p-2"
value={o[key]}
onChange={(e) =>
update(index, {
[key]: e.target.value,
})
}
/>
</label>
))}
<label className="grid gap-1">
Mês económico
<input
className="w-full min-w-0 rounded border p-2"
type="number"
min="1"
max={plan.periods}
value={o.month}
onChange={(e) =>
update(index, {
month: Number(e.target.value),
})
}
/>
</label>
<label className="grid gap-1">
Reconhecimento
<select
className="w-full min-w-0 rounded border p-2"
value={o.recognitionBasis}
onChange={(e) =>
update(index, {
recognitionBasis: e.target
.value as DayTermOperation['recognitionBasis'],
})
}
>
<option value="unknown">
Data por confirmar (excluída)
</option>
<option value="monthly">
Último dia do mês (aproximação)
</option>
<option value="date">
Data individual
</option>
</select>
</label>
{o.recognitionBasis === 'date' && (
<label className="grid gap-1">
Data de reconhecimento
<input
className="w-full min-w-0 rounded border p-2"
type="date"
value={o.recognitionDate}
onChange={(e) =>
update(index, {
recognitionDate:
e.target.value,
})
}
/>
</label>
)}
<label className="grid gap-1">
Origem do prazo
<select
className="w-full min-w-0 rounded border p-2"
value={o.originBasis}
onChange={(e) =>
update(index, {
originBasis: e.target
.value as DayTermOperation['originBasis'],
})
}
>
<option value="unknown">
Evento por confirmar (excluído)
</option>
<option value="recognition">
Na data do reconhecimento
</option>
<option value="date">
Data do evento contratual
</option>
</select>
</label>
{o.originBasis === 'date' && (
<label className="grid gap-1">
Data de origem do prazo
<input
className="w-full min-w-0 rounded border p-2"
type="date"
value={o.originDate}
onChange={(e) =>
update(index, {
originDate: e.target.value,
})
}
/>
</label>
)}
<button
type="button"
className="rounded border px-3 py-2"
onClick={() =>
save({
...config,
operations:
config.operations.filter(
(_, i) => i !== index,
),
})
}
>
Remover parcela {index + 1}
</button>
</div>
),
)}
<button
type="button"
className="rounded border px-3 py-2"
disabled={config.operations.length >= 240}
onClick={() =>
save({
...config,
operations: [
...config.operations,
{
kind,
originId: '',
parcelId: '',
month: 1,
amount: '',
termDays: '',
recognitionBasis: 'unknown',
recognitionDate: '',
originBasis: 'unknown',
originDate: '',
},
],
})
}
>
Adicionar parcela de {dayTermLabels[kind]}
</button>
</fieldset>
))}
{calculated?.dayTermEvents && (
<section aria-label="Vencimentos em dias" className="space-y-2">
<h4 className="font-semibold">Vencimentos previstos</h4>
{calculated.dayTermEvents.map((e) => (
<p
key={JSON.stringify([
e.kind,
e.originId,
e.parcelId,
])}
>
{dayTermLabels[e.kind]} — {e.originId}/{e.parcelId}:
reconhecimento {e.recognition}; origem {e.origin};
vencimento {e.due}; {e.amount} {plan.currency}.{' '}
{e.approximate
? 'Aproximação mensal explícita.'
: 'Datas individuais.'}{' '}
{e.outsideHorizon
? 'Fora do horizonte; não incluído na caixa do plano.'
: `Caixa no mês ${e.dueMonth}.`}
</p>
))}
</section>
)}
</details>
);
}
@@ -26,6 +26,7 @@ import { MarketAnalysisPlan } from '@/components/market-analysis-plan';
import { FinancialRatiosPlan } from '@/components/financial-ratios-plan';
import { PlanEconomicClassification } from '@/components/plan-economic-classification';
import { FinancialPlanDetails } from '@/components/financial-plan-details';
import { FinancialDayTerms } from '@/components/financial-day-terms';
import { StartupAssetRequirements } from '@/components/startup-asset-requirements';
import {
forecastErrorShownInReport,
@@ -948,6 +949,7 @@ export function SimulationBusinessPlan({
)}
<PlanEconomicClassification plan={plan} onChange={savePlan} />
<FinancialPlanDetails plan={plan} onChange={savePlan} />
<FinancialDayTerms plan={plan} onChange={savePlan} />
<StartupAssetRequirements
plan={plan}
onChange={savePlan}
+179 -45
View File
@@ -1,3 +1,8 @@
import {
buildDayTermSchedule,
isDayTerms,
type DayTerms,
} from './financial-day-terms.ts';
import { csvCell } from './csv.js';
import { calculateStartupAssetRequirements } from './startup-asset-requirements.ts';
@@ -83,6 +88,8 @@ function validCurrency(value: string): boolean {
}
export type BusinessFinancialPlanInput = {
/** Explicit opt-in. Missing keeps all historical calculations unchanged. */
dayTerms?: DayTerms;
economicClassification?: {
code: string;
revision: string;
@@ -202,22 +209,25 @@ export function serializeBusinessPlanSnapshot(
plan: BusinessFinancialPlanInput,
): string {
const snapshot = JSON.stringify({
version: plan.startupAssetRequirements
? 19
: [
'applyAnnualGrowth',
'creditTermDays',
'dividendsByPeriod',
'operatingExpenseLines',
'fundingBreakdown',
'reportSource',
].some(
(key) =>
plan[key as keyof BusinessFinancialPlanInput] !==
undefined,
)
? 18
: 17,
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: {
...plan,
...(plan.useSupplierPaymentTerms === true
@@ -301,12 +311,18 @@ export function restoreBusinessPlanSnapshot(
decoded.version !== 16 &&
decoded.version !== 17 &&
decoded.version !== 18 &&
decoded.version !== 19) ||
decoded.version !== 19 &&
decoded.version !== 20) ||
!decoded.plan ||
typeof decoded.plan !== 'object'
)
return null;
const plan = decoded.plan as Record<string, unknown>;
if (
plan.dayTerms !== undefined &&
(decoded.version !== 20 || !isDayTerms(plan.dayTerms))
)
return null;
if (
decoded.version < 18 &&
[
@@ -439,7 +455,7 @@ export function restoreBusinessPlanSnapshot(
)
return null;
if (
[12, 13, 14, 15, 16, 17].includes(Number(decoded.version)) &&
[12, 13, 14, 15, 16, 17, 20].includes(Number(decoded.version)) &&
(!Object.hasOwn(plan, 'inventoryPurchaseSchedule') ||
!Object.hasOwn(plan, 'useInventoryPurchaseSchedule') ||
typeof plan.useInventoryPurchaseSchedule !== 'boolean')
@@ -450,7 +466,9 @@ export function restoreBusinessPlanSnapshot(
plan.inventoryPurchaseSchedule !== null
) {
if (
![12, 13, 14, 15, 16, 17].includes(Number(decoded.version)) ||
![12, 13, 14, 15, 16, 17, 20].includes(
Number(decoded.version),
) ||
!Array.isArray(plan.inventoryPurchaseSchedule) ||
plan.inventoryPurchaseSchedule.length < Number(plan.periods) ||
plan.inventoryPurchaseSchedule.length > 60 ||
@@ -473,14 +491,14 @@ export function restoreBusinessPlanSnapshot(
)
return null;
if (
[13, 14, 15, 16, 17].includes(Number(decoded.version)) &&
[13, 14, 15, 16, 17, 20].includes(Number(decoded.version)) &&
!Object.hasOwn(plan, 'monthlyVariableCostPaymentsByPeriod')
)
return null;
if (
plan.monthlyVariableCostPaymentsByPeriod !== undefined &&
plan.monthlyVariableCostPaymentsByPeriod !== null &&
(![13, 14, 15, 16, 17].includes(Number(decoded.version)) ||
(![13, 14, 15, 16, 17, 20].includes(Number(decoded.version)) ||
!Array.isArray(plan.monthlyVariableCostPaymentsByPeriod) ||
plan.monthlyVariableCostPaymentsByPeriod.length <
Number(plan.periods) ||
@@ -545,7 +563,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].includes(
[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20].includes(
Number(decoded.version),
)
) {
@@ -618,7 +636,7 @@ export function restoreBusinessPlanSnapshot(
)
return null;
if (
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17].includes(
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20].includes(
Number(decoded.version),
)
) {
@@ -657,7 +675,7 @@ export function restoreBusinessPlanSnapshot(
const schedule = plan[field];
if (
schedule !== undefined &&
(![11, 12, 13, 14, 15, 16, 17].includes(
(![11, 12, 13, 14, 15, 16, 17, 20].includes(
Number(decoded.version),
) ||
!Array.isArray(schedule) ||
@@ -747,7 +765,7 @@ export function restoreBusinessPlanSnapshot(
const costSchedule = productData.unitVariableCostByPeriod;
const validMoneySchedule = (values: unknown) =>
values === undefined ||
([10, 11, 12, 13, 14, 15, 16, 17].includes(
([10, 11, 12, 13, 14, 15, 16, 17, 20].includes(
Number(decoded.version),
) &&
Array.isArray(values) &&
@@ -756,7 +774,7 @@ export function restoreBusinessPlanSnapshot(
values.every((value) => typeof value === 'string'));
return (
(schedule !== undefined &&
(![9, 10, 11, 12, 13, 14, 15, 16, 17].includes(
(![9, 10, 11, 12, 13, 14, 15, 16, 17, 20].includes(
Number(decoded.version),
) ||
!Array.isArray(schedule) ||
@@ -795,7 +813,7 @@ export function restoreBusinessPlanSnapshot(
entry.paymentLagMonths < 0 ||
entry.paymentLagMonths > 12)) ||
(entry.paymentInstallments !== undefined &&
(![16, 17].includes(
(![16, 17, 20].includes(
Number(decoded.version),
) ||
!Array.isArray(
@@ -853,7 +871,7 @@ export function restoreBusinessPlanSnapshot(
})
)
return null;
return {
const restored = {
...plan,
inventoryPurchaseLeadMonths: Number(
plan.inventoryPurchaseLeadMonths ?? 0,
@@ -915,6 +933,9 @@ export function restoreBusinessPlanSnapshot(
? plan.monthlyVariableCostPaymentsByPeriod.map(String)
: null,
} as unknown as BusinessFinancialPlanInput;
if (restored.dayTerms && !options.editable)
forecastBusinessPlan(restored);
return restored;
} catch {
return null;
}
@@ -1439,7 +1460,47 @@ export function compareBusinessScenarios(input: BusinessFinancialPlanInput) {
}
/** Forecast separates invoiced sales, collections, accounting expenses and cash payments. */
type ActiveDayTerms = ReturnType<typeof buildDayTermSchedule> & {
config: DayTerms;
};
export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
const config = input.dayTerms;
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.
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 });
}
function forecastBusinessPlanBase(
input: BusinessFinancialPlanInput,
day?: ActiveDayTerms,
) {
if (input.startupAssetRequirements) {
const needs = calculateStartupAssetRequirements(input);
if (
@@ -2243,10 +2304,13 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
const rows = [];
for (let month = 1; month <= periods; month++) {
const periodVariableCostPayment =
variableCostPaymentsByPeriod[month - 1];
const periodVariableCostPayment = day?.config.purchases
? day.schedules.purchases[month - 1]
: variableCostPaymentsByPeriod[month - 1];
const periodOperatingExpense = operatingExpenseByPeriod[month - 1];
const periodOperatingPayment = operatingPaymentsByPeriod[month - 1];
const periodOperatingPayment = 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];
@@ -2368,7 +2432,14 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
let salesCollections: bigint | null = null;
let salesScheduledCollections: bigint | null = null;
let salesRecoveryCollections: bigint | null = null;
if (salesCollectionLagMonths !== null) {
if (day?.config.sales) {
salesCollections = day.schedules.sales[month - 1];
salesScheduledCollections = salesCollections;
salesRecoveryCollections = 0n;
salesReceivables += revenue - salesCollections;
totalSalesCollections += salesCollections;
totalScheduledSalesCollections += salesCollections;
} else if (salesCollectionLagMonths !== null) {
const collectionMonth = month + salesCollectionLagMonths;
const scheduledCollection =
(revenue * salesCollectionRate + 50_000_000n) / 100_000_000n;
@@ -2415,7 +2486,13 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
totalSalesRecoveryCollections += salesRecoveryCollections;
totalSalesCollections += salesCollections;
}
const totalCollections = monthlyCollections + (salesCollections ?? 0n);
const activeManualCollections =
day?.config.sales &&
input.reportAssumptions?.manualCollectionsKind !== 'other_income'
? 0n
: monthlyCollections;
const totalCollections =
activeManualCollections + (salesCollections ?? 0n);
const legacyOpeningReceivablesCollections =
month === openingReceivablesCollectionMonth
? openingReceivablesCollectionAmount
@@ -2463,7 +2540,9 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
? null
: format(salesRecoveryCollections),
otherCollections:
salesCollections === null ? null : format(monthlyCollections),
salesCollections === null
? null
: format(activeManualCollections),
salesReceivablesClosing:
salesCollections === null ? null : format(salesReceivables),
variableCost: format(costOfSales),
@@ -2572,8 +2651,9 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
paymentLagMonths: order.paymentLagMonths,
}),
),
paymentSchedule:
supplierPaymentSchedules?.[index] ?? null,
paymentSchedule: day?.config.purchases
? null
: (supplierPaymentSchedules?.[index] ?? null),
totalPurchases: format(
productStockInputs[index].orders!.reduce(
(sum, order) => sum + order.amount,
@@ -2651,26 +2731,36 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
amount: format(installment.amount),
})),
totalSalesCollections:
salesCollectionLagMonths === null
salesCollectionLagMonths === null && !day?.config.sales
? null
: format(totalSalesCollections),
totalScheduledSalesCollections:
salesCollectionLagMonths === null
salesCollectionLagMonths === null && !day?.config.sales
? null
: format(totalScheduledSalesCollections),
totalSalesRecoveryCollections:
salesCollectionLagMonths === null
salesCollectionLagMonths === null && !day?.config.sales
? null
: format(totalSalesRecoveryCollections),
salesReceivablesAtEnd:
salesCollectionLagMonths === null ? null : format(salesReceivables),
salesCollectionLagMonths === null && !day?.config.sales
? null
: format(salesReceivables),
salesCollectionLagMonths,
salesCollectionPercent:
salesCollectionLagMonths === null ? null : salesCollectionPercent,
salesCollectionLagMonths === null && !day?.config.sales
? null
: salesCollectionPercent,
totalPayments: format(totalOperatingPayments),
supplierPaymentsOutstandingAtEnd: useSupplierPaymentTerms
? format(supplierPaymentsOutstanding)
: null,
supplierPaymentsOutstandingAtEnd: 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,
@@ -2940,7 +3030,19 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
),
),
};
return { ...output, presentationCurrency, conversion };
return {
...output,
presentationCurrency,
conversion,
...(day
? {
dayTermEvents: day.events.map((e) => ({
...e,
amount: format(BigInt(e.amount)),
})),
}
: {}),
};
}
/** Reproducible local report: original assumptions, declared FX basis, and the same forecast totals. */
@@ -3495,6 +3597,38 @@ export function exportBusinessPlanCsv(
'Estimativa sem aconselhamento fiscal, parâmetros legais, sazonalidade, inflação ou validação contabilística. Moeda original preservada.',
],
];
if (result.dayTermEvents) {
rows.push(
[],
[
'Prazos em dias — agendas anteriores das categorias seleccionadas conservadas inactivas',
],
[
'Categoria',
'Origem',
'Parcela',
'Reconhecimento',
'Origem do prazo',
'Vencimento',
'Montante',
'Precisão',
'Horizonte',
],
...result.dayTermEvents.map((e) => [
e.kind,
e.originId,
e.parcelId,
e.recognition,
e.origin,
e.due,
e.amount,
e.approximate ? 'aproximação mensal' : 'datas individuais',
e.outsideHorizon
? 'fora do horizonte, sem caixa neste plano'
: `mês ${e.dueMonth}`,
]),
);
}
return `\uFEFF${rows
.map((row) => row.map(csvCell).join(','))
.join('\r\n')}`;
+205
View File
@@ -0,0 +1,205 @@
export type DayTermKind = 'sales' | 'purchases' | 'services';
export type DayTermOperation = {
originId: string;
parcelId: string;
kind: DayTermKind;
month: number;
amount: string;
recognitionBasis: 'monthly' | 'date' | 'unknown';
recognitionDate: string;
originBasis: 'recognition' | 'date' | 'unknown';
originDate: string;
termDays: string;
};
export type DayTerms = {
sales: boolean;
purchases: boolean;
services: boolean;
operations: DayTermOperation[];
};
export const dayTermLabels: Record<DayTermKind, string> = {
sales: 'Vendas e prestações',
purchases: 'Mercadorias recebidas',
services: 'Serviços adquiridos reconhecidos',
};
export function isDayTerms(value: unknown): value is DayTerms {
if (!value || typeof value !== 'object') return false;
const c = value as DayTerms;
return (
['sales', 'purchases', 'services'].every(
(k) => typeof c[k as DayTermKind] === 'boolean',
) &&
Array.isArray(c.operations) &&
c.operations.length <= 240 &&
c.operations.every(
(o) =>
o &&
Object.hasOwn(dayTermLabels, o.kind) &&
Number.isSafeInteger(o.month) &&
o.month >= 1 &&
o.month <= 60 &&
[
'originId',
'parcelId',
'amount',
'recognitionDate',
'originDate',
'termDays',
].every(
(k) =>
typeof o[k as keyof DayTermOperation] === 'string' &&
String(o[k as keyof DayTermOperation]).length <= 160,
) &&
['monthly', 'date', 'unknown'].includes(o.recognitionBasis) &&
['recognition', 'date', 'unknown'].includes(o.originBasis),
)
);
}
function civilDate(value: string): Date | null {
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
const d = new Date(value + 'T00:00:00.000Z');
return Number.isFinite(d.getTime()) &&
d.toISOString().slice(0, 10) === value
? d
: null;
}
const iso = (d: Date) => d.toISOString().slice(0, 10);
/** Only opted-in channels replace their complete cash agenda. No legacy input is mutated. */
export function buildDayTermSchedule(
config: DayTerms,
year: number,
periods: number,
recognized: Record<DayTermKind, (bigint | null)[]>,
parseAmount: (value: string, label: string) => bigint,
) {
if (!isDayTerms(config))
throw new Error(
'Prazos em dias: estrutura inválida. Reveja operações e parcelas.',
);
if (!Number.isSafeInteger(year) || year < 1900 || year > 9993)
throw new Error(
'Prazos em dias — Ano inicial: indique o ano do relatório entre 1900 e 9993.',
);
const schedules: Record<DayTermKind, bigint[]> = {
sales: Array(periods).fill(0n),
purchases: Array(periods).fill(0n),
services: Array(periods).fill(0n),
};
const amounts: Record<DayTermKind, bigint[]> = {
sales: Array(periods).fill(0n),
purchases: Array(periods).fill(0n),
services: Array(periods).fill(0n),
};
const seen = new Set<string>();
const origins = new Map<string, string>();
const events = config.operations
.filter((o) => config[o.kind])
.map((o) => {
const label = `Prazos em dias — ${dayTermLabels[o.kind]}, origem ${o.originId || 'por preencher'}, parcela ${o.parcelId || 'por preencher'}`;
const fail = (message: string): never => {
throw new Error(`${label}: ${message}`);
};
if (!o.originId.trim() || !o.parcelId.trim())
fail('preencha a origem e a parcela para impedir duplicações.');
const key = JSON.stringify([
o.kind,
o.originId.trim(),
o.parcelId.trim(),
]);
if (seen.has(key))
fail(
'parcela duplicada; conserve apenas um movimento da mesma origem/parcela.',
);
seen.add(key);
if (o.month > periods)
fail(
'mês de reconhecimento fora do horizonte; reveja o mês ou use a agenda manual.',
);
const start = new Date(Date.UTC(year, o.month - 1, 1));
const recognition =
o.recognitionBasis === 'monthly'
? new Date(Date.UTC(year, o.month, 0))
: o.recognitionBasis === 'date'
? civilDate(o.recognitionDate)
: null;
if (!recognition)
fail(
'data de reconhecimento insuficiente ou inválida; indique uma data ou escolha explicitamente a aproximação mensal. Operação excluída do cálculo automático.',
);
const r = recognition!;
if (
r.getUTCFullYear() !== start.getUTCFullYear() ||
r.getUTCMonth() !== start.getUTCMonth()
)
fail(
'data de reconhecimento não pertence ao mês económico indicado; corrija a data ou o mês.',
);
const origin =
o.originBasis === 'recognition'
? r
: o.originBasis === 'date'
? civilDate(o.originDate)
: null;
if (!origin)
fail(
'data de origem do prazo insuficiente ou inválida; indique o evento contratual ou escolha reconhecimento. Operação excluída do cálculo automático.',
);
if (o.kind === 'sales' && iso(origin!) !== iso(r))
fail(
'origem do recebimento deve ser a venda/prestação reconhecida; corrija a origem.',
);
if (!/^\d+$/.test(o.termDays) || Number(o.termDays) > 365)
fail(
'Prazo (dias): indique um inteiro entre 0 e 365; vazio não significa zero.',
);
const due = new Date(origin!.getTime());
due.setUTCDate(due.getUTCDate() + Number(o.termDays));
if (due < r)
fail(
'vencimento anterior ao reconhecimento: antecipação excluída de F20-A. Use a agenda manual existente; adiantamentos identificados dependem de F20-B.',
);
const amount = parseAmount(o.amount, `${label} — Montante`);
const originKey = JSON.stringify([o.kind, o.originId.trim()]);
const identity = JSON.stringify([
o.month,
iso(r),
o.recognitionBasis,
]);
if (origins.has(originKey) && origins.get(originKey) !== identity)
fail(
'parcelas da mesma origem têm reconhecimentos diferentes; confira origem, mês e data.',
);
origins.set(originKey, identity);
amounts[o.kind][o.month - 1] += amount;
const dueMonth =
(due.getUTCFullYear() - year) * 12 + due.getUTCMonth() + 1;
if (dueMonth <= periods) schedules[o.kind][dueMonth - 1] += amount;
return {
...o,
amount: amount.toString(),
recognition: iso(r),
origin: iso(origin!),
due: iso(due),
dueMonth,
approximate: o.recognitionBasis === 'monthly',
outsideHorizon: dueMonth > periods,
};
});
for (const kind of Object.keys(dayTermLabels) as DayTermKind[]) {
if (!config[kind]) continue;
for (let i = 0; i < periods; i++) {
if (recognized[kind][i] === null)
throw new Error(
`Prazos em dias — ${dayTermLabels[kind]}, mês ${i + 1}: reconhecimento indeterminado; preencha a agenda económica antes de activar este modo.`,
);
if (amounts[kind][i] !== recognized[kind][i])
throw new Error(
`Prazos em dias — ${dayTermLabels[kind]}, mês ${i + 1}: a soma dos montantes das origens/parcelas deve coincidir com o valor reconhecido. Corrija a distribuição; não some uma coorte às operações já individualizadas.`,
);
}
}
return { schedules, events };
}
@@ -224,6 +224,7 @@ export function buildIntegralFinancialTables(
'Escolha o tratamento das subvenções: capital ou passivo diferido.',
);
if (
!plan.dayTerms?.sales &&
cents(plan.monthlyCollections) > 0n &&
!['sales', 'other_income'].includes(a.manualCollectionsKind)
)
@@ -784,6 +785,15 @@ export function buildIntegralFinancialTables(
table('break-even').notes.push(
'Vendas de equilíbrio = custos fixos operacionais, pessoal e depreciação ÷ margem de contribuição ponderada. Juros e impostos excluídos. Arredondamento apenas no resultado final, ao centavo.',
);
if (result.dayTermEvents) {
table('cashflow').notes.push(
'Prazos em dias: as agendas seleccionadas substituem as agendas anteriores de caixa, conservadas inactivas. Saldos de abertura mantêm as agendas próprias. Não inclui adiantamentos.',
...result.dayTermEvents.map(
(e) =>
`${e.kind === 'sales' ? 'Vendas/prestações' : e.kind === 'purchases' ? 'Mercadorias recebidas' : 'Serviços adquiridos'} — ${e.originId}/${e.parcelId}: ${e.amount} ${plan.currency}; reconhecimento ${e.recognition}; origem ${e.origin}; vencimento ${e.due}${e.approximate ? ' (aproximação mensal)' : ''}; ${e.outsideHorizon ? 'fora do horizonte, sem movimento de caixa neste plano' : `mês de caixa ${e.dueMonth}`}.`,
),
);
}
} catch (error) {
for (const entry of tables)
entry.issues.push(