correcao de conflitos
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-23 16:03:34 +02:00
150 changed files with 12991 additions and 439 deletions
+50
View File
@@ -19,6 +19,22 @@ export function inheritCompatibleFields(scope:string, values:Record<string,unkno
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;
if (key === 'context_applicability_snapshot') {
// Read-only assessment of the current dossier, not a deliberate form answer.
if (signature(values[key]) !== signature(value)) patch[key] = value;
next[key] = signature(value); inherited.push(key);
continue;
}
if (key.endsWith('_label')) {
const base = key.slice(0, -6);
const baseOwned = previous[base] === signature(values[base]);
const baseVacant = empty(values[base]) && !(base in previous);
if (!(base in source) || (geo.includes(base) && geoConflict) || (!baseOwned && !baseVacant && signature(values[base]) !== signature(source[base]))) continue;
// A label describes its identifier; it must never lag behind an adopted identifier.
if (signature(values[key]) !== signature(value)) patch[key] = value;
next[key] = signature(value); inherited.push(key);
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));
@@ -42,6 +58,40 @@ export function inheritCompatibleFields(scope:string, values:Record<string,unkno
return {patch,metadata:JSON.stringify({version:1,scope,inherited:next}),inherited,conflicts};
}
/** Presentation only: a saved, unedited inherited value can be shown without asking again. */
export function reusedInvestmentValue(scope: string, key: string, values: Record<string, unknown>): string | null {
if (!['journey_type', 'purpose', 'project_title', 'project_summary', 'sector_id', 'province_id', 'district_id', 'admin_post_id', 'locality_id'].includes(key)) return null;
try {
const metadata = JSON.parse(String(values.context_reuse ?? ''));
if (metadata.version !== 1 || metadata.scope !== scope || empty(values[key]) || metadata.inherited?.[key] !== signature(values[key])) return null;
if (key.endsWith('_id') || ['journey_type', 'purpose'].includes(key)) {
const label = values[`${key}_label`];
return typeof label === 'string' && label.trim() && metadata.inherited?.[`${key}_label`] === signature(label) ? label : null;
}
return typeof values[key] === 'string' ? values[key] : null;
} catch { return null; }
}
/** Report the lineage without changing a stored answer or disclosing the tracking hash. */
export function investmentFieldOrigin(values: Record<string, unknown>, key: string, fallback: string): string {
try {
const reuse = JSON.parse(String(values.context_reuse ?? ''));
if (reuse.version !== 1 || !/^dossier:.+:simulator$/.test(reuse.scope) || !reuse.inherited?.[key]) return fallback;
const snapshot = JSON.parse(String(values.context_applicability_snapshot ?? ''));
const origin = snapshot.field_provenance?.[key];
const source = origin?.kind === 'opportunity' ? `oportunidade «${origin.title ?? 'referência guardada'}»`
: origin?.kind === 'process_declaration' || origin?.kind === 'dossier' ? 'dados introduzidos pelo utilizador no dossier'
: origin?.kind === 'sector' ? `catálogo sectorial «${origin.title ?? 'referência guardada'}»`
: origin?.kind === 'territory' ? `catálogo territorial «${origin.title ?? 'referência guardada'}»`
: origin?.kind === 'linked_simulation' ? 'simulador ligado ao mesmo dossier'
: 'dossier de investimento';
const version = origin?.version ? `, versão ${origin.version}` : '';
return reuse.inherited[key] === signature(values[key])
? `Herdado de ${source}${version}`
: `Alterado posteriormente pelo utilizador; origem anterior: ${source}${version}`;
} catch { return fallback; }
}
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;
@@ -0,0 +1,19 @@
export type LandPreparation = { need: 'yes' | 'no' | 'unknown'; reason: string };
/** Preparation decision from the same saved dossier, never evidence of a land right. */
export function investmentLandPreparation(raw: unknown): LandPreparation {
try {
const snapshot = JSON.parse(String(raw ?? ''));
if (snapshot.version !== 1) return { need: 'unknown', reason: '' };
const decision = snapshot.land_preparation;
if (decision && ['yes', 'no', 'unknown'].includes(decision.need))
return { need: decision.need, reason: typeof decision.reason === 'string' ? decision.reason : '' };
// Existing snapshots already carry S10 applicability; no reimport is required.
const step = Array.isArray(snapshot.path?.steps) ? snapshot.path.steps.find((row: { code?: string } | null) => row?.code === 'S10') : null;
return { need: step?.applicability === 'not_needed_for_preparation' ? 'no' : step?.applicability === 'applicable' ? 'yes' : 'unknown', reason: typeof step?.reason === 'string' ? step.reason : '' };
} catch { return { need: 'unknown', reason: '' }; }
}
export function landStatusVisible(draft: Record<string, unknown>): boolean {
return !draft.context_applicability_snapshot || investmentLandPreparation(draft.context_applicability_snapshot).need === 'yes';
}
+23
View File
@@ -38,7 +38,26 @@ export type ContextReference = {
visibility?: 'private' | 'public';
state?: string | null;
};
export type RequirementsAssessment = {version: string; fiscal_notice: string; requirements: {opportunity_key: string; opportunity_title: string; code: string; title: string; state: string; step: string; authority: string; documents: string[]; basis: string; source_url: string; decision: string}[]};
export type OpportunityChoice = {
portfolio_origins?: {id:string;title:string;kind:string;href:string;version:number;sha256:string}[];
corridor_key?: string | null;
corridor_name?: string | null;
allowed_provinces?: import('@/components/investment-territory').TerritoryOption[];
activities?: string[];
territory_path?: import('@/components/investment-territory').TerritoryOption[];
confirm_location_change?: boolean;
opportunity: ContextReference;
territory: ContextReference | null;
location_reason: string;
location_state: string;
coverage?: string | null;
source?: string | null;
source_sha256?: string | null;
};
export type DossierContext = {
requirements_assessment?: RequirementsAssessment;
opportunity_choices?: OpportunityChoice[];
revision: number;
selection: Partial<
Record<
@@ -79,6 +98,8 @@ export type ContextView = {
notice: string;
};
export type ContextPlan = {
requirements_assessment?: RequirementsAssessment;
opportunity_choices?: OpportunityChoice[];
private_investment?: { before: Preparation; after: Preparation } | null;
preview_hash: string;
version: number;
@@ -102,8 +123,10 @@ export async function contextApi<T>(
url: string,
body?: unknown,
method = 'POST',
keepalive = false,
): Promise<T> {
const response = await fetch(url, {
keepalive,
method: body === undefined ? 'GET' : method,
credentials: 'same-origin',
headers: {
+2
View File
@@ -8,6 +8,7 @@ export type PortalNavItem = {
children?: PortalNavItem[];
};
export type PortalNavAccess = {
procurement?: boolean;
authenticated: boolean;
manager: boolean;
businesses?: boolean;
@@ -461,6 +462,7 @@ export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
),
link('sectors', 'Sectores de investimento', '/sectores'),
link('locations', 'Localizações', '/oportunidades?view=map'),
...(access.procurement ? [link('procurement','Concursos e anúncios','/concursos')] : []),
{
id: 'related-catalogues',
label: 'Catálogos relacionados',
+13 -3
View File
@@ -229,8 +229,8 @@ function makeSections(
{
field: 'Projecto',
value: absent(text(draft, 'project_title')),
origin: 'Informação introduzida no dossier',
classification: 'Declarada pelo utilizador',
origin: rows.find(row => row[1] === 'Título')?.[3] ?? 'Informação introduzida no dossier',
classification: 'Origem indicada no dossier',
},
{
field: 'Data de geração',
@@ -316,7 +316,16 @@ function makeSections(
preparation.calculation_notice,
preparation.notice,
);
for (const requirement of preparation.requirements ?? [])
const omitted = (preparation.requirements ?? []).filter(
(requirement: { state: string }) => requirement.state === 'not_applicable',
);
if (omitted.length)
section?.paragraphs.push(
`Não exigido neste contexto: ${omitted.map((requirement: { label: string; reason: string }) => `${requirement.label} (${requirement.reason})`).join('; ')}.`,
);
for (const requirement of preparation.requirements ?? []) {
// Keep an explicitly associated historical document visible without requiring it again.
if (requirement.state === 'not_applicable' && !requirement.document_id && !requirement.document) continue;
section?.rows.push({
field: requirement.label,
value:
@@ -331,6 +340,7 @@ function makeSections(
classification:
'Preparação informativa — simulação, sem submissão à Administração',
});
}
}
if (zone?.href)
section?.rows.push({
+25 -1
View File
@@ -1,4 +1,6 @@
import { displayValue } from './display-value.ts';
import { investmentFieldOrigin } from './context-inheritance.ts';
import { investmentLandPreparation } from './investment-land-preparation.ts';
import { monthlyIvaInput, monthlyIvaKey, readMonthlyIvaRecord, readMonthlyIvaSettings } from './monthly-iva.ts';
import { modeloAPurchaseReferences } from './iva-modelo-a.ts';
import { fiscalQaRows } from './fiscal-qa-preview.ts';
@@ -686,7 +688,29 @@ export function buildProjectDossierRows(
]);
}
}
return rows;
if (draft.context_applicability_snapshot) {
try {
const context = JSON.parse(String(draft.context_applicability_snapshot));
if (context.version === 1 && Array.isArray(context.opportunity_choices)) for (const choice of context.opportunity_choices) {
if (typeof choice?.opportunity?.title !== 'string') continue;
rows.push(['Localização', 'Oportunidade escolhida', choice.opportunity.title, 'Referência escolhida no mesmo dossier']);
rows.push(['Localização', 'Localização da oportunidade', typeof choice.territory?.title === 'string' ? choice.territory.title : 'Por definir', choice.opportunity.title]);
if (Array.isArray(choice.portfolio_origins)) for (const origin of choice.portfolio_origins) {
if (typeof origin?.title !== 'string') continue;
rows.push(['Localização', 'Associação escolhida na carteira', origin.title, choice.opportunity.title+'; referência documental consultada, sem inferir implantação ou benefícios']);
}
}
} catch { /* An unreadable context remains indeterminate; do not reconstruct associations. */ }
const land = investmentLandPreparation(draft.context_applicability_snapshot);
rows.push(['Localização', 'Necessidade de terra', land.need === 'no' ? 'Não' : land.need === 'yes' ? 'Sim' : 'Por definir', land.reason || 'Decisão de preparação do dossier; não comprova direitos sobre a terra']);
if (land.need === 'yes') rows.push(['Localização', 'Situação do terreno', String(draft.land_status_label ?? ({ owned: 'Próprio', duat: 'DUAT', leased: 'Arrendado', requested: 'Pedido em curso', unknown: 'Por determinar' } as Record<string, string>)[String(draft.land_status)] ?? 'Informação em falta'), 'Informação declarada; não comprova título ou disponibilidade']);
else rows.push(['Localização', 'Preparação do terreno', land.need === 'no' ? 'Situação do terreno não aplicável à preparação actual; valores anteriores conservados.' : 'Definir se precisa de terra; pode continuar a preparar o investimento.', 'Sem inferência de dispensa legal']);
}
const lineageFields: Record<string, string> = {'Título':'project_title','Resumo':'project_summary','Sector':'sector_id','Província':'province_id','Distrito':'district_id','Posto administrativo':'admin_post_id','Localidade':'locality_id'};
return rows.map(row => {
const key = lineageFields[row[1]];
return key && row[2] ? [row[0], row[1], row[2], investmentFieldOrigin(draft, key, row[3])] : row;
});
}
export function exportProjectDossierCsv(
+10
View File
@@ -1,6 +1,16 @@
const levels = ['province_id', 'district_id', 'admin_post_id', 'locality_id'];
const searchRoutes = ['/carteira', '/oportunidades', '/zonas', '/educacao'];
/** Carry the explicitly consulted portfolio origin and search geography into the existing preparation entry. */
export function investmentPreparationHref(opportunity: number, pageUrl: string, origin?: string | null): string {
const source = new URL(pageUrl, 'https://portal.invalid');
const inherited = source.searchParams.has('catalogue_query') ? new URLSearchParams(source.searchParams.get('catalogue_query')!) : source.searchParams;
const query = new URLSearchParams({source: `opportunity:${opportunity}`});
if (origin) query.set('from_dossier', origin);
for (const field of levels) if (inherited.get(field)) query.set(field, inherited.get(field)!);
return '/investimentos/iniciar?' + query.toString();
}
/** URL-scoped search context, never a saved investment or another browser tab. */
export function searchTerritoryHref(href: string, pageUrl: string): string {
const base = 'https://portal.invalid';
@@ -0,0 +1,5 @@
/** Compression can mark the representation weak; the draft version token itself is unchanged. */
export function simulationDraftEtag(header: string | null): string | null {
if (header && /^W\/"sfd-[0-9a-f-]{36}-v[1-9][0-9]*"$/i.test(header)) return header.slice(2);
return header;
}
+2 -1
View File
@@ -1,4 +1,5 @@
import { inheritSimulatorFields } from './context-inheritance.ts';
import { landStatusVisible } from './investment-land-preparation.ts';
import { csvCell } from './csv.js';
import { fiscalQaRows } from './fiscal-qa-preview.ts';
import { isApiSimulationResultSnapshotV1 } from './simulation-contract.ts';
@@ -738,7 +739,7 @@ export const simulationFieldGroups: Record<
label: 'Situação do terreno',
options: 'land_status',
showWhen: (d) =>
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
landStatusVisible(d) && (d.purpose !== 'simulate_only' || isInvestorProjectJourney(d)),
},
{
key: 'area_required',