feat: implement F22 period financing and asset agendas in isolated QA
This commit is contained in:
@@ -0,0 +1,479 @@
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
type BusinessFinancialPlanInput,
|
||||
} from '@/lib/business-financial-plan';
|
||||
import type {
|
||||
PeriodInvestments,
|
||||
PeriodFinancing,
|
||||
PeriodAsset,
|
||||
} from '@/lib/period-investments';
|
||||
|
||||
export function PeriodInvestmentsEditor({
|
||||
plan,
|
||||
onChange,
|
||||
}: {
|
||||
plan: BusinessFinancialPlanInput;
|
||||
onChange: (p: BusinessFinancialPlanInput) => void;
|
||||
}) {
|
||||
const c: PeriodInvestments = plan.periodInvestments ?? {
|
||||
enabled: false,
|
||||
financings: [],
|
||||
assets: [],
|
||||
};
|
||||
const save = (v: PeriodInvestments) =>
|
||||
onChange({ ...plan, periodInvestments: v });
|
||||
const fund = (i: number, p: Partial<PeriodFinancing>) =>
|
||||
save({
|
||||
...c,
|
||||
financings: c.financings.map((f, j) =>
|
||||
j === i ? { ...f, ...p } : f,
|
||||
),
|
||||
});
|
||||
const asset = (i: number, p: Partial<PeriodAsset>) =>
|
||||
save({
|
||||
...c,
|
||||
assets: c.assets.map((a, j) => (j === i ? { ...a, ...p } : a)),
|
||||
});
|
||||
const field = (
|
||||
label: string,
|
||||
value: string,
|
||||
change: (v: string) => void,
|
||||
type = 'text',
|
||||
) => (
|
||||
<label key={label} className="grid min-w-0 gap-1">
|
||||
{label}
|
||||
<input
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
type={type}
|
||||
value={value}
|
||||
onChange={(e) => change(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
let ledger: ReturnType<
|
||||
typeof forecastBusinessPlan
|
||||
>['periodInvestmentLedger'];
|
||||
let error = '';
|
||||
try {
|
||||
ledger = forecastBusinessPlan(plan).periodInvestmentLedger;
|
||||
} catch (e) {
|
||||
error =
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Confira os movimentos por período.';
|
||||
}
|
||||
return (
|
||||
<details className="my-3 min-w-0 space-y-3 rounded border p-3">
|
||||
<summary className="font-semibold">
|
||||
Novos financiamentos e activos por período
|
||||
</summary>
|
||||
<p>
|
||||
Projecções opcionais, separadas dos valores de abertura. Escolha
|
||||
o regime no plano antes de preparar este incremento. Não executa
|
||||
pagamentos nem cria financiamento para eliminar caixa negativa.
|
||||
</p>
|
||||
<p>
|
||||
Aquisições integralmente reconhecidas e pagas no mesmo mês, sem
|
||||
pagamento anterior ao reconhecimento. Crédito e adiantamentos
|
||||
para activos excluídos. A depreciação começa na disponibilidade
|
||||
para uso declarada: primeiro mês proporcional aos dias,
|
||||
inclusive; quotas mensais equivalentes e última parcela
|
||||
complementar. Arredondamento acumulado ao centavo. O fim do
|
||||
horizonte não antecipa o fecho da vida útil.
|
||||
</p>
|
||||
<p>
|
||||
Regime do plano: {plan.accountingRegime || 'por escolher'}.
|
||||
Horizonte: {plan.periods ?? 12} meses. As agendas existentes
|
||||
continuam a tratar exclusivamente os valores de abertura; não
|
||||
repita nelas os novos movimentos. Juros reconhecidos e pagos são
|
||||
independentes e não são capitalizados automaticamente no activo.
|
||||
</p>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={c.enabled}
|
||||
disabled={!plan.accountingRegime}
|
||||
onChange={(e) => {
|
||||
if (
|
||||
e.target.checked &&
|
||||
!window.confirm(
|
||||
'Activar os novos movimentos declarados? Os montantes de abertura e as agendas de prazos e adiantamentos ficam preservados; não repita os mesmos movimentos nas agendas antigas.',
|
||||
)
|
||||
)
|
||||
return;
|
||||
save({ ...c, enabled: e.target.checked });
|
||||
}}
|
||||
/>
|
||||
Activar novos movimentos por período (adesão explícita)
|
||||
</label>
|
||||
<p>
|
||||
Desactivar conserva os dados deste incremento, sem os incluir no
|
||||
cálculo. Campos vazios não são zero.
|
||||
</p>
|
||||
{c.financings.map((f, i) => (
|
||||
<details key={i} className="min-w-0 rounded border p-3" open>
|
||||
<summary>
|
||||
Financiamento {i + 1} — {f.label || 'por identificar'}
|
||||
</summary>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{field('Identificador do financiamento', f.id, (v) =>
|
||||
fund(i, { id: v }),
|
||||
)}
|
||||
{field('Designação do financiamento', f.label, (v) =>
|
||||
fund(i, { label: v }),
|
||||
)}
|
||||
<label className="grid gap-1">
|
||||
Tipo de financiamento
|
||||
<select
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
value={f.kind}
|
||||
onChange={(e) =>
|
||||
fund(i, {
|
||||
kind: e.target
|
||||
.value as PeriodFinancing['kind'],
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="bank">
|
||||
Empréstimo bancário
|
||||
</option>
|
||||
<option value="shareholder">Suprimento</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
{f.drawdowns.map((d, j) => (
|
||||
<div
|
||||
key={j}
|
||||
className="my-2 grid gap-2 rounded border p-2 sm:grid-cols-3"
|
||||
aria-label={`Desembolso ${j + 1} do financiamento ${i + 1}`}
|
||||
>
|
||||
{field('Identificador do desembolso', d.id, (v) =>
|
||||
fund(i, {
|
||||
drawdowns: f.drawdowns.map((x, k) =>
|
||||
k === j ? { ...x, id: v } : x,
|
||||
),
|
||||
}),
|
||||
)}
|
||||
{field(
|
||||
'Data do desembolso',
|
||||
d.date,
|
||||
(v) =>
|
||||
fund(i, {
|
||||
drawdowns: f.drawdowns.map((x, k) =>
|
||||
k === j ? { ...x, date: v } : x,
|
||||
),
|
||||
}),
|
||||
'date',
|
||||
)}
|
||||
{field('Montante do desembolso', d.amount, (v) =>
|
||||
fund(i, {
|
||||
drawdowns: f.drawdowns.map((x, k) =>
|
||||
k === j ? { ...x, amount: v } : x,
|
||||
),
|
||||
}),
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
onClick={() =>
|
||||
fund(i, {
|
||||
drawdowns: f.drawdowns.filter(
|
||||
(_, k) => k !== j,
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Remover desembolso {j + 1}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
disabled={f.drawdowns.length >= 60}
|
||||
onClick={() =>
|
||||
fund(i, {
|
||||
drawdowns: [
|
||||
...f.drawdowns,
|
||||
{ id: '', date: '', amount: '' },
|
||||
],
|
||||
})
|
||||
}
|
||||
>
|
||||
Adicionar desembolso ao financiamento {i + 1}
|
||||
</button>
|
||||
<details className="my-2 rounded border p-2">
|
||||
<summary>
|
||||
Agenda mensal do financiamento {i + 1}
|
||||
</summary>
|
||||
<p>
|
||||
Agendas por período, sem taxas ou condições
|
||||
bancárias presumidas. Cada mês exige os três
|
||||
montantes declarados, incluindo zero quando
|
||||
aplicável. O principal é limitado ao saldo deste
|
||||
financiamento, após desembolsos desse mês.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
onClick={() =>
|
||||
fund(i, {
|
||||
agenda: Array.from(
|
||||
{ length: plan.periods ?? 12 },
|
||||
(_, m) =>
|
||||
f.agenda.find(
|
||||
(a) => a.month === m + 1,
|
||||
) ?? {
|
||||
month: m + 1,
|
||||
interestExpense: '',
|
||||
interestPaid: '',
|
||||
principal: '',
|
||||
},
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Completar meses em falta do financiamento {i + 1}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
onClick={() =>
|
||||
fund(i, {
|
||||
agenda: f.agenda.map((a) => ({
|
||||
...a,
|
||||
interestExpense:
|
||||
a.interestExpense || '0',
|
||||
interestPaid: a.interestPaid || '0',
|
||||
principal: a.principal || '0',
|
||||
})),
|
||||
})
|
||||
}
|
||||
>
|
||||
Declarar zero nos campos vazios do financiamento{' '}
|
||||
{i + 1}
|
||||
</button>
|
||||
{f.agenda.map((a, j) => (
|
||||
<div
|
||||
key={j}
|
||||
className="my-2 grid gap-2 rounded border p-2 sm:grid-cols-3"
|
||||
aria-label={`Mês ${a.month} do financiamento ${i + 1}`}
|
||||
>
|
||||
<p>Mês {a.month}</p>
|
||||
{(
|
||||
[
|
||||
'interestExpense',
|
||||
'interestPaid',
|
||||
'principal',
|
||||
] as const
|
||||
).map((k) =>
|
||||
field(
|
||||
k === 'interestExpense'
|
||||
? `Juros reconhecidos, mês ${a.month}`
|
||||
: k === 'interestPaid'
|
||||
? `Juros pagos, mês ${a.month}`
|
||||
: `Principal, mês ${a.month}`,
|
||||
a[k],
|
||||
(v) =>
|
||||
fund(i, {
|
||||
agenda: f.agenda.map((x, n) =>
|
||||
n === j
|
||||
? { ...x, [k]: v }
|
||||
: x,
|
||||
),
|
||||
}),
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</details>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
onClick={() =>
|
||||
save({
|
||||
...c,
|
||||
financings: c.financings.filter(
|
||||
(_, j) => j !== i,
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Remover financiamento {i + 1}
|
||||
</button>
|
||||
</details>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
disabled={!plan.accountingRegime || c.financings.length >= 60}
|
||||
onClick={() =>
|
||||
save({
|
||||
...c,
|
||||
financings: [
|
||||
...c.financings,
|
||||
{
|
||||
id: '',
|
||||
label: '',
|
||||
kind: 'bank',
|
||||
drawdowns: [],
|
||||
agenda: Array.from(
|
||||
{ length: plan.periods ?? 12 },
|
||||
(_, i) => ({
|
||||
month: i + 1,
|
||||
interestExpense: '',
|
||||
interestPaid: '',
|
||||
principal: '',
|
||||
}),
|
||||
),
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
>
|
||||
Adicionar financiamento por período
|
||||
</button>
|
||||
{c.assets.map((a, i) => (
|
||||
<fieldset
|
||||
key={i}
|
||||
className="grid min-w-0 gap-2 rounded border p-3 sm:grid-cols-2"
|
||||
>
|
||||
<legend>Activo posterior {i + 1}</legend>
|
||||
{field('Identificador do activo', a.id, (v) =>
|
||||
asset(i, { id: v }),
|
||||
)}
|
||||
{field('Designação do activo', a.label, (v) =>
|
||||
asset(i, { label: v }),
|
||||
)}
|
||||
{field(
|
||||
'Reconhecimento do activo',
|
||||
a.recognitionDate,
|
||||
(v) => asset(i, { recognitionDate: v }),
|
||||
'date',
|
||||
)}
|
||||
{field(
|
||||
'Pagamento do activo',
|
||||
a.paymentDate,
|
||||
(v) => asset(i, { paymentDate: v }),
|
||||
'date',
|
||||
)}
|
||||
{field('Valor da aquisição', a.cost, (v) =>
|
||||
asset(i, { cost: v }),
|
||||
)}
|
||||
{field('Base depreciável do novo activo', a.base, (v) =>
|
||||
asset(i, { base: v }),
|
||||
)}
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={a.depreciable}
|
||||
onChange={(e) =>
|
||||
asset(i, { depreciable: e.target.checked })
|
||||
}
|
||||
/>
|
||||
Activo depreciável
|
||||
</label>
|
||||
{a.depreciable && (
|
||||
<>
|
||||
{field(
|
||||
'Vida útil do novo activo (meses)',
|
||||
a.lifeMonths,
|
||||
(v) => asset(i, { lifeMonths: v }),
|
||||
)}
|
||||
{field(
|
||||
'Disponibilidade para uso',
|
||||
a.availableDate,
|
||||
(v) => asset(i, { availableDate: v }),
|
||||
'date',
|
||||
)}
|
||||
{plan.accountingRegime === 'PGC-NIRF' &&
|
||||
field(
|
||||
'Fundamentação do método linear PGC-NIRF',
|
||||
a.linearBasis,
|
||||
(v) => asset(i, { linearBasis: v }),
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
onClick={() =>
|
||||
save({
|
||||
...c,
|
||||
assets: c.assets.filter((_, j) => j !== i),
|
||||
})
|
||||
}
|
||||
>
|
||||
Remover activo posterior {i + 1}
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
disabled={!plan.accountingRegime || c.assets.length >= 60}
|
||||
onClick={() =>
|
||||
save({
|
||||
...c,
|
||||
assets: [
|
||||
...c.assets,
|
||||
{
|
||||
id: '',
|
||||
label: '',
|
||||
recognitionDate: '',
|
||||
paymentDate: '',
|
||||
cost: '',
|
||||
base: '',
|
||||
lifeMonths: '',
|
||||
availableDate: '',
|
||||
linearBasis: '',
|
||||
depreciable: true,
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
>
|
||||
Adicionar activo por período
|
||||
</button>
|
||||
{c.enabled && error && <p role="alert">{error}</p>}
|
||||
{ledger && (
|
||||
<section
|
||||
aria-label="Resumo dos novos movimentos por período"
|
||||
className="space-y-2"
|
||||
>
|
||||
<h4>Novos movimentos conferidos</h4>
|
||||
{ledger.financings.map((f) => (
|
||||
<p key={f.id}>
|
||||
{f.id} — {f.label}:{' '}
|
||||
{f.kind === 'bank'
|
||||
? 'empréstimo bancário'
|
||||
: 'suprimento'}
|
||||
; saldo no horizonte {f.monthly.at(-1)?.balance}{' '}
|
||||
{plan.currency}.{' '}
|
||||
{f.drawdowns
|
||||
.filter((d) => d.outsideHorizon)
|
||||
.map(
|
||||
(d) =>
|
||||
`Desembolso ${d.id} de ${d.amount} em ${d.date}: fora do horizonte.`,
|
||||
)
|
||||
.join(' ')}
|
||||
</p>
|
||||
))}
|
||||
{ledger.assets.map((a) => (
|
||||
<p key={a.id}>
|
||||
{a.id} — {a.label}: aquisição {a.cost}; base{' '}
|
||||
{a.base}; fracção inicial{' '}
|
||||
{a.firstFraction ?? 'não depreciável'}; último mês{' '}
|
||||
{a.lastMonth ?? 'não aplicável'}; base ainda não
|
||||
depreciada {a.remainingDepreciation} {plan.currency}
|
||||
.{' '}
|
||||
{a.outsideHorizon
|
||||
? 'Aquisição fora do horizonte, sem caixa ou reconhecimento antecipado.'
|
||||
: ''}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</details>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { SupplierAdvancesEditor } from '@/components/supplier-advances';
|
||||
import { PeriodInvestmentsEditor } from '@/components/period-investments';
|
||||
import CurrencySelect from '@/components/currency-select';
|
||||
import { useEffect, useId, useState } from 'react';
|
||||
import {
|
||||
@@ -952,6 +953,7 @@ export function SimulationBusinessPlan({
|
||||
<FinancialPlanDetails plan={plan} onChange={savePlan} />
|
||||
<FinancialDayTerms plan={plan} onChange={savePlan} />
|
||||
<SupplierAdvancesEditor plan={plan} onChange={savePlan} />
|
||||
<PeriodInvestmentsEditor plan={plan} onChange={savePlan} />
|
||||
<StartupAssetRequirements
|
||||
plan={plan}
|
||||
onChange={savePlan}
|
||||
|
||||
@@ -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(
|
||||
[],
|
||||
|
||||
@@ -121,7 +121,9 @@ function assertForecastReconciles(forecast: Forecast): void {
|
||||
cents(String(row.operatingPayments)) -
|
||||
cents(String(row.payrollPayments)) -
|
||||
cents(String(row.interestPayment)) -
|
||||
cents(String(row.principalRepayment));
|
||||
cents(String(row.principalRepayment)) +
|
||||
cents(row.newBorrowings ?? '0') -
|
||||
cents(row.assetAcquisitions ?? '0');
|
||||
if (netCashFlow !== cents(String(row.netCashFlow)))
|
||||
throw new Error(
|
||||
'O fluxo líquido mensal não reconcilia com recebimentos e pagamentos.',
|
||||
|
||||
@@ -485,6 +485,10 @@ export function buildIntegralFinancialTables(
|
||||
cumulativeProfit = -startup,
|
||||
principal = 0n;
|
||||
let distributedDividends = 0n;
|
||||
let subsequentFixed = 0n,
|
||||
subsequentBorrowings = 0n;
|
||||
let legacyPrincipal = 0n,
|
||||
legacyDepreciation = 0n;
|
||||
let obligationsKnown = true;
|
||||
const fixed =
|
||||
openingFixed +
|
||||
@@ -512,6 +516,9 @@ export function buildIntegralFinancialTables(
|
||||
`Saldos de abertura não reconciliados: diferença ${reportMoney(initialDifference)}. Confira o património e o capital anteriores; não há compensação automática.`,
|
||||
);
|
||||
const ledger = result.rows.map((row, i) => {
|
||||
const movements = result.periodInvestmentLedger?.monthly[i];
|
||||
subsequentFixed += cents(row.assetAcquisitions ?? '0');
|
||||
subsequentBorrowings += cents(row.newBorrowings ?? '0');
|
||||
const otherIncome =
|
||||
a.manualCollectionsKind === 'other_income'
|
||||
? cents(plan.monthlyCollections)
|
||||
@@ -551,10 +558,23 @@ export function buildIntegralFinancialTables(
|
||||
obligations += cents(
|
||||
result.supplierAdvanceLedger?.monthly[i].refunded ?? '0',
|
||||
);
|
||||
const grossObligations = obligations + advance;
|
||||
// New financing interest is shown separately from trade obligations.
|
||||
obligations -=
|
||||
cents(row.newInterestExpense ?? '0') -
|
||||
cents(row.newInterestPayment ?? '0');
|
||||
const tradeObligations = obligations + advance;
|
||||
const interestLiabilities = cents(
|
||||
movements?.interestLiabilities ?? '0',
|
||||
);
|
||||
const interestAssets = cents(movements?.interestAssets ?? '0');
|
||||
taxDue += taxExpenses[i] - taxPayments[i];
|
||||
depreciation += cents(row.depreciation);
|
||||
principal += cents(row.principalRepayment);
|
||||
legacyPrincipal +=
|
||||
cents(row.principalRepayment) -
|
||||
cents(row.newPrincipalRepayment ?? '0');
|
||||
legacyDepreciation +=
|
||||
cents(row.depreciation) - cents(row.newDepreciation ?? '0');
|
||||
cumulativeProfit += profit;
|
||||
distributedDividends += cents(row.dividends);
|
||||
const inventory =
|
||||
@@ -565,11 +585,11 @@ export function buildIntegralFinancialTables(
|
||||
table('balance').issues.push(
|
||||
`Mês ${i + 1}: existências insuficientes para as vendas declaradas.`,
|
||||
);
|
||||
if (depreciation > fixed)
|
||||
if (legacyDepreciation > fixed)
|
||||
table('balance').issues.push(
|
||||
`Balanço Projectado — mês ${i + 1}: a depreciação acumulada excede os activos fixos disponíveis. Confira «Base depreciável contabilística» e «Vida útil (meses)» face a «Aquisição de activos» e «Activos fixos anteriores (valor líquido)»; corrija os pressupostos inconsistentes.`,
|
||||
);
|
||||
if (principal > loans)
|
||||
if (legacyPrincipal > loans)
|
||||
table('balance').issues.push(
|
||||
`Balanço Projectado — mês ${i + 1}: o capital reembolsado acumulado excede a dívida declarada. Confira «Reembolso de capital» face a «Empréstimo recebido» e «Suprimentos»; corrija os pressupostos inconsistentes.`,
|
||||
);
|
||||
@@ -577,17 +597,21 @@ export function buildIntegralFinancialTables(
|
||||
cash +
|
||||
positive(receivables) +
|
||||
(inventory ?? 0n) +
|
||||
fixed -
|
||||
fixed +
|
||||
subsequentFixed -
|
||||
depreciation +
|
||||
otherAssets +
|
||||
positive(-grossObligations) +
|
||||
positive(-tradeObligations) +
|
||||
interestAssets +
|
||||
advance +
|
||||
positive(-taxDue);
|
||||
const liabilities =
|
||||
positive(-receivables) +
|
||||
positive(grossObligations) +
|
||||
positive(tradeObligations) +
|
||||
interestLiabilities +
|
||||
positive(taxDue) +
|
||||
loans -
|
||||
loans +
|
||||
subsequentBorrowings -
|
||||
principal +
|
||||
deferredGrant;
|
||||
const capital =
|
||||
@@ -596,7 +620,7 @@ export function buildIntegralFinancialTables(
|
||||
opening,
|
||||
cash,
|
||||
receivables,
|
||||
obligations: obligationsKnown ? grossObligations : null,
|
||||
obligations: obligationsKnown ? tradeObligations : null,
|
||||
advance,
|
||||
taxDue,
|
||||
profit,
|
||||
@@ -608,10 +632,10 @@ export function buildIntegralFinancialTables(
|
||||
inventory === null || !obligationsKnown
|
||||
? null
|
||||
: assets - liabilities - capital,
|
||||
loans: loans - principal,
|
||||
loans: loans + subsequentBorrowings - principal,
|
||||
paidCapital,
|
||||
accumulatedResults: cumulativeProfit - distributedDividends,
|
||||
fixed: fixed - depreciation,
|
||||
fixed: fixed + subsequentFixed - depreciation,
|
||||
inventory,
|
||||
};
|
||||
});
|
||||
@@ -670,6 +694,32 @@ export function buildIntegralFinancialTables(
|
||||
),
|
||||
];
|
||||
flows('cashflow', 'Recebimentos', data('cashCollections'));
|
||||
if (result.periodInvestmentLedger) {
|
||||
flows(
|
||||
'cashflow',
|
||||
'Novos empréstimos e suprimentos',
|
||||
result.rows.map((r) => cents(r.newBorrowings ?? '0')),
|
||||
);
|
||||
flows(
|
||||
'cashflow',
|
||||
'Aquisições posteriores de activos',
|
||||
result.rows.map((r) => cents(r.assetAcquisitions ?? '0')),
|
||||
);
|
||||
stocks(
|
||||
'balance',
|
||||
'Juros de novos financiamentos por pagar',
|
||||
result.periodInvestmentLedger.monthly.map((r) =>
|
||||
cents(r.interestLiabilities),
|
||||
),
|
||||
);
|
||||
stocks(
|
||||
'balance',
|
||||
'Juros de novos financiamentos pagos antecipadamente',
|
||||
result.periodInvestmentLedger.monthly.map((r) =>
|
||||
cents(r.interestAssets),
|
||||
),
|
||||
);
|
||||
}
|
||||
for (const [key, label] of [
|
||||
['variableCostPayments', 'Pagamentos de compras'],
|
||||
['operatingPayments', 'Pagamentos operacionais'],
|
||||
@@ -874,6 +924,82 @@ export function buildIntegralFinancialTables(
|
||||
),
|
||||
);
|
||||
}
|
||||
if (result.periodInvestmentLedger) {
|
||||
const movement = result.periodInvestmentLedger;
|
||||
tables.push({
|
||||
id: 'period-investments',
|
||||
title: 'Financiamentos e activos por período',
|
||||
headers: [
|
||||
'Tipo',
|
||||
'Origem',
|
||||
'Mês',
|
||||
'Desembolso',
|
||||
'Principal',
|
||||
'Juros reconhecidos',
|
||||
'Juros pagos',
|
||||
'Saldo de capital',
|
||||
'Aquisição',
|
||||
'Depreciação',
|
||||
'Activo líquido',
|
||||
],
|
||||
rows: [
|
||||
...movement.financings.flatMap((f) =>
|
||||
f.monthly.map((r) => [
|
||||
f.kind === 'bank'
|
||||
? 'Empréstimo bancário'
|
||||
: 'Suprimento',
|
||||
`${f.id} — ${f.label}`,
|
||||
String(r.month),
|
||||
r.borrowings,
|
||||
r.principal,
|
||||
r.interestExpense,
|
||||
r.interestPaid,
|
||||
r.balance,
|
||||
'—',
|
||||
'—',
|
||||
'—',
|
||||
]),
|
||||
),
|
||||
...movement.assets.flatMap((a) =>
|
||||
a.monthly.map((r) => [
|
||||
'Activo',
|
||||
`${a.id} — ${a.label}`,
|
||||
String(r.month),
|
||||
'—',
|
||||
'—',
|
||||
'—',
|
||||
'—',
|
||||
'—',
|
||||
r.acquisition,
|
||||
r.depreciation,
|
||||
r.net,
|
||||
]),
|
||||
),
|
||||
],
|
||||
issues: [],
|
||||
notes: [
|
||||
`Regime ${movement.regime}. Projecções declaradas; não são desembolsos, pagamentos ou lançamentos efectuados. Juros não são capitalizados automaticamente.`,
|
||||
...movement.assets.map(
|
||||
(a) =>
|
||||
`${a.id}: reconhecimento ${a.recognitionDate}; pagamento ${a.paymentDate}; disponibilidade ${a.availableDate || 'não depreciável'}; base ${a.base}; vida útil ${a.lifeMonths || 'não aplicável'} meses; primeira fracção ${a.firstFraction || 'não aplicável'}; último mês de depreciação ${a.lastMonth ?? 'não aplicável'}; base ainda não depreciada ${a.remainingDepreciation}. ${a.linearBasis}`,
|
||||
),
|
||||
...movement.financings.flatMap((f) =>
|
||||
f.drawdowns
|
||||
.filter((d) => d.outsideHorizon)
|
||||
.map(
|
||||
(d) =>
|
||||
`${f.id}/${d.id}: desembolso ${d.amount} em ${d.date}, fora do horizonte; não incluído na caixa.`,
|
||||
),
|
||||
),
|
||||
...movement.assets
|
||||
.filter((a) => a.outsideHorizon)
|
||||
.map(
|
||||
(a) =>
|
||||
`${a.id}: aquisição ${a.cost} em ${a.recognitionDate}, fora do horizonte; não incluída na caixa nem nos activos reconhecidos deste plano.`,
|
||||
),
|
||||
],
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
for (const entry of tables)
|
||||
entry.issues.push(
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
export type PeriodFinancing = {
|
||||
id: string;
|
||||
label: string;
|
||||
kind: 'bank' | 'shareholder';
|
||||
drawdowns: { id: string; date: string; amount: string }[];
|
||||
agenda: {
|
||||
month: number;
|
||||
interestExpense: string;
|
||||
interestPaid: string;
|
||||
principal: string;
|
||||
}[];
|
||||
};
|
||||
export type PeriodAsset = {
|
||||
id: string;
|
||||
label: string;
|
||||
recognitionDate: string;
|
||||
paymentDate: string;
|
||||
cost: string;
|
||||
depreciable: boolean;
|
||||
base: string;
|
||||
lifeMonths: string;
|
||||
availableDate: string;
|
||||
linearBasis: string;
|
||||
};
|
||||
export type PeriodInvestments = {
|
||||
enabled: boolean;
|
||||
financings: PeriodFinancing[];
|
||||
assets: PeriodAsset[];
|
||||
};
|
||||
const text = (v: unknown) => typeof v === 'string' && v.length <= 160;
|
||||
export function isPeriodInvestments(v: unknown): v is PeriodInvestments {
|
||||
if (!v || typeof v !== 'object') return false;
|
||||
const c = v as PeriodInvestments;
|
||||
return (
|
||||
typeof c.enabled === 'boolean' &&
|
||||
Array.isArray(c.assets) &&
|
||||
c.assets.length <= 60 &&
|
||||
Array.isArray(c.financings) &&
|
||||
c.financings.length <= 60 &&
|
||||
c.assets.every(
|
||||
(a) =>
|
||||
a &&
|
||||
[
|
||||
'id',
|
||||
'label',
|
||||
'recognitionDate',
|
||||
'paymentDate',
|
||||
'cost',
|
||||
'base',
|
||||
'lifeMonths',
|
||||
'availableDate',
|
||||
'linearBasis',
|
||||
].every((k) => text(a[k as keyof PeriodAsset])) &&
|
||||
typeof a.depreciable === 'boolean',
|
||||
) &&
|
||||
c.financings.every(
|
||||
(f) =>
|
||||
f &&
|
||||
text(f.id) &&
|
||||
text(f.label) &&
|
||||
['bank', 'shareholder'].includes(f.kind) &&
|
||||
Array.isArray(f.drawdowns) &&
|
||||
f.drawdowns.length <= 60 &&
|
||||
f.drawdowns.every(
|
||||
(d) => d && text(d.id) && text(d.date) && text(d.amount),
|
||||
) &&
|
||||
Array.isArray(f.agenda) &&
|
||||
f.agenda.length <= 60 &&
|
||||
f.agenda.every(
|
||||
(a) =>
|
||||
a &&
|
||||
Number.isSafeInteger(a.month) &&
|
||||
a.month >= 1 &&
|
||||
a.month <= 60 &&
|
||||
['interestExpense', 'interestPaid', 'principal'].every(
|
||||
(k) => text(a[k as keyof typeof a]),
|
||||
),
|
||||
),
|
||||
)
|
||||
);
|
||||
}
|
||||
export const periodMoney = (v: bigint) =>
|
||||
`${v < 0n ? '-' : ''}${(v < 0n ? -v : v) / 100n}.${String((v < 0n ? -v : v) % 100n).padStart(2, '0')}`;
|
||||
const positive = (v: bigint) => (v > 0n ? v : 0n);
|
||||
function date(v: string, label: string) {
|
||||
const d = new Date(v + 'T00:00:00Z');
|
||||
if (
|
||||
!/^\d{4}-\d{2}-\d{2}$/.test(v) ||
|
||||
!Number.isFinite(d.getTime()) ||
|
||||
d.toISOString().slice(0, 10) !== v
|
||||
)
|
||||
throw Error(
|
||||
`${label}: indique uma data individual válida; não se presume o dia pela factura ou pagamento.`,
|
||||
);
|
||||
return d;
|
||||
}
|
||||
/** New cohorts only. Exact rational cumulative rounding leaves legacy depreciation untouched. */
|
||||
export function buildPeriodInvestments(
|
||||
config: PeriodInvestments,
|
||||
regime: unknown,
|
||||
year: number,
|
||||
periods: number,
|
||||
cents: (v: string, label: string) => bigint,
|
||||
) {
|
||||
if (!isPeriodInvestments(config))
|
||||
throw Error('Movimentos por período: estrutura inválida.');
|
||||
if (!['PGC-PE', 'PGC-NIRF'].includes(String(regime)))
|
||||
throw Error(
|
||||
'Movimentos por período — Regime: escolha explicitamente PGC-PE ou PGC-NIRF no plano.',
|
||||
);
|
||||
if (!Number.isSafeInteger(year) || year < 1900 || year > 9993)
|
||||
throw Error(
|
||||
'Movimentos por período — Ano inicial: preencha o ano do relatório entre 1900 e 9993.',
|
||||
);
|
||||
const index = (d: Date) =>
|
||||
(d.getUTCFullYear() - year) * 12 + d.getUTCMonth() + 1;
|
||||
const rows = Array.from({ length: periods }, (_, i) => ({
|
||||
month: i + 1,
|
||||
borrowings: 0n,
|
||||
bankBalance: 0n,
|
||||
shareholderBalance: 0n,
|
||||
principal: 0n,
|
||||
interestExpense: 0n,
|
||||
interestPaid: 0n,
|
||||
interestLiabilities: 0n,
|
||||
interestAssets: 0n,
|
||||
acquisitions: 0n,
|
||||
depreciation: 0n,
|
||||
grossAssets: 0n,
|
||||
netAssets: 0n,
|
||||
}));
|
||||
const unique = (set: Set<string>, id: string, label: string) => {
|
||||
if (!id.trim() || set.has(id.trim()))
|
||||
throw Error(
|
||||
`${label}: identificador em falta ou duplicado; corrija a origem, sem duplicar movimentos.`,
|
||||
);
|
||||
set.add(id.trim());
|
||||
};
|
||||
const fundingIds = new Set<string>();
|
||||
const financings = config.financings.map((f) => {
|
||||
const label = `Movimentos por período — Financiamento ${f.id || 'por identificar'}`;
|
||||
unique(fundingIds, f.id, label);
|
||||
if (!f.label.trim())
|
||||
throw Error(`${label} — Designação: preencha este campo.`);
|
||||
const draws = new Set<string>();
|
||||
const drawdowns = f.drawdowns.map((d) => {
|
||||
unique(draws, d.id, label + ' — Desembolso');
|
||||
const when = date(d.date, label + ' — Data do desembolso');
|
||||
const month = index(when);
|
||||
if (month < 1)
|
||||
throw Error(
|
||||
`${label}: desembolso anterior ao plano; não converter saldos de abertura.`,
|
||||
);
|
||||
const amount = cents(d.amount, label + ' — Montante do desembolso');
|
||||
if (amount <= 0n)
|
||||
throw Error(
|
||||
`${label}: montante do desembolso deve ser positivo.`,
|
||||
);
|
||||
return { ...d, month, amount, outsideHorizon: month > periods };
|
||||
});
|
||||
const months = new Set<number>();
|
||||
const agenda = f.agenda.map((a) => {
|
||||
if (months.has(a.month))
|
||||
throw Error(
|
||||
`${label}: mês duplicado na agenda; corrija as parcelas.`,
|
||||
);
|
||||
months.add(a.month);
|
||||
return {
|
||||
month: a.month,
|
||||
interestExpense: cents(
|
||||
a.interestExpense,
|
||||
label + ` — Juros reconhecidos, mês ${a.month}`,
|
||||
),
|
||||
interestPaid: cents(
|
||||
a.interestPaid,
|
||||
label + ` — Juros pagos, mês ${a.month}`,
|
||||
),
|
||||
principal: cents(
|
||||
a.principal,
|
||||
label + ` — Principal, mês ${a.month}`,
|
||||
),
|
||||
};
|
||||
});
|
||||
for (let m = 1; m <= periods; m++)
|
||||
if (!months.has(m))
|
||||
throw Error(
|
||||
`${label}: declare a agenda completa de juros e principal, incluindo zero quando aplicável, no mês ${m}.`,
|
||||
);
|
||||
let balance = 0n,
|
||||
interestBalance = 0n;
|
||||
const monthly = [];
|
||||
for (let m = 1; m <= 60; m++) {
|
||||
const borrowed = drawdowns
|
||||
.filter((d) => d.month === m)
|
||||
.reduce((s, d) => s + d.amount, 0n);
|
||||
const a = agenda.find((a) => a.month === m);
|
||||
const principal = a?.principal ?? 0n;
|
||||
balance += borrowed;
|
||||
if (principal > balance)
|
||||
throw Error(
|
||||
`${label} — Principal, mês ${m}: reembolso excede a dívida disponível deste financiamento; não use saldo de outro empréstimo.`,
|
||||
);
|
||||
balance -= principal;
|
||||
interestBalance +=
|
||||
(a?.interestExpense ?? 0n) - (a?.interestPaid ?? 0n);
|
||||
if (m <= periods) {
|
||||
const r = rows[m - 1];
|
||||
r.borrowings += borrowed;
|
||||
r.principal += principal;
|
||||
r.interestExpense += a!.interestExpense;
|
||||
r.interestPaid += a!.interestPaid;
|
||||
r.interestLiabilities += positive(interestBalance);
|
||||
r.interestAssets += positive(-interestBalance);
|
||||
if (f.kind === 'bank') r.bankBalance += balance;
|
||||
else r.shareholderBalance += balance;
|
||||
monthly.push({
|
||||
month: m,
|
||||
borrowings: periodMoney(borrowed),
|
||||
principal: periodMoney(principal),
|
||||
interestExpense: periodMoney(a!.interestExpense),
|
||||
interestPaid: periodMoney(a!.interestPaid),
|
||||
balance: periodMoney(balance),
|
||||
interestBalance: periodMoney(interestBalance),
|
||||
});
|
||||
}
|
||||
}
|
||||
return {
|
||||
...f,
|
||||
drawdowns: drawdowns.map((d) => ({
|
||||
...d,
|
||||
amount: periodMoney(d.amount),
|
||||
})),
|
||||
monthly,
|
||||
};
|
||||
});
|
||||
const assetIds = new Set<string>();
|
||||
const assets = config.assets.map((a) => {
|
||||
const label = `Movimentos por período — Activo ${a.id || 'por identificar'}`;
|
||||
unique(assetIds, a.id, label);
|
||||
if (!a.label.trim())
|
||||
throw Error(`${label} — Designação: preencha este campo.`);
|
||||
const recognized = date(a.recognitionDate, label + ' — Reconhecimento'),
|
||||
paid = date(a.paymentDate, label + ' — Pagamento');
|
||||
const month = index(recognized);
|
||||
if (month < 1)
|
||||
throw Error(
|
||||
`${label}: aquisição anterior ao plano; preserve os activos iniciais.`,
|
||||
);
|
||||
if (paid < recognized)
|
||||
throw Error(
|
||||
`${label}: pagamento antecipado excluído, mesmo no mesmo mês; corrija as datas sem converter o adiantamento em pagamento normal.`,
|
||||
);
|
||||
if (index(paid) !== month)
|
||||
throw Error(
|
||||
`${label}: reconhecimento e pagamento têm de ocorrer no mesmo período; crédito para activos fora deste incremento.`,
|
||||
);
|
||||
const cost = cents(a.cost, label + ' — Valor da aquisição'),
|
||||
base = cents(a.base, label + ' — Base depreciável');
|
||||
if (cost <= 0n || base > cost)
|
||||
throw Error(
|
||||
`${label}: valor positivo e base depreciável não superior ao custo são necessários.`,
|
||||
);
|
||||
if (!a.depreciable && base !== 0n)
|
||||
throw Error(
|
||||
`${label}: activo não depreciável exige base zero expressamente declarada.`,
|
||||
);
|
||||
let start = 0,
|
||||
life = 0,
|
||||
days = 1,
|
||||
availableDays = 1;
|
||||
if (a.depreciable) {
|
||||
const available = date(
|
||||
a.availableDate,
|
||||
label + ' — Disponibilidade para uso',
|
||||
);
|
||||
if (available < recognized)
|
||||
throw Error(
|
||||
`${label}: disponibilidade para uso anterior ao reconhecimento; confira as datas.`,
|
||||
);
|
||||
if (
|
||||
!/^\d+$/.test(a.lifeMonths) ||
|
||||
!Number.isSafeInteger(Number(a.lifeMonths)) ||
|
||||
Number(a.lifeMonths) < 1
|
||||
)
|
||||
throw Error(
|
||||
`${label} — Vida útil: indique um número inteiro positivo de meses.`,
|
||||
);
|
||||
if (regime === 'PGC-NIRF' && !a.linearBasis.trim())
|
||||
throw Error(
|
||||
`${label} — Fundamentação linear: indique por que o método linear é adequado a este activo PGC-NIRF.`,
|
||||
);
|
||||
start = index(available);
|
||||
life = Number(a.lifeMonths);
|
||||
days = new Date(
|
||||
Date.UTC(
|
||||
available.getUTCFullYear(),
|
||||
available.getUTCMonth() + 1,
|
||||
0,
|
||||
),
|
||||
).getUTCDate();
|
||||
availableDays = days - available.getUTCDate() + 1;
|
||||
}
|
||||
const endMonth = a.depreciable
|
||||
? start + life - (availableDays === days ? 1 : 0)
|
||||
: null;
|
||||
const denominator = BigInt(life || 1) * BigInt(days);
|
||||
let priorTarget = 0n,
|
||||
gross = 0n;
|
||||
const monthly = rows.map((r) => {
|
||||
const acquired = r.month === month ? cost : 0n;
|
||||
gross += acquired;
|
||||
let target = 0n;
|
||||
if (a.depreciable && r.month >= start) {
|
||||
const k = r.month - start;
|
||||
const units = BigInt(availableDays) + BigInt(k) * BigInt(days);
|
||||
const capped = units > denominator ? denominator : units;
|
||||
target = (base * capped + denominator / 2n) / denominator;
|
||||
}
|
||||
const depreciation = target - priorTarget;
|
||||
priorTarget = target;
|
||||
r.acquisitions += acquired;
|
||||
r.depreciation += depreciation;
|
||||
r.grossAssets += gross;
|
||||
r.netAssets += gross - target;
|
||||
return {
|
||||
month: r.month,
|
||||
acquisition: periodMoney(acquired),
|
||||
depreciation: periodMoney(depreciation),
|
||||
accumulated: periodMoney(target),
|
||||
net: periodMoney(gross - target),
|
||||
};
|
||||
});
|
||||
return {
|
||||
...a,
|
||||
cost: periodMoney(cost),
|
||||
base: periodMoney(base),
|
||||
acquisitionMonth: month,
|
||||
firstMonth: start || null,
|
||||
lastMonth: endMonth,
|
||||
firstFraction: a.depreciable ? `${availableDays}/${days}` : null,
|
||||
outsideHorizon: month > periods,
|
||||
remainingDepreciation: periodMoney(
|
||||
month > periods ? base : base - priorTarget,
|
||||
),
|
||||
monthly,
|
||||
};
|
||||
});
|
||||
return {
|
||||
regime: String(regime),
|
||||
financings,
|
||||
assets,
|
||||
monthly: rows.map(
|
||||
(r) =>
|
||||
Object.fromEntries(
|
||||
Object.entries(r).map(([k, v]) => [
|
||||
k,
|
||||
typeof v === 'bigint' ? periodMoney(v) : v,
|
||||
]),
|
||||
) as { month: number } & Record<
|
||||
Exclude<keyof typeof r, 'month'>,
|
||||
string
|
||||
>,
|
||||
),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user