feat: implement F22 period financing and asset agendas in isolated QA

This commit is contained in:
2026-11-21 11:55:43 +02:00
parent 6b91fd2bcd
commit 1950bb69ec
35 changed files with 2298 additions and 61 deletions
@@ -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}