Preserve dossier context and expose contextual applicability in QA

This commit is contained in:
2026-10-22 09:16:15 +02:00
parent 57fc914821
commit a76369eb86
23 changed files with 530 additions and 111 deletions
+66
View File
@@ -0,0 +1,66 @@
import { restoreBusinessPlanSnapshot } from './business-financial-plan.ts';
const empty = (value: unknown) => value == null || value === '' || (Array.isArray(value) && value.length === 0);
function canonical(value: unknown): unknown {
if (Array.isArray(value)) return value.map(canonical);
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([key,item])=>[key,canonical(item)]));
return value;
}
// Change tracking only, never an authorization, integrity or legal-acceptance token. No personal values in metadata.
function signature(value: unknown): string {
const text=JSON.stringify(canonical(value)) ?? 'undefined';let hash=14695981039346656037n;
for(let index=0;index<text.length;index++) hash=BigInt.asUintN(64,(hash^BigInt(text.charCodeAt(index)))*1099511628211n);
return `${text.length}:${hash.toString(16)}`;
}
export function inheritCompatibleFields(scope:string, values:Record<string,unknown>, source:Record<string,unknown>, raw:unknown, allowed?:string[]): {patch:Record<string,unknown>; metadata:string; inherited:string[]; conflicts:string[]} {
let previous:Record<string,string>={};
try { const saved=JSON.parse(String(raw ?? ''));if(saved.version===1 && saved.scope===scope && saved.inherited && typeof saved.inherited==='object') previous=saved.inherited; } catch { /* Legacy inputs are retained, not overwritten. */ }
const next={...previous};const patch:Record<string,unknown>={};const inherited:string[]=[];const conflicts:string[]=[];
const geo=['province_id','district_id','admin_post_id','locality_id'];
const geoConflict=geo.some(key=>(!empty(values[key]) || key in previous) && signature(values[key])!==signature(source[key]) && previous[key]!==signature(values[key]));
for(const [key,value] of Object.entries(source)) {
if ((allowed && !allowed.includes(key)) || (empty(value) && !(key in previous))) continue;
const current=values[key];
const track = (item:unknown) => key==='parcels' ? Object.fromEntries(geo.map(field=>[field,(item as Array<Record<string,unknown>>)?.[0]?.[field] ?? ''])) : item;
const owned=previous[key]===signature(track(current));
const vacant=key==='parcels' ? geo.every(field=>empty((current as Array<Record<string,unknown>>)?.[0]?.[field])) : empty(current);
if ((geo.includes(key) && geoConflict) || (!owned && (!vacant || key in previous))) {
if(signature(current)!==signature(value)) conflicts.push(key);
continue;
}
if(key==='parcels') {
const parcels=current as Array<Record<string,unknown>>|undefined;
if(!owned && parcels?.length && geo.some(field=>!empty(parcels[0]?.[field]))) {conflicts.push(key);continue;}
}
if(signature(track(current))!==signature(track(value))) {
if(key==='parcels') {
const parcels=(current as Array<Record<string,unknown>>) ?? [];
patch[key]=[{...parcels[0],...Object.fromEntries(geo.map(field=>[field,(value as Array<Record<string,unknown>>)[0]?.[field] ?? '']))},...parcels.slice(1)];
} else patch[key]=value;
}
next[key]=signature(track(value));inherited.push(key);
}
return {patch,metadata:JSON.stringify({version:1,scope,inherited:next}),inherited,conflicts};
}
export function inheritSimulatorFields<T extends Record<string,unknown>>(draft:T): T {
const source:Record<string,unknown>={};
const plan=draft.business_plan_snapshot ? restoreBusinessPlanSnapshot(String(draft.business_plan_snapshot)) : null;
if(plan?.currency) source.currency=plan.currency;
const currency=draft.currency || source.currency;
if(currency) {source.fiscal_currency=currency;source.opportunity_currency=currency;source.published_iva_currency=currency;}
if(draft.tax_residency_country) source.fiscal_residency_country=draft.tax_residency_country;
if(draft.fiscal_reference_date) source.published_iva_date=draft.fiscal_reference_date;
let settings:Record<string,unknown>={start:'',basis:'unknown',declared:false,auto:false};
let settingsValid=!draft.monthly_iva_settings;
try {const saved=JSON.parse(String(draft.monthly_iva_settings ?? ''));if(saved && !Array.isArray(saved) && typeof saved.start==='string' && ['net','included','unknown'].includes(saved.basis) && typeof saved.declared==='boolean' && typeof saved.auto==='boolean') {settings=saved;settingsValid=true;}} catch { /* Invalid stored inputs remain intact. */ }
const start=String(draft.expected_start_date ?? '');
if(/^\d{4}-\d{2}-\d{2}$/.test(start)) source.monthly_iva_start=start.slice(0,7);
else if(/^\d{4}$/.test(String(draft.fiscal_period)) && draft.fiscal_periodicity==='monthly' && /^(0?[1-9]|1[0-2])$/.test(String(draft.fiscal_month))) source.monthly_iva_start=`${draft.fiscal_period}-${String(draft.fiscal_month).padStart(2,'0')}`;
if(!settingsValid) delete source.monthly_iva_start;
const values={...draft,monthly_iva_start:settings.start ?? ''};
const patch=inheritCompatibleFields('simulator-compatible-fields',values,source,draft.compatible_fields_snapshot);
const next:Record<string,unknown>={...draft,...patch.patch,compatible_fields_snapshot:patch.metadata};
if('monthly_iva_start' in patch.patch) next.monthly_iva_settings=JSON.stringify({...settings,start:patch.patch.monthly_iva_start});
delete next.monthly_iva_start;
return JSON.stringify(next)===JSON.stringify(draft) ? draft : next as T;
}
+15
View File
@@ -134,4 +134,19 @@ export const contextFieldNames: Record<string, string> = {
province: 'Província',
district: 'Distrito',
location: 'Localização',
currency: 'Moeda do projecto',
person_type: 'Tipo de pessoa',
fiscal_period: 'Ano fiscal',
fiscal_periodicity: 'Periodicidade',
fiscal_month: 'Mês fiscal',
fiscal_residency_country: 'País de residência fiscal declarado',
activity_id: 'Actividade',
project_type: 'Modalidade do investimento',
maturity_stage: 'Fase do investimento',
expected_start_date: 'Início previsto',
investor_origin: 'Origem do investidor',
entity_stage: 'Situação da entidade',
tax_residency_country: 'Residência fiscal declarada',
investment_regime: 'Enquadramento territorial consultado',
special_zone_id: 'ZEE, ZFI ou parque',
};
+1
View File
@@ -21,6 +21,7 @@ export function monthlySalesFromDraft(draft: Record<string, unknown>): { amounts
if (draft.business_plan_snapshot) {
const plan = restoreBusinessPlanSnapshot(String(draft.business_plan_snapshot));
if (!plan) throw new Error('Não foi possível recuperar a projecção de vendas. Os dados guardados não foram substituídos.');
if (draft.currency && plan.currency && draft.currency !== plan.currency) throw new Error(`A projecção de vendas está em ${plan.currency}, mas o projecto está em ${String(draft.currency)}. Reveja a moeda da projecção; os valores não foram convertidos nem reclassificados.`);
return {amounts: monthlyProjectedSales(plan), source: 'Vendas por produto e mês do plano empresarial; mesmos pressupostos e representação monetária da projecção de vendas.'};
}
if (draft.cashflow_snapshot) {
@@ -277,6 +277,19 @@ function makeSections(
}
}
if (draft.context_applicability_snapshot) {
try {
const context = JSON.parse(String(draft.context_applicability_snapshot));
if (context.version === 1) {
const section = sections.get('sources');
const zone = context.zone;
section?.rows.push({field:'Contexto do investimento',value:`Revisão ${context.context_revision}; ${zone ? `${zone.title}, versão ${zone.version}` : 'sem ZEE, ZFI ou parque seleccionado'}`,origin:'Referência do mesmo dossier no momento da gravação',classification:'Contexto versionado; não é reconhecimento jurídico'});
section?.paragraphs.push(zone ? 'Benefício fiscal da zona indeterminado: falta regra executável ligada às condições e reconhecimento. O IVA apresentado é apenas cenário geral sem benefício; não representa o regime especial nem o apuramento final.' : 'Cenário geral de preparação; sem confirmação automática de elegibilidade fiscal.');
if(zone?.href) section?.rows.push({field:'Ficha e fundamentos da zona',value:zone.href,origin:`Versão consultada ${zone.version}`,classification:'Referência consultável; condições por verificar'});
}
} catch { sections.get('sources')?.paragraphs.push('Não foi possível recuperar o contexto guardado; o enquadramento territorial permanece indeterminado.'); }
}
for (const [sectionName, field, value, origin] of rows.slice(1)) {
// Questionnaire schema identifiers remain stored; they do not help the
// reader assess the project and are not a business report field.
+2 -1
View File
@@ -1,3 +1,4 @@
import { inheritSimulatorFields } from './context-inheritance.ts';
import { csvCell } from './csv.js';
import { fiscalQaRows } from './fiscal-qa-preview.ts';
import { isApiSimulationResultSnapshotV1 } from './simulation-contract.ts';
@@ -1530,7 +1531,7 @@ export function restoreSimulationDraft(
}
}
}
return draft as SimulationDraft;
return inheritSimulatorFields(draft as SimulationDraft);
}
export function simulationDraftFingerprint(draft: SimulationDraft): string {