This commit is contained in:
2026-11-02 20:31:15 +02:00
parent 8ddfa93f45
commit 1da273f1f3
131 changed files with 14802 additions and 526 deletions
+20 -1
View File
@@ -1,6 +1,25 @@
import { searchTerritoryHref } from './search-territory.ts';
/** Only a query string is carried; the return destination is always local. */
export function catalogueDetailHref(path: string, query: string): string {
export function catalogueDetailHref(
path: string,
query: string,
pageUrl?: string,
): string {
if (pageUrl) {
const page = new URL(
pageUrl,
'https://portal.invalid',
).searchParams.get('page');
if (
page &&
/^[1-9]\d*$/.test(page) &&
Number.isSafeInteger(Number(page))
) {
const params = new URLSearchParams(query);
params.set('page', page);
query = params.toString();
}
}
return query
? `${path}?catalogue_query=${encodeURIComponent(query)}`
: path;
+23
View File
@@ -0,0 +1,23 @@
type ConditionalField = { when?: { field: string; equals: string } };
export function deskFieldApplies(
key: string,
fields: Record<string, ConditionalField>,
payload: Record<string, unknown>,
ancestors: ReadonlySet<string> = new Set(),
): boolean {
const field = fields[key];
if (!field || ancestors.has(key)) return false;
if (!field.when) return true;
const value = payload[field.when.field];
if (!['string', 'number', 'boolean'].includes(typeof value)) return false;
const answer =
typeof value === 'boolean' ? (value ? '1' : '') : String(value);
if (answer !== field.when.equals) return false;
return deskFieldApplies(
field.when.field,
fields,
payload,
new Set([...ancestors, key]),
);
}
+14 -7
View File
@@ -3,12 +3,19 @@ import type {
PreparationDocument,
} from '@/components/private-investment-preparation';
function csrfToken(): string {
return decodeURIComponent(
document.cookie
.split('; ')
.find((c) => c.startsWith('XSRF-TOKEN='))
?.slice('XSRF-TOKEN='.length) ?? '',
);
try {
return decodeURIComponent(
document.cookie
.split(';')
.map((value) => value.trim())
.find((c) => c.startsWith('XSRF-TOKEN='))
?.slice('XSRF-TOKEN='.length) ?? '',
);
} catch {
throw new Error(
'A sessão não pôde ser validada. Actualize a página e tente novamente.',
);
}
}
export type ContextDocument = {
resource_id: number;
@@ -185,7 +192,7 @@ export async function contextApi<T>(
...(serializedBody === undefined ? {} : { body: serializedBody }),
});
const data = await response.json().catch(() => null);
if (!response.ok)
if (!response.ok || data === null)
throw new Error(
data?.message ||
`Não foi possível recuperar ou guardar o contexto (HTTP ${response.status}).`,
+32
View File
@@ -0,0 +1,32 @@
/** Browser persistence is optional; the current selection remains usable without it. */
const selectionKey = 'investment-opportunity-selection';
export function readOpportunitySelection(): number[] {
try {
const value: unknown = JSON.parse(
sessionStorage.getItem(selectionKey) ?? '[]',
);
if (!Array.isArray(value)) return [];
return [
...new Set(
value.filter(
(id): id is number =>
typeof id === 'number' &&
Number.isSafeInteger(id) &&
id > 0,
),
),
];
} catch {
return [];
}
}
export function persistOpportunitySelection(ids: number[]): boolean {
try {
if (ids.length)
sessionStorage.setItem(selectionKey, JSON.stringify(ids));
else sessionStorage.removeItem(selectionKey);
return true;
} catch {
return false;
}
}
+11 -4
View File
@@ -101,7 +101,9 @@ export class PortalApiError extends Error {
? 'O registo solicitado já não está disponível.'
: status === 422
? 'Verifique os campos assinalados.'
: 'Não foi possível comunicar com o portal. Tente novamente.',
: status === 419
? 'A sessão não pôde ser validada. Actualize a página e tente novamente.'
: 'Não foi possível comunicar com o portal. Tente novamente.',
);
this.status = status;
this.errors = errors;
@@ -122,10 +124,15 @@ export async function portalRequest<T>(
typeof document === 'undefined'
? undefined
: document.cookie
.split('; ')
.split(';')
.map((value) => value.trim())
.find((value) => value.startsWith('XSRF-TOKEN='))
?.slice(11);
if (token) headers.set('X-XSRF-TOKEN', decodeURIComponent(token));
try {
if (token) headers.set('X-XSRF-TOKEN', decodeURIComponent(token));
} catch {
throw new PortalApiError(419);
}
}
const response = await fetch(url, {
...options,
@@ -136,7 +143,7 @@ export async function portalRequest<T>(
if (!response.ok || body === null) {
throw new PortalApiError(
response.status,
response.status === 422 ? body?.errors : undefined,
response.status === 422 ? (body?.errors ?? {}) : undefined,
);
}
return body as T;
+19 -5
View File
@@ -14,6 +14,7 @@ export type PortalNavAccess = {
};
scopedAdministration?: { label: string; href: string }[];
procurement?: boolean;
funding?: boolean;
authenticated: boolean;
manager: boolean;
businesses?: boolean;
@@ -486,11 +487,6 @@ export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
'Porquê investir em Moçambique?',
'/porque-investir',
),
link(
'idea-entry',
'Partir de uma ideia',
'/investimentos/iniciar',
),
link(
'opportunities',
'Consultar oportunidades',
@@ -503,6 +499,24 @@ export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
),
link('sectors', 'Sectores de investimento', '/sectores'),
link('locations', 'Localizações', '/oportunidades?view=map'),
...(access.funding
? [
link(
'funding',
'Fundos e programas de apoio',
'/fundos',
),
...(access.authenticated
? [
link(
'funding-saved',
'Programas que guardei',
'/fundos/guardados',
),
]
: []),
]
: []),
...(access.procurement
? [
link(
+31 -9
View File
@@ -12,29 +12,51 @@ export async function profileJson(
data: object = {},
method: 'GET' | 'POST' = 'POST',
) {
const cookie = document.cookie
.split('; ')
.find((c) => c.startsWith('XSRF-TOKEN='));
let token = '';
if (method !== 'GET') {
const cookie =
typeof document === 'undefined'
? undefined
: document.cookie
.split(';')
.map((value) => value.trim())
.find((value) => value.startsWith('XSRF-TOKEN='));
try {
token = cookie ? decodeURIComponent(cookie.slice(11)) : '';
} catch {
throw new ProfileValidationError(
'A sessão não pôde ser validada. Actualize a página e tente novamente.',
{},
);
}
}
const response = await fetch(url, {
method,
credentials: 'same-origin',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': cookie ? decodeURIComponent(cookie.slice(11)) : '',
...(method === 'GET' ? {} : { 'X-XSRF-TOKEN': token }),
},
...(method === 'GET' ? {} : { body: JSON.stringify(data) }),
});
const result = await response.json();
if (!response.ok)
const result = await response.json().catch(() => null);
const reauthenticate =
response.headers.get('X-Portal-Reauthentication') === 'required';
if (!response.ok || (result === null && response.status !== 204))
throw new ProfileValidationError(
result.message ?? 'A ação não foi concluída.',
typeof result?.message === 'string'
? result.message
: response.status === 419
? 'A sessão expirou. Actualize a página e tente novamente.'
: 'A ação não foi concluída. Tente novamente.',
Object.fromEntries(
Object.entries(result.errors ?? {}).map(([key, value]) => [
Object.entries(result?.errors ?? {}).map(([key, value]) => [
key,
Array.isArray(value) ? value.join(' ') : String(value),
]),
),
response.headers.get('X-Portal-Reauthentication') === 'required',
reauthenticate,
);
return result;
}
@@ -0,0 +1,85 @@
import {
publicRecordOfflineHtml,
downloadOfflineHtml,
offlineValue as display,
} from './public-record-offline.ts';
export type PublicBusinessOffline = {
slug: string;
title: string;
modality: string;
objective?: string | null;
stage?: string | null;
activity_code?: string | null;
amount_min?: string | null;
amount_max?: string | null;
available_percentage?: string | null;
currency?: string | null;
province?: string | null;
district?: string | null;
locality?: string | null;
published_at?: string | null;
sector?: { name: string } | null;
};
/** Fixed public projection: private or future properties are never serialised. */
export function publicBusinessOfflineHtml(
record: PublicBusinessOffline,
modalityLabel: string,
origin: string,
savedAt: Date,
): string {
const rows: [string, string][] = [
['Modalidade', display(modalityLabel)],
['Sector', display(record.sector?.name)],
['Fase', display(record.stage)],
['Actividade', display(record.activity_code)],
[
'Localização divulgada',
[record.locality, record.district, record.province]
.filter(Boolean)
.join(', ') || 'Não indicada',
],
[
'Montante mínimo indicado',
display(record.amount_min) +
(record.currency ? ` ${record.currency}` : ''),
],
[
'Montante máximo indicado',
display(record.amount_max) +
(record.currency ? ` ${record.currency}` : ''),
],
[
'Participação indicada',
record.available_percentage
? `${record.available_percentage}%`
: 'Não indicada',
],
['Publicação no portal', display(record.published_at)],
];
return publicRecordOfflineHtml(
{
title: record.title,
kind: 'Ficha p\u00fablica de neg\u00f3cio',
sourcePath: `/negocios/${encodeURIComponent(record.slug)}`,
rows,
sections: [{ title: 'Objectivo', text: display(record.objective) }],
notice: 'A publica\u00e7\u00e3o n\u00e3o constitui garantia de titularidade, avalia\u00e7\u00e3o, transmissibilidade ou retorno.',
},
origin,
savedAt,
);
}
export function downloadPublicBusinessOffline(
record: PublicBusinessOffline,
modalityLabel: string,
): void {
const html = publicBusinessOfflineHtml(
record,
modalityLabel,
window.location.origin,
new Date(),
);
downloadOfflineHtml(html, 'negocio', record.slug || 'ficha');
}
@@ -0,0 +1,87 @@
import {
publicRecordOfflineHtml,
downloadOfflineHtml,
offlineValue as display,
} from './public-record-offline.ts';
type PublicOpportunity = {
title: string;
slug: string;
reference: string;
summary?: string | null;
description?: string | null;
sector?: { name: string } | null;
province?: string | null;
district?: string | null;
maturity_label?: string | null;
estimated_investment_amount?: string | null;
estimated_investment_currency?: string | null;
financing_modality?: string | null;
expected_impact?: string | null;
last_validated_at?: string | null;
};
export function publicOpportunityOfflineHtml(
record: PublicOpportunity,
origin: string,
savedAt: Date,
): string {
return publicRecordOfflineHtml(
{
title: record.title,
kind: 'Ficha pública de oportunidade',
sourcePath: `/oportunidades/${encodeURIComponent(record.slug)}`,
rows: [
['Referência', display(record.reference)],
['Sector', display(record.sector?.name)],
['Preparação', display(record.maturity_label)],
[
'Contexto territorial indicado na ficha',
[record.district, record.province]
.filter(Boolean)
.join(', ') || 'Não indicado',
],
[
'Investimento estimado',
display(record.estimated_investment_amount) +
(record.estimated_investment_currency
? ` ${record.estimated_investment_currency}`
: ''),
],
[
'Modalidade de financiamento',
display(record.financing_modality),
],
[
'Última validação indicada',
display(record.last_validated_at),
],
],
sections: [
{ title: 'Resumo', text: display(record.summary) },
{ title: 'Descrição', text: display(record.description) },
{
title: 'Impacto esperado',
text: display(record.expected_impact),
},
],
notice: 'O contexto territorial não confirma a implantação. A execução depende das condições e autorizações aplicáveis ao projecto. Esta cópia não inclui mapas, anexos ou dados do dossier privado.',
},
origin,
savedAt,
);
}
export function downloadPublicOpportunityOffline(
record: PublicOpportunity,
): void {
downloadOfflineHtml(
publicOpportunityOfflineHtml(
record,
window.location.origin,
new Date(),
),
'oportunidade',
record.slug || 'ficha',
);
}
+64
View File
@@ -0,0 +1,64 @@
type OfflineContent = {
title: string;
kind: string;
sourcePath: string;
rows: [string, string][];
sections: { title: string; text: string }[];
notice: string;
};
export const offlineValue = (value?: string | null) =>
value?.trim() || 'Não indicado';
const escapeHtml = (value: string) =>
value.replace(
/[&<>"']/g,
(character) =>
({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
})[character]!,
);
/** All content is plain text; assets and executable content are excluded. */
export function publicRecordOfflineHtml(
content: OfflineContent,
origin: string,
savedAt: Date,
): string {
const base = new URL(origin);
if (!['http:', 'https:'].includes(base.protocol))
throw new Error('Origem do portal inválida.');
const source = new URL(content.sourcePath, base.origin);
if (
source.origin !== base.origin ||
!content.sourcePath.startsWith('/') ||
content.sourcePath.startsWith('//')
)
throw new Error('Referência da ficha inválida.');
return `<!doctype html><html lang="pt-MZ"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"><title>${escapeHtml(content.title)} — consulta offline</title><style>body{font:1rem/1.6 system-ui,sans-serif;margin:2rem auto;padding:0 1rem;max-width:55rem;color:#172b23;background:white}h1{line-height:1.2;overflow-wrap:anywhere}dt{font-weight:700}dd{margin:0 0 1rem;white-space:pre-wrap;overflow-wrap:anywhere}p{white-space:pre-wrap;overflow-wrap:anywhere}a{color:#14623d}footer{border-top:1px solid #ccc;margin-top:2rem;padding-top:1rem}</style></head><body><main><h1>${escapeHtml(content.title)}</h1><p>${escapeHtml(content.kind)} — InvesteMoz</p><p>Cópia guardada em ${escapeHtml(savedAt.toISOString())}. Consulte a ficha online para verificar actualizações.</p><dl>${content.rows.map(([label, value]) => `<dt>${escapeHtml(label)}</dt><dd>${escapeHtml(value)}</dd>`).join('')}</dl>${content.sections.map((section) => `<h2>${escapeHtml(section.title)}</h2><p>${escapeHtml(section.text)}</p>`).join('')}<p>${escapeHtml(content.notice)}</p><p><a href="${escapeHtml(source.href)}" rel="noreferrer">Consultar a ficha de origem online</a></p></main><footer>Fonte: ficha pública no portal InvesteMoz. Esta cópia conserva a informação apresentada no momento em que foi guardada.</footer></body></html>`;
}
export function downloadOfflineHtml(
html: string,
prefix: string,
slug: string,
): void {
const url = URL.createObjectURL(
new Blob([html], { type: 'text/html;charset=utf-8' }),
);
const link = document.createElement('a');
link.href = url;
link.download =
`${prefix}-${slug}`.replace(/[^a-zA-Z0-9_-]/g, '-').slice(0, 120) +
'.html';
try {
document.body.appendChild(link);
link.click();
} finally {
link.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
}
}