Start scoped IRPC L5 withholding workflow with document and payment reuse

This commit is contained in:
2026-10-25 18:45:04 +02:00
parent 5c0cb25cea
commit da0d8abb47
19 changed files with 964 additions and 4 deletions
@@ -1,3 +1,4 @@
import {SimulationIrpcWithholdings} from '@/components/simulation-irpc-withholdings';
import {SimulationIspcResiduals} from '@/components/simulation-ispc-residuals';
import {SimulationIspcWithholding} from '@/components/simulation-ispc-withholding';
import {SimulationIspcQuarter} from '@/components/simulation-ispc-quarter';
@@ -3509,6 +3510,7 @@ export function SimulationForm() {
{(current.id === 'financial' || current.id === 'tax') && <SimulationIspcQuarter draft={draft} onChange={change} />}
{(current.id === 'financial' || current.id === 'tax') && <SimulationIspcWithholding draft={draft} onChange={change} />}
{(current.id === 'financial' || current.id === 'tax') && <SimulationIspcResiduals draft={draft} onChange={change} />}
{(current.id === 'financial' || current.id === 'tax') && <SimulationIrpcWithholdings draft={draft} onChange={change} />}
{(current.id === 'financial' || current.id === 'tax') && <SimulationMonthlyIva draft={draft} busy={isCalculating} onCalculate={runSimulation} onChange={change} />}
{current.id === 'financial' &&
(draft.detail_level === 'advanced' ||
@@ -0,0 +1,23 @@
import {useState} from 'react';
import {irpcBook,saveIrpcBook,reuseIrpcSources,irpcSources,newIrpcRow,recordIrpc,irpcKinds,irpcReportRows,irpcPreparationHtml,type IrpcBook,type IrpcRow,type IrpcEvent,type IrpcPayment} from '@/lib/irpc-withholdings';
export function SimulationIrpcWithholdings({draft,onChange}:{draft:Record<string,unknown>;onChange:(field:string,value:string)=>void}){
const[error,setError]=useState('');if(draft.fiscal_component!=='irpc'&&draft.fiscal_component!=='withholding')return null;
try{const book=irpcBook(draft),sources=irpcSources(draft),save=(b:IrpcBook)=>{try{onChange('modelo_a_snapshot',saveIrpcBook(draft,b));setError('');}catch(e){setError(String(e));}},change=(id:string,p:Partial<IrpcRow>)=>save({...book,rows:book.rows.map(r=>r.id===id?{...r,...p}:r)}),uid=()=>crypto.randomUUID();
const field=(r:IrpcRow,k:keyof IrpcRow,label:string,type='text')=><label className="block">{label}<input className="block rounded border p-2" type={type} value={String(r[k]??'')} onChange={e=>change(r.id,{[k]:e.target.value})}/></label>;
const select=(r:IrpcRow,k:keyof IrpcRow,label:string,options:Array<[string,string]>)=><label className="block">{label}<select className="block rounded border p-2" value={String(r[k]??'')} onChange={e=>change(r.id,{[k]:e.target.value})}>{options.map(([v,l])=><option key={v} value={v}>{l}</option>)}</select></label>;
const yn:Array<[string,string]>=[['','Por esclarecer'],['yes','Sim'],['no','Não']];
const eventLabels:Array<[IrpcEvent['kind'],string]>=[['cost','Reconhecimento do custo'],['payment','Pagamento do rendimento'],['maturity','Vencimento, ainda que presumido'],['availability','Colocação à disposição'],['liquidation','Liquidação'],['quantification','Apuramento do quantitativo']];
const paymentChange=(id:string,p:Partial<IrpcPayment>)=>save({...book,payments:book.payments.map(v=>v.id===id?{...v,...p}:v)});
return<section aria-label="Retenções de IRPC" className="space-y-4 rounded border p-4"><h4>IRPC — retenções e preparação documental</h4><p>Reutilize documentos e contrapartes existentes. Classifique o rendimento e o evento aplicável:facturar,pagar e reconhecer o custo são factos distintos. Este incremento calcula10% nos casos digitais/moeda electrónica não residentes,não imputáveis aEP,documentados abaixo. Outros enquadramentos ficam visíveis e indeterminados,sem bloquear estes casos.</p>{error&&<p role="alert">{error}</p>}
<button type="button" className="rounded border p-2" onClick={()=>{try{save(reuseIrpcSources(draft,book));}catch(e){setError(String(e));}}}>Reutilizar contrapartes e documentos existentes</button><button type="button" className="rounded border p-2" onClick={()=>save({...book,rows:[...book.rows,newIrpcRow(uid())]})}>Acrescentar rendimento IRPC</button>
{book.rows.map(r=><fieldset key={r.id} className="space-y-3 rounded border p-3"><legend>{r.description||r.documentRef||'Rendimento por identificar'}</legend>{r.source&&<p>Origem:{r.source.id}. Entradas deliberadamente editadas são conservadas. {sources.find(s=>s.id===r.source!.id)?.key!==r.source.key&&<><strong>Origem alterada ou indisponível.</strong>{sources.find(s=>s.id===r.source!.id)&&<><span> Base actual:{r.base};base na origem:{sources.find(s=>s.id===r.source!.id)?.amount||'desconhecida'};documento actual:{r.documentRef};origem:{sources.find(s=>s.id===r.source!.id)?.documentRef||'desconhecido'}.</span><button type="button" className="rounded border p-2" onClick={()=>{const s=sources.find(s=>s.id===r.source!.id)!;if(window.confirm('Confirma a reconciliação da origem indicada, conservando as entradas deliberadas e os resultados anteriores no histórico?'))change(r.id,{source:{...r.source!,key:s.key}});}}>Conservar edições e reconciliar origem</button></>}</>}</p>}
<div className="grid gap-3 md:grid-cols-2">{select(r,'direction','Perspectiva',[['paid','Rendimento pago — retenção a entregar'],['received','Rendimento recebido — retenção sofrida']])}{field(r,'counterparty','Contraparte')}{field(r,'documentRef','Documento / operação / linha distinta')}{field(r,'description','Descrição')}{select(r,'origin','Origem',[['projected','Projecção com pressupostos'],['effective','Factos documentados']])}{select(r,'kind','Natureza do rendimento',irpcKinds)}{field(r,'base','Base do rendimento, separada do IVA')}{field(r,'currency','Moeda da base')}{select(r,'recipientIrpc','Titular sujeito a IRPC neste rendimento',yn)}{select(r,'payerIrpc','Devedor sujeito a IRPC',yn)}{select(r,'residence','Residência do titular',[['','Por esclarecer'],['resident','Residente'],['nonresident','Não residente']])}{r.residence==='nonresident'&&<>{select(r,'permanentEstablishment','Existe estabelecimento estável em Moçambique',yn)}{r.permanentEstablishment==='yes'&&select(r,'attributable','Rendimento imputável ao estabelecimento',yn)}</>}{select(r,'mozambique','Rendimento obtido em Moçambique, conforme qualificação legal',yn)}{field(r,'qualificationRef','Suporte / pressuposto da qualificação, residência e incidência')}{select(r,'specialRelief','Convenção, isenção ou dispensa aplicável',[['','Por esclarecer'],['none','Não invocada neste caso qualificado'],['claimed','Invocada — correspondência específica necessária']])}{r.specialRelief==='claimed'&&field(r,'reliefRef','Artigo, condições, período e prova invocados')}</div>
<h5>Eventos aplicáveis — artigo67(5), versão2026</h5>{r.events.map((e,n)=><div key={n} className="grid gap-2 md:grid-cols-3"><label>Evento<select value={e.kind} onChange={ev=>change(r.id,{events:r.events.map((v,j)=>j===n?{...v,kind:ev.target.value as IrpcEvent['kind']}:v)})}>{eventLabels.map(([k,l])=><option key={k} value={k}>{l}</option>)}</select></label><label>Data<input type="date" value={e.date} onChange={ev=>change(r.id,{events:r.events.map((v,j)=>j===n?{...v,date:ev.target.value}:v)})}/></label><label>Suporte / pressuposto<input value={e.reference} onChange={ev=>change(r.id,{events:r.events.map((v,j)=>j===n?{...v,reference:ev.target.value}:v)})}/></label></div>)}<button type="button" onClick={()=>change(r.id,{events:[...r.events,{kind:'cost',date:'',reference:''}]})}>Acrescentar evento aplicável</button>{select(r,'eventsComplete','Todos os eventos aplicáveis identificados, incluindo custo quando aplicável',yn)}
{select(r,'settlement','Reconciliação da entrega / prova de retenção sofrida',[['','Por esclarecer'],['none','Ainda sem entrega / prova'],['complete','Pagamentos / provas associados completos']])}{field(r,'settlementRef','Referência da situação declarada')}
{r.allocations.map((a,n)=><div key={n}><label>Pagamento / prova existente<select value={a.paymentId} onChange={e=>change(r.id,{allocations:r.allocations.map((v,j)=>j===n?{...v,paymentId:e.target.value}:v)})}><option value="">Seleccione</option>{book.payments.map(p=><option key={p.id} value={p.id}>{p.reference} — {p.amount} {p.currency} — {p.kind}</option>)}</select></label><label>Parcela usada<input value={a.amount} onChange={e=>change(r.id,{allocations:r.allocations.map((v,j)=>j===n?{...v,amount:e.target.value}:v)})}/></label></div>)}{r.settlement==='complete'&&<button type="button" onClick={()=>change(r.id,{allocations:[...r.allocations,{paymentId:'',amount:''}]})}>Associar pagamento/prova existente</button>}
</fieldset>)}
<h5>Pagamentos e comprovativos reutilizáveis neste livro</h5><p>Uma referência é registada uma vez e repartida entre rendimentos sem exceder o montante. Pagamento ao fornecedor não é entrega à AT; pagamentos de IVA conservam o seu vínculo anterior e não são automaticamente usados em IRPC.</p>{book.payments.map(p=><fieldset key={p.id} className="grid gap-2 rounded border p-2 md:grid-cols-3"><label>Natureza<select value={p.kind} onChange={e=>paymentChange(p.id,{kind:e.target.value as IrpcPayment['kind']})}><option value="remittance">Entrega IRPC à AT</option><option value="withholding_proof">Comprovativo de retenção sofrida</option><option value="beneficiary">Pagamento ao beneficiário</option></select></label>{(['reference','date','amount','currency']as const).map(k=><label key={k}>{({reference:'Referência',date:'Data',amount:'Montante',currency:'Moeda'})[k]}<input type={k==='date'?'date':'text'} value={p[k]} onChange={e=>paymentChange(p.id,{[k]:e.target.value})}/></label>)}</fieldset>)}<button type="button" onClick={()=>save({...book,payments:[...book.payments,{id:uid(),kind:'remittance',reference:'',date:'',amount:'',currency:'MZN'}]})}>Registar pagamento/prova para reutilização</button>
<div className="space-x-3"><button type="button" className="rounded border p-2" onClick={()=>{try{save(recordIrpc(draft,book));}catch(e){setError(String(e));}}}>Calcular e guardar retenções IRPC</button><button type="button" className="rounded border p-2" onClick={()=>{try{const html=irpcPreparationHtml(draft),u=URL.createObjectURL(new Blob([html],{type:'text/html;charset=utf-8'})),a=document.createElement('a');a.href=u;a.download='IRPC-L5-preparacao.html';a.click();URL.revokeObjectURL(u);setError('');}catch(e){setError(String(e));}}}>Exportar preparação IRPC</button></div>
{irpcReportRows(draft).map((r,n)=><p key={n}><strong>{r[1]}</strong>: {r[2]}<small className="block">{r[3]}</small></p>)}<p>Formalidades externas:MRFTA19/39 e guia M/39 preservados. CER/rubricas digitais e remissão67(7)→62(6) por corresponder. Exportar não submete nem obtém aceitação AT. L5 continua aberto;ISPC e IRPS conservam os seus limites anteriores.</p></section>;
}catch(e){return<p role="alert">{String(e)}</p>;}
}
+80
View File
@@ -0,0 +1,80 @@
import {acquisitionBook,acquisitionScope} from './iva-acquisitions.ts';
import {salesBook} from './iva-operations.ts';
import {closureFingerprint} from './iva-closure.ts';
import {addFractions,decimalFraction,fraction,fractionPresentation,subtractFractions,type FiscalFraction} from './fiscal-rational.ts';
export const irpcWithholdingVersion='irpc-L5/1';
export const irpcWithholdingSource='Lei12/2025,BR248/2025,PDF19/p2180(19):arts5(5/7),20(2)c,62(5)a/b e67(5/7);CIRPC Lei34/2007 arts2,67(3),68,PDF18–19/p768(72–73). Art67(7)remete62(6),enquanto taxa nova consta62(5):divergência formal preservada,sem renumerar o original. MRFTA19/39AT,p1–2. Código2002 revogado não usado. Outros regimes/taxas dependem da correspondência específica,sem zero presumido.';
type Choice=''|'yes'|'no';
export type IrpcKind=''|'digital_goods'|'digital_services'|'emoney_commission'|'royalty'|'equipment'|'rent'|'capital'|'services'|'other';
export const irpcKinds:Array<[IrpcKind,string]>=[['','Por identificar'],['digital_goods','Transmissão de bens digitais'],['digital_services','Prestação de serviços digitais'],['emoney_commission','Comissão de agente de moeda electrónica'],['royalty','Propriedade intelectual/industrial'],['equipment','Uso de equipamento'],['rent','Rendimento predial'],['capital','Aplicação de capitais'],['services','Outras prestações/intermediação'],['other','Outro enquadramento']];
export type IrpcEvent={kind:'cost'|'payment'|'maturity'|'availability'|'liquidation'|'quantification';date:string;reference:string};
export type IrpcPayment={id:string;kind:'beneficiary'|'remittance'|'withholding_proof';reference:string;date:string;amount:string;currency:string};
export type IrpcRow={id:string;direction:'paid'|'received';counterparty:string;documentRef:string;description:string;base:string;currency:string;origin:'projected'|'effective';kind:IrpcKind;recipientIrpc:Choice;payerIrpc:Choice;residence:''|'resident'|'nonresident';permanentEstablishment:Choice;attributable:Choice;mozambique:Choice;qualificationRef:string;specialRelief:''|'none'|'claimed';reliefRef:string;eventsComplete:Choice;events:IrpcEvent[];settlement:''|'none'|'complete';settlementRef:string;allocations:Array<{paymentId:string;amount:string}>;source?:{id:string;key:string;fingerprint:string};};
export type IrpcResult={id:string;status:'calculated'|'indeterminate'|'outside_scope';reason:string;period:string;eventDate:string;nature:'definitive'|'on_account'|null;rate:number|null;base:FiscalFraction|null;tax:FiscalFraction|null;settled:FiscalFraction|null;outstanding:FiscalFraction|null;direction:IrpcRow['direction']};
export type IrpcBook={version:1;rows:IrpcRow[];payments:IrpcPayment[];result?:{version:string;key:string;calculatedAt:string;inputs:IrpcRow[];payments:IrpcPayment[];rows:IrpcResult[]};history?:Array<NonNullable<IrpcBook['result']>>};
export const newIrpcRow=(id:string):IrpcRow=>({id,direction:'paid',counterparty:'',documentRef:'',description:'',base:'',currency:'MZN',origin:'projected',kind:'',recipientIrpc:'',payerIrpc:'',residence:'',permanentEstablishment:'',attributable:'',mozambique:'',qualificationRef:'',specialRelief:'',reliefRef:'',eventsComplete:'',events:[],settlement:'',settlementRef:'',allocations:[]});
function store(d:Record<string,unknown>){const s=JSON.parse(String(d.modelo_a_snapshot||'{"version":1,"books":{}}'));if(s.version!==1||!s.books||typeof s.books!=='object'||Array.isArray(s.books))throw Error('Livros fiscais não recuperáveis;originais preservados.');return s;}
function map(d:Record<string,unknown>):Record<string,IrpcBook>{const m=store(d).irpcWithholdings;if(m===undefined)return{};if(!m||typeof m!=='object'||Array.isArray(m))throw Error('Mapa IRPC não recuperável;originais preservados.');return m;}
function validate(b:IrpcBook){
if(!b||b.version!==1||!Array.isArray(b.rows)||!Array.isArray(b.payments)||b.history!==undefined&&!Array.isArray(b.history))throw Error('Livro IRPC não recuperável.');
for(const r of b.rows){const template=newIrpcRow('');if(!r||Object.keys(template).filter(k=>typeof template[k as keyof IrpcRow]==='string').some(k=>typeof r[k as keyof IrpcRow]!=='string')||!['paid','received'].includes(r.direction)||!['projected','effective'].includes(r.origin)||!irpcKinds.some(([k])=>k===r.kind)||!['','resident','nonresident'].includes(r.residence)||!['','none','claimed'].includes(r.specialRelief)||!['','none','complete'].includes(r.settlement)||['recipientIrpc','payerIrpc','permanentEstablishment','attributable','mozambique','eventsComplete'].some(k=>!['','yes','no'].includes(r[k as keyof IrpcRow]as string))||!Array.isArray(r.events)||!Array.isArray(r.allocations)||r.events.some(e=>!e||!['cost','payment','maturity','availability','liquidation','quantification'].includes(e.kind)||typeof e.date!=='string'||typeof e.reference!=='string')||r.allocations.some(a=>!a||typeof a.paymentId!=='string'||typeof a.amount!=='string')||r.source!==undefined&&(!r.source||!['id','key','fingerprint'].every(k=>typeof r.source![k as keyof NonNullable<IrpcRow['source']>]==='string')))throw Error('Entradas IRPC não recuperáveis;sem apagar ou repor vazios.');}
for(const p of b.payments)if(!p||!['id','reference','date','amount','currency'].every(k=>typeof p[k as keyof IrpcPayment]==='string')||!['beneficiary','remittance','withholding_proof'].includes(p.kind))throw Error('Pagamento IRPC inválido;originais preservados.');
if(b.result&&(!Array.isArray(b.result.rows)||!Array.isArray(b.result.inputs)||typeof b.result.key!=='string'||b.result.version!==irpcWithholdingVersion))throw Error('Resultado IRPC não recuperável.');
if(b.payments.some((p,i)=>p.reference.trim()&&b.payments.some((q,j)=>i!==j&&q.kind===p.kind&&q.reference.trim()===p.reference.trim()&&q.date===p.date&&q.currency===p.currency)))throw Error('Pagamento/prova já registado:reutilize a referência existente em vez de duplicar.');
if(new Set(b.rows.map(r=>r.id)).size!==b.rows.length||new Set(b.payments.map(p=>p.id)).size!==b.payments.length)throw Error('Identificadores IRPC repetidos.');
}
export function irpcBook(d:Record<string,unknown>):IrpcBook{const b=map(d)[acquisitionScope(d)]??{version:1,rows:[],payments:[]};validate(b);return b;}
export function saveIrpcBook(d:Record<string,unknown>,b:IrpcBook):string{validate(b);return JSON.stringify({...store(d),irpcWithholdings:{...map(d),[acquisitionScope(d)]:b}});}
export function irpcSources(d:Record<string,unknown>){return[
...acquisitionBook(d).rows.map(r=>({id:'acquisition:'+r.id,key:closureFingerprint(r),counterparty:r.supplier,documentRef:r.documentRef+(r.documentLine?' / linha '+r.documentLine:''),description:r.description,amount:r.net,currency:acquisitionBook(d).currency,direction:'paid' as const,origin:r.origin})),
...salesBook(d).rows.map(r=>({id:'sale:'+r.id,key:closureFingerprint(r),counterparty:'',documentRef:r.evidence,description:r.description,amount:r.basis==='net'?r.amount:'',currency:r.sourceCurrency,direction:'received' as const,origin:'projected' as const})),
];}
export function reuseIrpcSources(d:Record<string,unknown>,b:IrpcBook):IrpcBook{validate(b);const rows=[...b.rows];for(const s of irpcSources(d))if(!rows.some(r=>r.source?.id===s.id)){const r={...newIrpcRow('irpc:'+s.id),counterparty:s.counterparty,documentRef:s.documentRef,description:s.description,base:s.amount,currency:s.currency,direction:s.direction,origin:s.origin};rows.push({...r,source:{id:s.id,key:s.key,fingerprint:closureFingerprint(r)}});}return{...b,rows};}
function sourceIssue(d:Record<string,unknown>,r:IrpcRow){if(!r.source)return'';const s=irpcSources(d).find(s=>s.id===r.source!.id);return !s?'Operação de origem não está disponível neste contexto;vínculo e edições conservados.':s.key!==r.source.key?'Documento/operação de origem alterado;compare o histórico e reconcilie a divergência antes de calcular.':'';}
const date=(s:string)=>/^20\d{2}-(0[1-9]|1[0-2])-\d{2}$/.test(s)&&!Number.isNaN(Date.parse(s))&&new Date(s).toISOString().slice(0,10)===s;
const positive=(f:FiscalFraction)=>BigInt(f.numerator)>0n;
export function evaluateIrpc(d:Record<string,unknown>,r:IrpcRow):IrpcResult{
const v:IrpcResult={id:r.id,status:'indeterminate',reason:'Identifique o rendimento e os intervenientes.',period:'',eventDate:'',nature:null,rate:null,base:null,tax:null,settled:null,outstanding:null,direction:r.direction};
const issue=sourceIssue(d,r);if(issue)return{...v,reason:issue};
if(r.recipientIrpc==='no')return{...v,status:'outside_scope',reason:'Titular fora de IRPC;sem converter em IRPS ou em isenção.'};
if(!r.counterparty.trim()||!r.documentRef.trim()||r.recipientIrpc!=='yes'||r.payerIrpc!=='yes'||!r.residence||!r.kind||!r.qualificationRef.trim())return{...v,reason:'Faltam contraparte,documento,qualificação do rendimento,titular IRPC,devedor IRPC ou residência. A via devedor IRPS exige âmbito próprio.'};
if(r.currency!=='MZN')return{...v,reason:'Base em moeda diferente de MZN: falta conversão documentada com data,taxa e fonte;não relabelar nem usar taxa actual.'};
if(r.mozambique!=='yes')return{...v,reason:'Falta correspondência territorial aos arts5/67;ser estrangeiro não resolve incidência nem isenção.'};
if(r.specialRelief!=='none')return{...v,reason:'Convenção,isenção ou dispensa invocada/desconhecida:identificar artigo,período,condições e prova;sem taxa reduzida ou zero automáticos.'};
if(!r.eventsComplete||r.eventsComplete!=='yes'||!r.events.length||r.events.some(e=>!date(e.date)||!e.reference.trim()))return{...v,reason:'Identifique os eventos aplicáveis67(5),incluindo reconhecimento do custo,e confirme a sua completude com suporte;uma factura ou pagamento isolado não fixa o momento.'};
v.eventDate=r.events.map(e=>e.date).sort()[0];v.period=v.eventDate.slice(0,7);
if(!v.eventDate.startsWith('2026-'))return{...v,reason:'Primeiro evento aplicável fora de2026;corresponder versão/período próprio,sem deslocar para o pagamento posterior.'};
try{v.base=decimalFraction(r.base);}catch{return{...v,reason:'Base do rendimento necessária,em decimal MZN separado do IVA;desconhecido não é zero.'};}
if(!['digital_goods','digital_services','emoney_commission'].includes(r.kind))return{...v,reason:'Rendimento preservado paraL5:confrontar arts62/67/68 e alterações20/2009,4/2012,19/2013,20/2022. O exemplar2002 não suporta uma taxa2026;normal/especial não presumidos.'};
if(r.residence==='nonresident'&&r.permanentEstablishment==='no')v.nature='definitive';
else if(r.residence==='nonresident'&&r.permanentEstablishment==='yes'&&r.attributable==='no')v.nature='definitive';
else return{...v,reason:'Para residente ou rendimento imputável aEP,corresponder concretamente a taxa62(5) com as dispensas68,em especial68(d),antes da liquidação. EP desconhecido permanece indeterminado;90dias/serviço digital não criam ausência deEP automática.'};
v.rate=10;v.tax=fraction(BigInt(v.base.numerator),BigInt(v.base.denominator)*10n);v.status='calculated';v.reason='Taxa10%62(5) sobre o rendimento identificado;retenção definitiva67(3) no recorte não residente/não imputável aEP. Qualificação e eventos documentados ou pressupostos expressos;procedimento67(7)/remissão62(6) e CER permanecem separados. Não é IVA nem crédito anual automático.';return v;
}
function sharedPayments(d:Record<string,unknown>,b:IrpcBook){const used=b.payments.filter(p=>b.rows.some(r=>r.allocations.some(a=>a.paymentId===p.id)));return Object.entries(map(d)).filter(([ctx])=>ctx!==acquisitionScope(d)).flatMap(([ctx,other])=>{validate(other);const payments=other.payments.filter(q=>used.some(p=>p.reference.trim()===q.reference.trim()&&p.date===q.date&&p.currency===q.currency&&p.kind===q.kind));return payments.length?[[ctx,payments,other.rows.flatMap(r=>r.allocations.filter(a=>payments.some(p=>p.id===a.paymentId)))]]:[];});}
function key(d:Record<string,unknown>,b:IrpcBook){return JSON.stringify([irpcWithholdingVersion,acquisitionScope(d),b.rows,b.payments,b.rows.map(r=>sourceIssue(d,r)),sharedPayments(d,b)]);}
export function irpcCurrent(d:Record<string,unknown>,b:IrpcBook){return !!b.result&&b.result.key===key(d,b);}
export function recordIrpc(d:Record<string,unknown>,b:IrpcBook,now=new Date().toISOString()):IrpcBook{
validate(b);const rows=b.rows.map(r=>evaluateIrpc(d,r));const allocations=new Map<string,FiscalFraction[]>();
const fail=(i:number,reason:string)=>{rows[i]={...rows[i],status:'indeterminate',reason,settled:null,outstanding:null};};
b.rows.forEach((r,i)=>{
if(rows[i].status!=='calculated')return;
if(r.settlement==='none'&&r.allocations.length){fail(i,'Ausência de entrega/prova contradiz pagamentos associados;conserve e reconcilie.');return;}
if(!r.settlement||!r.settlementRef.trim()){rows[i].reason+=' Entrega à AT/retenção sofrida ainda não reconciliada;não presumir zero pago.';return;}
const parts:FiscalFraction[]=[];const seen=new Set<string>();
for(const a of r.allocations){const p=b.payments.find(p=>p.id===a.paymentId);try{
if(!p||seen.has(p.id)||p.currency!=='MZN'||!date(p.date)||p.date<rows[i].eventDate||!p.reference.trim()||p.kind!==(r.direction==='paid'?'remittance':'withholding_proof'))throw Error();
seen.add(p.id);const amount=decimalFraction(a.amount);decimalFraction(p.amount);parts.push(amount);allocations.set(p.id,[...(allocations.get(p.id)??[]),amount]);
}catch{fail(i,'Pagamento/prova ausente,incoerente,repetido ou de outra natureza:pagamento ao fornecedor e imposto IVA não são entrega IRPC.');return;}}
const settled=addFractions(parts);if(positive(subtractFractions(settled,rows[i].tax!))){fail(i,'Valor associado excede a retenção calculada;reconcilie excesso sem gerar crédito automático.');return;}
rows[i].settled=settled;rows[i].outstanding=subtractFractions(rows[i].tax!,settled);
});
for(const [id,parts]of allocations){const p=b.payments.find(p=>p.id===id)!;let excess=false;try{const elsewhere:FiscalFraction[]=[];for(const [ctx,other]of Object.entries(map(d))){if(ctx===acquisitionScope(d))continue;validate(other);for(const q of other.payments.filter(q=>q.reference.trim()===p.reference.trim()&&q.date===p.date&&q.kind===p.kind&&q.currency===p.currency)){if(q.amount!==p.amount)throw Error('Montantes divergentes');for(const r of other.rows)for(const a of r.allocations.filter(a=>a.paymentId===q.id))elsewhere.push(decimalFraction(a.amount));}}excess=positive(subtractFractions(addFractions([...parts,...elsewhere]),decimalFraction(p.amount)));}catch{excess=true;}if(excess)b.rows.forEach((r,i)=>{if(r.allocations.some(a=>a.paymentId===id))fail(i,'Mesmo pagamento utilizado além do montante disponível;reparta sem duplicação.');});}
// An identical source document/income cannot become a second tax just by adding a row.
b.rows.forEach((r,i)=>{if(b.rows.some((s,j)=>j!==i&&(r.source&&s.source?.id===r.source.id||r.documentRef.trim()&&s.documentRef.trim()===r.documentRef.trim()&&s.counterparty.trim()===r.counterparty.trim()&&s.direction===r.direction))){fail(i,'Documento/rendimento repetido neste livro;identifique parcelas próprias antes de somar,sem duplicação.');}});
return{...b,history:b.result?[...(b.history??[]),structuredClone(b.result)]:b.history,result:{version:irpcWithholdingVersion,key:key(d,b),calculatedAt:now,inputs:structuredClone(b.rows),payments:structuredClone(b.payments),rows}};
}
const amount=(v:FiscalFraction|null)=>v?fractionPresentation(v).decimal+' MZN':'Indeterminado';
export function irpcReportRows(d:Record<string,unknown>):Array<[string,string,string,string]>{try{const b=irpcBook(d),r=b.result;if(!r)return[];return r.rows.map(v=>{const i=r.inputs.find(i=>i.id===v.id)!;return['IRPC — retenções',`${i.documentRef} — ${i.counterparty}`,`${v.status};${i.direction==='paid'?'retida a entregar':'sofrida'};base:${amount(v.base)};taxa:${v.rate??'por corresponder'}%;retenção:${amount(v.tax)};entrega/prova:${amount(v.settled)};saldo:${amount(v.outstanding)};${v.reason}`,`${acquisitionScope(d)};${i.origin};${v.period};evento:${v.eventDate};${v.nature??'natureza por determinar'};${irpcCurrent(d,b)?'Entradas correspondentes':'Histórico;entradas/origem divergentes'};${r.calculatedAt};${irpcWithholdingSource}`];});}catch(e){return[['IRPC — retenções','Livro não recuperável',String(e),'Originais e histórico preservados.']];}}
export function irpcPreparationHtml(d:Record<string,unknown>):string{const b=irpcBook(d);if(!b.result||!irpcCurrent(d,b))throw Error('Calcule e guarde as entradas actuais antes de preparar.');const esc=(v:unknown)=>String(v).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]!));return'<!doctype html><html lang="pt"><meta charset="utf-8"><title>IRPC — preparação das retenções</title><body><h1>Preparação IRPC — L5</h1><p>Mapa de trabalho;sem submissão,recepção ou aceitação AT. MRFTA19/39:quadro1 retenção;quadro2 mês/ano único por declaração;quadro7 base/taxa/imposto. CER e correspondência das rubricas digitais/moeda electrónica por esclarecer;67(7)remete62(6),mas taxa nova em62(5). Não preencher assinatura ou uso dos serviços. Não consolidar períodos diferentes nem transformar retenções sofridas em imposto a entregar.</p>'+irpcReportRows(d).map(r=>'<section><h2>'+esc(r[1])+'</h2><p>'+esc(r[2])+'</p><small>'+esc(r[3])+'</small></section>').join('')+'<p>Instruções do exemplar:prazo nominal dia20 do mês seguinte à dedução,sem ajuste de calendário/prorrogação ou procedimento2026 presumidos. Juros não calculados. GuiaM/39 anterior preservada,sem actualizar remissões do original.</p></body></html>';}
+2
View File
@@ -1,3 +1,4 @@
import {irpcReportRows} from './irpc-withholdings.ts';
import {ispcResidualReportRows} from './ispc-residuals.ts';
import {ispcWithholdingReportRows} from './ispc-withholding.ts';
import {ispcQuarterReportRows} from './ispc-quarter.ts';
@@ -693,6 +694,7 @@ export function buildProjectDossierRows(
rows.push(...ispcQuarterReportRows(draft));
rows.push(...ispcWithholdingReportRows(draft));
rows.push(...ispcResidualReportRows(draft));
rows.push(...irpcReportRows(draft));
rows.push(...fiscalCalculationGapReportRows(draft));
rows.push(...l3FormPreparationReportRows(draft));
const operationRows = salesReportRows(draft);