418 lines
17 KiB
TypeScript
418 lines
17 KiB
TypeScript
export type AdvanceKind = 'purchases' | 'services';
|
|
export type AdvanceEventKind = 'advance' | 'apply' | 'refund' | 'settle';
|
|
export type AccountingRegime = 'PGC-PE' | 'PGC-NIRF';
|
|
export type SupplierAdvanceOperation = {
|
|
originId: string;
|
|
parcelId: string;
|
|
supplier: string;
|
|
kind: AdvanceKind;
|
|
amount: string;
|
|
recognitionDate: string;
|
|
invoiceDate: string;
|
|
formalAgreement?: { date: string; reference: string };
|
|
ordinaryContract: boolean;
|
|
events: {
|
|
id: string;
|
|
kind: AdvanceEventKind;
|
|
date: string;
|
|
amount: string;
|
|
}[];
|
|
};
|
|
export type SupplierAdvances = {
|
|
regime: '' | AccountingRegime;
|
|
purchases: boolean;
|
|
services: boolean;
|
|
operations: SupplierAdvanceOperation[];
|
|
};
|
|
export const advanceLabels = {
|
|
purchases: 'Mercadorias',
|
|
services: 'Serviços adquiridos',
|
|
};
|
|
export const advanceEventLabels = {
|
|
advance: 'Pagamento antecipado',
|
|
apply: 'Aplicação do adiantamento',
|
|
refund: 'Devolução do adiantamento',
|
|
settle: 'Pagamento do remanescente',
|
|
};
|
|
export function advanceDocumentLabel(status: string) {
|
|
const labels: Record<string, string> = {
|
|
not_recognized: 'Ainda não reconhecido',
|
|
invoice: 'Fornecimento facturado',
|
|
formal_agreement: 'Fornecimento formalmente acordado',
|
|
pending_documentation:
|
|
'Fornecimento reconhecido, documentação por confirmar',
|
|
};
|
|
return labels[status] ?? 'Por confirmar';
|
|
}
|
|
const text = (v: unknown) => typeof v === 'string' && v.length <= 160;
|
|
export function isSupplierAdvances(v: unknown): v is SupplierAdvances {
|
|
if (!v || typeof v !== 'object') return false;
|
|
const c = v as SupplierAdvances;
|
|
return (
|
|
['', 'PGC-PE', 'PGC-NIRF'].includes(c.regime) &&
|
|
typeof c.purchases === 'boolean' &&
|
|
typeof c.services === 'boolean' &&
|
|
Array.isArray(c.operations) &&
|
|
c.operations.length <= 120 &&
|
|
c.operations.every(
|
|
(o) =>
|
|
o &&
|
|
['purchases', 'services'].includes(o.kind) &&
|
|
typeof o.ordinaryContract === 'boolean' &&
|
|
(o.formalAgreement === undefined ||
|
|
(o.formalAgreement &&
|
|
text(o.formalAgreement.date) &&
|
|
text(o.formalAgreement.reference))) &&
|
|
[
|
|
'originId',
|
|
'parcelId',
|
|
'supplier',
|
|
'amount',
|
|
'recognitionDate',
|
|
'invoiceDate',
|
|
].every((k) => text(o[k as keyof SupplierAdvanceOperation])) &&
|
|
Array.isArray(o.events) &&
|
|
o.events.length <= 60 &&
|
|
o.events.every(
|
|
(e) =>
|
|
e &&
|
|
text(e.id) &&
|
|
text(e.date) &&
|
|
text(e.amount) &&
|
|
Object.hasOwn(advanceEventLabels, e.kind),
|
|
),
|
|
)
|
|
);
|
|
}
|
|
|
|
function date(value: string): Date | null {
|
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
|
|
const d = new Date(value + 'T00:00:00Z');
|
|
return Number.isFinite(d.getTime()) &&
|
|
d.toISOString().slice(0, 10) === value
|
|
? d
|
|
: null;
|
|
}
|
|
const money = (n: bigint) => `${n / 100n}.${String(n % 100n).padStart(2, '0')}`;
|
|
|
|
/** Projected events only. No accounting postings or actual payments are executed. */
|
|
export function buildSupplierAdvances(
|
|
config: SupplierAdvances,
|
|
year: number,
|
|
periods: number,
|
|
recognized: Record<AdvanceKind, (bigint | null)[]>,
|
|
parse: (value: string, label: string) => bigint,
|
|
) {
|
|
if (!isSupplierAdvances(config))
|
|
throw Error('Adiantamentos: estrutura inválida.');
|
|
if (!['PGC-PE', 'PGC-NIRF'].includes(config.regime))
|
|
throw Error(
|
|
'Adiantamentos: seleccione explicitamente PGC-PE ou PGC-NIRF.',
|
|
);
|
|
if (!Number.isSafeInteger(year) || year < 1900 || year > 9993)
|
|
throw Error(
|
|
'Adiantamentos: preencha o ano inicial do relatório entre 1900 e 9993.',
|
|
);
|
|
const index = (d: Date) =>
|
|
(d.getUTCFullYear() - year) * 12 + d.getUTCMonth();
|
|
const start = new Date(Date.UTC(year, 0, 1));
|
|
const end = new Date(Date.UTC(year, periods, 1));
|
|
const sums = {
|
|
purchases: Array<bigint>(periods).fill(0n),
|
|
services: Array<bigint>(periods).fill(0n),
|
|
};
|
|
const payments = {
|
|
purchases: Array<bigint>(periods).fill(0n),
|
|
services: Array<bigint>(periods).fill(0n),
|
|
};
|
|
const refunds = Array<bigint>(periods).fill(0n);
|
|
const paid = Array<bigint>(periods).fill(0n);
|
|
const applied = Array<bigint>(periods).fill(0n);
|
|
const settled = Array<bigint>(periods).fill(0n);
|
|
const balances = Array.from({ length: periods }, () => ({
|
|
advance: 0n,
|
|
obligation: 0n,
|
|
netDue: 0n,
|
|
}));
|
|
const seen = new Set<string>();
|
|
const origins = new Map<string, string>();
|
|
const operations = config.operations
|
|
.filter((o) => config[o.kind])
|
|
.map((o) => {
|
|
const label = `Adiantamentos — ${o.originId || 'operação por preencher'}/${o.parcelId || 'parcela por preencher'}`;
|
|
const fail = (message: string): never => {
|
|
throw Error(`${label}: ${message}`);
|
|
};
|
|
if (!o.originId.trim() || !o.parcelId.trim() || !o.supplier.trim())
|
|
fail('identifique operação, parcela e fornecedor.');
|
|
if (!o.ordinaryContract)
|
|
fail(
|
|
'confirme contrato ordinário; contratos especiais estão excluídos.',
|
|
);
|
|
const key = JSON.stringify([
|
|
o.kind,
|
|
o.originId.trim(),
|
|
o.parcelId.trim(),
|
|
]);
|
|
if (seen.has(key)) fail('operação/parcela duplicada.');
|
|
seen.add(key);
|
|
const originKey = JSON.stringify([o.kind, o.originId.trim()]);
|
|
const identity = JSON.stringify([
|
|
o.supplier.trim(),
|
|
o.recognitionDate,
|
|
o.invoiceDate,
|
|
...(config.regime === 'PGC-NIRF'
|
|
? [
|
|
o.formalAgreement?.date ?? '',
|
|
o.formalAgreement?.reference.trim() ?? '',
|
|
]
|
|
: []),
|
|
]);
|
|
if (origins.has(originKey) && origins.get(originKey) !== identity)
|
|
fail(
|
|
'parcelas da mesma operação devem conservar fornecedor, reconhecimento e factura.',
|
|
);
|
|
origins.set(originKey, identity);
|
|
const amount = parse(o.amount, `${label} — valor da operação`);
|
|
if (amount <= 0n)
|
|
fail('indique um valor positivo para a operação.');
|
|
const recognition = o.recognitionDate
|
|
? date(o.recognitionDate)
|
|
: null;
|
|
const invoice = o.invoiceDate ? date(o.invoiceDate) : null;
|
|
const agreement =
|
|
config.regime === 'PGC-NIRF' && o.formalAgreement
|
|
? date(o.formalAgreement.date)
|
|
: null;
|
|
if (
|
|
config.regime === 'PGC-NIRF' &&
|
|
o.formalAgreement &&
|
|
(!agreement || !o.formalAgreement.reference.trim())
|
|
)
|
|
fail(
|
|
'acordo formal exige data válida e referência identificada da mesma operação; não basta orçamento ou encomenda.',
|
|
);
|
|
if (o.recognitionDate && !recognition)
|
|
fail('data de reconhecimento inválida.');
|
|
if (o.invoiceDate && !invoice) fail('data de factura inválida.');
|
|
if (recognition && recognition < start)
|
|
fail(
|
|
'saldos anteriores não podem ser individualizados por inferência; use apenas operações novas do plano.',
|
|
);
|
|
if (recognition && index(recognition) < periods)
|
|
sums[o.kind][index(recognition)] += amount;
|
|
const ids = new Set<string>();
|
|
const events = o.events
|
|
.map((e, order) => {
|
|
if (!e.id.trim() || ids.has(e.id.trim()))
|
|
fail('identifique cada movimento sem duplicações.');
|
|
ids.add(e.id.trim());
|
|
const when = date(e.date);
|
|
if (!when || when < start)
|
|
fail(
|
|
'data de movimento insuficiente, inválida ou anterior ao plano.',
|
|
);
|
|
const value = parse(
|
|
e.amount,
|
|
`${label} — ${advanceEventLabels[e.kind]}`,
|
|
);
|
|
if (value <= 0n)
|
|
fail('os movimentos devem ter montantes positivos.');
|
|
return { ...e, value, when: when!, order };
|
|
})
|
|
.sort(
|
|
(a, b) =>
|
|
a.when.getTime() - b.when.getTime() ||
|
|
a.order - b.order,
|
|
);
|
|
let advance = 0n,
|
|
obligation = 0n,
|
|
isRecognized = false,
|
|
eventIndex = 0;
|
|
const audit: {
|
|
id: string;
|
|
kind: AdvanceEventKind;
|
|
date: string;
|
|
amount: string;
|
|
outsideHorizon: boolean;
|
|
advance: string;
|
|
obligation: string;
|
|
netDue: string;
|
|
applicationBasis?: {
|
|
kind: 'invoice' | 'formal_agreement';
|
|
date: string;
|
|
reference: string;
|
|
};
|
|
}[] = [];
|
|
const process = (e: (typeof events)[number]) => {
|
|
if (!isRecognized && recognition && recognition <= e.when) {
|
|
obligation = amount;
|
|
isRecognized = true;
|
|
}
|
|
const m = index(e.when);
|
|
const inside = m >= 0 && m < periods;
|
|
let applicationBasis:
|
|
| {
|
|
kind: 'invoice' | 'formal_agreement';
|
|
date: string;
|
|
reference: string;
|
|
}
|
|
| undefined;
|
|
if (e.kind === 'advance') {
|
|
if (isRecognized)
|
|
fail(
|
|
'pagamento após reconhecimento deve ser remanescente, não novo adiantamento.',
|
|
);
|
|
advance += e.value;
|
|
if (inside) {
|
|
payments[o.kind][m] += e.value;
|
|
paid[m] += e.value;
|
|
}
|
|
} else if (e.kind === 'apply') {
|
|
const hasInvoice = !!invoice && invoice <= e.when;
|
|
const hasAgreement = !!agreement && agreement <= e.when;
|
|
if (!isRecognized || (!hasInvoice && !hasAgreement))
|
|
fail(
|
|
config.regime === 'PGC-NIRF'
|
|
? 'aplicação exige reconhecimento e factura ou acordo formal correspondente já datado e identificado, sem antecipar datas.'
|
|
: 'aplicação exige reconhecimento e factura correspondente, sem antecipar datas.',
|
|
);
|
|
if (config.regime === 'PGC-NIRF')
|
|
applicationBasis = hasInvoice
|
|
? {
|
|
kind: 'invoice',
|
|
date: o.invoiceDate,
|
|
reference: o.originId + '/' + o.parcelId,
|
|
}
|
|
: {
|
|
kind: 'formal_agreement',
|
|
date: o.formalAgreement!.date,
|
|
reference: o.formalAgreement!.reference,
|
|
};
|
|
if (e.value > advance || e.value > obligation)
|
|
fail(
|
|
'aplicação excede o saldo da mesma parcela ou a obrigação reconhecida.',
|
|
);
|
|
advance -= e.value;
|
|
obligation -= e.value;
|
|
if (inside) applied[m] += e.value;
|
|
} else if (e.kind === 'refund') {
|
|
if (e.value > advance)
|
|
fail(
|
|
'devolução excede o adiantamento não utilizado da mesma parcela.',
|
|
);
|
|
advance -= e.value;
|
|
if (inside) refunds[m] += e.value;
|
|
} else {
|
|
const netDue =
|
|
obligation > advance ? obligation - advance : 0n;
|
|
if (!isRecognized || !invoice || invoice > e.when)
|
|
fail(
|
|
'pagamento do remanescente exige reconhecimento e factura.',
|
|
);
|
|
if (e.value > netDue)
|
|
fail(
|
|
'pagamento excede o líquido por liquidar; não volte a pagar o adiantamento associado.',
|
|
);
|
|
obligation -= e.value;
|
|
if (inside) {
|
|
payments[o.kind][m] += e.value;
|
|
settled[m] += e.value;
|
|
}
|
|
}
|
|
audit.push({
|
|
id: e.id,
|
|
kind: e.kind,
|
|
date: e.date,
|
|
amount: money(e.value),
|
|
outsideHorizon: !inside,
|
|
advance: money(advance),
|
|
obligation: money(obligation),
|
|
netDue: money(
|
|
obligation > advance ? obligation - advance : 0n,
|
|
),
|
|
...(applicationBasis ? { applicationBasis } : {}),
|
|
});
|
|
};
|
|
const monthly = [];
|
|
for (let m = 0; m < periods; m++) {
|
|
const boundary = new Date(Date.UTC(year, m + 1, 1));
|
|
while (
|
|
eventIndex < events.length &&
|
|
events[eventIndex].when < boundary
|
|
)
|
|
process(events[eventIndex++]);
|
|
if (!isRecognized && recognition && recognition < boundary) {
|
|
obligation = amount;
|
|
isRecognized = true;
|
|
}
|
|
const netDue = obligation > advance ? obligation - advance : 0n;
|
|
balances[m].advance += advance;
|
|
balances[m].obligation += obligation;
|
|
balances[m].netDue += netDue;
|
|
monthly.push({
|
|
month: m + 1,
|
|
advance: money(advance),
|
|
obligation: money(obligation),
|
|
netDue: money(netDue),
|
|
recognized: isRecognized,
|
|
...(config.regime === 'PGC-NIRF'
|
|
? {
|
|
documentaryStatus: !isRecognized
|
|
? 'not_recognized'
|
|
: invoice && invoice < boundary
|
|
? 'invoice'
|
|
: agreement && agreement < boundary
|
|
? 'formal_agreement'
|
|
: 'pending_documentation',
|
|
}
|
|
: {}),
|
|
});
|
|
}
|
|
// Validate future events as well; they never leak into the last month of cash.
|
|
while (eventIndex < events.length) process(events[eventIndex++]);
|
|
return {
|
|
originId: o.originId,
|
|
parcelId: o.parcelId,
|
|
supplier: o.supplier,
|
|
kind: o.kind,
|
|
amount: money(amount),
|
|
recognitionDate: o.recognitionDate,
|
|
invoiceDate: o.invoiceDate,
|
|
...(config.regime === 'PGC-NIRF' && o.formalAgreement
|
|
? { formalAgreement: o.formalAgreement }
|
|
: {}),
|
|
recognitionOutsideHorizon: !recognition || recognition >= end,
|
|
monthly,
|
|
events: audit,
|
|
};
|
|
});
|
|
for (const kind of ['purchases', 'services'] as const) {
|
|
if (!config[kind]) continue;
|
|
for (let m = 0; m < periods; m++) {
|
|
if (
|
|
recognized[kind][m] === null ||
|
|
sums[kind][m] !== recognized[kind][m]
|
|
)
|
|
throw Error(
|
|
`Adiantamentos — ${advanceLabels[kind]}, mês ${m + 1}: distribua exactamente o reconhecimento económico por operações/parcelas, sem repetir valores nem converter dados desconhecidos em zero.`,
|
|
);
|
|
}
|
|
}
|
|
return {
|
|
payments,
|
|
refunds,
|
|
operations,
|
|
monthly: balances.map((b, i) => ({
|
|
month: i + 1,
|
|
advance: money(b.advance),
|
|
obligation: money(b.obligation),
|
|
netDue: money(b.netDue),
|
|
paid: money(paid[i]),
|
|
applied: money(applied[i]),
|
|
refunded: money(refunds[i]),
|
|
settled: money(settled[i]),
|
|
})),
|
|
};
|
|
}
|