Implement Tempo FX selection and offer request decision workflow in QA

This commit is contained in:
2026-10-25 10:54:51 +02:00
parent 8b3ec2b04d
commit 9536eb710b
27 changed files with 406 additions and 21 deletions
@@ -1,10 +1,11 @@
import {SimulationFxSelection} from './simulation-fx-selection';
import {useState} from 'react';
import {currencyEventBook,currencyEventCurrent,currencyEventReportRows,currencyEventSource,currencyEventTreatments,newCurrencyEvent,recordCurrencyEvents,saveCurrencyEventBook,switchCurrencyEvent,type CurrencyEventBook,type CurrencyEventRow} from '@/lib/iva-currency-events';
export function SimulationCurrencyEvents({draft,onChange}:{draft:Record<string,unknown>;onChange:(field:string,value:string)=>void}){
const[error,setError]=useState('');let book:CurrencyEventBook;try{book=currencyEventBook(draft);}catch(e){return<p role="alert">{String(e)}</p>;}
const save=(next:CurrencyEventBook)=>{try{onChange('modelo_a_snapshot',saveCurrencyEventBook(draft,next));setError('');}catch(e){setError(String(e));}};
const change=(id:string,patch:Partial<CurrencyEventRow>)=>save({...book,rows:book.rows.map(r=>r.id===id?{...r,...patch}:r)});
return <details className="rounded border p-3"><summary>Moeda e datas do facto gerador/exigibilidade</summary><p>Facto gerador e exigibilidade são estados separados. Identifique a operação já preparada,sem repetir os seus cálculos. Conversão P104 é apenas cenário condicionado,enquanto a regra fiscal permanece por corresponder.</p><p>{currencyEventSource}</p>{error&&<p role="alert">{error}</p>}
return <details className="rounded border p-3"><summary>Moeda e datas do facto gerador/exigibilidade</summary><p>Facto gerador e exigibilidade são estados separados. Identifique a operação já preparada,sem repetir os seus cálculos. P104 permite a selecção operacional definida pela Tempo;os cenários antigos permanecem condicionados até selecção explícita,sem recálculo de históricos.</p><p>{currencyEventSource}</p>{error&&<p role="alert">{error}</p>}
<button type="button" onClick={()=>save({...book,rows:[...book.rows,newCurrencyEvent(crypto.randomUUID(),String(draft.currency??''))]})}>Acrescentar moeda/evento</button>
{book.rows.map(row=><details key={row.id} className="rounded border p-3"><summary>{row.description||'Operação por identificar'} — {row.period||'mês por indicar'}</summary>
<label>Percurso de moeda/evento<select value={row.treatment} onChange={e=>change(row.id,switchCurrencyEvent(row,e.target.value))}><option value="">Por indicar</option>{currencyEventTreatments.map(t=><option key={t.id} value={t.id}>{t.label}</option>)}</select></label>
@@ -12,8 +13,9 @@ export function SimulationCurrencyEvents({draft,onChange}:{draft:Record<string,u
{([['description','Operação identificada'],['operationRef','Referência da operação existente'],['period','Mês do contexto'],['documentRef','Documento / referência da previsão'],['documentDate','Data do documento'],['scope','Âmbito e parcelas abrangidas'],['evidence','Factos ou pressupostos expressos'],['amount','Montante total do âmbito identificado'],['currency','Moeda do montante / destino da conversão']] as const).map(([field,label])=><label className="block" key={field}>{label}<input value={row[field]} type={field==='period'?'month':field==='documentDate'?'date':'text'} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}
<label>Factos próprios correspondem ao percurso,operação e âmbito<select value={row.factsConfirmed} onChange={e=>change(row.id,{factsConfirmed:e.target.value as CurrencyEventRow['factsConfirmed']})}><option value="">Por esclarecer</option><option value="yes">Sim</option><option value="no">Não</option></select></label>
{row.treatment==='foreign_scenario'?<>
<SimulationFxSelection row={row} onChange={patch=>change(row.id,patch)}/>
{([['sourceCurrency','Moeda original'],['fxRate','Taxa de conversão indicada'],['fxDate','Data efectiva da taxa'],['fxSource','Fonte e exemplar da taxa'],['fxRuleRef','Regra/pressuposto da escolha da taxa e data']] as const).map(([field,label])=><label className="block" key={field}>{label}<input value={row[field]} type={field==='fxDate'?'date':'text'} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}
<label>Direcção da taxa<select value={row.fxDirection} onChange={e=>change(row.id,{fxDirection:e.target.value as CurrencyEventRow['fxDirection']})}><option value="">Por indicar</option><option value="mzn_per_unit">MZN por unidade da moeda original</option><option value="units_per_mzn">Unidades da moeda original por MZN</option></select></label><p>O valor convertido é uma simulação condicionada. Não substitui a base fiscal,nem altera os valores/moedas dos livros anteriores.</p>
<label>Direcção da taxa<select value={row.fxDirection} onChange={e=>change(row.id,{fxDirection:e.target.value as CurrencyEventRow['fxDirection']})}><option value="">Por indicar</option><option value="mzn_per_unit">MZN por unidade da moeda original</option><option value="units_per_mzn">Unidades da moeda original por MZN</option></select></label><p>{row.fxSelection?.applied?'Conversão operacional após selecção explícita da taxa.':'Cenário histórico condicionado;selecção operacional ainda não aplicada.'} Não activa base fiscal,IVA ou dedução,nem altera os livros anteriores.</p>
</>:row.treatment&&<>
{([['eventDate','Data própria do evento escolhido'],['eventRef','Referência e factos do evento7/8'],['reviewDate','Data até à qual os eventos foram conferidos']] as const).filter(([field])=>field!=='eventDate'||!['advance_payment','consignment_deadline'].includes(row.treatment)).map(([field,label])=><label className="block" key={field}>{label}<input value={row[field]} type={field==='eventRef'?'text':'date'} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}
{['consignment_deadline','service_early_charge','contract_effects'].includes(row.treatment)&&<label>{row.treatment==='consignment_deadline'?'Entrega ao destinatário da consignação':row.treatment==='service_early_charge'?'Data de realização do serviço posterior à cobrança/débito':'Disponibilização anterior aos efeitos translativos'}<input type="date" value={row.otherDate} onChange={e=>change(row.id,{otherDate:e.target.value})}/></label>}
@@ -34,6 +36,6 @@ export function SimulationCurrencyEvents({draft,onChange}:{draft:Record<string,u
</>}
<p>Trocar percurso conserva dados ocultos e referências;reveja as confirmações aplicáveis.</p></details>)}
{!!book.rows.length&&<button type="button" onClick={()=>{try{save(recordCurrencyEvents(draft,book));}catch(e){setError(String(e));}}}>Conferir moeda/eventos e guardar versão</button>}
{book.result&&<><p role="status">{currencyEventCurrent(draft,book)?'Resultados correspondentes às entradas guardadas.':'Entradas alteradas;histórico conservado.'} {book.history?.length??0} versões anteriores.P104condicionado,semIVA/base/dedução activados.</p><dl>{currencyEventReportRows(draft).map(([,label,value,origin],i)=><div key={i}><dt>{label}</dt><dd>{value}<small className="block">{origin}</small></dd></div>)}</dl></>}
{book.result&&<><p role="status">{currencyEventCurrent(draft,book)?'Resultados correspondentes às entradas guardadas.':'Entradas alteradas;histórico conservado.'} {book.history?.length??0} versões anteriores.P104 conserva a natureza operacional ou condicionada indicada em cada resultado;semIVA/base/dedução activados.</p><dl>{currencyEventReportRows(draft).map(([,label,value,origin],i)=><div key={i}><dt>{label}</dt><dd>{value}{label.startsWith('P104')?<details><summary>Fonte,âmbito e versão</summary><small className="block">{origin}</small></details>:<small className="block">{origin}</small>}</dd></div>)}</dl></>}
</details>;
}
@@ -0,0 +1,21 @@
import {useState} from 'react';
import type {CurrencyEventRow} from '@/lib/iva-currency-events';
import {emptyFxSelection,selectFx,fxTempoSource,type FxSelection} from '@/lib/iva-fx-selection';
const columnLabels:Record<string,string>={buy:'Compra',sell:'Venda',mean:'Média de referência BM',exception:'Excepção fiscal identificada'};
const directionLabels:Record<string,string>={mzn_per_unit:'MZN por unidade da moeda original',units_per_mzn:'unidades da moeda original por MZN'};
export function SimulationFxSelection({row,onChange}:{row:CurrencyEventRow;onChange:(patch:Partial<CurrencyEventRow>)=>void}){
const[error,setError]=useState(''),[preview,setPreview]=useState<ReturnType<typeof selectFx>|null>(null);const s=row.fxSelection??{...emptyFxSelection(),sourceCurrency:row.sourceCurrency,direction:row.fxDirection};
const edit=(patch:Partial<FxSelection>)=>{setPreview(null);onChange({fxSelection:{...s,...patch}});};
const text=(key:'submissionDate'|'bulletinDate'|'bulletinRef'|'source'|'sourceCurrency'|'bulletinPerspective'|'buy'|'sell'|'mean'|'exceptionRef'|'exceptionScope'|'exceptionDate'|'exceptionRate',label:string)=><label className="block" key={key}>{label}<input value={s[key]} type={key.endsWith('Date')?'date':'text'} onChange={e=>edit({[key]:e.target.value})}/></label>;
return<fieldset className="rounded border p-3"><legend>P104 — selecção da taxa segundo orientação da Tempo</legend><p>{fxTempoSource}</p>
<label>Natureza da operação declarada<select value={s.nature} onChange={e=>edit({nature:e.target.value as FxSelection['nature']})}><option value="">Por indicar</option><option value="purchase">Compra de moeda</option><option value="sale">Venda de moeda</option><option value="commercial">Operação comercial</option></select></label>
{text('submissionDate','Data de submissão indicada')}{text('sourceCurrency','Moeda original já declarada')}{text('bulletinRef','Boletim,edição e série de referência')}{text('source','Fonte do boletim;URL do Banco de Moçambique para operações comerciais')}{text('bulletinDate','Data do boletim')}<label>Emitente identificado do boletim,quando a fonte é um exemplar arquivado<input value={s.issuer??''} onChange={e=>edit({issuer:e.target.value})}/></label>
<label>Sentido da cotação<select value={s.direction} onChange={e=>edit({direction:e.target.value as FxSelection['direction']})}><option value="">Por indicar</option><option value="mzn_per_unit">MZN por unidade da moeda original</option><option value="units_per_mzn">Unidades da moeda original porMZN</option></select></label>
<button type="button" onClick={()=>edit({sourceCurrency:s.sourceCurrency||row.sourceCurrency,direction:s.direction||row.fxDirection,submissionDate:s.submissionDate||row.fxDate,bulletinDate:s.bulletinDate||row.fxDate,source:s.source||row.fxSource})}>Reutilizar moeda,sentido e data já indicados nos campos vazios;conferir a data de submissão</button>
<label>Regra aplicável<select value={s.mode} onChange={e=>edit({mode:e.target.value as FxSelection['mode']})}><option value="general">Procedimento geral da Tempo</option><option value="exception">Excepção fiscal específica identificada</option></select></label>
{s.mode==='exception'?<>{text('exceptionRef','Disposição fiscal que impõe outra data/taxa')}{text('exceptionScope','Âmbito da excepção')}{text('exceptionDate','Data imposta pela disposição')}{text('exceptionRate','Taxa da excepção,com fonte no boletim indicado')}</>:s.nature==='commercial'?text('mean','Coluna Média da série de referênciaBM;sem calcular média própria'):<>{text('bulletinPerspective','Perspectiva de compra/venda indicada no boletim')}
<label>Relação da natureza declarada com a perspectiva do boletim<select value={s.relation} onChange={e=>edit({relation:e.target.value as FxSelection['relation']})}><option value="">Por conferir</option><option value="same">Mesma perspectiva</option><option value="opposite">Perspectiva contrária:compra do cliente corresponde a venda do emitente,ou inversamente</option></select></label>{text('buy','Taxa da coluna Compra do boletim')}{text('sell','Taxa da coluna Venda do boletim')}</>}
{error&&<p role="alert">{error}</p>}<button type="button" onClick={()=>{try{setPreview(selectFx(s));setError('');}catch(e){setError(String(e));}}}>Conferir selecção e impacto</button>
{preview&&<div><p>Coluna:{columnLabels[preview.column]};taxa:{preview.rate};data:{preview.date};sentido:{directionLabels[s.direction]}. Confirmação substitui os campos cambiais desta linha:{row.fxRate||'taxa vazia'} → {preview.rate};{row.fxDate||'data vazia'} → {preview.date};{row.sourceCurrency||'moeda vazia'} → {s.sourceCurrency}. O resultado e os históricos permanecem até usar «Conferir moeda/eventos e guardar versão».</p><button type="button" onClick={()=>{onChange({fxSelection:{...s,applied:preview},sourceCurrency:s.sourceCurrency,fxDirection:s.direction,fxRate:preview.rate,fxDate:preview.date,fxSource:preview.source,fxRuleRef:s.mode==='exception'?s.exceptionRef:fxTempoSource});setPreview(null);}}>Confirmar selecção nesta linha</button></div>}
<p>Não usar taxa de apresentação nem a mais recente como substituto de boletim ausente. Compra/venda são interpretadas pela perspectiva indicada;relação desconhecida fica por esclarecer. Alterações não recalculam versões anteriores.</p></fieldset>;
}
@@ -1,5 +1,6 @@
import { SimulationObjectiveImports } from './simulation-objective-imports';
import { SimulationMiners } from './simulation-miners';
import { SimulationReturnees } from './simulation-returnees';
import { SimulationDigital } from './simulation-digital';
import { SimulationTravel } from './simulation-travel';
import { SimulationTravelEvents } from './simulation-travel-events';
@@ -117,6 +118,7 @@ export function SimulationMonthlyIva({draft, busy, onCalculate, onChange}: {
<SimulationImportExemptions draft={draft} onChange={onChange} />
<SimulationObjectiveImports draft={draft} onChange={onChange} />
<SimulationMiners draft={draft} onChange={onChange} />
<SimulationReturnees draft={draft} onChange={onChange} />
<SimulationPublicAuthorityBase draft={draft} onChange={onChange} />
<SimulationCommissionBase draft={draft} onChange={onChange} />
<SimulationActSaleBase draft={draft} onChange={onChange} />
@@ -1,3 +1,4 @@
import {SimulationOfferWorkflow} from './simulation-offer-workflow';
import { useState } from 'react';
import { newOfferPreparation,offerPreparationBook,offerPreparationSource,offerReusableData,recordOfferPreparations,reuseOfferData,saveOfferPreparationBook,emptyOfferRequest,recordOfferRequest,offerRequestLabels,offerScenarios,type OfferRequest,type OfferPreparation,type OfferPreparationBook } from '@/lib/iva-offer-preparations';
@@ -10,7 +11,7 @@ export function SimulationOfferPreparations({draft,onChange}:{draft:Record<strin
const question=(row:OfferPreparation,key:'nationalInstitution'|'publicSocialInstitution'|'goodsSuitable'|'publicInterestUse'|'mitigation',label:string)=><label className="block" key={key}>{label}<select className="block rounded border p-2" value={row[key]} onChange={e=>change(row.id,{[key]:e.target.value})}><option value="">Por indicar</option><option value="yes">Sim</option><option value="no">Não</option></select></label>;
return <details className="space-y-3 rounded border p-3"><summary>Ofertas a instituições e para calamidades — preparar rascunhos</summary>
<p>Prepare apenas as ofertas relevantes para a oportunidade {String(draft.context_opportunity||'entrada geral')}. Pode guardar dados incompletos e reutilizar referências existentes. A reutilização preenche apenas campos vazios; as suas edições mantêm-se.</p>
<p>O procedimento de aplicação do benefício está em pesquisa. Prepare o pedido e compare o cenário normal com uma hipótese condicionada à isenção. Apresentar o pedido não concede isenção. Estes cenários não alteram a dedução no campo11; os restantes enquadramentos continuam disponíveis.</p>
<p>Procedimento operacional indicado pela Tempo:prepare o pedido escrito,registe a apresentação externa,a decisão com despacho e o formulário aplicável. Antes do deferimento,compare o cenário normal com uma hipótese condicionada. Apresentar o pedido não concede isenção. Estes cenários não alteram a dedução no campo11; os restantes enquadramentos continuam disponíveis.</p>
{error&&<p role="alert">{error}</p>}
<button type="button" className="underline" onClick={()=>run(()=>save({...book,rows:[...book.rows,newOfferPreparation(crypto.randomUUID(),'P084',String(draft.currency??''))]}))}>Preparar oferta a instituição</button>{' '}
<button type="button" className="underline" onClick={()=>run(()=>save({...book,rows:[...book.rows,newOfferPreparation(crypto.randomUUID(),'P085',String(draft.currency??''))]}))}>Preparar oferta para calamidade</button>
@@ -24,7 +25,7 @@ export function SimulationOfferPreparations({draft,onChange}:{draft:Record<strin
{row.branch==='P085'&&<label>Finalidade humanitária da resposta à emergência<textarea className="block w-full rounded border p-2" value={row.humanitarianPurpose??''} onChange={e=>change(row.id,{humanitarianPurpose:e.target.value})}/></label>}
<label>Documentos disponíveis e respectivas referências<textarea className="block w-full rounded border p-2" value={row.availableDocuments??''} onChange={e=>change(row.id,{availableDocuments:e.target.value})}/></label>
{!!row.documentRef&&<button type="button" className="underline" onClick={()=>{const reference=[row.documentRef,row.documentDate].filter(Boolean).join(', ');if(!(row.availableDocuments??'').includes(reference))change(row.id,{availableDocuments:[row.availableDocuments,reference].filter(Boolean).join('\n')});}}>Juntar referência do documento já indicado</button>}
{row.branch==='P084'&&(()=>{const request=row.request??emptyOfferRequest();const edit=(patch:Partial<OfferRequest>)=>change(row.id,{request:{...request,...patch}});return <fieldset className="rounded border p-3"><legend>Pedido e âmbito da decisão</legend>
{(()=>{const request=row.request??emptyOfferRequest();const edit=(patch:Partial<OfferRequest>)=>change(row.id,{request:{...request,...patch}});return <fieldset className="rounded border p-3"><legend>Pedido e âmbito da decisão</legend>
<p>Registe o estado declarado e os elementos disponíveis. Este registo não apresenta um pedido à autoridade nem concede o benefício. Conserve o âmbito exacto de cada decisão, mesmo que cubra apenas parte dos bens ou períodos.</p>
<label>Estado declarado do pedido<select className="block rounded border p-2" value={request.state} onChange={e=>edit({state:e.target.value as OfferRequest['state']})}>{Object.entries(offerRequestLabels).map(([value,label])=><option key={value} value={value}>{label}</option>)}</select></label>
{(['reference','presentedOn','decisionRef','decisionOn','goods','periodFrom','periodTo','conditions'] as const).map((key,index)=><label className="block" key={key}>{['Referência do pedido','Data de apresentação, se disponível','Documento / referência da decisão, se disponível','Data da decisão, se disponível','Bens abrangidos pela decisão','Início do período abrangido','Fim do período abrangido','Condições, limites ou fundamento da decisão'][index]}<input className="block rounded border p-2" type={key==='presentedOn'||key==='decisionOn'?'date':'text'} placeholder={key==='periodFrom'||key==='periodTo'?'AAAA-MM ou AAAA-MM-DD, conforme a decisão':undefined} value={request[key]} onChange={e=>edit({[key]:e.target.value})}/></label>)}
@@ -35,13 +36,14 @@ export function SimulationOfferPreparations({draft,onChange}:{draft:Record<strin
<button type="button" className="rounded border p-2" onClick={()=>run(()=>save({...book,rows:book.rows.map(item=>item.id===row.id?recordOfferRequest(item):item)}))}>Registar estado declarado e âmbito</button>
{(row.requestRecords??[]).map((record,index)=><p key={index}>{offerRequestLabels[record.request.state]} — {record.recordedAt}; bens: {record.request.goods||'por indicar'}; operação: {record.request.operationScope||record.request.operation||'por indicar'}; período: {record.request.periodScope||`${record.request.periodFrom||'por indicar'} a ${record.request.periodTo||'por indicar'}`}; condições: {record.request.conditions||'por indicar'}; decisão: {record.request.decisionRef||'por indicar'}. Este âmbito não se estende automaticamente à restante operação ou oportunidade.</p>)}
</fieldset>;})()}
<SimulationOfferWorkflow row={row} draft={draft} onChange={patch=>change(row.id,patch)}/>
<fieldset className="rounded border p-3"><legend>Cenário normal e cenário condicionado à isenção</legend>
<label>IVA no cenário normal, indicado em documento ou pressuposto<input className="block rounded border p-2" inputMode="decimal" value={row.normalVat??''} onChange={e=>change(row.id,{normalVat:e.target.value})}/></label>
<label>Documento ou pressuposto do IVA normal<input className="block rounded border p-2" value={row.normalVatSource??''} onChange={e=>change(row.id,{normalVatSource:e.target.value})}/></label>
<label>Assumir, apenas para comparar, a hipótese condicionada de isenção<select className="block rounded border p-2" value={row.conditionalAssumption??''} onChange={e=>change(row.id,{conditionalAssumption:e.target.value as ''|'yes'|'no'})}><option value="">Por indicar</option><option value="yes">Sim, como hipótese condicionada</option><option value="no">Não</option></select></label>
{(()=>{const scenarios=offerScenarios(row);return <><table><thead><tr><th>Cenário</th><th>IVA ({row.currency})</th></tr></thead><tbody><tr><td>Normal — valor indicado, sem taxa presumida</td><td>{scenarios.normalVat??'Indeterminado'}</td></tr><tr><td>Condicionado à isenção — hipótese, não concessão</td><td>{scenarios.conditionalVat??'Indeterminado'}</td></tr></tbody></table><p>{scenarios.conditionalReason}</p><p>O cenário condicionado não altera imposto, dedução, totais ou o estado do pedido. O procedimento só será aplicado quando a correspondência regulamentar estiver demonstrada.</p></>;})()}
{(()=>{const scenarios=offerScenarios(row);return <><table><thead><tr><th>Cenário</th><th>IVA ({row.currency})</th></tr></thead><tbody><tr><td>Normal — valor indicado, sem taxa presumida</td><td>{scenarios.normalVat??'Indeterminado'}</td></tr><tr><td>Condicionado à isenção — hipótese, não concessão</td><td>{scenarios.conditionalVat??'Indeterminado'}</td></tr>{scenarios.applied&&<tr><td>Tratamento deferido apenas no âmbito do despacho</td><td>{scenarios.appliedVat}</td></tr>}</tbody></table><p>{scenarios.conditionalReason}</p><p>O cenário condicionado não altera imposto,dedução,totais ou o estado do pedido. O tratamento deferido exige despacho registado e correspondência expressa desta linha ao âmbito;alterar os dados exige nova conferência.</p></>;})()}
</fieldset>
</details>)}
{!!book.rows.length&&<><button type="button" className="rounded border p-2" onClick={()=>run(()=>save(recordOfferPreparations(book)))}>Guardar versão dos rascunhos de ofertas</button><p role="status">{book.saved?'Versão de preparação conservada; alterações seguintes não substituem essa versão.':'Preparação em curso; pode guardar mesmo com informação em falta.'} Benefício não aplicado. {book.history?.length??0} versões anteriores.</p></>}
{!!book.rows.length&&<><button type="button" className="rounded border p-2" onClick={()=>run(()=>save(recordOfferPreparations(book)))}>Guardar versão dos rascunhos de ofertas</button><p role="status">{book.saved?'Versão de preparação conservada; alterações seguintes não substituem essa versão.':'Preparação em curso; pode guardar mesmo com informação em falta.'} Estado e âmbito do tratamento indicados em cada linha. {book.history?.length??0} versões anteriores.</p></>}
</details>;
}
@@ -0,0 +1,35 @@
import {buildOfferPackage} from '@/lib/iva-offer-package';
import {useRef,useState} from 'react';
import {emptyOfferRequest,offerRequestLabels,type OfferPreparation} from '@/lib/iva-offer-preparations';
import {emptyOfferWorkflow,offerWrittenRequest,offerWorkflowSource,offerWorkflowApplied,recordOfferWorkflow,offerAttachmentValid,type OfferAttachment,type OfferWorkflow} from '@/lib/iva-offer-workflow';
export function SimulationOfferWorkflow({row,draft,onChange}:{row:OfferPreparation;draft:Record<string,unknown>;onChange:(patch:Partial<OfferPreparation>)=>void}){
const stageLabels:Record<string,string>={request:'Pedido em preparação',presented:'Pedido apresentado',decision:'Decisão recebida',form:'Formulário preparado'};const latest=useRef(row);latest.current=row;const[notice,setNotice]=useState('');const[error,setError]=useState(''),[busy,setBusy]=useState(false),[documents,setDocuments]=useState<OfferAttachment[]>([]),[draftId,setDraftId]=useState('');const w=row.workflow??emptyOfferWorkflow();
const edit=(patch:Partial<OfferWorkflow>)=>onChange({workflow:{...(latest.current.workflow??emptyOfferWorkflow()),...patch}});
const action=async(fn:()=>void|Promise<void>)=>{setBusy(true);try{await fn();setError('');}catch(e){setError(String(e));}finally{setBusy(false);}};
const current=async()=>{const response=await fetch('/api/v1/simulation-drafts/current',{credentials:'same-origin',cache:'no-store',headers:{Accept:'application/json'}});if(!response.ok)throw Error('Não foi possível localizar a gravação privada.');const data=(await response.json()).data;if(!data?.id)throw Error('Guarde primeiro o rascunho no portal para lhe associar anexos privados.');if(data.economic_snapshot?.context_opportunity!==draft.context_opportunity)throw Error('A gravação actual pertence a outro contexto;guarde este rascunho antes de anexar.');setDraftId(data.id);return data.id as string;};
const list=async()=>{const id=await current(),response=await fetch(`/api/v1/simulation-drafts/${id}/offer-documents`,{credentials:'same-origin',headers:{Accept:'application/json'}});if(response.status===401||response.status===403)throw Error('Autentique-se para anexar ou consultar documentos privados;os dados preparados mantêm-se.');if(!response.ok)throw Error('Não foi possível recuperar anexos privados.');setDocuments((await response.json()).data);};
const attach=async(file:File,field:'requestAttachment'|'decisionAttachment'|'formAttachment')=>{const id=await current(),data=new FormData();data.append('file',file);const csrf=document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.content;const xsrf=document.cookie.split('; ').find(c=>c.startsWith('XSRF-TOKEN='))?.slice(11);const response=await fetch(`/api/v1/simulation-drafts/${id}/offer-documents`,{method:'POST',credentials:'same-origin',headers:{Accept:'application/json',...(csrf?{'X-CSRF-TOKEN':csrf}:{}),...(xsrf?{'X-XSRF-TOKEN':decodeURIComponent(xsrf)}:{})},body:data});if(!response.ok)throw Error(response.status===401?'Autentique-se para guardar anexos privados.':'Anexo não confirmado;rascunho preservado. '+(await response.text()).slice(0,250));const doc=(await response.json()).data;if(!offerAttachmentValid(doc))throw Error('Confirmação do anexo inválida.');edit({[field]:doc});setDocuments(previous=>[...previous.filter(d=>d.id!==doc.id),doc]);};
const download=(blob:Blob,name:string)=>{const url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
const packageForm=async()=>{const result=await buildOfferPackage(latest.current,async(url)=>{const response=await fetch(url,{credentials:'same-origin'});if(!response.ok)throw Error('Anexo conservado;aguarde análise antimalware concluída antes de descarregar o conjunto.');return response.arrayBuffer();});download(new Blob([Uint8Array.from(result.bytes).buffer],{type:'application/zip'}),`${row.branch}-pedido-decisao-formulario.zip`);onChange({workflow:result.row.workflow});setNotice('Conjunto preparado com pedido,elementos do formulário e despacho original conferido porSHA256;descarga iniciada.Submissão à autoridade permanece externa.');};
const text=(field:'recipient'|'writtenRequest'|'decisionIssuer'|'formName'|'formSource'|'formContent'|'submissionReference',label:string)=><label className="block" key={field}>{label}<textarea className="block w-full rounded border p-2" value={w[field]} onChange={e=>edit({[field]:e.target.value})}/></label>;
const attachment=(field:'requestAttachment'|'decisionAttachment'|'formAttachment',label:string)=><fieldset><legend>{label}</legend><label>Reutilizar anexo privado<select value={w[field]?.id??''} onChange={e=>edit({[field]:documents.find(d=>d.id===e.target.value)})}><option value="">Escolher documento existente</option>{documents.map(d=><option key={d.id} value={d.id}>{d.name} — {d.scan}</option>)}</select></label><label>Juntar ficheiro privado<input type="file" accept="application/pdf,text/plain,image/png,image/jpeg" disabled={busy} onChange={e=>{const file=e.target.files?.[0];if(file)void action(()=>attach(file,field));e.target.value='';}}/></label>{w[field]&&<p>{w[field]!.name};SHA256:{w[field]!.sha256};estado da análise na associação:{w[field]!.scan}. Original privado conservado;nenhuma publicação automática.</p>}</fieldset>;
return<fieldset className="rounded border p-3"><legend>Pedido → decisão → formulário com despacho</legend><p>{offerWorkflowSource}</p><p>A submissão ao Ministério das Finanças/AT ocorre fora do InvesteMoz. Pode preparar e guardar informação incompleta. Guardar anexos privados reutiliza a autenticação e a análise antimalware existentes;PDF,texto,PNG/JPEG até10MB é o limite técnico de transferência,não condição do benefício.</p>{error&&<p role="alert">{error}</p>}{notice&&<p role="status">{notice}</p>}
{!row.request&&<button type="button" onClick={()=>onChange({request:emptyOfferRequest(),workflow:w})}>Iniciar acompanhamento do pedido</button>}
{text('recipient','Destinatário do pedido escrito')}{text('writtenRequest','Justificação e elementos adicionais do pedido')}
<button type="button" onClick={()=>download(new Blob([offerWrittenRequest(row,w)],{type:'text/plain;charset=utf-8'}),`${row.branch}-pedido.txt`)}>Preparar pedido escrito com os dados existentes</button>
<button type="button" disabled={busy} onClick={()=>void action(list)}>Recuperar anexos privados desta gravação</button>{draftId&&<p>Anexos associados à gravação privada actual.</p>}{attachment('requestAttachment','Pedido escrito e comprovativo de apresentação,quando disponíveis')}
<button type="button" disabled={busy} onClick={()=>void action(()=>onChange({workflow:recordOfferWorkflow(latest.current,'request').workflow}))}>Registar preparação do pedido</button>
<button type="button" disabled={busy} onClick={()=>void action(()=>onChange({workflow:recordOfferWorkflow(latest.current,'presented').workflow}))}>Registar pedido apresentado fora do portal</button>
{text('decisionIssuer','Entidade emitente do despacho recebido')}{attachment('decisionAttachment','Despacho recebido — original anexo')}
<label>Esta linha está abrangida pelos bens,operação,período e condições do despacho<select value={w.scopeConfirmed} onChange={e=>edit({scopeConfirmed:e.target.value as OfferWorkflow['scopeConfirmed'],scopeKey:undefined})}><option value="">Por conferir</option><option value="yes">Sim,apenas esta linha e âmbito indicado</option><option value="no">Não</option></select></label>
<button type="button" disabled={busy} onClick={()=>void action(()=>onChange({workflow:recordOfferWorkflow(latest.current,'decision').workflow}))}>Registar decisão recebida e âmbito desta linha</button><p role="status">{offerWorkflowApplied(row).reason}</p>
{text('formName','Formulário aplicável:designação/versão')}{text('formSource','Referência que demonstra a aplicabilidade deste formulário')}{text('formContent','Elementos para o formulário,com despacho de isenção anexo')}
<button type="button" onClick={()=>edit({formContent:w.formContent||`${offerWrittenRequest(row,w)}\nDespacho:${row.request?.decisionRef??''};${row.request?.decisionOn??''};emitente:${w.decisionIssuer}\nÂmbito:${row.request?.goods??''};${row.request?.operationScope||row.request?.operation||''};${row.request?.periodScope||`${row.request?.periodFrom??''} a ${row.request?.periodTo??''}`};${row.request?.conditions??''}\nAnexo:${w.decisionAttachment?.name??''};SHA256:${w.decisionAttachment?.sha256??''}`})}>Reutilizar dados e despacho nos campos vazios do formulário</button>
{attachment('formAttachment','Exemplar do formulário preenchido,quando disponível')}
<button type="button" disabled={busy} onClick={()=>void action(()=>onChange({workflow:recordOfferWorkflow(latest.current,'form').workflow}))}>Preparar formulário com despacho associado</button>
<button type="button" disabled={busy} onClick={()=>void action(packageForm)}>Descarregar conjunto do pedido,formulário e despacho</button>
{text('submissionReference','Referência da apresentação externa do formulário,se já ocorreu')}
<p>O ModeloI.1 não é seleccionado automaticamente para estes ramos. O conteúdo preparado só substitui o preenchimento do exemplar quando houver correspondência demonstrada;uma referência em falta não apaga a decisão recebida.</p>
{w.records.map((record,i)=><p key={i}>{record.at} — {stageLabels[record.stage]??record.stage} — {offerRequestLabels[record.request.state]};pedido:{record.request.reference};despacho:{record.request.decisionRef};bens:{record.request.goods};anexo:{record.workflow.decisionAttachment?.name||'não registado'}.</p>)}
</fieldset>;
}
@@ -0,0 +1,26 @@
import {useState} from 'react';
import {returneeBook,saveReturneeBook,newReturnee,returneeTreatments,returneeConditions,recordReturnees,returneeReportRows,returneeCurrent,returneeSource,type ReturneeBook,type ReturneeRow} from '@/lib/iva-returnees';
export function SimulationReturnees({draft,onChange}:{draft:Record<string,unknown>;onChange:(field:string,value:string)=>void}){
const[error,setError]=useState('');let book:ReturneeBook;try{book=returneeBook(draft);}catch(e){return<p role="alert">{String(e)}</p>;}
const save=(b:ReturneeBook)=>{try{onChange('modelo_a_snapshot',saveReturneeBook(draft,b));setError('');}catch(e){setError(String(e));}};
const change=(id:string,patch:Partial<ReturneeRow>)=>save({...book,rows:book.rows.map(r=>r.id===id?{...r,...patch}:r)});
return<details className="rounded border p-3"><summary>Regresso definitivo — veículos (P058, cobertura parcial)</summary>
<p>Prepare o veículo e simule o enquadramento do artigo63.º do Decreto37/2023. Isenção, redução de80% e redução excepcional de50% têm condições distintas. Estas percentagens são benefícios sobre as imposições; não são taxas deIVA. Não se aplicam aqui as condições dos mineirosP059.</p>
<p>Bagagem e outros bens continuam por concluir emP058. A remissão do artigo57(2)b ao próprio n.º2 está incoerente no exemplar e não foi corrigida por presunção. O caso de exactamente180dias de propriedade fica indeterminado. O marco da conferência do tempo de propriedade deve vir do enquadramento/documento indicado;sem escolher a chegada ou o despacho automaticamente. Aquisição interna, direitos,ICE,dedução e alteração de destino não são calculados neste incremento.</p>
{error&&<p role="alert">{error}</p>}<button type="button" onClick={()=>{const next=newReturnee(crypto.randomUUID(),String(draft.currency??''));const candidates=book.rows.filter(r=>r.beneficiary);if(new Set(candidates.map(r=>r.beneficiary)).size===1)next.beneficiary=candidates[0].beneficiary;save({...book,rows:[...book.rows,next]});}}>Acrescentar veículo no regresso</button>
{book.rows.map(row=>{const text=(field:Exclude<keyof ReturneeRow,'conditions'>,label:string,type='text')=><label key={field} className="block">{label}<input type={type} value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>;const choice=(key:keyof ReturneeRow['conditions'],label:string)=><label key={key} className="block">{label}<select value={row.conditions[key]??''} onChange={e=>change(row.id,{conditions:{...row.conditions,[key]:e.target.value}})}><option value="">Por esclarecer</option><option value="yes">Sim,segundo factos ou pressupostos identificados</option><option value="no">Não</option></select></label>;
return<details key={row.id}><summary>{row.description||'Veículo por preparar'}</summary><label>Percurso do veículo<select value={row.treatment} onChange={e=>change(row.id,{treatment:e.target.value,conditions:Object.fromEntries(returneeConditions.map(([k])=>[k,row.conditions[k]]))})}><option value="">Escolher percurso</option>{returneeTreatments.map(t=><option key={t.id} value={t.id}>{t.label}</option>)}</select></label>
{text('description','Veículo identificado')}{text('beneficiary','Beneficiário')}{text('period','Período da importação','month')}{text('importDate','Data da importação ou previsão','date')}
<label>Natureza dos dados<select value={row.origin} onChange={e=>change(row.id,{origin:e.target.value as ReturneeRow['origin']})}><option value="projected">Pressupostos de projecção</option><option value="effective">Factos efectivos declarados</option></select></label>
{text('documentRef','Documentos disponíveis ou previsão')}{text('scope','Âmbito:bens,operação,período e condições')}{text('evidence','Factos ou pressupostos expressos')}{returneeConditions.map(([k,l])=>choice(k,l))}
{text('stayStart','Início da estadia no estrangeiro','date')}{text('stayEnd','Fim da estadia no estrangeiro','date')}{text('arrival','Chegada no regresso definitivo','date')}{text('request','Requerimento do benefício','date')}
{row.treatment!=='separate'&&<>{text('ownedSince','Início da propriedade no país de procedência','date')}{text('ownershipAssessment','Data à qual o documento confere o tempo de propriedade no país de procedência','date')}</>}
{choice('extension','Invoca prorrogação excepcional do prazo de60dias,até30dias adicionais?')}{row.conditions.extension==='yes'&&text('extensionRef','Prorrogação pelo Director-Geral das Alfândegas:referência,âmbito e prazo ou pressuposto expresso')}
{row.treatment==='separate'&&<>{choice('substitution','Substituição excepcional do benefício por veículo separado da bagagem?')}{text('decisionRef','Referência e âmbito da substituição ou pressuposto expresso;pedido não equivale a concessão')}{choice('exception','Invoca excepção por estadia insuficiente no estrangeiro?')}{row.conditions.exception==='yes'&&text('exceptionRef','Autorização do Ministro das Finanças:motivos e âmbito ou pressuposto expresso')}</>}
<label>Benefício anterior de veículo<select value={row.previous} onChange={e=>change(row.id,{previous:e.target.value as ReturneeRow['previous']})}><option value="">Por esclarecer</option><option value="none">Nenhum,segundo histórico identificado</option><option value="known">Sim,data conhecida</option></select></label>{row.previous==='known'&&text('previousDate','Data da numeração do despacho anterior','date')}{text('historyRef','Histórico de benefícios,incluindo fora deste dossier')}
{['recent','separate'].includes(row.treatment)&&<>{text('normalVat','IVA normal desta importação informado emMZN')}{text('normalVatRef','Referência do IVA normal ou pressuposto expresso')}</>}
<p>Mudar percurso conserva os campos ocultos e limpa confirmações específicas. A fonte exige documentos de titularidade e residência e declaração de uso;reutilize os documentos disponíveis. A aplicação não emite despacho nem concede o benefício.</p></details>;})}
{!!book.rows.length&&<button type="button" onClick={()=>{try{save(recordReturnees(draft,book));}catch(e){setError(String(e));}}}>Conferir veículos no regresso e guardar versão</button>}
{book.result&&<><p role="status">{returneeCurrent(draft,book)?'Resultado corresponde às entradas guardadas.':'Entradas alteradas;resultado histórico conservado.'} {book.history?.length??0} versões anteriores.Cobertura parcialP058.</p><dl>{returneeReportRows(draft).map(([,label,value,source],i)=><div key={i}><dt>{label}</dt><dd>{value}<small className="block">{source}</small></dd></div>)}</dl></>}
<details><summary>Fonte e âmbito documental</summary><p>{returneeSource}</p></details></details>;
}
@@ -4,8 +4,8 @@ export function SimulationTravelEvents({draft,onChange}:{draft:Record<string,unk
const[error,setError]=useState('');let book:TravelEventBook;try{book=travelEventBook(draft);}catch(e){return<p role="alert">{String(e)}</p>;}
const save=(next:TravelEventBook)=>{try{onChange('modelo_a_snapshot',saveTravelEventBook(draft,next));setError('');}catch(e){setError(String(e));}};
const change=(id:string,patch:Partial<TravelEventRow>)=>save({...book,rows:book.rows.map(r=>r.id===id?{...r,...patch}:r)});
const fields=(row:TravelEventRow,list:ReadonlyArray<readonly[keyof TravelEventRow,string]>)=>list.map(([key,label])=><label className="block" key={key}>{label}<input type={key==='period'?'month':String(key).endsWith('Date')||key==='legalDeadline'?'date':'text'} value={row[key]} onChange={e=>change(row.id,{[key]:e.target.value})}/></label>);
const select=(row:TravelEventRow,key:keyof TravelEventRow,label:string,options:ReadonlyArray<readonly[string,string]>)=><label>{label}<select value={row[key]} onChange={e=>change(row.id,{[key]:e.target.value})}><option value="">Por esclarecer</option>{options.map(([value,text])=><option key={value} value={value}>{text}</option>)}</select></label>;
const fields=(row:TravelEventRow,list:ReadonlyArray<readonly[Exclude<keyof TravelEventRow,'fxSelection'>,string]>)=>list.map(([key,label])=><label className="block" key={key}>{label}<input type={key==='period'?'month':String(key).endsWith('Date')||key==='legalDeadline'?'date':'text'} value={row[key]} onChange={e=>change(row.id,{[key]:e.target.value})}/></label>);
const select=(row:TravelEventRow,key:Exclude<keyof TravelEventRow,'fxSelection'>,label:string,options:ReadonlyArray<readonly[string,string]>)=><label>{label}<select value={row[key]} onChange={e=>change(row.id,{[key]:e.target.value})}><option value="">Por esclarecer</option>{options.map(([value,text])=><option key={value} value={value}>{text}</option>)}</select></label>;
const yn=[['yes','Sim'],['no','Não']] as const;
let sources:ReturnType<typeof travelEventSources>=[];try{sources=travelEventSources(draft);}catch{/* Origin reader preserves originals. */}
return<details className="rounded border p-3"><summary>Eventos de viagens e cessação de regimes suspensivos</summary><p>Conserve separados facto gerador e exigibilidade. Não inferir pagamento integral por um sinal, início pela emissão do bilhete ou cessação do regime por mudança de armazém. Estes eventos não calculam imposto nem concedem benefício.</p><p>{travelEventSource}</p>{error&&<p role="alert">{error}</p>}