Entrega dashboard e correccoes transversais preservando Ofertas instalado
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-15 18:56:39 +02:00
parent 1349789226
commit fb076c174f
117 changed files with 10380 additions and 1905 deletions
+35
View File
@@ -0,0 +1,35 @@
export const normaliseChoice = (value: string) =>
value
.normalize('NFD')
.replace(/\p{Diacritic}/gu, '')
.toLocaleLowerCase('pt')
.trim();
export function matchesChoice(query: string, labels: string[]): boolean {
const needle = normaliseChoice(query);
return (
!needle ||
labels.some((label) => normaliseChoice(label).includes(needle))
);
}
/** The same ISO currency source already used by the simulator, with readable labels. */
export function currencyChoices(codes?: readonly string[]) {
const intl = Intl as unknown as {
supportedValuesOf?: (key: string) => string[];
};
const names = new Intl.DisplayNames(['pt-MZ'], { type: 'currency' });
return [
...new Set(
codes ??
intl.supportedValuesOf?.('currency') ?? [
'MZN',
'USD',
'EUR',
'ZAR',
],
),
].map((code) => ({
value: code,
label: `${names.of(code) ?? code} — ${code}`,
keywords: [code, names.of(code) ?? code],
}));
}
+110 -7
View File
@@ -1,10 +1,94 @@
import { searchTerritoryHref } from './search-territory.ts';
const geography = [
'province_id',
'district_id',
'admin_post_id',
'locality_id',
];
const catalogueKeys: Record<string, string[]> = {
'/carteira': ['q', 'kind', 'sector', 'geo_location_id'],
'/zonas': [
'q',
'category',
'physical_category',
'legal_regime',
'development_status',
'availability_status',
'province',
],
'/oportunidades': [
'q',
'query',
'sector',
'province',
'district',
'geo_location_id',
'include_national',
'cluster_id',
'zee_id',
'zfi_id',
'park_id',
'corridor_id',
'project_id',
'education',
'min_amount',
'max_amount',
'currency',
'maturity_level',
'preparation',
'before',
'sort',
'facets[]',
'view',
'dimension',
'association_type',
'association_target',
'association_state',
'association_purpose',
'chain_id',
'subsector_id',
],
};
function family(path: string): string {
if (path.startsWith('/management/portfolio')) return '/carteira';
if (path.startsWith('/management/investment/zones')) return '/zonas';
if (path === '/educacao' || path.startsWith('/educacao/'))
return '/oportunidades';
return (
Object.keys(catalogueKeys).find(
(route) => path === route || path.startsWith(route + '/'),
) ?? ''
);
}
/** Explicit URL criteria only. No ambient storage, dossier IDs or nested return URLs. */
export function catalogueQuery(path: string, query: string): URLSearchParams {
const group = family(path);
const allowed = new Set(
group
? [...geography, ...catalogueKeys[group], 'page', 'per_page']
: [],
);
const result = new URLSearchParams();
for (const [key, value] of new URLSearchParams(query)) {
if (!allowed.has(key) || !value || value.length > 2000) continue;
if (
['page', 'per_page'].includes(key) &&
(!/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(Number(value)))
)
continue;
if (!key.endsWith('[]')) result.delete(key);
result.append(key, value);
}
return result;
}
/** Only a query string is carried; the return destination is always local. */
export function catalogueDetailHref(
path: string,
query: string,
pageUrl?: string,
): string {
const target = new URL(path, 'https://portal.invalid');
if (target.origin !== 'https://portal.invalid') return path;
if (pageUrl) {
const page = new URL(
pageUrl,
@@ -20,16 +104,35 @@ export function catalogueDetailHref(
query = params.toString();
}
}
return query
? `${path}?catalogue_query=${encodeURIComponent(query)}`
: path;
const selected = catalogueQuery(target.pathname, query).toString();
if (selected) target.searchParams.set('catalogue_query', selected);
return target.pathname + target.search + target.hash;
}
export function catalogueReturnHref(base: string, pageUrl: string): string {
const query = new URL(pageUrl, 'https://portal.invalid').searchParams.get(
'catalogue_query',
);
const source = new URL(pageUrl, 'https://portal.invalid');
const target = new URL(base, 'https://portal.invalid');
if (target.origin !== 'https://portal.invalid') return base;
const query = source.searchParams.get('catalogue_query');
const selected = catalogueQuery(target.pathname, query ?? '');
let changedAncestor = false;
for (const key of geography) {
if (target.searchParams.has(key))
changedAncestor ||=
target.searchParams.get(key) !== selected.get(key);
else if (changedAncestor) selected.delete(key);
}
const explicit = new Set(target.searchParams.keys());
for (const [key, value] of selected) {
// Text, kind, price and page belong to their original catalogue only.
if (
family(source.pathname) !== family(target.pathname) &&
!geography.includes(key)
)
continue;
if (!explicit.has(key)) target.searchParams.append(key, value);
}
return searchTerritoryHref(
base + (query ? `?${new URLSearchParams(query).toString()}` : ''),
target.pathname + target.search + target.hash,
pageUrl,
);
}
+8
View File
@@ -1,3 +1,11 @@
/** Historical definitions remain stored verbatim; internal delivery wording is not investor guidance. */
export function companyPreparationNotice(notice: string): string {
return notice.replace(
'Os sete exemplares referidos no complemento ainda não foram fornecidos.',
'Os modelos contratuais não estão disponíveis nesta preparação.',
);
}
export type Party = {
id: string;
name: string | null;
+124
View File
@@ -0,0 +1,124 @@
import type { DemographicAnalysis } from '../components/demographic-evidence';
type Series = DemographicAnalysis['territories'][number]['series'][number];
type Row = Series['values'][number];
const children = ['0-4', '5-9', '10-14'];
const adults = [
'15-19',
'20-24',
'25-29',
'30-34',
'35-39',
'40-44',
'45-49',
'50-54',
'55-59',
'60-64',
];
// Display-only derivation. Original decimals, persisted evidence and fiscal calculations are untouched.
function numeric(row: Row | undefined): number | null {
if (
!row ||
!['pessoas', 'persons'].includes(row.unit) ||
!/^\d+(\.\d+)?$/.test(row.value)
)
return null;
const n = Number(row.value);
return Number.isFinite(n) && n <= Number.MAX_SAFE_INTEGER ? n : null;
}
function one(rows: Row[], age: string, residence = 'all'): Row | undefined {
const found = rows.filter(
(r) =>
r.indicator === 'population' &&
r.age_group === age &&
r.residence === residence,
);
return found.length === 1 ? found[0] : undefined;
}
export const populationLabel = (n: number | null) =>
n === null
? 'Sem dados'
: new Intl.NumberFormat('pt-MZ', { maximumFractionDigits: 0 }).format(
n,
);
export const percentageLabel = (n: number | null) =>
n === null
? 'Sem dados'
: new Intl.NumberFormat('pt-MZ', {
maximumFractionDigits: 1,
minimumFractionDigits: 1,
}).format(n) + '%';
export function demographicReading(series: Series, start: number, end: number) {
function year(year: number) {
const rows = series.values.filter((r) => r.year === year);
const totalRow = one(rows, 'all');
const total = numeric(totalRow);
const compatible = (r: Row | undefined) =>
r &&
totalRow &&
r.unit === totalRow.unit &&
r.data_kind === totalRow.data_kind;
const part = (age: string, residence = 'all') => {
const r = one(rows, age, residence);
return compatible(r) ? numeric(r) : null;
};
const sum = (ages: string[]) => {
const values = ages.map((age) => part(age));
return values.every((v) => v !== null)
? values.reduce<number>((a, v) => a + (v ?? 0), 0)
: null;
};
const share = (n: number | null) =>
total !== null && total > 0 && n !== null && n <= total
? (n / total) * 100
: null;
const urban = part('all', 'urban'),
rural = part('all', 'rural');
const residenceReconciled =
total !== null &&
urban !== null &&
rural !== null &&
Math.abs(urban + rural - total) <=
Math.max(0.000001, total * 1e-10);
const under15 = sum(children),
age15to64 = sum(adults);
return {
year,
total,
kind: totalRow?.data_kind,
unit: totalRow?.unit,
urban,
rural,
urbanShare: residenceReconciled ? share(urban) : null,
ruralShare: residenceReconciled ? share(rural) : null,
under15,
under15Share: share(under15),
age15to64,
age15to64Share: share(age15to64),
};
}
const first = year(start),
last = year(end);
const comparable =
end > start &&
first.total !== null &&
last.total !== null &&
first.kind === last.kind &&
first.unit === last.unit;
const delta = comparable ? last.total! - first.total! : null;
const growth =
delta !== null && first.total! > 0
? (delta / first.total!) * 100
: null;
return {
first,
last,
delta,
growth,
years: Array.from({ length: end - start + 1 }, (_, i) =>
year(start + i),
),
};
}
+14 -9
View File
@@ -329,19 +329,24 @@ export function buildLoanSchedule(input: LoanScheduleInput) {
}
/** A simple one-period budget allows an operating deficit; it is not forced to zero. */
function sumMonetaryInputs(values: string[], label: string): bigint {
if (!values.length)
throw new Error('Indique pelo menos uma parcela conhecida.');
return values.reduce(
(sum, value) => sum + decimalToInteger(value, 2, label),
0n,
);
}
export function sumFinancialAmounts(values: string[]): string {
return money(sumMonetaryInputs(values, 'Parcela'));
}
export function calculateBudget(incomes: string[], expenses: string[]) {
if (incomes.length === 0 || expenses.length === 0)
throw new Error(
'Introduza pelo menos uma linha de receitas e uma linha de despesas; use zero apenas quando esse valor for conhecido.',
);
const incomeTotal = incomes.reduce(
(sum, value) => sum + decimalToInteger(value, 2, 'Receita'),
0n,
);
const expenseTotal = expenses.reduce(
(sum, value) => sum + decimalToInteger(value, 2, 'Despesa'),
0n,
);
const incomeTotal = sumMonetaryInputs(incomes, 'Receita');
const expenseTotal = sumMonetaryInputs(expenses, 'Despesa');
return {
incomeTotal: money(incomeTotal),
expenseTotal: money(expenseTotal),
@@ -444,7 +449,7 @@ export function exportFinancialToolsCsv(
['Estado', 'Estimativa com pressupostos introduzidos pelo utilizador'],
[
'Fonte dos pressupostos',
'Valores editaveis desta ferramenta; os valores iniciais sao exemplos demonstrativos',
'Pressupostos editáveis introduzidos ou recuperados pelo utilizador; conferir antes de utilizar os resultados.',
],
['Período do orçamento e dos custos fixos', input.budgetPeriod],
[
@@ -0,0 +1,94 @@
export type OperatingAssumptions = {
model: '' | 'hotel' | 'agriculture' | 'other';
capacity: string;
price: string;
occupancy: string;
frequency: string;
source: string;
costs: { label: string; annual: string }[];
};
export const emptyOperatingAssumptions = (): OperatingAssumptions => ({
model: '',
capacity: '',
price: '',
occupancy: '',
frequency: '',
source: '',
costs: [],
});
export function restoreOperatingAssumptions(
snapshot: string,
): OperatingAssumptions {
try {
const parsed = JSON.parse(snapshot);
const data = parsed?.data;
if (
parsed.version !== 1 ||
!data ||
!['', 'hotel', 'agriculture', 'other'].includes(data.model)
)
return emptyOperatingAssumptions();
if (
!['capacity', 'price', 'occupancy', 'frequency', 'source'].every(
(key) =>
typeof data[key] === 'string' && data[key].length <= 1000,
)
)
return emptyOperatingAssumptions();
if (
!Array.isArray(data.costs) ||
data.costs.length > 30 ||
!data.costs.every(
(row: { label: unknown; annual: unknown }) =>
typeof row?.label === 'string' &&
typeof row?.annual === 'string' &&
row.label.length <= 120 &&
row.annual.length <= 40,
)
)
return emptyOperatingAssumptions();
return data;
} catch {
return emptyOperatingAssumptions();
}
}
function hundredths(value: string): bigint {
const match = /^(\d{1,15})(?:\.(\d{1,2}))?$/.exec(value.trim());
if (!match)
throw new Error(
'Indique cada pressuposto em falta, com até duas casas decimais.',
);
return BigInt(match[1]) * 100n + BigInt((match[2] ?? '').padEnd(2, '0'));
}
const money = (cents: bigint) =>
`${cents / 100n}.${String(cents % 100n).padStart(2, '0')}`;
export function estimateOperatingRevenue(data: OperatingAssumptions): string {
if (!data.model)
throw new Error('Escolha o modelo de actividade que pretende estimar.');
const capacity = hundredths(data.capacity),
price = hundredths(data.price),
frequency = hundredths(data.frequency);
let numerator = capacity * price * frequency;
let divisor = 10000n;
if (data.model === 'hotel') {
const occupancy = hundredths(data.occupancy);
if (occupancy > 10000n)
throw new Error('A ocupação não pode exceder 100%.');
numerator *= occupancy;
divisor *= 10000n;
}
return money((numerator + divisor / 2n) / divisor);
}
export function estimateOperatingCosts(data: OperatingAssumptions): string {
if (!data.costs.length)
throw new Error(
'Acrescente as categorias de custos que conhece. Valores em falta não são zero.',
);
return money(
data.costs.reduce((total, row) => {
if (!row.label.trim())
throw new Error('Identifique a categoria de cada custo.');
return total + hundredths(row.annual);
}, 0n),
);
}
+31
View File
@@ -32,6 +32,27 @@ export type ContextDocument = {
opportunity_id: number;
download_url: string;
};
export type SupplyAggregate = {
context_revision: number;
recorded_at: string;
requested_territory: { id: string; name: string };
scope: { id: string; name: string; level: string };
broader_context: boolean;
entities: number;
repeated: number;
uncertain: number;
groups: {
code: string;
label: string;
total: number;
first_year: string | null;
last_year: string | null;
}[];
truncated: boolean;
coverage_unknown: boolean;
limitations: string;
interpretation: string;
};
export type ContextReference = {
key: string;
kind: string;
@@ -92,6 +113,7 @@ export type OpportunityChoice = {
source_sha256?: string | null;
};
export type DossierContext = {
promoter_entity?: PromoterEntity;
complements?: import('@/components/investment-complements').Complement[];
requirements_assessment?: RequirementsAssessment;
opportunity_choices?: OpportunityChoice[];
@@ -115,6 +137,12 @@ export type DossierContext = {
updated_at?: string;
dependency_hash?: string;
};
export type PromoterEntity = {
kind: 'company' | 'organization' | 'being_formed' | 'undetermined';
id?: string | null;
source_version?: number | null;
snapshot?: Record<string, string | null>;
};
export type ContextView = {
private_investment?: Preparation | null;
preparation_documents?: PreparationDocument[];
@@ -203,6 +231,9 @@ export async function contextApi<T>(
}
}
export const contextFieldNames: Record<string, string> = {
products_services: 'Actividade concreta e produto ou serviço',
investment_budget_min: 'Orçamento previsto — mínimo',
investment_budget_max: 'Orçamento previsto — máximo',
investment_form: 'Tipo do investimento',
investment_preparation: 'Preparação do pedido',
investment_activity_scope: 'Natureza da actividade',
+166 -4
View File
@@ -1,5 +1,7 @@
import { pathStates, type PathResult } from './investor-path.ts';
import type { SupplyAggregate } from './investor-context';
import { restoreFinancialToolsSnapshot } from './financial-calculators.ts';
import { restoreOperatingAssumptions } from './investment-operating-assistance.ts';
import { buildProjectDossierRows } from './project-dossier.ts';
import type { SwotDraft } from './investment-preparation.ts';
import type {
@@ -34,6 +36,7 @@ export type PreparationReport = {
swot_review_required: boolean;
};
export type InvestorDossierReportInput = {
supply_aggregates?: SupplyAggregate[];
case: { id: string; title: string; version: number };
context_opportunity: string | null;
opportunity_options: unknown[];
@@ -322,6 +325,7 @@ export function createInvestorDossierReport(
generatedAt = new Date().toISOString(),
): DossierReportModel {
const index = investorDossierReportIndex(input);
const supply = input.supply_aggregates?.at(-1);
const row = (
field: string,
value: string,
@@ -339,11 +343,101 @@ export function createInvestorDossierReport(
result.context_state !== 'review_required'
? 'Estimativa guardada'
: 'Histórico — rever antes de utilizar';
const preparation = result.preparation_snapshot ?? {};
for (const [key, label] of Object.entries({
total_investment: 'Investimento declarado do cenário',
secured_amount: 'Financiamento efectivamente mobilizado',
planned_funding: 'Financiamento previsto — não mobilizado',
requested_funding: 'Financiamento solicitado — não mobilizado',
approved_funding: 'Financiamento aprovado — não mobilizado',
annual_revenue: 'Receitas anuais estimadas',
annual_operating_costs: 'Custos anuais estimados',
investment_budget_min: 'Orçamento previsto — mínimo do intervalo',
investment_budget_max: 'Orçamento previsto — máximo do intervalo',
})) {
if (typeof preparation[key] === 'string' && preparation[key].trim())
finance.push(
row(
label,
`${preparation[key]} ${result.currency ?? ''}`.trim(),
reference,
state,
),
);
}
const assumptions = restoreOperatingAssumptions(
preparation.planning_assumptions_snapshot ?? '',
);
if (assumptions.model) {
const assumptionLabels = {
model: 'Modelo escolhido para estimar receitas',
capacity:
assumptions.model === 'hotel'
? 'Quartos disponíveis'
: 'Unidades vendáveis por ciclo',
price: 'Preço declarado',
occupancy: 'Ocupação prevista (%)',
frequency:
assumptions.model === 'hotel'
? 'Dias de funcionamento no ano'
: 'Ciclos ou períodos no ano',
source: 'Fundamento dos pressupostos',
};
for (const [key, label] of Object.entries(assumptionLabels)) {
const value =
key === 'model'
? {
hotel: 'Hotel',
agriculture: 'Agronegócio',
other: 'Outra actividade',
}[assumptions.model]
: assumptions[key as keyof typeof assumptionLabels];
finance.push(
row(
label,
value || 'Por confirmar',
reference,
'Pressuposto declarado, não comprova procura ou rentabilidade',
),
);
}
for (const cost of assumptions.costs)
finance.push(
row(
`Custo anual — ${cost.label}`,
cost.annual || 'Por confirmar',
reference,
state,
),
);
}
try {
if (
result.engine !== 'financial-calculators:v1' ||
!restoreFinancialToolsSnapshot(result.financial_snapshot)
)
const budget = JSON.parse(
preparation.initial_budget_snapshot ?? '{}',
);
if (budget.version === 1 && Array.isArray(budget.rows))
for (const part of budget.rows) {
if (
typeof part?.label === 'string' &&
typeof part?.amount === 'string'
)
finance.push(
row(
`Investimento inicial — ${part.label}`,
part.amount || 'Por confirmar',
reference,
state,
),
);
}
} catch {
/* The original remains stored; malformed optional details do not become invented amounts. */
}
try {
const tools = restoreFinancialToolsSnapshot(
result.financial_snapshot,
);
if (result.engine !== 'financial-calculators:v1' || !tools)
throw new Error('Versão não recuperável');
const currency = result.currency ?? '';
const baseline = new Set(
@@ -358,6 +452,25 @@ export function createInvestorDossierReport(
'Financiamento',
'Orçamento',
]);
if (
preparation.planning_loan === 'no' ||
[
tools.loan.principal,
tools.loan.rate,
tools.loan.months,
].every((value) => !value.trim())
)
sections.delete('Empréstimo educativo');
if (Object.values(tools.breakEven).every((value) => !value.trim()))
sections.delete('Ponto de equilíbrio');
if (
[...tools.incomes, ...tools.expenses].every(
(value) => !value.amount.trim(),
)
)
sections.delete('Orçamento');
if (Object.values(tools.funding).every((value) => !value.trim()))
sections.delete('Financiamento');
const rows = buildProjectDossierRows({
currency,
financial_tools_snapshot: result.financial_snapshot,
@@ -400,6 +513,50 @@ export function createInvestorDossierReport(
'O índice referencia os originais; não incorpora automaticamente os seus anexos nem envia dados a entidades externas.',
],
sections: [
{
id: 'supply',
title: 'Actividades existentes — análise agregada',
private: true,
paragraphs: supply
? [
`Consulta de ${supply.recorded_at}; contexto v${supply.context_revision}.`,
`Âmbito: ${supply.scope.name} (${supply.scope.level}). Local escolhido: ${supply.requested_territory.name}.`,
supply.broader_context
? 'Contexto administrativo mais amplo; não representa apenas a localidade escolhida.'
: 'Âmbito da localização escolhida.',
supply.context_revision !==
input.investment_context?.revision
? 'Contexto alterado; análise anterior preservada e por rever.'
: 'Análise guardada para esta revisão do contexto.',
supply.interpretation,
supply.limitations,
]
: ['Análise agregada ainda não guardada neste dossier.'],
rows: supply
? [
row(
'Entidades identificadas administrativamente',
String(supply.entities),
),
row(
'Observações repetidas, separadas do total',
String(supply.repeated),
),
row(
'Identificações incertas, separadas do total',
String(supply.uncertain),
),
...supply.groups.map((group) =>
row(
group.label,
String(group.total),
`${group.first_year ?? 'Período por confirmar'}–${group.last_year ?? ''}; ${supply.scope.name}`,
'Actividade actual e relação económica por confirmar',
),
),
]
: [],
},
{
id: 'project',
title: 'Investimento e localização em preparação',
@@ -410,11 +567,16 @@ export function createInvestorDossierReport(
rows: Object.entries({
project_title: 'Projecto',
project_summary: 'Descrição',
products_services: 'Actividade e produtos ou serviços',
sector: 'Sector',
province: 'Província',
district: 'Distrito',
location: 'Localização',
total_investment: 'Investimento previsto',
investment_budget_min:
'Orçamento previsto — mínimo do intervalo',
investment_budget_max:
'Orçamento previsto — máximo do intervalo',
currency: 'Moeda',
expected_start_date: 'Início previsto',
})
+1
View File
@@ -22,6 +22,7 @@ export type PathResult = {
context_opportunity?: string | null;
id: string;
financial_snapshot: string;
preparation_snapshot?: Record<string, string>;
currency: string | null;
draft_id: string;
draft_version: number;
+8 -8
View File
@@ -2,16 +2,16 @@ import { csvCell } from './csv.js';
export function defaultCashflowDraftInputs() {
return {
openingCash: '0',
monthlyRevenue: '200000',
monthlyOperatingCosts: '150000',
monthlyDebtService: '0',
openingCash: '',
monthlyRevenue: '',
monthlyOperatingCosts: '',
monthlyDebtService: '',
monthlyTaxAssessed: '',
monthlyTaxSchedule: Array.from({ length: 12 }, () => ''),
vatCreditEstimated: '0',
vatRefundRequested: '0',
vatRefundRecognized: '0',
vatRefundExpectedReceipt: '0',
vatCreditEstimated: '',
vatRefundRequested: '',
vatRefundRecognized: '',
vatRefundExpectedReceipt: '',
vatRefundExpectedMonth: '',
};
}
+8 -1
View File
@@ -91,10 +91,17 @@ export function monthlyIvaInput(
draft: Record<string, unknown>,
settings: MonthlyIvaSettings,
): MonthlyIvaInput {
if (
draft.fiscal_period &&
inputText(draft.fiscal_period) !== settings.start.slice(0, 4)
)
throw new Error(
'O ano escolhido no enquadramento fiscal difere do primeiro mês da projecção. Confira o período; nenhum ano foi alterado automaticamente.',
);
const sales = monthlySalesFromDraft(draft);
if (!/^2026-(0[1-9]|1[0-2])$/.test(settings.start))
throw new Error(
'Indique o primeiro mês real da projecção. Este lote abrange apenas 2026.',
'Indique o primeiro mês real da projecção. Este cálculo dispõe de cobertura apenas para 2026.',
);
const start = Number(settings.start.slice(5));
if (sales.amounts.length > 12 || start + sales.amounts.length > 13)
+45
View File
@@ -0,0 +1,45 @@
export type NavigationFocus = {
case_id: string;
step_code: string | null;
version: number;
};
const key = (actor: number) => `investmoz-navigation-focus:${actor}`;
/** A per-tab hint, never authority to access a dossier. Recheck the server listing. */
export function readNavigationFocus(
actor: number,
allowed: string[],
): NavigationFocus | null {
try {
const value = JSON.parse(sessionStorage.getItem(key(actor)) ?? 'null');
if (
!value ||
!allowed.includes(value.case_id) ||
!Number.isSafeInteger(value.version) ||
value.version < 0
)
return null;
if (
value.step_code !== null &&
!/^S(0[1-9]|1[0-9])$/.test(value.step_code)
)
return null;
return {
case_id: value.case_id,
step_code: value.step_code,
version: value.version,
};
} catch {
return null;
}
}
export function rememberNavigationFocus(
actor: number,
focus: NavigationFocus | null,
): void {
try {
if (focus) sessionStorage.setItem(key(actor), JSON.stringify(focus));
else sessionStorage.removeItem(key(actor));
} catch {
// The current consultation remains usable when browser storage is blocked.
}
}
@@ -0,0 +1,61 @@
import { restoreFinancialToolsSnapshot } from './financial-calculators.ts';
const amount = (value: unknown): string | null => {
if (typeof value !== 'string') return null;
const match = /^(\d+)(?:\.(\d+))?$/.exec(value.trim());
if (!match) return null;
return (
match[1].replace(/^0+(?=\d)/, '') +
'.' +
(match[2] ?? '').replace(/0+$/, '')
);
};
export const samePlanningAmount = (a: string, b: string) =>
(!a && !b) || (amount(a) !== null && amount(a) === amount(b));
/** Compare named origins without adopting either one or turning unknown into zero. */
export function fundingDifferences(
source: { total: string; secured: string },
calculator: { total: string; secured: string },
) {
return (['total', 'secured'] as const).filter(
(key) => !samePlanningAmount(source[key], calculator[key]),
);
}
/** Unknown calculator inputs may reuse the canonical source; a known divergent value requires a decision. */
export function canLinkFundingSource(
source: { total: string; secured: string } | undefined,
stored: { total: string; secured: string } | undefined,
): boolean {
return Boolean(
source &&
(!stored ||
(['total', 'secured'] as const).every(
(key) =>
!stored[key].trim() ||
samePlanningAmount(source[key], stored[key]),
)),
);
}
export function draftFundingDifferences(draft: Record<string, unknown>) {
const snapshot = restoreFinancialToolsSnapshot(
typeof draft.financial_tools_snapshot === 'string'
? draft.financial_tools_snapshot
: undefined,
);
if (!snapshot) return [];
return fundingDifferences(
{
total:
typeof draft.total_investment === 'string'
? draft.total_investment
: '',
secured:
typeof draft.secured_amount === 'string'
? draft.secured_amount
: '',
},
snapshot.funding,
);
}
+50
View File
@@ -0,0 +1,50 @@
/** Only confirmed context becomes a criterion; titles never assign a sector. */
export function preparationSearch(
query: string,
sector: string,
path: { id: string; location_type: string }[],
) {
const params = new URLSearchParams();
if (query.trim()) params.set('q', query.trim());
if (/^sector:[1-9]\d*$/.test(sector))
params.set('sector_id', sector.slice(7));
for (const place of path)
if (
['province', 'district', 'admin_post', 'locality'].includes(
place.location_type,
)
)
params.set(place.location_type + '_id', place.id);
return params.toString();
}
/** Carry only deliberate preparation criteria, never catalogue relationships. */
export function createInvestmentHref(
values: Record<string, unknown>,
path: { id: string; location_type: string }[] = [],
) {
const query = new URLSearchParams();
for (const key of ['sector_id', 'project_title', 'currency']) {
if (typeof values[key] === 'string' && values[key])
query.set(key, values[key]);
}
if (typeof values.sector === 'string' && values.sector)
query.set('sector', values.sector);
for (const [from, to] of [
['min_amount', 'investment_budget_min'],
['max_amount', 'investment_budget_max'],
] as const) {
if (typeof values[from] === 'string' && values[from] !== '')
query.set(to, values[from]);
}
for (const place of path)
if (
['province', 'district', 'admin_post', 'locality'].includes(
place.location_type,
)
)
query.set(place.location_type + '_id', place.id);
return (
'/investimentos/iniciar' + (query.size ? '?' + query.toString() : '')
);
}
+2 -1
View File
@@ -33,7 +33,8 @@ export const dossierReportSections = [
] as const;
export type DossierReportSectionId =
(typeof dossierReportSections)[number]['id'];
| (typeof dossierReportSections)[number]['id']
| 'supply';
export type DossierReference = {
version: number;
date: string;
+1
View File
@@ -38,6 +38,7 @@ export function simulationApiFieldErrors(
for (const [path, messages] of Object.entries(value.errors ?? {})) {
const key = path
.replace(/^(economic_snapshot|personal_snapshot)\./, '')
.replace(/^selection_labels\./, '')
.split('.')[0];
if (/^[a-z][a-z0-9_]*$/.test(key) && messages.length)
fields[key] = messages.join(' ');
+164 -2
View File
@@ -8,6 +8,114 @@ export type SimulationDraft = Record<string, string | string[]>;
export const projectQuestionnaireVersion =
'investmoz-project-dossier-2026-10-05.1';
export function isAssistedInvestmentJourney(draft: SimulationDraft): boolean {
return (
draft.journey_type === 'investor' &&
['simulate_only', 'own_investment'].includes(String(draft.purpose)) &&
draft.detail_level !== 'advanced'
);
}
export const assistedInvestmentSections = [
{ id: 'purpose', title: 'Intenção, entidade e localização' },
{ id: 'market', title: 'Mercado e dimensão do negócio' },
{ id: 'investment', title: 'Investimento inicial' },
{ id: 'financial', title: 'Financiamento' },
{ id: 'operating', title: 'Receitas e custos' },
{ id: 'cashflow', title: 'Tesouraria e cenários' },
{ id: 'tax', title: 'Enquadramento fiscal' },
{ id: 'review', title: 'Resultados e próximos passos' },
];
/** One field contract for rendering, validation and the final review. */
export function simulationFieldsForSection(
draft: SimulationDraft,
section: string,
) {
if (!isAssistedInvestmentJourney(draft))
return simulationFieldGroups[section] ?? [];
const unique = (fields: (typeof simulationFieldGroups)[string]) =>
fields.filter(
(field, index) =>
fields.findIndex((other) => other.key === field.key) === index,
);
if (section === 'purpose')
return unique([
...simulationFieldGroups.purpose.filter((field) =>
[
'journey_type',
'detail_level',
'purpose',
'preferred_language',
].includes(field.key),
),
...simulationFieldGroups.project.filter((field) =>
[
'project_title',
'project_summary',
'products_services',
'sector_id',
'activity_id',
].includes(field.key),
),
...simulationFieldGroups.location.filter((field) =>
[
'province_id',
'district_id',
'admin_post_id',
'locality_id',
].includes(field.key),
),
]);
if (section === 'market')
return unique([
...simulationFieldGroups.project.filter(
(field) =>
![
'project_title',
'project_summary',
'products_services',
'sector_id',
'activity_id',
].includes(field.key),
),
...simulationFieldGroups.market,
]);
if (section === 'investment')
return simulationFieldGroups.financial.filter((field) =>
['cost_estimate_status', 'currency', 'total_investment'].includes(
field.key,
),
);
if (section === 'financial')
return simulationFieldGroups.financial.filter(
(field) =>
![
'cost_estimate_status',
'currency',
'total_investment',
'annual_revenue',
'annual_operating_costs',
'expected_profit',
'receivables_timing_status',
'planning_loan',
].includes(field.key),
);
if (section === 'operating')
return simulationFieldGroups.financial.filter((field) =>
[
'annual_revenue',
'annual_operating_costs',
'expected_profit',
].includes(field.key),
);
if (section === 'cashflow')
return simulationFieldGroups.financial.filter((field) =>
['receivables_timing_status', 'planning_loan'].includes(field.key),
);
return simulationFieldGroups[section] ?? [];
}
function isProjectGuidedJourney(draft: SimulationDraft): boolean {
return (
draft.purpose === 'simulate_only' &&
@@ -80,6 +188,7 @@ export const simulationSections = [
/** Keep the anonymous arithmetic journey short; formal submissions retain the full questionnaire. */
export function getSimulationSections(draft: SimulationDraft) {
if (isAssistedInvestmentJourney(draft)) return assistedInvestmentSections;
if (isProjectGuidedJourney(draft)) {
if (draft.journey_type === 'small_business') {
return [
@@ -192,7 +301,28 @@ export const advancedSimulationFields = new Set([
'required_documents',
]);
export function simulationFieldAvailableAtDetailLevel(
draft: SimulationDraft,
section: string,
key: string,
): boolean {
return (
draft.detail_level === 'advanced' ||
(isAssistedInvestmentJourney(draft) &&
[
'secured_amount',
'sought_amount',
'annual_revenue',
'annual_operating_costs',
'expected_profit',
].includes(key)) ||
(section === 'procedures' && key === 'required_documents') ||
!advancedSimulationFields.has(key)
);
}
export const simulationOptions: Record<string, string[]> = {
planning_loan: ['yes', 'no', 'unknown'],
journey_type: ['personal', 'small_business', 'company', 'investor'],
detail_level: ['simple', 'advanced'],
purpose: [
@@ -784,6 +914,30 @@ export const simulationFieldGroups: Record<
},
],
financial: [
{
key: 'planning_loan',
label: 'Pretende estudar um empréstimo neste cenário?',
options: 'planning_loan',
showWhen: isAssistedInvestmentJourney,
},
{
key: 'planned_funding',
label: 'Financiamento previsto (ainda não mobilizado)',
type: 'number',
showWhen: isAssistedInvestmentJourney,
},
{
key: 'requested_funding',
label: 'Financiamento solicitado (ainda não mobilizado)',
type: 'number',
showWhen: isAssistedInvestmentJourney,
},
{
key: 'approved_funding',
label: 'Financiamento aprovado (ainda não mobilizado)',
type: 'number',
showWhen: isAssistedInvestmentJourney,
},
{
key: 'cost_estimate_status',
label: 'Já identificou os principais custos e respectiva periodicidade?',
@@ -1540,6 +1694,9 @@ export function restoreSimulationDraft(
export function simulationDraftFingerprint(draft: SimulationDraft): string {
const sort = (value: unknown): unknown => {
// Nullable empty form inputs are normalised to null by the HTTP
// middleware. They remain unknown, never numeric zero.
if (value === null) return '';
if (Array.isArray(value)) return value.map(sort);
if (value && typeof value === 'object')
return Object.fromEntries(
@@ -1561,7 +1718,7 @@ export function validateSimulationDraft(
if (sectionId === 'tax' && draft.fiscal_scenario_mode === 'custom_planning')
return {};
const errors: Record<string, string> = {};
for (const field of simulationFieldGroups[sectionId] ?? []) {
for (const field of simulationFieldsForSection(draft, sectionId)) {
if (field.showWhen && !field.showWhen(draft)) continue;
if (
sectionId === 'tax' &&
@@ -1581,7 +1738,12 @@ export function validateSimulationDraft(
if (
required &&
empty &&
!(sectionId === 'tax' && isInvestorProjectJourney(draft))
!(isAssistedInvestmentJourney(draft) && sectionId !== 'purpose') &&
!(
sectionId === 'tax' &&
(isInvestorProjectJourney(draft) ||
isAssistedInvestmentJourney(draft))
)
) {
errors[field.key] = 'Este campo é obrigatório.';
}