Implement Tempo FX selection and offer request decision workflow in QA
This commit is contained in:
@@ -1,9 +1,10 @@
|
||||
import {selectFx,fxSelectionKey,fxTempoSource,type FxSelection} from './iva-fx-selection.ts';
|
||||
import {acquisitionScope,readAcquisitionStore} from './iva-acquisitions.ts';
|
||||
import {convertCents as convertScaledAmount} from './business-financial-plan.ts';
|
||||
export const currencyEventVersion='currency-events/1';
|
||||
export const currencyEventSource='CIVA Lei13/2016,7(1)–(7),PDF8/p1426(266);8,PDF9/p1426(267);15(8),PDF14/p1426(272).Lei22/2022 eLei10/2025 não alteram7/8,15(8)mantido.RIVA21/2008PDF4:regra histórica5dias úteis,não prazo automático vigente;usar prazo e disposição aplicáveis identificados. P104:Lei2/2006 obtida,106(5)conferido;regra taxa/data ainda por demonstrar;conversão apenas cenário condicionado,sem base fiscal confirmada.';
|
||||
export const currencyEventSource='CIVA Lei13/2016,7(1)–(7),PDF8/p1426(266);8,PDF9/p1426(267);15(8),PDF14/p1426(272).Lei22/2022 eLei10/2025 não alteram7/8,15(8)mantido.RIVA21/2008PDF4:regra histórica5dias úteis,não prazo automático vigente;usar prazo e disposição aplicáveis identificados. P104:orientação operacional da Tempo25/10/2026 compra/venda/médiaBM conforme natureza e perspectiva;data de submissão indicada;excepções fiscais identificadas. Cenários históricos permanecem condicionados;sem base/IVA/dedução automaticamente activados.';
|
||||
export const currencyEventTreatments=[
|
||||
{id:'foreign_scenario',branch:'P104',label:'Moeda estrangeira — cenário condicionado'},
|
||||
{id:'foreign_scenario',branch:'P104',label:'Moeda estrangeira — selecção operacional / cenário histórico'},
|
||||
{id:'goods_available',branch:'P131',label:'Bens postos à disposição7(1)a'},
|
||||
{id:'goods_transport',branch:'P131',label:'Início do transporte7(2)'},
|
||||
{id:'goods_installation',branch:'P131',label:'Instalação/montagem concluída7(2)'},
|
||||
@@ -20,7 +21,7 @@ export const currencyEventTreatments=[
|
||||
{id:'advance_payment',branch:'P132',label:'Pagamento anterior à factura8c'},
|
||||
] as const;
|
||||
type Choice=''|'yes'|'no';
|
||||
export type CurrencyEventRow={id:string;treatment:string;description:string;period:string;origin:'projected'|'effective';operationRef:string;documentRef:string;documentDate:string;scope:string;evidence:string;eventDate:string;eventRef:string;otherDate:string;reviewDate:string;factsConfirmed:Choice;invoiceRequired:Choice;invoiceState:''|'issued'|'not_issued';invoiceDate:string;invoiceRef:string;legalDeadline:string;deadlineRef:string;paymentState:''|'none'|'received';paymentDate:string;paymentRef:string;amount:string;paymentAmount:string;currency:string;sourceCurrency:string;fxRate:string;fxDate:string;fxSource:string;fxRuleRef:string;fxDirection:''|'mzn_per_unit'|'units_per_mzn';};
|
||||
export type CurrencyEventRow={fxSelection?:FxSelection;id:string;treatment:string;description:string;period:string;origin:'projected'|'effective';operationRef:string;documentRef:string;documentDate:string;scope:string;evidence:string;eventDate:string;eventRef:string;otherDate:string;reviewDate:string;factsConfirmed:Choice;invoiceRequired:Choice;invoiceState:''|'issued'|'not_issued';invoiceDate:string;invoiceRef:string;legalDeadline:string;deadlineRef:string;paymentState:''|'none'|'received';paymentDate:string;paymentRef:string;amount:string;paymentAmount:string;currency:string;sourceCurrency:string;fxRate:string;fxDate:string;fxSource:string;fxRuleRef:string;fxDirection:''|'mzn_per_unit'|'units_per_mzn';};
|
||||
type DueEvent={date:string;amount:string|null;reason:string};
|
||||
type LineResult={id:string;status:'determined'|'not_applicable'|'indeterminate'|'conditional';eventDate:string|null;dueEvents:DueEvent[];remainingPending:boolean;scenarioAmount:string|null;baseAmount:null;vat:null;rate:null;reason:string};
|
||||
export type CurrencyEventCalculation={version:string;revision:number;calculatedAt:string;opportunity:string;location:string;sourceKey:string;source:string;inputs:CurrencyEventRow[];rows:LineResult[]};
|
||||
@@ -47,6 +48,14 @@ export function evaluateCurrencyEvent(row:CurrencyEventRow):LineResult{
|
||||
const amount=decimal(row.amount),fx=decimal(row.fxRate,8);
|
||||
if(row.currency!=='MZN'||!['USD','EUR','ZAR','GBP','CNY','BRL','JPY','CHF','AUD','CAD'].includes(row.sourceCurrency)||amount===null||fx===null||fx===0n||date(row.fxDate)===null||![row.fxSource,row.fxRuleRef].every(v=>!!v.trim())||!['mzn_per_unit','units_per_mzn'].includes(row.fxDirection))return stop('Indique moeda original,valor,taxa positiva,direcção,data,fonte e regra/pressuposto expresso.Sem substituir moeda original porMZN ou reutilizar taxa de apresentação como regra fiscal.');
|
||||
result.scenarioAmount=money(row.fxDirection==='mzn_per_unit'?convertScaledAmount(amount,fx,100000000n):(amount*100000000n+fx/2n)/fx);
|
||||
if(row.fxSelection){
|
||||
const converted=result.scenarioAmount;result.scenarioAmount=null;
|
||||
try{const selected=selectFx(row.fxSelection),applied=row.fxSelection.applied;if(!applied||applied.selectionKey!==fxSelectionKey(row.fxSelection)||applied.rate!==selected.rate||applied.date!==selected.date||row.sourceCurrency!==row.fxSelection.sourceCurrency||row.fxDirection!==row.fxSelection.direction||row.fxRate!==selected.rate||row.fxDate!==selected.date||row.fxSource!==applied.source)return stop('Selecção cambial alterada ou não aplicada explicitamente;histórico preservado,sem recálculo automático.');
|
||||
result.scenarioAmount=converted;
|
||||
const columnLabel=({buy:'Compra',sell:'Venda',mean:'Média de referência BM',exception:'Excepção fiscal identificada'} as Record<string,string>)[selected.column];
|
||||
return stop(`Conversão operacional segundo a orientação da Tempo de25/10/2026:${row.amount} ${row.sourceCurrency} → ${result.scenarioAmount} MZN. Coluna ${columnLabel};taxa ${row.fxRate};${row.fxDirection==='mzn_per_unit'?'MZN por unidade da moeda original':'unidades da moeda original por MZN'};data ${row.fxDate};boletim ${row.fxSelection.bulletinRef}. Sem cálculo de IVA ou dedução e sem alteração dos livros fiscais anteriores.`,'determined');
|
||||
}catch(error){return stop(String(error));}
|
||||
}
|
||||
return stop(`P104:cenário condicionado=${result.scenarioAmount}MZN,origem${row.sourceCurrency},taxa${row.fxRate},${row.fxDirection},data${row.fxDate}. CotejoLei2/2006 concluido:106(5)nao define taxa/data;regra complementar15(8) ainda por demonstrar;referência indicada é pressuposto,não validação da taxa legal.Base fiscal permanece indeterminada.Sem IVA ou activação nos livros anteriores.`,`conditional`);
|
||||
}
|
||||
const review=date(row.reviewDate),event=date(row.eventDate);if(review===null||!row.eventRef.trim())return stop('Identifique data de conferência e documento/âmbito do evento específico.');
|
||||
@@ -91,4 +100,4 @@ export function evaluateCurrencyEvent(row:CurrencyEventRow):LineResult{
|
||||
function key(draft:Record<string,unknown>,book:CurrencyEventBook):string{return JSON.stringify({version:currencyEventVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},rows:book.rows});}
|
||||
export function currencyEventCurrent(draft:Record<string,unknown>,book:CurrencyEventBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
|
||||
export function recordCurrencyEvents(draft:Record<string,unknown>,book:CurrencyEventBook):CurrencyEventBook{if(!book.rows.length||new Set(book.rows.map(r=>r.id)).size!==book.rows.length)throw new Error('Indique operações com identidades distintas;originais conservados.');const result:CurrencyEventCalculation={version:currencyEventVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:currencyEventSource,inputs:structuredClone(book.rows),rows:book.rows.map(evaluateCurrencyEvent)};const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveCurrencyEventBook(draft,next);return next;}
|
||||
export function currencyEventReportRows(draft:Record<string,unknown>):Array<[string,string,string,string]>{try{const book=currencyEventBook(draft),r=book.result;if(!r)return[];return r.inputs.map((row,i)=>['IVA mensal',`${currencyEventTreatments.find(t=>t.id===row.treatment)?.branch??'Evento'} — ${row.period} — ${row.id}`,`${row.description};${r.rows[i].reason};facto gerador:${r.rows[i].eventDate??'Indeterminado/não apurado'};parcelas:${r.rows[i].dueEvents.map(p=>p.date+': '+(p.amount??'Montante indeterminado')+' '+row.currency+' ('+p.reason+')').join('; ')||'Nenhuma apurada'};restante pendente:${r.rows[i].status==='indeterminate'?'Indeterminado':r.rows[i].remainingPending?'Sim':'Não'};cenário condicionado:${r.rows[i].scenarioAmount??'Indeterminado'};base/IVA:Indeterminados`,`${r.opportunity};${r.location};${currencyEventCurrent(draft,book)?'Resultado actual':'Entradas alteradas;resultado histórico conservado'};versão${r.revision};${r.calculatedAt};${r.source};${row.origin};documento ${row.documentRef},${row.documentDate};ambito ${row.scope};${row.treatment==='foreign_scenario'?`origem ${row.amount} ${row.sourceCurrency};taxa ${row.fxRate},${row.fxDirection},${row.fxDate};fonte ${row.fxSource};pressuposto ${row.fxRuleRef}`:`evento ${row.eventDate},${row.eventRef};outra data ${row.otherDate};conferencia ${row.reviewDate};factura ${row.invoiceRequired},${row.invoiceState},${row.invoiceDate},${row.invoiceRef};prazo ${row.legalDeadline},${row.deadlineRef};recebimento ${row.paymentState},${row.paymentDate},${row.paymentAmount},${row.paymentRef};total do ambito ${row.amount} ${row.currency}`};fundamento ${row.evidence};sem nova dedução/campo11/IVA ou activação cambial nos livros anteriores.`]);}catch{return[['IVA mensal','Moeda/eventos','Dados não recuperáveis','Originais preservados;sem substituição porzero.']];}}
|
||||
export function currencyEventReportRows(draft:Record<string,unknown>):Array<[string,string,string,string]>{try{const book=currencyEventBook(draft),r=book.result;if(!r)return[];return r.inputs.map((row,i):[string,string,string,string]=>{if(row.treatment==='foreign_scenario'&&row.fxSelection)return['IVA mensal',`P104 — ${row.period} — ${row.id}`,`${row.description};${r.rows[i].reason};Original:${row.amount} ${row.sourceCurrency};Convertido:${r.rows[i].scenarioAmount??'Indeterminado'} MZN`,`${r.opportunity};${currencyEventCurrent(draft,book)?'Resultado actual':'Entradas alteradas;resultado histórico conservado'};versão${r.revision};${r.calculatedAt};documento:${row.documentRef},${row.documentDate};âmbito:${row.scope};boletim:${row.fxSelection.bulletinRef};fonte:${row.fxSelection.source};natureza:${row.fxSelection.nature};perspectiva:${row.fxSelection.bulletinPerspective};relação:${row.fxSelection.relation};taxa:${row.fxRate};data:${row.fxDate};sentido:${row.fxDirection};regra/excepção:${row.fxRuleRef};sem base/IVA/dedução activados.`];return['IVA mensal',`${currencyEventTreatments.find(t=>t.id===row.treatment)?.branch??'Evento'} — ${row.period} — ${row.id}`,`${row.description};${r.rows[i].reason};facto gerador:${r.rows[i].eventDate??'Indeterminado/não apurado'};parcelas:${r.rows[i].dueEvents.map(p=>p.date+': '+(p.amount??'Montante indeterminado')+' '+row.currency+' ('+p.reason+')').join('; ')||'Nenhuma apurada'};restante pendente:${r.rows[i].status==='indeterminate'?'Indeterminado':r.rows[i].remainingPending?'Sim':'Não'};${row.treatment==='foreign_scenario'&&r.rows[i].status==='determined'?'conversão operacional':'cenário condicionado'}:${r.rows[i].scenarioAmount??'Indeterminado'};base/IVA:Indeterminados`,`${r.opportunity};${r.location};${currencyEventCurrent(draft,book)?'Resultado actual':'Entradas alteradas;resultado histórico conservado'};versão${r.revision};${r.calculatedAt};${r.source};${row.origin};documento ${row.documentRef},${row.documentDate};ambito ${row.scope};${row.treatment==='foreign_scenario'?`origem ${row.amount} ${row.sourceCurrency};taxa ${row.fxRate},${row.fxDirection},${row.fxDate};fonte ${row.fxSource};pressuposto ${row.fxRuleRef}`:`evento ${row.eventDate},${row.eventRef};outra data ${row.otherDate};conferencia ${row.reviewDate};factura ${row.invoiceRequired},${row.invoiceState},${row.invoiceDate},${row.invoiceRef};prazo ${row.legalDeadline},${row.deadlineRef};recebimento ${row.paymentState},${row.paymentDate},${row.paymentAmount},${row.paymentRef};total do ambito ${row.amount} ${row.currency}`};fundamento ${row.evidence};sem nova dedução/campo11/IVA ou activação cambial nos livros anteriores.`];});}catch{return[['IVA mensal','Moeda/eventos','Dados não recuperáveis','Originais preservados;sem substituição porzero.']];}}
|
||||
|
||||
Reference in New Issue
Block a user