export type DayTermKind = 'sales' | 'purchases' | 'services'; export type DayTermOperation = { originId: string; parcelId: string; kind: DayTermKind; month: number; amount: string; recognitionBasis: 'monthly' | 'date' | 'unknown'; recognitionDate: string; originBasis: 'recognition' | 'date' | 'unknown'; originDate: string; termDays: string; }; export type DayTerms = { sales: boolean; purchases: boolean; services: boolean; operations: DayTermOperation[]; }; export const dayTermLabels: Record = { sales: 'Vendas e prestações', purchases: 'Mercadorias recebidas', services: 'Serviços adquiridos reconhecidos', }; export function isDayTerms(value: unknown): value is DayTerms { if (!value || typeof value !== 'object') return false; const c = value as DayTerms; return ( ['sales', 'purchases', 'services'].every( (k) => typeof c[k as DayTermKind] === 'boolean', ) && Array.isArray(c.operations) && c.operations.length <= 240 && c.operations.every( (o) => o && Object.hasOwn(dayTermLabels, o.kind) && Number.isSafeInteger(o.month) && o.month >= 1 && o.month <= 60 && [ 'originId', 'parcelId', 'amount', 'recognitionDate', 'originDate', 'termDays', ].every( (k) => typeof o[k as keyof DayTermOperation] === 'string' && String(o[k as keyof DayTermOperation]).length <= 160, ) && ['monthly', 'date', 'unknown'].includes(o.recognitionBasis) && ['recognition', 'date', 'unknown'].includes(o.originBasis), ) ); } function civilDate(value: string): Date | null { if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return null; const d = new Date(value + 'T00:00:00.000Z'); return Number.isFinite(d.getTime()) && d.toISOString().slice(0, 10) === value ? d : null; } const iso = (d: Date) => d.toISOString().slice(0, 10); /** Only opted-in channels replace their complete cash agenda. No legacy input is mutated. */ export function buildDayTermSchedule( config: DayTerms, year: number, periods: number, recognized: Record, parseAmount: (value: string, label: string) => bigint, ) { if (!isDayTerms(config)) throw new Error( 'Prazos em dias: estrutura inválida. Reveja operações e parcelas.', ); if (!Number.isSafeInteger(year) || year < 1900 || year > 9993) throw new Error( 'Prazos em dias — Ano inicial: indique o ano do relatório entre 1900 e 9993.', ); const schedules: Record = { sales: Array(periods).fill(0n), purchases: Array(periods).fill(0n), services: Array(periods).fill(0n), }; const amounts: Record = { sales: Array(periods).fill(0n), purchases: Array(periods).fill(0n), services: Array(periods).fill(0n), }; const seen = new Set(); const origins = new Map(); const events = config.operations .filter((o) => config[o.kind]) .map((o) => { const label = `Prazos em dias — ${dayTermLabels[o.kind]}, origem ${o.originId || 'por preencher'}, parcela ${o.parcelId || 'por preencher'}`; const fail = (message: string): never => { throw new Error(`${label}: ${message}`); }; if (!o.originId.trim() || !o.parcelId.trim()) fail('preencha a origem e a parcela para impedir duplicações.'); const key = JSON.stringify([ o.kind, o.originId.trim(), o.parcelId.trim(), ]); if (seen.has(key)) fail( 'parcela duplicada; conserve apenas um movimento da mesma origem/parcela.', ); seen.add(key); if (o.month > periods) fail( 'mês de reconhecimento fora do horizonte; reveja o mês ou use a agenda manual.', ); const start = new Date(Date.UTC(year, o.month - 1, 1)); const recognition = o.recognitionBasis === 'monthly' ? new Date(Date.UTC(year, o.month, 0)) : o.recognitionBasis === 'date' ? civilDate(o.recognitionDate) : null; if (!recognition) fail( 'data de reconhecimento insuficiente ou inválida; indique uma data ou escolha explicitamente a aproximação mensal. Operação excluída do cálculo automático.', ); const r = recognition!; if ( r.getUTCFullYear() !== start.getUTCFullYear() || r.getUTCMonth() !== start.getUTCMonth() ) fail( 'data de reconhecimento não pertence ao mês económico indicado; corrija a data ou o mês.', ); const origin = o.originBasis === 'recognition' ? r : o.originBasis === 'date' ? civilDate(o.originDate) : null; if (!origin) fail( 'data de origem do prazo insuficiente ou inválida; indique o evento contratual ou escolha reconhecimento. Operação excluída do cálculo automático.', ); if (o.kind === 'sales' && iso(origin!) !== iso(r)) fail( 'origem do recebimento deve ser a venda/prestação reconhecida; corrija a origem.', ); if (!/^\d+$/.test(o.termDays) || Number(o.termDays) > 365) fail( 'Prazo (dias): indique um inteiro entre 0 e 365; vazio não significa zero.', ); const due = new Date(origin!.getTime()); due.setUTCDate(due.getUTCDate() + Number(o.termDays)); if (due < r) fail( 'vencimento anterior ao reconhecimento: antecipação excluída de F20-A. Use a agenda manual existente; adiantamentos identificados dependem de F20-B.', ); const amount = parseAmount(o.amount, `${label} — Montante`); const originKey = JSON.stringify([o.kind, o.originId.trim()]); const identity = JSON.stringify([ o.month, iso(r), o.recognitionBasis, ]); if (origins.has(originKey) && origins.get(originKey) !== identity) fail( 'parcelas da mesma origem têm reconhecimentos diferentes; confira origem, mês e data.', ); origins.set(originKey, identity); amounts[o.kind][o.month - 1] += amount; const dueMonth = (due.getUTCFullYear() - year) * 12 + due.getUTCMonth() + 1; if (dueMonth <= periods) schedules[o.kind][dueMonth - 1] += amount; return { ...o, amount: amount.toString(), recognition: iso(r), origin: iso(origin!), due: iso(due), dueMonth, approximate: o.recognitionBasis === 'monthly', outsideHorizon: dueMonth > periods, }; }); for (const kind of Object.keys(dayTermLabels) as DayTermKind[]) { if (!config[kind]) continue; for (let i = 0; i < periods; i++) { if (recognized[kind][i] === null) throw new Error( `Prazos em dias — ${dayTermLabels[kind]}, mês ${i + 1}: reconhecimento indeterminado; preencha a agenda económica antes de activar este modo.`, ); if (amounts[kind][i] !== recognized[kind][i]) throw new Error( `Prazos em dias — ${dayTermLabels[kind]}, mês ${i + 1}: a soma dos montantes das origens/parcelas deve coincidir com o valor reconhecido. Corrija a distribuição; não some uma coorte às operações já individualizadas.`, ); } } return { schedules, events }; }