Implement L2 D allocation and provisional proportions with exact totals and frozen history

This commit is contained in:
2026-10-25 13:00:59 +02:00
parent 855ab066c4
commit 2c2a2f2010
12 changed files with 435 additions and 20 deletions
+9 -7
View File
@@ -1,4 +1,5 @@
import type {Acquisition,AcquisitionResult} from './iva-acquisitions.ts';
import type {AcquisitionEligibility} from './iva-acquisition-right.ts';
import {acquisitionScope,readAcquisitionStore} from './iva-acquisitions.ts';
import {linkedOperationRight,linkedBeverageDeductionRight} from './iva-acquisition-right.ts';
import {acquisitionTreatmentIssue} from './iva-acquisition-continuity.ts';
@@ -27,8 +28,8 @@ export function reuseAcquisitionImport(draft:Record<string,unknown>,row:Acquisit
}
export function acquisitionBCSourceKey(draft:Record<string,unknown>,rows:Acquisition[]):string{return rows.some(r=>r.bc)?JSON.stringify({version:acquisitionBCVersion,sources:rows.filter(r=>r.bc?.source).map(r=>acquisitionImportSources(draft).find(s=>s.map===r.bc!.source!.map&&s.row.id===r.bc!.source!.id)?.row??null)}):'';}
function validDate(value:string){const d=new Date(value+'T00:00:00Z');return /^\d{4}-\d{2}-\d{2}$/.test(value)&&Number.isFinite(d.getTime())&&d.toISOString().slice(0,10)===value;}
export function evaluateAcquisitionBC(row:Acquisition,currency:string,registered:Choice,draft:Record<string,unknown>|undefined,raw:AcquisitionResult):AcquisitionResult{
const bc=row.bc!;let right=row.deductionLink&&draft?linkedOperationRight(draft,row.deductionLink):{status:'indeterminate' as const,reason:'Vínculo à operação de destino em falta.',source:acquisitionBCSource};
export function evaluateAcquisitionBC(row:Acquisition,currency:string,registered:Choice,draft:Record<string,unknown>|undefined,raw:AcquisitionResult,partial?:{right:AcquisitionEligibility;noExcludedPayments:Choice}):AcquisitionResult{
const bc=row.bc!;let right=partial?.right??(row.deductionLink&&draft?linkedOperationRight(draft,row.deductionLink):{status:'indeterminate' as const,reason:'Vínculo à operação de destino em falta.',source:acquisitionBCSource});
const stop=(reason:string,status:'eligible'|'no_right'|'indeterminate'='indeterminate',percent?:number):AcquisitionResult=>{
const exact=percent!==undefined&&raw.vat!==null?decimalFraction(raw.vat):null;
const deductibleExact=exact?fraction(BigInt(exact.numerator)*BigInt(percent!),BigInt(exact.denominator)*100n):undefined;
@@ -48,13 +49,14 @@ export function evaluateAcquisitionBC(row:Acquisition,currency:string,registered
if(bc.source){const src=draft?acquisitionImportSources(draft).find(s=>s.map===bc.source!.map&&s.row.id===bc.source!.id):undefined;if(!src||JSON.stringify(src.row)!==bc.source.fingerprint)return stop('OrigemL1 da importação alterada:adopte explicitamente os dados actuais,conservando edições e histórico.');if(['service_in_customs_value','accessory_service_first_destination'].includes(src.row.treatment??''))return stop('Origem é serviço incluído na base aduaneira12(1)(e),não IVA próprio da importação de bens;identifique o bilhete dos bens,sem somar novamente IVA do serviço.');}
if(registered!=='yes')return stop('Enquadramento do adquirente no regime normal por confirmar.');
if(row.allocation==='no_right'||row.integrity==='no'||row.exclusion==='excluded')return stop('Sem direito pela afectação,exclusão expressa ou impedimento18(3–5) declarado.','no_right',0);
if(row.allocation==='mixed')return stop('Afectação parcial/pro rata depende deD;sem dedução integral presumida.');
if(!row.deductionLink||row.deductionLink.scopeConfirmed!=='yes'||!row.deductionLink.allocationRef.trim()||row.allocation!=='taxable_only')return stop('Confirme afectação exclusiva e referência à operação ligada.');
if(bc.expense==='beverages'&&bc.facts.beverageSpecial==='yes'&&bc.beveragePath==='deduction'&&draft)right=linkedBeverageDeductionRight(draft,row.deductionLink,bc.facts.notCoastalFishing==='yes');
if(row.allocation==='mixed'&&!partial)return stop('Afectação parcial/pro rata depende deD;sem dedução integral presumida.');
if(!partial&&(!row.deductionLink||row.deductionLink.scopeConfirmed!=='yes'||!row.deductionLink.allocationRef.trim()||row.allocation!=='taxable_only'))return stop('Confirme afectação exclusiva e referência à operação ligada.');
if(!partial&&bc.expense==='beverages'&&bc.facts.beverageSpecial==='yes'&&bc.beveragePath==='deduction'&&draft&&row.deductionLink)right=linkedBeverageDeductionRight(draft,row.deductionLink,bc.facts.notCoastalFishing==='yes');
if(right.status==='no_right')return stop(right.reason,'no_right',0);
if(right.status!=='eligible')return stop(right.reason);
if(row.deductionLink.noExcludedPayments==='no')return stop('Pagamentos15(6)(c)/19(2) excluídos.','no_right',0);
if(row.deductionLink.noExcludedPayments!=='yes')return stop('Exclusão19(2) por esclarecer.');
const noExcludedPayments=partial?.noExcludedPayments??row.deductionLink?.noExcludedPayments;
if(noExcludedPayments==='no')return stop('Pagamentos15(6)(c)/19(2) excluídos.','no_right',0);
if(noExcludedPayments!=='yes')return stop('Exclusão19(2) por esclarecer.');
if(!validDate(row.documentDate)||row.documentDate.slice(0,7)!==row.period)return stop('Documento e exercício no mesmo mês neste incremento;dedução posterior não presumida.');
if(!row.documentRef.trim()||row.legalDocument!=='yes'||row.held!=='yes'||row.integrity!=='yes')return stop('Referência,forma legal,posse e integridade do documento por completar.');
if(row.domestic==='no'){