Prepare L3 C substitutions with frozen predecessor and payment reconciliation in QA
This commit is contained in:
@@ -34,7 +34,8 @@ function inputKey(r:ClosureInput){return closureFingerprint(r);}
|
||||
function financialKey(r:ClosureInput){const{payments:_,...rest}=r;return closureFingerprint(rest);}
|
||||
function otherUses(d:Record<string,unknown>,b:ClosureBook):ClosureInput[]{return[...b.rows,...Object.entries(maps(d)).filter(([id])=>id!==scope(d)).flatMap(([,book])=>{validate(book);return book.rows.filter(r=>r.origin==='effective');})];}
|
||||
function duplicateCredits(d:Record<string,unknown>,b:ClosureBook):Set<string>{const uses=new Map<string,number>();for(const r of otherUses(d,b))for(const c of r.credits){const k=creditIdentity(r,c);uses.set(k,(uses.get(k)??0)+1);}return new Set([...uses].filter(([,n])=>n>1).map(([k])=>k));}
|
||||
function bookKey(d:Record<string,unknown>,b:ClosureBook){const sources=closureSources(d);return closureFingerprint([b.rows,b.rows.map(r=>sources.some(s=>JSON.stringify(s)===JSON.stringify(r.source))),otherUses(d,b).map(r=>[normalize(r.entityRef),r.origin,r.period,r.credits.map(c=>creditIdentity(r,c)),r.payments.map(p=>paymentIdentity(r,p))])]);}
|
||||
function substitutionPayments(d:Record<string,unknown>):string[]{const m=store(d).ivaSubstitutions as Record<string,{result?:{inputs:Array<{id:string;prior:{entityRef:string;origin:string}|null;payments:ClosurePayment[]}>;rows:Array<{id:string;status:string;paid:FiscalFraction|null}>};history?:Array<{inputs:Array<{id:string;prior:{entityRef:string;origin:string}|null;payments:ClosurePayment[]}>;rows:Array<{id:string;status:string;paid:FiscalFraction|null}>}>}>|undefined;return Object.entries(m??{}).flatMap(([id,b])=>[...(b.history??[]),...(b.result?[b.result]:[])].flatMap(c=>c.inputs.filter(r=>r.prior&&(id===scope(d)||r.prior.origin==='effective')&&c.rows.some(v=>v.id===r.id&&v.status==='determined'&&v.paid)).flatMap(r=>r.payments.map(p=>closureFingerprint([normalize(r.prior!.entityRef),r.prior!.origin,normalize(p.reference)])))));}
|
||||
function bookKey(d:Record<string,unknown>,b:ClosureBook){const sources=closureSources(d);const values:unknown[]=[b.rows,b.rows.map(r=>sources.some(s=>JSON.stringify(s)===JSON.stringify(r.source))),otherUses(d,b).map(r=>[normalize(r.entityRef),r.origin,r.period,r.credits.map(c=>creditIdentity(r,c)),r.payments.map(p=>paymentIdentity(r,p))])];const reserved=substitutionPayments(d),conflicts=b.rows.flatMap(r=>r.payments.map(p=>paymentIdentity(r,p))).filter(k=>reserved.includes(k));if(conflicts.length)values.push(conflicts);return closureFingerprint(values);}
|
||||
export function closureCurrent(d:Record<string,unknown>,b:ClosureBook):boolean{return !!b.result&&b.result.key===bookKey(d,b)&&b.result.rows.length===b.rows.length&&b.rows.every(r=>b.result!.rows.filter(x=>x.id===r.id&&x.inputKey===inputKey(r)).length===1);}
|
||||
export function adoptPreviousCredit(c:ClosureCredit,previous:ClosureResult):ClosureCredit{if(previous.status!=='determined'||!previous.fields['26'])throw Error('Fecho anterior indeterminado;sem crédito presumido.');return{...c,kind:'previous',period:previous.period,reference:`Fecho ${previous.id}`,previousId:previous.id,carryKey:previous.carryKey,amount:fractionPresentation(previous.fields['26']).decimal,date:''};}
|
||||
export function recordClosure(d:Record<string,unknown>,b:ClosureBook,now=new Date().toISOString()):ClosureBook{
|
||||
@@ -81,7 +82,7 @@ export function recordClosure(d:Record<string,unknown>,b:ClosureBook,now=new Dat
|
||||
if(!fields['24']){stop('Juros23 por identificar:indique montante documentado/pressuposto ou inexistência expressa com motivo;sem taxa presumida.');continue;}
|
||||
r.status='determined';r.carryKey=closureFingerprint([r.id,r.financialKey,fields['26'],scope(d)]);
|
||||
const payments:FiscalFraction[]=[];
|
||||
for(const p of row.payments){if(!p.reference.trim()||!validDate(p.date)||(puses.get(paymentIdentity(row,p))??0)>1){invalid='Pagamento sem referência/data ou repetido noutro período/declaração;conserve o documento e reconcilie a imputação.';break;}try{payments.push(decimalFraction(p.amount));}catch{invalid='Montante de pagamento por identificar;sem baixa presumida.';break;}}
|
||||
for(const p of row.payments){if(!p.reference.trim()||!validDate(p.date)||(puses.get(paymentIdentity(row,p))??0)>1||substitutionPayments(d).includes(paymentIdentity(row,p))){invalid='Pagamento sem referência/data ou repetido noutro período/declaração;conserve o documento e reconcilie a imputação.';break;}try{payments.push(decimalFraction(p.amount));}catch{invalid='Montante de pagamento por identificar;sem baixa presumida.';break;}}
|
||||
if(invalid){stop(invalid);continue;}
|
||||
r.paid=addFractions(payments);r.outstanding=positiveFraction(subtractFractions(fields['24'],r.paid));r.overpayment=positiveFraction(subtractFractions(r.paid,fields['24']));
|
||||
r.status='determined';r.carryKey=closureFingerprint([r.id,r.financialKey,fields['26'],scope(d)]);r.reason='Saldo calculado, pagamentos registados e crédito transportado distintos. Pagamento não altera22/25/26;excedente pago não cria crédito20 sem comunicação.21 não aplicável à primeira declaração;27zero pela opção expressa de reporte integral. '+(row.origin==='projected'?'Pressupostos de simulação,sem declaração ou pagamento efectuados pelo portal.':'Dados efectivos declarados;registo não certifica cobrança nem submissãoAT.');results.push(r);
|
||||
|
||||
Reference in New Issue
Block a user