366 lines
14 KiB
TypeScript
366 lines
14 KiB
TypeScript
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
|
|
>,
|
|
),
|
|
};
|
|
}
|