Files
Investidor-V2/resources/js/lib/supplier-advances.ts
T

341 lines
14 KiB
TypeScript

export type AdvanceKind = 'purchases' | 'services';
export type AdvanceEventKind = 'advance' | 'apply' | 'refund' | 'settle';
export type SupplierAdvanceOperation = {
originId: string;
parcelId: string;
supplier: string;
kind: AdvanceKind;
amount: string;
recognitionDate: string;
invoiceDate: string;
ordinaryContract: boolean;
events: {
id: string;
kind: AdvanceEventKind;
date: string;
amount: string;
}[];
};
export type SupplierAdvances = {
regime: '' | 'PGC-PE';
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',
};
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'].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' &&
[
'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 (config.regime !== 'PGC-PE')
throw Error(
'Adiantamentos: seleccione explicitamente PGC-PE. Outros regimes não estão automatizados.',
);
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,
]);
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;
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;
}[] = [];
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;
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') {
if (!isRecognized || !invoice || invoice > e.when)
fail(
'aplicação exige reconhecimento e factura correspondente, sem antecipar datas.',
);
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,
),
});
};
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,
});
}
// 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,
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]),
})),
};
}