fix: make financial institution local presence explicit

This commit is contained in:
Codex
2026-11-15 19:34:01 +02:00
parent bd000d04d2
commit afa02559a1
11 changed files with 689 additions and 763 deletions
@@ -155,6 +155,10 @@ final class FundingProgrammeController extends Controller
'sector' => ['nullable', 'integer', Rule::in(Sector::choices()->whereNotNull('published_at')->pluck('id')->all())], 'sector' => ['nullable', 'integer', Rule::in(Sector::choices()->whereNotNull('published_at')->pluck('id')->all())],
'certainty' => 'nullable|in:include_unknown,documented', 'state' => 'nullable|in:open,closed,upcoming,unknown']); 'certainty' => 'nullable|in:include_unknown,documented', 'state' => 'nullable|in:open,closed,upcoming,unknown']);
$filters = array_filter($filters, fn ($value) => $value !== null && $value !== ''); $filters = array_filter($filters, fn ($value) => $value !== null && $value !== '');
// A local search excludes unlocated records unless explicitly requested.
if (($filters['location_mode'] ?? '') === 'physical' && ! isset($filters['certainty'])) {
$filters['certainty'] = 'documented';
}
$dossier = $request->user() && ! empty($filters['context']) ? app(FundingDossierPreparation::class)->context($request->user(), $filters['context'], $filters['opportunity'] ?? null) : null; $dossier = $request->user() && ! empty($filters['context']) ? app(FundingDossierPreparation::class)->context($request->user(), $filters['context'], $filters['opportunity'] ?? null) : null;
$explicitLocation = $request->hasAny(['territory', 'province_id', 'district_id', 'admin_post_id', 'locality_id']); $explicitLocation = $request->hasAny(['territory', 'province_id', 'district_id', 'admin_post_id', 'locality_id']);
if ($dossier && ! $explicitLocation && empty($filters['territory']) && $dossier['territory']) { if ($dossier && ! $explicitLocation && empty($filters['territory']) && $dossier['territory']) {
@@ -10224,3 +10224,7 @@ A Tempo autorizou expressamente `3558647e`, incluindo menus, mantendo fecho púb
# Instalação exacta das Ofertas — falha antes da promoção e correcção QA, 14/11/2026 # Instalação exacta das Ofertas — falha antes da promoção e correcção QA, 14/11/2026
O fast-forward autorizado `96f51096 → 3558647e` foi efectuado sem força ou commits posteriores. Janela com path automático pausado, lock exclusivo e chamada única ao executor existente, recusando qualquer outro SHA. Novo backup/restauro isolado 219 tabelas/417 ficheiros aprovado. O executor passou schema isolado 1/3106 e build, mas parou em tipos: colisão Wayfinder entre a acção GET `reportForm` e o formulário gerado para POST `report`. Sem promoção, migrações, alteração operacional ou reversão; homologação servida permanece `96f51096`, 219 tabelas/417 ficheiros reconferidos intactos. Lock libertado, path original restaurado, fila vazia. Correcção mínima em QA: acção GET `reportPage`, mesmo URL e corpo, com geração real/produção/tipos/PHPStan/Pint e 28 testes/403 asserções aprovados, numa base isolada separada da prévia. Nenhum novo push ou instalação. Relatório: `../v2/auditoria-portal/ofertas-instalacao-privada-incidente-wayfinder-20261114.md`; recibo `outputs/offers-exact-install-20261114/qa-result.json`. Nova revisão correctiva exige autorização expressa antes de integrar/instalar; publicação, correio, pagamentos e decisões jurídicas continuam nos limites anteriores. O fast-forward autorizado `96f51096 → 3558647e` foi efectuado sem força ou commits posteriores. Janela com path automático pausado, lock exclusivo e chamada única ao executor existente, recusando qualquer outro SHA. Novo backup/restauro isolado 219 tabelas/417 ficheiros aprovado. O executor passou schema isolado 1/3106 e build, mas parou em tipos: colisão Wayfinder entre a acção GET `reportForm` e o formulário gerado para POST `report`. Sem promoção, migrações, alteração operacional ou reversão; homologação servida permanece `96f51096`, 219 tabelas/417 ficheiros reconferidos intactos. Lock libertado, path original restaurado, fila vazia. Correcção mínima em QA: acção GET `reportPage`, mesmo URL e corpo, com geração real/produção/tipos/PHPStan/Pint e 28 testes/403 asserções aprovados, numa base isolada separada da prévia. Nenhum novo push ou instalação. Relatório: `../v2/auditoria-portal/ofertas-instalacao-privada-incidente-wayfinder-20261114.md`; recibo `outputs/offers-exact-install-20261114/qa-result.json`. Nova revisão correctiva exige autorização expressa antes de integrar/instalar; publicação, correio, pagamentos e decisões jurídicas continuam nos limites anteriores.
### 2026-11-15 — pesquisa local de instituições
AUD-FUND-01: diagnóstico e delta sobre bd000d04 registados em `../v2/auditoria-portal/apresentacao-contexto-qa-20261115.md`. Filtros existentes; corrigidas em código a predefinição física e a apresentação das moradas/incerteza. 10 testes frontend aprovados; API, tipos globais/build e visual da candidata por concluir. Sem instalação ou alteração de dados.
@@ -230,3 +230,14 @@ A captura nativa do Edge recuperou nesta passagem; o conector de abas continua a
Foram observados em computador e em emulação móvel (390 px e 360 × 844): cartões em uma coluna, leitura da variação temporal, abertura da série anual, ano ausente como «Sem dados» e recuperação do detalhe de fontes/originais. A primeira captura móvel detectou palavras comprimidas na tabela original; foi aplicada largura mínima com deslocamento interno, seguida de nova conferência. As capturas são evidência da **prévia de componentes**, não de aceitação autenticada integral ou de utilização num telefone físico. Foram observados em computador e em emulação móvel (390 px e 360 × 844): cartões em uma coluna, leitura da variação temporal, abertura da série anual, ano ausente como «Sem dados» e recuperação do detalhe de fontes/originais. A primeira captura móvel detectou palavras comprimidas na tabela original; foi aplicada largura mínima com deslocamento interno, seguida de nova conferência. As capturas são evidência da **prévia de componentes**, não de aceitação autenticada integral ou de utilização num telefone físico.
Continuam pendentes a conferência autenticada dos percursos completos e a aceitação do responsável. Sem instalação no activo, sem alteração do esquema ou de permissões e sem envio externo. A pendência de obter/comparar o bundle fica encerrada por esta reconciliação selectiva. Continuam pendentes a conferência autenticada dos percursos completos e a aceitação do responsável. Sem instalação no activo, sem alteração do esquema ou de permissões e sem envio externo. A pendência de obter/comparar o bundle fica encerrada por esta reconciliação selectiva.
## 2026-11-15 — localização nas instituições financeiras (AUD-FUND-01)
Base conferida: bd000d04. Na homologação, os selectores de província/distrito/posto/localidade existem. A pesquisa por presença física em Tete com inclusão de desconhecidos devolveu 140 resultados; os primeiros cartões não mostravam moradas nem assinalavam presença por confirmar. Ao seleccionar apenas âmbito documentado, o resultado mudou para instituições com presença cadastrada, incluindo Access Bank, Socremo e seguradoras. Esta observação não certifica que todos os balcões reais estejam cadastrados ou actualizados.
Delta preparado em ramo isolado: modo e território juntos; pesquisa depois dos critérios; modo físico começa com âmbito documentado, mantendo a escolha explícita de desconhecidos e URLs anteriores; o controlador aplica a mesma predefinição quando omitida. Cartões mostram a morada no território escolhido, sem mostrar a sede de outra província como presença local. Desconhecidos incluídos voluntariamente recebem indicação específica. O detalhe conserva todas as moradas existentes e o retorno conserva critérios. Nenhum registo, fonte ou permissão foi alterado. Cobertura de financiamento permanece distinta de presença física.
Verificação: 10 testes frontend aprovados (3 novos), incluindo renderização dos componentes reais, critérios dependentes, retorno explícito de desconhecidos e preservação do detalhe; lint dirigido e git diff --check aprovados. Teste HTTP acrescentado a FundingCriteriaCoherenceTest, não executado neste ambiente sem PHP/PostgreSQL. TypeScript global executado mas bloqueado pela ausência de módulos routes/actions gerados; sem diagnósticos nos ficheiros funding alterados. Não foi executado build global nem conferência visual da candidata. A observação visual refere-se apenas ao activo anterior.
Entrega: patch e bundle a produzir a partir de bd000d04; sem push autenticado ou instalação nesta sessão. Antes de instalar, executar o teste HTTP na base QA isolada já definida no teste, gerar routes/actions, concluir tipos/build e conferir a candidata em computador e móvel. Não repetir testes fiscais ou importar dados para esta correcção.
File diff suppressed because one or more lines are too long
+131 -180
View File
@@ -2,17 +2,15 @@ import {
ClassificationFields, ClassificationFields,
evidenceLabels, evidenceLabels,
type Classification, type Classification,
} from '@/components/funding-classification'; } from "@/components/funding-classification";
import { import {
fundingPublicPresentation, fundingPublicPresentation,
publicInstitutionContacts, publicInstitutionContacts,
publicInstitutionLocations, publicInstitutionLocations,
} from '@/lib/funding-public-presentation'; matchingInstitutionLocations,
import { } from "@/lib/funding-public-presentation";
financialCategories, import { financialCategories, financialTypes } from "@/components/funding-classification";
financialTypes, import { card, input, button } from "@/pages/investment/shared";
} from '@/components/funding-classification';
import { card, input, button } from '@/pages/investment/shared';
export type FundingSource = { export type FundingSource = {
source_url: string | null; source_url: string | null;
@@ -33,7 +31,7 @@ export type FundingLocation = FundingSource & {
label: string; label: string;
address: string; address: string;
territory_id: string; territory_id: string;
territory_path?: { name: string }[]; territory_path?: { id?: string; name: string }[];
}; };
export type FundingProduct = FundingSource & { export type FundingProduct = FundingSource & {
code: string; code: string;
@@ -57,22 +55,22 @@ export type InstitutionDetails = Classification & {
products: FundingProduct[]; products: FundingProduct[];
}; };
export const emptyInstitution: InstitutionDetails = { export const emptyInstitution: InstitutionDetails = {
institution_key: '', institution_key: "",
institution_nature: 'unknown', institution_nature: "unknown",
contacts: [], contacts: [],
locations: [], locations: [],
products: [], products: [],
}; };
const source: FundingSource = { const source: FundingSource = {
source_url: '', source_url: "",
source_reference: '', source_reference: "",
checked_on: '', checked_on: "",
}; };
function Text({ function Text({
label, label,
value, value,
change, change,
type = 'text', type = "text",
}: { }: {
label: string; label: string;
value: string; value: string;
@@ -85,8 +83,8 @@ function Text({
<input <input
className={input} className={input}
type={type} type={type}
value={value ?? ''} value={value ?? ""}
maxLength={type === 'text' ? 1500 : undefined} maxLength={type === "text" ? 1500 : undefined}
onChange={(e) => change(e.target.value)} onChange={(e) => change(e.target.value)}
/> />
</label> </label>
@@ -105,24 +103,20 @@ function Sources({
<Text <Text
label="Endereço da fonte" label="Endereço da fonte"
type="url" type="url"
value={value.source_url ?? ''} value={value.source_url ?? ""}
change={(source_url) => change({ source_url })} change={(source_url) => change({ source_url })}
/> />
{!value.source_url && ( {!value.source_url && (
<> <>
<Text <Text
label="Documento de origem" label="Documento de origem"
value={value.source_document_name ?? ''} value={value.source_document_name ?? ""}
change={(source_document_name) => change={(source_document_name) => change({ source_document_name })}
change({ source_document_name })
}
/> />
<Text <Text
label="SHA-256 do original" label="SHA-256 do original"
value={value.source_document_sha256 ?? ''} value={value.source_document_sha256 ?? ""}
change={(source_document_sha256) => change={(source_document_sha256) => change({ source_document_sha256 })}
change({ source_document_sha256 })
}
/> />
</> </>
)} )}
@@ -131,10 +125,8 @@ function Sources({
Situação desta informação Situação desta informação
<select <select
className={input} className={input}
value={value.evidence_status ?? 'to_confirm'} value={value.evidence_status ?? "to_confirm"}
onChange={(e) => onChange={(e) => change({ evidence_status: e.target.value })}
change({ evidence_status: e.target.value })
}
> >
{Object.entries(evidenceLabels).map(([key, label]) => ( {Object.entries(evidenceLabels).map(([key, label]) => (
<option key={key} value={key}> <option key={key} value={key}>
@@ -171,22 +163,20 @@ export function InstitutionFields({
natures: Record<string, string>; natures: Record<string, string>;
needs: Record<string, string>; needs: Record<string, string>;
}) { }) {
const update = <K extends 'contacts' | 'locations' | 'products'>( const update = <K extends "contacts" | "locations" | "products">(
key: K, key: K,
index: number, index: number,
patch: Partial<InstitutionDetails[K][number]>, patch: Partial<InstitutionDetails[K][number]>,
) => ) =>
change({ change({
[key]: value[key].map((row, i) => [key]: value[key].map((row, i) => (i === index ? { ...row, ...patch } : row)),
i === index ? { ...row, ...patch } : row,
),
}); });
return ( return (
<section className={card}> <section className={card}>
<h2>Instituição, presença física e produtos</h2> <h2>Instituição, presença física e produtos</h2>
<p> <p>
A sede ou balcão não determina a cobertura do financiamento. Não A sede ou balcão não determina a cobertura do financiamento. Não preencha condições
preencha condições desconhecidas por inferência. desconhecidas por inferência.
</p> </p>
<ClassificationFields value={value} change={change} needs={needs} /> <ClassificationFields value={value} change={change} needs={needs} />
<Text <Text
@@ -199,9 +189,7 @@ export function InstitutionFields({
<select <select
className={input} className={input}
value={value.institution_nature} value={value.institution_nature}
onChange={(e) => onChange={(e) => change({ institution_nature: e.target.value })}
change({ institution_nature: e.target.value })
}
> >
{Object.entries(natures).map(([id, label]) => ( {Object.entries(natures).map(([id, label]) => (
<option key={id} value={id}> <option key={id} value={id}>
@@ -218,15 +206,13 @@ export function InstitutionFields({
<select <select
className={input} className={input}
value={row.kind} value={row.kind}
onChange={(e) => onChange={(e) => update("contacts", i, { kind: e.target.value })}
update('contacts', i, { kind: e.target.value })
}
> >
{Object.entries({ {Object.entries({
website: 'Página institucional', website: "Página institucional",
email: 'Email', email: "Email",
phone: 'Telefone', phone: "Telefone",
address: 'Endereço postal', address: "Endereço postal",
}).map(([id, label]) => ( }).map(([id, label]) => (
<option key={id} value={id}> <option key={id} value={id}>
{label} {label}
@@ -236,19 +222,14 @@ export function InstitutionFields({
<Text <Text
label="Contacto documentado" label="Contacto documentado"
value={row.value} value={row.value}
change={(v) => update('contacts', i, { value: v })} change={(v) => update("contacts", i, { value: v })}
/>
<Sources
value={row}
change={(v) => update('contacts', i, v)}
/> />
<Sources value={row} change={(v) => update("contacts", i, v)} />
<button <button
type="button" type="button"
onClick={() => onClick={() =>
change({ change({
contacts: value.contacts.filter( contacts: value.contacts.filter((_, n) => n !== i),
(_, n) => n !== i,
),
}) })
} }
> >
@@ -264,7 +245,7 @@ export function InstitutionFields({
change({ change({
contacts: [ contacts: [
...value.contacts, ...value.contacts,
{ ...source, kind: 'website', value: '' }, { ...source, kind: "website", value: "" },
], ],
}) })
} }
@@ -273,18 +254,14 @@ export function InstitutionFields({
</button> </button>
</details> </details>
<details> <details>
<summary> <summary>Sede e balcões ({value.locations.length}) — Alterar</summary>
Sede e balcões ({value.locations.length}) — Alterar
</summary>
{value.locations.map((row, i) => ( {value.locations.map((row, i) => (
<fieldset className={card} key={i}> <fieldset className={card} key={i}>
<legend>Local físico {i + 1}</legend> <legend>Local físico {i + 1}</legend>
<select <select
className={input} className={input}
value={row.role} value={row.role}
onChange={(e) => onChange={(e) => update("locations", i, { role: e.target.value })}
update('locations', i, { role: e.target.value })
}
> >
<option value="headquarters">Sede</option> <option value="headquarters">Sede</option>
<option value="branch">Balcão</option> <option value="branch">Balcão</option>
@@ -295,31 +272,25 @@ export function InstitutionFields({
<Text <Text
label="Designação" label="Designação"
value={row.label} value={row.label}
change={(label) => change={(label) => update("locations", i, { label })}
update('locations', i, { label })
}
/> />
<Text <Text
label="Morada documentada" label="Morada documentada"
value={row.address} value={row.address}
change={(address) => change={(address) => update("locations", i, { address })}
update('locations', i, { address })
}
/> />
<label> <label>
Local do cadastro Local do cadastro
<select <select
className={input} className={input}
value={row.territory_id ?? ''} value={row.territory_id ?? ""}
onChange={(e) => onChange={(e) =>
update('locations', i, { update("locations", i, {
territory_id: e.target.value, territory_id: e.target.value,
}) })
} }
> >
<option value=""> <option value="">Correspondência por confirmar</option>
Correspondência por confirmar
</option>
{territories.map((t) => ( {territories.map((t) => (
<option key={t.id} value={t.id}> <option key={t.id} value={t.id}>
{t.name} {t.name}
@@ -327,17 +298,12 @@ export function InstitutionFields({
))} ))}
</select> </select>
</label> </label>
<Sources <Sources value={row} change={(v) => update("locations", i, v)} />
value={row}
change={(v) => update('locations', i, v)}
/>
<button <button
type="button" type="button"
onClick={() => onClick={() =>
change({ change({
locations: value.locations.filter( locations: value.locations.filter((_, n) => n !== i),
(_, n) => n !== i,
),
}) })
} }
> >
@@ -355,10 +321,10 @@ export function InstitutionFields({
...value.locations, ...value.locations,
{ {
...source, ...source,
role: 'headquarters', role: "headquarters",
label: '', label: "",
address: '', address: "",
territory_id: '', territory_id: "",
}, },
], ],
}) })
@@ -368,23 +334,19 @@ export function InstitutionFields({
</button> </button>
</details> </details>
<details> <details>
<summary> <summary>Programas/produtos ({value.products.length}) — Alterar</summary>
Programas/produtos ({value.products.length}) — Alterar
</summary>
{value.products.map((row, i) => ( {value.products.map((row, i) => (
<fieldset className={card} key={row.code}> <fieldset className={card} key={row.code}>
<legend>Produto {i + 1}</legend> <legend>Produto {i + 1}</legend>
<Text <Text
label="Nome documentado" label="Nome documentado"
value={row.title} value={row.title}
change={(title) => update('products', i, { title })} change={(title) => update("products", i, { title })}
/> />
<Text <Text
label="Instrumento" label="Instrumento"
value={row.instrument} value={row.instrument}
change={(instrument) => change={(instrument) => update("products", i, { instrument })}
update('products', i, { instrument })
}
/> />
<label> <label>
Necessidades documentadas Necessidades documentadas
@@ -393,11 +355,8 @@ export function InstitutionFields({
className={input} className={input}
value={row.needs} value={row.needs}
onChange={(e) => onChange={(e) =>
update('products', i, { update("products", i, {
needs: Array.from( needs: Array.from(e.target.selectedOptions, (o) => o.value),
e.target.selectedOptions,
(o) => o.value,
),
}) })
} }
> >
@@ -414,22 +373,18 @@ export function InstitutionFields({
className={input} className={input}
value={row.coverage} value={row.coverage}
onChange={(e) => onChange={(e) =>
update('products', i, { update("products", i, {
coverage: e.target.value, coverage: e.target.value,
territory_ids: [], territory_ids: [],
}) })
} }
> >
<option value="unknown">Por confirmar</option> <option value="unknown">Por confirmar</option>
<option value="national"> <option value="national">Nacional, segundo a fonte</option>
Nacional, segundo a fonte <option value="territorial">Locais documentados</option>
</option>
<option value="territorial">
Locais documentados
</option>
</select> </select>
</label> </label>
{row.coverage === 'territorial' && ( {row.coverage === "territorial" && (
<label> <label>
Locais abrangidos Locais abrangidos
<select <select
@@ -437,7 +392,7 @@ export function InstitutionFields({
className={input} className={input}
value={row.territory_ids} value={row.territory_ids}
onChange={(e) => onChange={(e) =>
update('products', i, { update("products", i, {
territory_ids: Array.from( territory_ids: Array.from(
e.target.selectedOptions, e.target.selectedOptions,
(o) => o.value, (o) => o.value,
@@ -456,9 +411,7 @@ export function InstitutionFields({
<Text <Text
label="Explicação da cobertura" label="Explicação da cobertura"
value={row.coverage_text} value={row.coverage_text}
change={(coverage_text) => change={(coverage_text) => update("products", i, { coverage_text })}
update('products', i, { coverage_text })
}
/> />
<label> <label>
Condições — vazio significa por confirmar Condições — vazio significa por confirmar
@@ -467,7 +420,7 @@ export function InstitutionFields({
value={row.conditions} value={row.conditions}
maxLength={4000} maxLength={4000}
onChange={(e) => onChange={(e) =>
update('products', i, { update("products", i, {
conditions: e.target.value, conditions: e.target.value,
}) })
} }
@@ -476,9 +429,7 @@ export function InstitutionFields({
<Text <Text
label="Montantes/moeda/prazos documentados — se conhecidos" label="Montantes/moeda/prazos documentados — se conhecidos"
value={row.amounts} value={row.amounts}
change={(amounts) => change={(amounts) => update("products", i, { amounts })}
update('products', i, { amounts })
}
/> />
<label> <label>
Disponibilidade Disponibilidade
@@ -486,40 +437,30 @@ export function InstitutionFields({
className={input} className={input}
value={row.availability} value={row.availability}
onChange={(e) => onChange={(e) =>
update('products', i, { update("products", i, {
availability: e.target.value, availability: e.target.value,
}) })
} }
> >
<option value="unknown">Por confirmar</option> <option value="unknown">Por confirmar</option>
<option value="documented"> <option value="documented">
Oferta identificada na fonte (não é Oferta identificada na fonte (não é concessão)
concessão)
</option>
<option value="closed">
Encerrada segundo a fonte
</option> </option>
<option value="closed">Encerrada segundo a fonte</option>
</select> </select>
</label> </label>
<Text <Text
label="Canal de contacto do produto" label="Canal de contacto do produto"
type="url" type="url"
value={row.contact_url} value={row.contact_url}
change={(contact_url) => change={(contact_url) => update("products", i, { contact_url })}
update('products', i, { contact_url })
}
/>
<Sources
value={row}
change={(v) => update('products', i, v)}
/> />
<Sources value={row} change={(v) => update("products", i, v)} />
<button <button
type="button" type="button"
onClick={() => onClick={() =>
change({ change({
products: value.products.filter( products: value.products.filter((_, n) => n !== i),
(_, n) => n !== i,
),
}) })
} }
> >
@@ -538,16 +479,16 @@ export function InstitutionFields({
{ {
...source, ...source,
code: crypto.randomUUID(), code: crypto.randomUUID(),
title: '', title: "",
instrument: '', instrument: "",
needs: [], needs: [],
coverage: 'unknown', coverage: "unknown",
coverage_text: '', coverage_text: "",
territory_ids: [], territory_ids: [],
conditions: '', conditions: "",
amounts: '', amounts: "",
availability: 'unknown', availability: "unknown",
contact_url: '', contact_url: "",
}, },
], ],
}) })
@@ -562,35 +503,51 @@ export function InstitutionFields({
export function InstitutionView({ export function InstitutionView({
value, value,
compact = false, compact = false,
physicalTerritory,
}: { }: {
value: InstitutionDetails & { title?: string; summary?: string }; value: InstitutionDetails & { title?: string; summary?: string };
compact?: boolean; compact?: boolean;
physicalTerritory?: string;
}) { }) {
const presentation = fundingPublicPresentation({ const presentation = fundingPublicPresentation({
...value, ...value,
title: value.title ?? '', title: value.title ?? "",
summary: value.summary ?? '', summary: value.summary ?? "",
kind: 'institution', kind: "institution",
}), }),
contacts = publicInstitutionContacts(value.contacts), contacts = publicInstitutionContacts(value.contacts),
locations = publicInstitutionLocations(value.locations); locations = publicInstitutionLocations(value.locations);
const localPresence = physicalTerritory
? matchingInstitutionLocations(value.locations, physicalTerritory)
: [];
const visibleLocations =
physicalTerritory && compact
? publicInstitutionLocations(
localPresence.map((location) => ({
...location,
address:
location.address?.trim() ||
location.territory_path?.map((node) => node.name).join(" / ") ||
location.location_text ||
location.label,
})),
)
: locations;
const category = (value.institution_categories ?? []) const category = (value.institution_categories ?? [])
.map((k) => financialCategories[k]) .map((k) => financialCategories[k])
.filter(Boolean) .filter(Boolean)
.join(' · '), .join(" · "),
types = (value.institution_types ?? []) types = (value.institution_types ?? [])
.map((k) => financialTypes[k]) .map((k) => financialTypes[k])
.filter(Boolean) .filter(Boolean)
.join(' · '); .join(" · ");
const urls = new Set<string>( const urls = new Set<string>(
compact compact
? [] ? []
: presentation.products : presentation.products.map((p) => p.url).filter((url): url is string => !!url),
.map((p) => p.url)
.filter((url): url is string => !!url),
); );
const sites = contacts const sites = contacts
.filter((c) => c.kind === 'website') .filter((c) => c.kind === "website")
.filter((c) => { .filter((c) => {
if (urls.has(c.value)) return false; if (urls.has(c.value)) return false;
urls.add(c.value); urls.add(c.value);
@@ -598,11 +555,7 @@ export function InstitutionView({
}); });
return ( return (
<section className="space-y-4" aria-label="Informação da instituição"> <section className="space-y-4" aria-label="Informação da instituição">
{!compact && ( {!compact && <h2 className="text-lg font-semibold">Instituição financeira</h2>}
<h2 className="text-lg font-semibold">
Instituição financeira
</h2>
)}
<div> <div>
<h3 className="font-semibold">Descrição</h3> <h3 className="font-semibold">Descrição</h3>
<p>{presentation.description}</p> <p>{presentation.description}</p>
@@ -610,13 +563,13 @@ export function InstitutionView({
{(category || types) && ( {(category || types) && (
<p> <p>
{category} {category}
{category && types ? ': ' : ''} {category && types ? ": " : ""}
{types} {types}
</p> </p>
)} )}
{['historical', 'merged'].includes( {["historical", "merged"].includes(value.institution_status ?? "") && (
value.institution_status ?? '', <p>Instituição histórica ou integrada noutra entidade.</p>
) && <p>Instituição histórica ou integrada noutra entidade.</p>} )}
<div> <div>
<h3 className="font-semibold">Produtos e serviços</h3> <h3 className="font-semibold">Produtos e serviços</h3>
{presentation.products.length ? ( {presentation.products.length ? (
@@ -635,17 +588,15 @@ export function InstitutionView({
) : ( ) : (
<strong>{p.title}</strong> <strong>{p.title}</strong>
)} )}
{p.detail ? ': ' + p.detail : ''} {p.detail ? ": " + p.detail : ""}
</li> </li>
))} ))}
</ul> </ul>
) : presentation.services.length ? ( ) : presentation.services.length ? (
<p>{presentation.services.join(' · ')}</p> <p>{presentation.services.join(" · ")}</p>
) : null} ) : null}
</div> </div>
{!compact && {!compact && (sites.length > 0 || contacts.some((c) => c.kind !== "website")) && (
(sites.length > 0 ||
contacts.some((c) => c.kind !== 'website')) && (
<div> <div>
<h3 className="font-semibold">Contactos</h3> <h3 className="font-semibold">Contactos</h3>
<ul className="space-y-1"> <ul className="space-y-1">
@@ -662,26 +613,17 @@ export function InstitutionView({
</li> </li>
))} ))}
{contacts {contacts
.filter((c) => c.kind !== 'website') .filter((c) => c.kind !== "website")
.map((c) => ( .map((c) => (
<li key={c.kind + c.value}> <li key={c.kind + c.value}>
{c.kind === 'email' ? ( {c.kind === "email" ? (
<a <a className="underline" href={"mailto:" + c.value}>
className="underline"
href={'mailto:' + c.value}
>
{c.value} {c.value}
</a> </a>
) : c.kind === 'phone' ? ( ) : c.kind === "phone" ? (
<a <a
className="underline" className="underline"
href={ href={"tel:" + c.value.replace(/[^+0-9]/g, "")}
'tel:' +
c.value.replace(
/[^+0-9]/g,
'',
)
}
> >
{c.value} {c.value}
</a> </a>
@@ -693,19 +635,28 @@ export function InstitutionView({
</ul> </ul>
</div> </div>
)} )}
{!compact && locations.length > 0 && ( {physicalTerritory && localPresence.length === 0 && (
<p className="rounded border border-amber-600 p-2">
Presença física por confirmar no local escolhido.
</p>
)}
{visibleLocations.length > 0 && (
<div> <div>
<h3 className="font-semibold">Localização</h3> <h3 className="font-semibold">
{physicalTerritory && compact
? "Presença no local escolhido"
: "Localização"}
</h3>
<ul className="space-y-1"> <ul className="space-y-1">
{locations.map((l, i) => ( {visibleLocations.map((l, i) => (
<li key={i}> <li key={i}>
{l.role === 'headquarters' {l.role === "headquarters"
? 'Sede: ' ? "Sede: "
: l.role === 'branch' : l.role === "branch"
? 'Balcão: ' ? "Balcão: "
: ''} : ""}
{l.address} {l.address}
{l.hours ? ' · ' + l.hours : ''} {l.hours ? " · " + l.hours : ""}
</li> </li>
))} ))}
</ul> </ul>
+76 -76
View File
@@ -13,115 +13,101 @@ export type PublicFunding = {
}[]; }[];
}; };
const descriptions: Record<string, string> = { const descriptions: Record<string, string> = {
commercial_bank: 'Instituição de banca comercial.', commercial_bank: "Instituição de banca comercial.",
investment_bank: 'Instituição especializada em banca de investimento.', investment_bank: "Instituição especializada em banca de investimento.",
bank: 'Instituição bancária.', bank: "Instituição bancária.",
microbank: 'Instituição de microfinanças.', microbank: "Instituição de microfinanças.",
cooperative: 'Cooperativa de crédito.', cooperative: "Cooperativa de crédito.",
savings: 'Organização de poupança e empréstimo.', savings: "Organização de poupança e empréstimo.",
investment_manager: investment_manager: "Sociedade especializada na gestão de fundos de investimento.",
'Sociedade especializada na gestão de fundos de investimento.', investment_company: "Sociedade de investimento.",
investment_company: 'Sociedade de investimento.', pension_manager: "Entidade gestora de fundos de pensões.",
pension_manager: 'Entidade gestora de fundos de pensões.', insurer: "Instituição do sector segurador.",
insurer: 'Instituição do sector segurador.', reinsurer: "Instituição especializada em resseguros.",
reinsurer: 'Instituição especializada em resseguros.', microinsurer: "Instituição de microsseguros.",
microinsurer: 'Instituição de microsseguros.', broker: "Entidade de corretagem de seguros.",
broker: 'Entidade de corretagem de seguros.', agent: "Entidade de mediação de seguros.",
agent: 'Entidade de mediação de seguros.', reinsurance_broker: "Entidade de corretagem de resseguros.",
reinsurance_broker: 'Entidade de corretagem de resseguros.', exchange_house: "Instituição de serviços cambiais.",
exchange_house: 'Instituição de serviços cambiais.', electronic_money: "Instituição de moeda electrónica.",
electronic_money: 'Instituição de moeda electrónica.', interbank: "Entidade de serviços interbancários.",
interbank: 'Entidade de serviços interbancários.', supervisor: "Entidade de supervisão do sistema financeiro.",
supervisor: 'Entidade de supervisão do sistema financeiro.',
}; };
const services: Record<string, string> = { const services: Record<string, string> = {
equity: 'Capital e participação no investimento', equity: "Capital e participação no investimento",
foreign_exchange: 'Câmbio', foreign_exchange: "Câmbio",
guarantee: 'Garantias', guarantee: "Garantias",
insurance: 'Seguros', insurance: "Seguros",
investment: 'Financiamento do investimento', investment: "Financiamento do investimento",
investment_management: 'Gestão de investimentos', investment_management: "Gestão de investimentos",
payments: 'Serviços de pagamento', payments: "Serviços de pagamento",
pension: 'Pensões', pension: "Pensões",
working_capital: 'Financiamento de tesouraria', working_capital: "Financiamento de tesouraria",
}; };
export function fundingPublicPresentation(p: PublicFunding) { export function fundingPublicPresentation(p: PublicFunding) {
const generic = const generic =
!p.summary.trim() || !p.summary.trim() ||
p.summary.trim() === p.summary.trim() ===
'Instituição identificada no documento fornecido. Categoria, localização e contactos são informativos; produtos, disponibilidade e condições não documentados permanecem por confirmar.'; "Instituição identificada no documento fornecido. Categoria, localização e contactos são informativos; produtos, disponibilidade e condições não documentados permanecem por confirmar.";
let description = generic let description = generic
? (descriptions[p.institution_types?.[0] ?? ''] ?? ? (descriptions[p.institution_types?.[0] ?? ""] ?? "Entidade do sector financeiro.")
'Entidade do sector financeiro.')
: p.summary : p.summary
.replace( .replace(/\s*Referência informativa, não concessão de financiamento\.?$/, "")
/\s*Referência informativa, não concessão de financiamento\.?$/, .replace(/Público\/finalidade:/g, "Soluções para")
'', .replace(/\.\./g, ".")
)
.replace(/Público\/finalidade:/g, 'Soluções para')
.replace(/\.\./g, '.')
.trim(); .trim();
const repeatedInstrument = (p.products ?? []).some( const repeatedInstrument = (p.products ?? []).some(
(product) => (product) =>
product.instrument?.trim() && product.instrument?.trim() && description.startsWith(product.instrument.trim()),
description.startsWith(product.instrument.trim()),
); );
if (repeatedInstrument) { if (repeatedInstrument) {
const audience = description.match( const audience = description.match(/Soluções para\s+(.+?)(?:\.|$)/i)?.[1];
/Soluções para\s+(.+?)(?:\.|$)/i,
)?.[1];
description = audience description = audience
? 'Soluções financeiras para ' + ? "Soluções financeiras para " +
audience.charAt(0).toLowerCase() + audience.charAt(0).toLowerCase() +
audience.slice(1) + audience.slice(1) +
'.' "."
: (descriptions[p.institution_types?.[0] ?? ''] ?? description); : (descriptions[p.institution_types?.[0] ?? ""] ?? description);
} }
const products = (p.products ?? []) const products = (p.products ?? [])
.filter((x) => x.availability !== 'closed') .filter((x) => x.availability !== "closed")
.map((x) => ({ .map((x) => ({
title: x.title.startsWith(p.title + ' — ') title: x.title.startsWith(p.title + " — ")
? x.title.slice(p.title.length + 3) ? x.title.slice(p.title.length + 3)
: x.title, : x.title,
detail: x.instrument?.trim() ?? '', detail: x.instrument?.trim() ?? "",
url: x.contact_url || x.source_url || null, url: x.contact_url || x.source_url || null,
})); }));
return { return {
description, description,
products, products,
services: [ services: [
...new Set( ...new Set((p.institution_services ?? []).map((s) => services[s]).filter(Boolean)),
(p.institution_services ?? [])
.map((s) => services[s])
.filter(Boolean),
),
], ],
}; };
} }
const normal = (s: string) => const normal = (s: string) =>
s s
.normalize('NFD') .normalize("NFD")
.replace(/[\u0300-\u036f]/g, '') .replace(/[\u0300-\u036f]/g, "")
.toLowerCase() .toLowerCase()
.replace(/[^a-z0-9]+/g, ' ') .replace(/[^a-z0-9]+/g, " ")
.trim(); .trim();
export function publicInstitutionContacts< export function publicInstitutionContacts<T extends { kind: string; value: string }>(rows: T[]) {
T extends { kind: string; value: string },
>(rows: T[]) {
const seen = new Set<string>(); const seen = new Set<string>();
return rows.flatMap((row) => { return rows.flatMap((row) => {
const value = const value =
row.kind === 'phone' row.kind === "phone"
? row.value.replace(/\s*Não encontrado\.?$/i, '').trim() ? row.value.replace(/\s*Não encontrado\.?$/i, "").trim()
: row.value.trim(); : row.value.trim();
if (!value) return []; if (!value) return [];
const key = const key =
row.kind + row.kind +
':' + ":" +
(row.kind === 'phone' (row.kind === "phone"
? value.replace(/\D/g, '') ? value.replace(/\D/g, "")
: value.toLowerCase().replace(/\/$/, '')); : value.toLowerCase().replace(/\/$/, ""));
if (seen.has(key)) return []; if (seen.has(key)) return [];
seen.add(key); seen.add(key);
return [{ ...row, value }]; return [{ ...row, value }];
@@ -137,31 +123,27 @@ export function publicInstitutionLocations<
>(rows: T[]) { >(rows: T[]) {
const result: T[] = []; const result: T[] = [];
for (const row of [...rows].sort( for (const row of [...rows].sort(
(a, b) => (a, b) => (a.role === "headquarters" ? 0 : 1) - (b.role === "headquarters" ? 0 : 1),
(a.role === 'headquarters' ? 0 : 1) -
(b.role === 'headquarters' ? 0 : 1),
)) { )) {
if (!row.address?.trim()) continue; if (!row.address?.trim()) continue;
const address = normal(row.address); const address = normal(row.address);
const duplicate = result.some((previous) => { const duplicate = result.some((previous) => {
const other = normal(previous.address ?? ''); const other = normal(previous.address ?? "");
if (address === other) return true; if (address === other) return true;
const short = address.length < other.length ? address : other, const short = address.length < other.length ? address : other,
long = address.length < other.length ? other : address; long = address.length < other.length ? other : address;
if (!long.startsWith(short + ' ')) return false; if (!long.startsWith(short + " ")) return false;
const rest = long.slice(short.length).trim(); const rest = long.slice(short.length).trim();
const localities = [ const localities = [
row.location_text ?? '', row.location_text ?? "",
previous.location_text ?? '', previous.location_text ?? "",
...(row.territory_path ?? []).map((x) => x.name), ...(row.territory_path ?? []).map((x) => x.name),
...(previous.territory_path ?? []).map((x) => x.name), ...(previous.territory_path ?? []).map((x) => x.name),
].map(normal); ].map(normal);
return ( return (
localities.includes(rest) || localities.includes(rest) ||
localities.some( localities.some(
(x) => (x) => x.replace(/^cidade de /, "") === rest.replace(/^cidade de /, ""),
x.replace(/^cidade de /, '') ===
rest.replace(/^cidade de /, ''),
) )
); );
}); });
@@ -169,3 +151,21 @@ export function publicInstitutionLocations<
} }
return result; return result;
} }
/** Only a documented point inside the requested territory establishes local presence. */
export function matchingInstitutionLocations<
T extends {
territory_id?: string;
territory_path?: { id?: string; name: string }[];
evidence_status?: string | null;
},
>(locations: T[], territory: string): T[] {
return locations.filter(
(location) =>
!["to_confirm", "historical", "conflict", "unlocated"].includes(
location.evidence_status ?? "reported",
) &&
(location.territory_id === territory ||
location.territory_path?.some((node) => node.id === territory)),
);
}
+134 -177
View File
@@ -1,19 +1,10 @@
import { import { InstitutionView, type InstitutionDetails } from "@/components/funding-institution";
InstitutionView, import { financialCategories, financialTypes } from "@/components/funding-classification";
type InstitutionDetails, import { Link, useForm } from "@inertiajs/react";
} from '@/components/funding-institution'; import { Frame, card, button } from "@/pages/investment/shared";
import { import { type Programme, windowLabels } from "./shared";
financialCategories, import { useRef, useState } from "react";
financialTypes, import { TerritoryFields, type TerritoryOption } from "@/components/investment-territory";
} from '@/components/funding-classification';
import { Link, useForm } from '@inertiajs/react';
import { Frame, card, button } from '@/pages/investment/shared';
import { type Programme, windowLabels } from './shared';
import { useRef, useState } from 'react';
import {
TerritoryFields,
type TerritoryOption,
} from '@/components/investment-territory';
export default function FundingIndex(props: Parameters<typeof Index>[0]) { export default function FundingIndex(props: Parameters<typeof Index>[0]) {
return <Index key={JSON.stringify(props.filters)} {...props} />; return <Index key={JSON.stringify(props.filters)} {...props} />;
@@ -63,33 +54,35 @@ function Index({
territorySelection?: TerritoryOption[]; territorySelection?: TerritoryOption[];
criteriaErrors?: Record<string, string[]>; criteriaErrors?: Record<string, string[]>;
}) { }) {
const [notice, setNotice] = useState(''); const [notice, setNotice] = useState("");
const form = useForm({ const form = useForm({
category: filters.category ?? '', category: filters.category ?? "",
institution_type: filters.institution_type ?? '', institution_type: filters.institution_type ?? "",
location_mode: filters.location_mode ?? 'coverage', location_mode: filters.location_mode ?? "coverage",
include_historical: filters.include_historical ?? '0', include_historical: filters.include_historical ?? "0",
context: filters.context ?? '', context: filters.context ?? "",
opportunity: filters.opportunity ?? '', opportunity: filters.opportunity ?? "",
need: filters.need ?? '', need: filters.need ?? "",
q: filters.q ?? '', q: filters.q ?? "",
kind: filters.kind ?? '', kind: filters.kind ?? "",
sector: filters.sector ?? '', sector: filters.sector ?? "",
territory: filters.territory ?? '', territory: filters.territory ?? "",
province_id: filters.province_id ?? '', province_id: filters.province_id ?? "",
district_id: filters.district_id ?? '', district_id: filters.district_id ?? "",
admin_post_id: filters.admin_post_id ?? '', admin_post_id: filters.admin_post_id ?? "",
locality_id: filters.locality_id ?? '', locality_id: filters.locality_id ?? "",
certainty: filters.certainty ?? 'include_unknown', certainty:
state: filters.state ?? '', filters.certainty ??
(filters.location_mode === "physical" ? "documented" : "include_unknown"),
state: filters.state ?? "",
}); });
const applied = useRef(JSON.stringify(form.data)); const applied = useRef(JSON.stringify(form.data));
const criteriaChanged = JSON.stringify(form.data) !== applied.current; const criteriaChanged = JSON.stringify(form.data) !== applied.current;
const typeAllowed = (category: string, type: string) => const typeAllowed = (category: string, type: string) =>
!category || !category ||
category === 'other' || category === "other" ||
!type || !type ||
type === 'other' || type === "other" ||
(categoryTypes[category] ?? []).includes(type); (categoryTypes[category] ?? []).includes(type);
return ( return (
<Frame title="Instituições financeiras, fundos e programas de apoio"> <Frame title="Instituições financeiras, fundos e programas de apoio">
@@ -102,33 +95,25 @@ function Index({
A minha selecção A minha selecção
</Link> </Link>
<p> <p>
Encontre bancos, seguradoras, fundos e outros parceiros Encontre bancos, seguradoras, fundos e outros parceiros financeiros. Explore as
financeiros. Explore as soluções e os contactos adequados ao seu soluções e os contactos adequados ao seu investimento.
investimento.
</p> </p>
<form <form
className={`${card} flex flex-wrap gap-4 [&_select]:w-full [&_select]:max-w-full [&_select]:min-w-0 [&>label]:w-full [&>label]:max-w-full [&>label]:min-w-0 sm:[&>label]:w-auto`} className={`${card} flex flex-wrap gap-4 [&_select]:w-full [&_select]:max-w-full [&_select]:min-w-0 [&>label]:w-full [&>label]:max-w-full [&>label]:min-w-0 sm:[&>label]:w-auto`}
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
form.get('/fundos'); form.get("/fundos");
}} }}
> >
{Object.keys(criteriaErrors).length > 0 && ( {Object.keys(criteriaErrors).length > 0 && (
<aside <aside className="basis-full rounded border border-amber-600 p-3" role="alert">
className="basis-full rounded border border-amber-600 p-3" <h2 className="font-semibold">Reveja esta combinação de critérios</h2>
role="alert" {Object.entries(criteriaErrors).map(([key, messages]) => (
> <p key={key}>{messages.join(" ")}</p>
<h2 className="font-semibold"> ))}
Reveja esta combinação de critérios
</h2>
{Object.entries(criteriaErrors).map(
([key, messages]) => (
<p key={key}>{messages.join(' ')}</p>
),
)}
<p> <p>
A pesquisa não foi executada. Corrija os critérios A pesquisa não foi executada. Corrija os critérios indicados e volte a
indicados e volte a pesquisar. pesquisar.
</p> </p>
</aside> </aside>
)} )}
@@ -143,16 +128,15 @@ function Index({
</p> </p>
))} ))}
{form.data.kind && {form.data.kind &&
form.data.kind !== 'institution' && form.data.kind !== "institution" &&
(form.data.category || (form.data.category ||
form.data.institution_type || form.data.institution_type ||
form.data.location_mode === 'physical') && ( form.data.location_mode === "physical") && (
<aside className="basis-full rounded border p-3"> <aside className="basis-full rounded border p-3">
<p> <p>
Categoria, tipo de instituição e presença física Categoria, tipo de instituição e presença física não identificam um
não identificam um fundo ou programa. Reveja o fundo ou programa. Reveja o tipo de registo ou retire apenas estes
tipo de registo ou retire apenas estes critérios critérios incompatíveis.
incompatíveis.
</p> </p>
<button <button
type="button" type="button"
@@ -160,17 +144,16 @@ function Index({
onClick={() => { onClick={() => {
form.setData({ form.setData({
...form.data, ...form.data,
category: '', category: "",
institution_type: '', institution_type: "",
location_mode: 'coverage', location_mode: "coverage",
}); });
setNotice( setNotice(
'Critérios de instituição retirados por sua escolha. Local, sector, necessidade e janela foram preservados.', "Critérios de instituição retirados por sua escolha. Local, sector, necessidade e janela foram preservados.",
); );
}} }}
> >
Manter o fundo/programa e rever os critérios de Manter o fundo/programa e rever os critérios de instituição
instituição
</button> </button>
</aside> </aside>
)} )}
@@ -181,31 +164,24 @@ function Index({
value={form.data.category} value={form.data.category}
onChange={(e) => { onChange={(e) => {
const category = e.target.value; const category = e.target.value;
const valid = typeAllowed( const valid = typeAllowed(category, form.data.institution_type);
category,
form.data.institution_type,
);
if (!valid) if (!valid)
setNotice( setNotice(
'O tipo anterior não pertence à nova categoria e foi retirado. Escolha um dos tipos aplicáveis.', "O tipo anterior não pertence à nova categoria e foi retirado. Escolha um dos tipos aplicáveis.",
); );
form.setData({ form.setData({
...form.data, ...form.data,
category, category,
institution_type: valid institution_type: valid ? form.data.institution_type : "",
? form.data.institution_type
: '',
}); });
}} }}
> >
<option value="">Todas</option> <option value="">Todas</option>
{Object.entries(financialCategories).map( {Object.entries(financialCategories).map(([id, label]) => (
([id, label]) => (
<option key={id} value={id}> <option key={id} value={id}>
{label} {label}
</option> </option>
), ))}
)}
</select> </select>
</label> </label>
<label> <label>
@@ -213,9 +189,7 @@ function Index({
<select <select
className="block rounded border p-2" className="block rounded border p-2"
value={form.data.institution_type} value={form.data.institution_type}
onChange={(e) => onChange={(e) => form.setData("institution_type", e.target.value)}
form.setData('institution_type', e.target.value)
}
> >
<option value="">Todos</option> <option value="">Todos</option>
{Object.entries(financialTypes) {Object.entries(financialTypes)
@@ -228,48 +202,27 @@ function Index({
<option key={id} value={id}> <option key={id} value={id}>
{typeAllowed(form.data.category, id) {typeAllowed(form.data.category, id)
? label ? label
: 'Incompatível: ' + label} : "Incompatível: " + label}
</option> </option>
))} ))}
</select> </select>
</label> </label>
<label>
Localização a pesquisar
<select
className="block rounded border p-2"
value={form.data.location_mode}
onChange={(e) =>
form.setData('location_mode', e.target.value)
}
>
<option value="physical">
Sede, balcão ou presença física
</option>
<option value="coverage">
Cobertura do financiamento/produto
</option>
</select>
</label>
<label> <label>
<input <input
type="checkbox" type="checkbox"
checked={form.data.include_historical === '1'} checked={form.data.include_historical === "1"}
onChange={(e) => onChange={(e) =>
form.setData( form.setData("include_historical", e.target.checked ? "1" : "0")
'include_historical',
e.target.checked ? '1' : '0',
)
} }
/> />
Incluir instituições históricas/fundidas, identificadas como Incluir instituições históricas/fundidas, identificadas como tal
tal
</label> </label>
<label> <label>
Necessidade do processo Necessidade do processo
<select <select
className="block rounded border p-2" className="block rounded border p-2"
value={form.data.need} value={form.data.need}
onChange={(e) => form.setData('need', e.target.value)} onChange={(e) => form.setData("need", e.target.value)}
> >
<option value="">Todas / por identificar</option> <option value="">Todas / por identificar</option>
{Object.entries(needs).map(([id, label]) => ( {Object.entries(needs).map(([id, label]) => (
@@ -285,7 +238,7 @@ function Index({
className="block rounded border p-2" className="block rounded border p-2"
value={form.data.q} value={form.data.q}
maxLength={150} maxLength={150}
onChange={(e) => form.setData('q', e.target.value)} onChange={(e) => form.setData("q", e.target.value)}
/> />
</label> </label>
<label> <label>
@@ -293,7 +246,7 @@ function Index({
<select <select
className="block rounded border p-2" className="block rounded border p-2"
value={form.data.kind} value={form.data.kind}
onChange={(e) => form.setData('kind', e.target.value)} onChange={(e) => form.setData("kind", e.target.value)}
> >
<option value="">Todos</option> <option value="">Todos</option>
{Object.entries(kinds).map(([key, name]) => ( {Object.entries(kinds).map(([key, name]) => (
@@ -303,15 +256,12 @@ function Index({
))} ))}
</select> </select>
</label> </label>
<button className={button} disabled={form.processing}>
Pesquisar
</button>
<label> <label>
Sector Sector
<select <select
className="block rounded border p-2" className="block rounded border p-2"
value={form.data.sector} value={form.data.sector}
onChange={(e) => form.setData('sector', e.target.value)} onChange={(e) => form.setData("sector", e.target.value)}
> >
<option value="">Todos</option> <option value="">Todos</option>
{options.sectors.map((item) => ( {options.sectors.map((item) => (
@@ -322,36 +272,51 @@ function Index({
</select> </select>
</label> </label>
<fieldset className="min-w-0 basis-full"> <fieldset className="min-w-0 basis-full">
<legend> <legend>Local de interesse — seleccione até ao nível conhecido</legend>
Local de interesse — seleccione até ao nível conhecido <label>
</legend> Localização a pesquisar
<select
className="block rounded border p-2"
value={form.data.location_mode}
onChange={(e) =>
form.setData({
...form.data,
location_mode: e.target.value,
certainty:
e.target.value === "physical"
? "documented"
: form.data.certainty,
})
}
>
<option value="physical">Sede, balcão ou presença física</option>
<option value="coverage">Cobertura do financiamento/produto</option>
</select>
</label>
<p className="mb-3 text-sm">
Escolha a província e, se necessário, o distrito. Sede e balcões identificam
onde pode contactar a instituição; a cobertura indica onde o financiamento
se aplica.
</p>
<TerritoryFields <TerritoryFields
initial={territorySelection} initial={territorySelection}
showMap={false} showMap={false}
onChange={(path) => onChange={(path) =>
form.setData({ form.setData({
...form.data, ...form.data,
territory: path.at(-1)?.id ?? '', territory: path.at(-1)?.id ?? "",
province_id: province_id:
path.find( path.find((node) => node.location_type === "province")?.id ??
(node) => "",
node.location_type === 'province',
)?.id ?? '',
district_id: district_id:
path.find( path.find((node) => node.location_type === "district")?.id ??
(node) => "",
node.location_type === 'district',
)?.id ?? '',
admin_post_id: admin_post_id:
path.find( path.find((node) => node.location_type === "admin_post")?.id ??
(node) => "",
node.location_type === 'admin_post',
)?.id ?? '',
locality_id: locality_id:
path.find( path.find((node) => node.location_type === "locality")?.id ??
(node) => "",
node.location_type === 'locality',
)?.id ?? '',
}) })
} }
/> />
@@ -361,13 +326,9 @@ function Index({
<select <select
className="block rounded border p-2" className="block rounded border p-2"
value={form.data.certainty} value={form.data.certainty}
onChange={(e) => onChange={(e) => form.setData("certainty", e.target.value)}
form.setData('certainty', e.target.value)
}
> >
<option value="include_unknown"> <option value="include_unknown">Incluir e assinalar</option>
Incluir e assinalar
</option>
<option value="documented"> <option value="documented">
Apenas âmbito documentado para os filtros escolhidos Apenas âmbito documentado para os filtros escolhidos
</option> </option>
@@ -378,7 +339,7 @@ function Index({
<select <select
className="block rounded border p-2" className="block rounded border p-2"
value={form.data.state} value={form.data.state}
onChange={(e) => form.setData('state', e.target.value)} onChange={(e) => form.setData("state", e.target.value)}
> >
<option value="">Qualquer estado</option> <option value="">Qualquer estado</option>
{Object.entries(windowLabels).map(([key, label]) => ( {Object.entries(windowLabels).map(([key, label]) => (
@@ -388,37 +349,35 @@ function Index({
))} ))}
</select> </select>
</label> </label>
<button className={button} disabled={form.processing}>
Pesquisar
</button>
</form> </form>
{criteriaChanged && ( {criteriaChanged && (
<p role="status"> <p role="status">
Alterou os critérios. Clique em Pesquisar para os aplicar. Alterou os critérios. Clique em Pesquisar para os aplicar. Os resultados
Os resultados anteriores ficam separados abaixo. anteriores ficam separados abaixo.
</p> </p>
)} )}
<details <details
open={ open={!criteriaChanged && Object.keys(criteriaErrors).length === 0}
!criteriaChanged && Object.keys(criteriaErrors).length === 0
}
className="space-y-3" className="space-y-3"
> >
<summary> <summary>
{Object.keys(criteriaErrors).length {Object.keys(criteriaErrors).length
? 'Pesquisa não executada — critérios inválidos' ? "Pesquisa não executada — critérios inválidos"
: criteriaChanged : criteriaChanged
? 'Resultados da pesquisa anterior — não correspondem aos critérios por aplicar' ? "Resultados da pesquisa anterior — não correspondem aos critérios por aplicar"
: 'Resultados correspondentes à pesquisa'} : "Resultados correspondentes à pesquisa"}
</summary> </summary>
<p className="text-sm"> <p className="text-sm">
Explore as instituições e soluções adequadas ao seu Explore as instituições e soluções adequadas ao seu investimento. Use os filtros
investimento. Use os filtros para encontrar a informação de para encontrar a informação de que precisa.
que precisa.
</p> </p>
{items.data.length === 0 && {items.data.length === 0 && Object.keys(criteriaErrors).length === 0 && (
Object.keys(criteriaErrors).length === 0 && (
<p> <p>
Não foram encontradas instituições, fundos ou Não foram encontradas instituições, fundos ou programas publicados que
programas publicados que correspondam a todos os correspondam a todos os critérios desta pesquisa.
critérios desta pesquisa.
</p> </p>
)} )}
{items.data.map((item) => ( {items.data.map((item) => (
@@ -426,14 +385,19 @@ function Index({
<h2 className="text-xl font-semibold"> <h2 className="text-xl font-semibold">
<Link <Link
className="underline" className="underline"
href={`/fundos/${item.id}?${new URLSearchParams(Object.entries(filters).filter((entry): entry is [string, string] => typeof entry[1] === 'string'))}`} href={`/fundos/${item.id}?${new URLSearchParams(Object.entries(filters).filter((entry): entry is [string, string] => typeof entry[1] === "string"))}`}
> >
{item.payload.title} {item.payload.title}
</Link> </Link>
</h2> </h2>
{item.payload.kind === 'institution' ? ( {item.payload.kind === "institution" ? (
<InstitutionView <InstitutionView
compact compact
physicalTerritory={
filters.location_mode === "physical"
? filters.territory
: undefined
}
value={ value={
item.payload as InstitutionDetails & { item.payload as InstitutionDetails & {
title: string; title: string;
@@ -444,30 +408,25 @@ function Index({
) : ( ) : (
<> <>
<p>{item.payload.summary}</p> <p>{item.payload.summary}</p>
<p> <p>Entidade gestora: {item.payload.manager_name}</p>
Entidade gestora:{' '} {Object.entries(item.filter_explanation ?? {}).map(
{item.payload.manager_name} ([key, message]) => (
</p>
{Object.entries(
item.filter_explanation ?? {},
).map(([key, message]) => (
<p key={key}>{message}</p> <p key={key}>{message}</p>
))} ),
)}
</> </>
)} )}
{item.payload.kind === 'institution' && {item.payload.kind === "institution" &&
item.payload.windows.length === 0 ? null : item.payload item.payload.windows.length === 0 ? null : item.payload.windows.length ===
.windows.length === 0 ? ( 0 ? (
<p> <p>
Não existe uma janela de candidatura confirmada Não existe uma janela de candidatura confirmada para este programa.
para este programa.
</p> </p>
) : ( ) : (
<ul> <ul>
{item.payload.windows.map((window) => ( {item.payload.windows.map((window) => (
<li key={window.code}> <li key={window.code}>
{window.title}:{' '} {window.title}: {windowLabels[window.state]}
{windowLabels[window.state]}
</li> </li>
))} ))}
</ul> </ul>
@@ -480,12 +439,10 @@ function Index({
<Link <Link
key={index} key={index}
href={link.url} href={link.url}
aria-current={link.active ? 'page' : undefined} aria-current={link.active ? "page" : undefined}
className="underline" className="underline"
> >
{link.label {link.label.replace(/&laquo;/g, "«").replace(/&raquo;/g, "»")}
.replace(/&laquo;/g, '«')
.replace(/&raquo;/g, '»')}
</Link> </Link>
) : null, ) : null,
)} )}
+46 -69
View File
@@ -1,16 +1,10 @@
import { fundingPublicPresentation } from '@/lib/funding-public-presentation'; import { fundingPublicPresentation } from "@/lib/funding-public-presentation";
import { import { InstitutionView, type InstitutionDetails } from "@/components/funding-institution";
InstitutionView, import { FundingDossierChoice, type FundingDossier } from "@/components/funding-dossier-choice";
type InstitutionDetails, import { Link, router } from "@inertiajs/react";
} from '@/components/funding-institution'; import FundingCriteriaAssessment from "@/components/funding-criteria-assessment";
import { import { Frame, card, button } from "@/pages/investment/shared";
FundingDossierChoice, import { type Programme, windowLabels } from "./shared";
type FundingDossier,
} from '@/components/funding-dossier-choice';
import { Link, router } from '@inertiajs/react';
import FundingCriteriaAssessment from '@/components/funding-criteria-assessment';
import { Frame, card, button } from '@/pages/investment/shared';
import { type Programme, windowLabels } from './shared';
export default function Show({ export default function Show({
record, record,
@@ -35,14 +29,14 @@ export default function Show({
<Link className="underline" href="/fundos/guardados"> <Link className="underline" href="/fundos/guardados">
A minha selecção A minha selecção
</Link> </Link>
<Link <Link className="underline" href={`/fundos?${new URLSearchParams(selection)}`}>
className="underline"
href={`/fundos?${new URLSearchParams(selection)}`}
>
Voltar aos fundos e programas Voltar aos fundos e programas
</Link> </Link>
{payload.kind === 'institution' ? ( {payload.kind === "institution" ? (
<InstitutionView <InstitutionView
physicalTerritory={
selection.location_mode === "physical" ? selection.territory : undefined
}
value={ value={
payload as InstitutionDetails & { payload as InstitutionDetails & {
title: string; title: string;
@@ -58,7 +52,7 @@ export default function Show({
)} )}
{authenticated && ( {authenticated && (
<FundingDossierChoice <FundingDossierChoice
key={`${record.id}:${record.version_id}:${dossier?.id ?? ''}:${dossier?.opportunity ?? ''}:${selection.territory ?? ''}`} key={`${record.id}:${record.version_id}:${dossier?.id ?? ""}:${dossier?.opportunity ?? ""}:${selection.territory ?? ""}`}
record={record} record={record}
dossier={dossier} dossier={dossier}
selection={selection} selection={selection}
@@ -66,36 +60,33 @@ export default function Show({
destinations={destinations} destinations={destinations}
/> />
)} )}
{payload.kind !== 'institution' && ( {payload.kind !== "institution" && (
<> <>
{' '} {" "}
<p>Entidade responsável: {payload.manager_name}.</p> <p>Entidade responsável: {payload.manager_name}.</p>
{(payload.territory_paths ?? []).map((path, index) => ( {(payload.territory_paths ?? []).map((path, index) => (
<p key={index}> <p key={index}>
Local abrangido:{' '} Local abrangido: {path.map((node) => node.name).join(" / ")}
{path.map((node) => node.name).join(' / ')}
</p> </p>
))} ))}
<p> <p>
Sectores:{' '} Sectores:{" "}
{payload.sectors_text || {payload.sectors_text ||
(payload.sectors_scope === 'all' (payload.sectors_scope === "all"
? 'Todos, segundo a fonte' ? "Todos, segundo a fonte"
: payload.sectors_scope === 'unknown' : payload.sectors_scope === "unknown"
? 'Por confirmar' ? "Por confirmar"
: (payload.sector_snapshots ?? []) : (payload.sector_snapshots ?? [])
.map((sector) => sector.name) .map((sector) => sector.name)
.join(', '))} .join(", "))}
</p> </p>
<p> <p>
{payload.coverage === 'national' {payload.coverage === "national"
? 'Cobertura nacional' ? "Cobertura nacional"
: payload.coverage === 'territorial' : payload.coverage === "territorial"
? 'Cobertura territorial' ? "Cobertura territorial"
: 'Cobertura por confirmar'} : "Cobertura por confirmar"}
{payload.coverage_text {payload.coverage_text ? ` — ${payload.coverage_text}` : ""}
? ` — ${payload.coverage_text}`
: ''}
</p> </p>
{payload.source_url && ( {payload.source_url && (
<details> <details>
@@ -108,24 +99,16 @@ export default function Show({
> >
Consultar informação da entidade Consultar informação da entidade
</a> </a>
<p> <p>Actualização consultada em {payload.source_checked_on}.</p>
Actualização consultada em{' '}
{payload.source_checked_on}.
</p>
</details> </details>
)} )}
</> </>
)} )}
{(payload.kind !== 'institution' || payload.windows.length > 0) && ( {(payload.kind !== "institution" || payload.windows.length > 0) && (
<section className={card}> <section className={card}>
<h2 className="text-xl font-semibold"> <h2 className="text-xl font-semibold">Janelas de candidatura</h2>
Janelas de candidatura
</h2>
{payload.windows.length === 0 && ( {payload.windows.length === 0 && (
<p> <p>Não há uma janela de candidatura confirmada para este programa.</p>
Não há uma janela de candidatura confirmada para
este programa.
</p>
)} )}
{payload.windows.map((item) => ( {payload.windows.map((item) => (
<article key={item.code} className="my-4"> <article key={item.code} className="my-4">
@@ -135,18 +118,16 @@ export default function Show({
{item.end_on && <p>Data-limite: {item.end_on}</p>} {item.end_on && <p>Data-limite: {item.end_on}</p>}
{item.coverage_text && <p>{item.coverage_text}</p>} {item.coverage_text && <p>{item.coverage_text}</p>}
<p> <p>
{item.coverage === 'programme' {item.coverage === "programme"
? 'Mesma cobertura do programa' ? "Mesma cobertura do programa"
: item.coverage === 'national' : item.coverage === "national"
? 'Chamada nacional' ? "Chamada nacional"
: item.coverage === 'unknown' : item.coverage === "unknown"
? 'Cobertura da chamada por confirmar' ? "Cobertura da chamada por confirmar"
: 'Chamada territorial'} : "Chamada territorial"}
</p> </p>
{(item.territory_paths ?? []).map((path, index) => ( {(item.territory_paths ?? []).map((path, index) => (
<p key={index}> <p key={index}>{path.map((node) => node.name).join(" / ")}</p>
{path.map((node) => node.name).join(' / ')}
</p>
))} ))}
<a <a
className="underline" className="underline"
@@ -171,13 +152,11 @@ export default function Show({
))} ))}
</section> </section>
)} )}
{(payload.kind !== 'institution' || {(payload.kind !== "institution" ||
payload.criteria.length > 0 || payload.criteria.length > 0 ||
payload.windows.some( payload.windows.some((window) => window.criteria.length > 0)) && (
(window) => window.criteria.length > 0,
)) && (
<FundingCriteriaAssessment <FundingCriteriaAssessment
key={record.id + ':' + record.version_id} key={record.id + ":" + record.version_id}
record={record} record={record}
/> />
)} )}
@@ -210,15 +189,13 @@ export default function Show({
<p> <p>
Guardado na versão {saved.version} Guardado na versão {saved.version}
{saved.version !== record.version {saved.version !== record.version
? '; existe uma versão pública mais recente' ? "; existe uma versão pública mais recente"
: ''} : ""}
. .
</p> </p>
<button <button
className={button} className={button}
onClick={() => onClick={() => router.delete(`/fundos/${record.id}/interesse`)}
router.delete(`/fundos/${record.id}/interesse`)
}
> >
Remover da minha lista Remover da minha lista
</button> </button>
@@ -68,6 +68,17 @@ final class FundingCriteriaCoherenceTest extends TestCase
$this->getJson('/api/v1/investment/territory-options?type=district&parent_id='.$this->geo['province'])->assertOk()->assertJsonCount(1, 'data'); $this->getJson('/api/v1/investment/territory-options?type=district&parent_id='.$this->geo['province'])->assertOk()->assertJsonCount(1, 'data');
} }
public function test_physical_search_defaults_to_documented_presence_but_preserves_explicit_unknown_choice(): void
{
$local = $this->publish('qa-local');
$this->publish('qa-unlocated', overrides: ['locations' => []]);
$filters = ['q' => 'SYNTHETIC qa-', 'location_mode' => 'physical', 'territory' => $this->geo['province']];
$this->get('/fundos?'.http_build_query($filters))->assertOk()->assertInertia(fn ($page) => $page
->where('filters.certainty', 'documented')->has('items.data', 1)->where('items.data.0.id', $local));
$this->get('/fundos?'.http_build_query([...$filters, 'certainty' => 'include_unknown']))->assertOk()->assertInertia(fn ($page) => $page
->where('filters.certainty', 'include_unknown')->has('items.data', 2));
}
public function test_contradictory_type_or_record_kind_and_incomplete_hierarchy_are_rejected(): void public function test_contradictory_type_or_record_kind_and_incomplete_hierarchy_are_rejected(): void
{ {
foreach ([['category' => 'banking', 'institution_type' => 'broker'], ['category' => 'banking', 'institution_type' => 'commercial_bank', 'kind' => 'fund', 'location_mode' => 'physical'], ['district_id' => $this->geo['district']]] as $filters) { foreach ([['category' => 'banking', 'institution_type' => 'broker'], ['category' => 'banking', 'institution_type' => 'commercial_bank', 'kind' => 'fund', 'location_mode' => 'physical'], ['district_id' => $this->geo['district']]] as $filters) {
@@ -1,26 +1,26 @@
import test from 'node:test'; import test from "node:test";
import assert from 'node:assert/strict'; import assert from "node:assert/strict";
import fs from 'node:fs'; import fs from "node:fs";
import { createRequire } from 'node:module'; import { createRequire } from "node:module";
import { compileFunction } from 'node:vm'; import { compileFunction } from "node:vm";
import React from 'react'; import React from "react";
import ts from 'typescript'; import ts from "typescript";
const require = createRequire(import.meta.url); const require = createRequire(import.meta.url);
const nodes = (tree) => const nodes = (tree) =>
Array.isArray(tree) Array.isArray(tree)
? tree.flatMap(nodes) ? tree.flatMap(nodes)
: tree && typeof tree === 'object' : tree && typeof tree === "object"
? [tree, ...nodes(tree.props?.children)] ? [tree, ...nodes(tree.props?.children)]
: []; : [];
const text = (tree) => const text = (tree) =>
Array.isArray(tree) Array.isArray(tree)
? tree.map(text).join('') ? tree.map(text).join("")
: tree?.props : tree?.props
? text(tree.props.children) ? text(tree.props.children)
: typeof tree === 'string' : typeof tree === "string"
? tree ? tree
: ''; : "";
// Real page event handlers, simulated Inertia transport. Not a browser or visual acceptance. // Real page event handlers, simulated Inertia transport. Not a browser or visual acceptance.
function harness(filters, errors = {}) { function harness(filters, errors = {}) {
@@ -32,8 +32,7 @@ function harness(filters, errors = {}) {
return [ return [
memory[id], memory[id],
(next) => { (next) => {
memory[id] = memory[id] = typeof next === "function" ? next(memory[id]) : next;
typeof next === 'function' ? next(memory[id]) : next;
}, },
]; ];
}; };
@@ -41,10 +40,7 @@ function harness(filters, errors = {}) {
let form; let form;
const TerritoryFields = () => null; const TerritoryFields = () => null;
const module = { exports: {} }; const module = { exports: {} };
const source = fs.readFileSync( const source = fs.readFileSync("resources/js/pages/funding/index.tsx", "utf8");
'resources/js/pages/funding/index.tsx',
'utf8',
);
compileFunction( compileFunction(
ts.transpileModule(source, { ts.transpileModule(source, {
compilerOptions: { compilerOptions: {
@@ -52,10 +48,10 @@ function harness(filters, errors = {}) {
jsx: ts.JsxEmit.ReactJSX, jsx: ts.JsxEmit.ReactJSX,
}, },
}).outputText, }).outputText,
['require', 'module', 'exports'], ["require", "module", "exports"],
)( )(
(id) => { (id) => {
if (id === 'react') if (id === "react")
return { return {
...React, ...React,
useState: state, useState: state,
@@ -64,9 +60,9 @@ function harness(filters, errors = {}) {
return value; return value;
}, },
}; };
if (id === '@inertiajs/react') if (id === "@inertiajs/react")
return { return {
Link: 'a', Link: "a",
useForm(initial) { useForm(initial) {
const [data, set] = state(initial); const [data, set] = state(initial);
form = { form = {
@@ -74,11 +70,7 @@ function harness(filters, errors = {}) {
errors: {}, errors: {},
processing: false, processing: false,
setData(key, value) { setData(key, value) {
set( set(typeof key === "string" ? { ...data, [key]: value } : key);
typeof key === 'string'
? { ...data, [key]: value }
: key,
);
}, },
get(url) { get(url) {
submitted = { url, data }; submitted = { url, data };
@@ -87,25 +79,22 @@ function harness(filters, errors = {}) {
return form; return form;
}, },
}; };
if (id === '@/pages/investment/shared') if (id === "@/pages/investment/shared") return { Frame: "main", card: "", button: "" };
return { Frame: 'main', card: '', button: '' }; if (id === "@/components/funding-classification")
if (id === '@/components/funding-classification')
return { return {
financialCategories: { financialCategories: {
banking: 'Banca', banking: "Banca",
insurance_intermediation: 'Mediação de seguros', insurance_intermediation: "Mediação de seguros",
}, },
financialTypes: { financialTypes: {
commercial_bank: 'Banco comercial', commercial_bank: "Banco comercial",
broker: 'Corretora', broker: "Corretora",
other: 'Outro', other: "Outro",
}, },
}; };
if (id === '@/components/investment-territory') if (id === "@/components/investment-territory") return { TerritoryFields };
return { TerritoryFields }; if (id === "@/components/funding-institution") return { InstitutionView: "article" };
if (id === '@/components/funding-institution') if (id === "./shared") return { windowLabels: {} };
return { InstitutionView: 'article' };
if (id === './shared') return { windowLabels: {} };
return require(id); return require(id);
}, },
module, module,
@@ -116,11 +105,11 @@ function harness(filters, errors = {}) {
criteriaErrors: errors, criteriaErrors: errors,
items: { data: [], links: [] }, items: { data: [], links: [] },
options: { sectors: [], territories: [] }, options: { sectors: [], territories: [] },
kinds: { institution: 'Instituição', fund: 'Fundo' }, kinds: { institution: "Instituição", fund: "Fundo" },
management: false, management: false,
categoryTypes: { categoryTypes: {
banking: ['commercial_bank'], banking: ["commercial_bank"],
insurance_intermediation: ['broker'], insurance_intermediation: ["broker"],
}, },
}; };
let tree; let tree;
@@ -131,11 +120,9 @@ function harness(filters, errors = {}) {
return tree; return tree;
} }
const select = (label) => const select = (label) =>
nodes( nodes(nodes(tree).find((n) => n.type === "label" && text(n).startsWith(label))).find(
nodes(tree).find( (n) => n.type === "select",
(n) => n.type === 'label' && text(n).startsWith(label), );
),
).find((n) => n.type === 'select');
render(); render();
return { return {
render, render,
@@ -147,76 +134,92 @@ function harness(filters, errors = {}) {
}; };
} }
test('institution category restricts types and removes only an incompatible dependent choice', () => { test("institution category restricts types and removes only an incompatible dependent choice", () => {
const h = harness({ const h = harness({
category: 'insurance_intermediation', category: "insurance_intermediation",
institution_type: 'broker', institution_type: "broker",
sector: '7', sector: "7",
need: 'investment', need: "investment",
territory: 'district-qa', territory: "district-qa",
}); });
h.select('Categoria da instituição').props.onChange({ h.select("Categoria da instituição").props.onChange({
target: { value: 'banking' }, target: { value: "banking" },
}); });
h.render(); h.render();
assert.equal(h.form().data.institution_type, ''); assert.equal(h.form().data.institution_type, "");
for (const [key, value] of Object.entries({ for (const [key, value] of Object.entries({
sector: '7', sector: "7",
need: 'investment', need: "investment",
territory: 'district-qa', territory: "district-qa",
})) }))
assert.equal(h.form().data[key], value); assert.equal(h.form().data[key], value);
assert.deepEqual( assert.deepEqual(
nodes(h.select('Tipo de instituição')) nodes(h.select("Tipo de instituição"))
.filter((n) => n.type === 'option') .filter((n) => n.type === "option")
.map((n) => n.props.value), .map((n) => n.props.value),
['', 'commercial_bank', 'other'], ["", "commercial_bank", "other"],
); );
assert.match(text(h.tree()), /tipo anterior não pertence/); assert.match(text(h.tree()), /tipo anterior não pertence/);
const results = nodes(h.tree()).find((n) => n.type === 'details'); const results = nodes(h.tree()).find((n) => n.type === "details");
assert.equal(results.props.open, false); assert.equal(results.props.open, false);
assert.match(text(results), /pesquisa anterior/); assert.match(text(results), /pesquisa anterior/);
}); });
test('contradictory record criteria remain explicit until the user chooses a correction', () => { test("contradictory record criteria remain explicit until the user chooses a correction", () => {
const h = harness( const h = harness(
{ {
kind: 'fund', kind: "fund",
category: 'banking', category: "banking",
institution_type: 'commercial_bank', institution_type: "commercial_bank",
location_mode: 'physical', location_mode: "physical",
province_id: 'province-qa', province_id: "province-qa",
sector: '8', sector: "8",
state: 'closed', state: "closed",
certainty: 'documented', certainty: "documented",
}, },
{ kind: ['Combinação incompatível.'] }, { kind: ["Combinação incompatível."] },
); );
assert.match(text(h.tree()), /A pesquisa não foi executada/); assert.match(text(h.tree()), /A pesquisa não foi executada/);
assert.equal(h.form().data.kind, 'fund'); assert.equal(h.form().data.kind, "fund");
const action = nodes(h.tree()).find( const action = nodes(h.tree()).find(
(n) => n.type === 'button' && /Manter o fundo/.test(text(n)), (n) => n.type === "button" && /Manter o fundo/.test(text(n)),
); );
action.props.onClick(); action.props.onClick();
h.render(); h.render();
assert.equal(h.form().data.category, ''); assert.equal(h.form().data.category, "");
assert.equal(h.form().data.institution_type, ''); assert.equal(h.form().data.institution_type, "");
assert.equal(h.form().data.location_mode, 'coverage'); assert.equal(h.form().data.location_mode, "coverage");
for (const [key, value] of Object.entries({ for (const [key, value] of Object.entries({
kind: 'fund', kind: "fund",
province_id: 'province-qa', province_id: "province-qa",
sector: '8', sector: "8",
state: 'closed', state: "closed",
certainty: 'documented', certainty: "documented",
})) }))
assert.equal(h.form().data[key], value); assert.equal(h.form().data[key], value);
nodes(h.tree()) nodes(h.tree())
.find((n) => n.type === 'form') .find((n) => n.type === "form")
.props.onSubmit({ preventDefault() {} }); .props.onSubmit({ preventDefault() {} });
assert.equal(h.submitted().url, '/fundos'); assert.equal(h.submitted().url, "/fundos");
assert.equal(h.submitted().data.province_id, 'province-qa'); assert.equal(h.submitted().data.province_id, "province-qa");
assert.ok( assert.ok(h.territory(), "the catalogue consumes the common hierarchical location control");
h.territory(), });
'the catalogue consumes the common hierarchical location control',
); test("local search defaults to documented presence and keeps the explicit unknown option and chosen territory", () => {
const h = harness({ territory: "district-qa", sector: "7" });
h.select("Localização a pesquisar").props.onChange({ target: { value: "physical" } });
h.render();
assert.equal(h.form().data.certainty, "documented");
assert.equal(h.form().data.territory, "district-qa");
assert.equal(h.form().data.sector, "7");
h.select("Informação por confirmar").props.onChange({ target: { value: "include_unknown" } });
h.render();
assert.equal(h.form().data.certainty, "include_unknown");
const resumed = harness({
location_mode: "physical",
territory: "district-qa",
certainty: "include_unknown",
});
assert.equal(resumed.form().data.certainty, "include_unknown");
assert.equal(harness({ location_mode: "physical" }).form().data.certainty, "documented");
}); });
@@ -1,32 +1,26 @@
import test from 'node:test'; import test from "node:test";
import assert from 'node:assert/strict'; import assert from "node:assert/strict";
import fs from 'node:fs'; import fs from "node:fs";
import path from 'node:path'; import path from "node:path";
import { compileFunction } from 'node:vm'; import { compileFunction } from "node:vm";
import { createRequire } from 'node:module'; import { createRequire } from "node:module";
import React from 'react'; import React from "react";
import { renderToStaticMarkup } from 'react-dom/server'; import { renderToStaticMarkup } from "react-dom/server";
import ts from 'typescript'; import ts from "typescript";
import * as presentation from '../../resources/js/lib/funding-public-presentation.ts'; import * as presentation from "../../resources/js/lib/funding-public-presentation.ts";
const require = createRequire(import.meta.url), const require = createRequire(import.meta.url),
records = Object.values( records = Object.values(
JSON.parse( JSON.parse(
fs.readFileSync( fs.readFileSync(
new URL( new URL("../../database/data/funding-institutions-nov2026.json", import.meta.url),
'../../database/data/funding-institutions-nov2026.json', "utf8",
import.meta.url,
),
'utf8',
), ),
).references, ).references,
).map((x) => x.draft); ).map((x) => x.draft);
function load(file) { function load(file) {
const module = { exports: {} }; const module = { exports: {} };
const output = ts.transpileModule( const output = ts.transpileModule(
fs.readFileSync( fs.readFileSync(new URL("../../resources/js/" + file, import.meta.url), "utf8"),
new URL('../../resources/js/' + file, import.meta.url),
'utf8',
),
{ {
compilerOptions: { compilerOptions: {
module: ts.ModuleKind.CommonJS, module: ts.ModuleKind.CommonJS,
@@ -35,98 +29,89 @@ function load(file) {
}, },
}, },
).outputText; ).outputText;
compileFunction(output, ['require', 'module', 'exports'])( compileFunction(output, ["require", "module", "exports"])(
(name) => (name) =>
name === '@/lib/funding-public-presentation' name === "@/lib/funding-public-presentation"
? presentation ? presentation
: name === '@/pages/investment/shared' : name === "@/pages/investment/shared"
? { ? {
Frame: ({ title, children }) => Frame: ({ title, children }) =>
React.createElement( React.createElement(
'main', "main",
null, null,
React.createElement('h1', null, title), React.createElement("h1", null, title),
children, children,
), ),
card: 'card', card: "card",
button: 'button', button: "button",
input: 'input', input: "input",
} }
: name === '@inertiajs/react' : name === "@inertiajs/react"
? { ? {
Link: ({ children, href }) => Link: ({ children, href }) =>
React.createElement('a', { href }, children), React.createElement("a", { href }, children),
router: {}, router: {},
useForm: (data) => ({ data, errors: {}, setData() {}, get() {} }), useForm: (data) => ({ data, errors: {}, setData() {}, get() {} }),
} }
: name === './shared' : name === "./shared"
? { windowLabels: {} } ? { windowLabels: {} }
: name === '@/lib/portal-api' : name === "@/lib/portal-api"
? { ? {
portalRequest: () => { portalRequest: () => {
throw Error( throw Error("Read-only rendering must not send requests");
'Read-only rendering must not send requests',
);
}, },
} }
: name === '@/components/funding-classification' : name === "@/components/funding-classification"
? load('components/funding-classification.tsx') ? load("components/funding-classification.tsx")
: name === '@/components/funding-institution' : name === "@/components/funding-institution"
? load('components/funding-institution.tsx') ? load("components/funding-institution.tsx")
: name === '@/components/funding-dossier-choice' : name === "@/components/funding-dossier-choice"
? { FundingDossierChoice: () => null } ? { FundingDossierChoice: () => null }
: name === : name === "@/components/funding-criteria-assessment"
'@/components/funding-criteria-assessment' ? load("components/funding-criteria-assessment.tsx")
? load(
'components/funding-criteria-assessment.tsx',
)
: resolveLocal(name, file), : resolveLocal(name, file),
module, module,
module.exports, module.exports,
); );
return module.exports; return module.exports;
} }
test('all270 imported institutions get readable descriptions and evidenced services without changing the published payload', () => { test("all270 imported institutions get readable descriptions and evidenced services without changing the published payload", () => {
assert.equal(records.length, 270); assert.equal(records.length, 270);
for (const p of records) { for (const p of records) {
const original = JSON.stringify(p), const original = JSON.stringify(p),
m = presentation.fundingPublicPresentation(p); m = presentation.fundingPublicPresentation(p);
assert.ok(m.description); assert.ok(m.description);
assert.doesNotMatch( assert.doesNotMatch(m.description, /documento fornecido|ficha|SHA-256|Público\/finalidade/);
m.description,
/documento fornecido|ficha|SHA-256|Público\/finalidade/,
);
assert.equal(JSON.stringify(p), original); assert.equal(JSON.stringify(p), original);
assert.equal( assert.equal(
m.products.length, m.products.length,
(p.products ?? []).filter((x) => x.availability !== 'closed') (p.products ?? []).filter((x) => x.availability !== "closed").length,
.length,
); );
} }
}); });
test('deliberate editorial descriptions survive and missing products are never fabricated', () => { test("deliberate editorial descriptions survive and missing products are never fabricated", () => {
const m = presentation.fundingPublicPresentation({ const m = presentation.fundingPublicPresentation({
title: 'Example', title: "Example",
kind: 'institution', kind: "institution",
summary: 'Apoio especializado ao investimento rural.', summary: "Apoio especializado ao investimento rural.",
products: [], products: [],
institution_types: ['insurer'], institution_types: ["insurer"],
}); });
assert.equal(m.description, 'Apoio especializado ao investimento rural.'); assert.equal(m.description, "Apoio especializado ao investimento rural.");
assert.deepEqual(m.products, []); assert.deepEqual(m.products, []);
assert.deepEqual(m.services, []); assert.deepEqual(m.services, []);
}); });
test('actual public cards and detail lead with description/products and keep import metadata out of the visitor text', () => { test("actual public cards and detail lead with description/products and keep import metadata out of the visitor text", () => {
const Index = load('pages/funding/index.tsx').default, const Index = load("pages/funding/index.tsx").default,
Show = load('pages/funding/show.tsx').default; Show = load("pages/funding/show.tsx").default;
for (const raw of [ for (const raw of [
records[0], records[0],
records.find((p) => p.institution_types.includes('investment_manager')), records.find((p) => p.institution_types.includes("investment_manager")),
]) { ]) {
const p = { ...raw, windows: [], documents: [] }, const p = { ...raw, windows: [], documents: [] },
item = { item = {
id: 'synthetic', id: "synthetic",
version_id: 'synthetic-version', version_id: "synthetic-version",
version: 1, version: 1,
payload: p, payload: p,
}; };
@@ -152,23 +137,15 @@ test('actual public cards and detail lead with description/products and keep imp
/ficha|documento fornecido|SHA-256|linha de origem|Instituições financeiras em Moçambique\.docx/i, /ficha|documento fornecido|SHA-256|linha de origem|Instituições financeiras em Moçambique\.docx/i,
); );
assert.match(html, /Produtos e serviços/); assert.match(html, /Produtos e serviços/);
assert.match( assert.match(html, new RegExp(raw.title.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")));
html,
new RegExp(raw.title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')),
);
} }
const out = new URL( const out = new URL("../../outputs/funding-public-editorial-20261111/", import.meta.url);
'../../outputs/funding-public-editorial-20261111/',
import.meta.url,
);
fs.mkdirSync(out, { recursive: true }); fs.mkdirSync(out, { recursive: true });
const name = p.products.length const name = p.products.length ? "bank-with-products" : "investment-manager";
? 'bank-with-products' fs.writeFileSync(new URL(name + "-index.html", out), index);
: 'investment-manager'; fs.writeFileSync(new URL(name + "-detail.html", out), detail);
fs.writeFileSync(new URL(name + '-index.html', out), index);
fs.writeFileSync(new URL(name + '-detail.html', out), detail);
fs.writeFileSync( fs.writeFileSync(
new URL('verification.json', out), new URL("verification.json", out),
JSON.stringify( JSON.stringify(
{ {
publishedSourceRecords: 270, publishedSourceRecords: 270,
@@ -189,21 +166,18 @@ test('actual public cards and detail lead with description/products and keep imp
} }
}); });
test('Quorus and Moza use one shared clean profile in both list and detail', () => { test("Quorus and Moza use one shared clean profile in both list and detail", () => {
const Index = load('pages/funding/index.tsx').default, const Index = load("pages/funding/index.tsx").default,
Show = load('pages/funding/show.tsx').default; Show = load("pages/funding/show.tsx").default;
const out = new URL( const out = new URL("../../outputs/funding-uniform-menu-20261111/", import.meta.url);
'../../outputs/funding-uniform-menu-20261111/',
import.meta.url,
);
fs.mkdirSync(out, { recursive: true }); fs.mkdirSync(out, { recursive: true });
for (const title of ['Quorus', 'Moza Banco']) { for (const title of ["Quorus", "Moza Banco"]) {
const raw = records.find((p) => p.title === title); const raw = records.find((p) => p.title === title);
assert.ok(raw, title); assert.ok(raw, title);
const p = { ...raw, windows: [], documents: [] }, const p = { ...raw, windows: [], documents: [] },
item = { item = {
id: 'synthetic', id: "synthetic",
version_id: 'synthetic-version', version_id: "synthetic-version",
version: 1, version: 1,
payload: p, payload: p,
}; };
@@ -224,8 +198,7 @@ test('Quorus and Moza use one shared clean profile in both list and detail', ()
}), }),
); );
for (const html of [ for (const html of [
index.match(/<article class="card">([\s\S]*?)<\/article>/)?.[0] ?? index.match(/<article class="card">([\s\S]*?)<\/article>/)?.[0] ?? index,
index,
detail, detail,
]) { ]) {
assert.doesNotMatch( assert.doesNotMatch(
@@ -235,62 +208,38 @@ test('Quorus and Moza use one shared clean profile in both list and detail', ()
assert.equal((html.match(/Produtos e serviços/g) || []).length, 1); assert.equal((html.match(/Produtos e serviços/g) || []).length, 1);
assert.equal((html.match(/Descrição/g) || []).length, 1); assert.equal((html.match(/Descrição/g) || []).length, 1);
} }
if (title === 'Quorus') { if (title === "Quorus") {
assert.equal( assert.equal((detail.match(/Entidade de corretagem de seguros/g) || []).length, 1);
(detail.match(/Entidade de corretagem de seguros/g) || []) assert.doesNotMatch(detail, /<h3[^>]*>Contactos|<h3[^>]*>Localização/);
.length,
1,
);
assert.doesNotMatch(
detail,
/<h3[^>]*>Contactos|<h3[^>]*>Localização/,
);
} else { } else {
assert.equal((detail.match(/21 342 000/g) || []).length, 1); assert.equal((detail.match(/21 342 000/g) || []).length, 1);
assert.equal((detail.match(/Rua dos Desportistas/g) || []).length, 1);
assert.equal( assert.equal(
(detail.match(/Rua dos Desportistas/g) || []).length, (detail.match(/Tesouraria, investimento, construção e equipamento/g) || []).length,
1,
);
assert.equal(
(
detail.match(
/Tesouraria, investimento, construção e equipamento/g,
) || []
).length,
1, 1,
); );
assert.doesNotMatch(detail, /500\.000|30\.000\.000|Prime|spread/); assert.doesNotMatch(detail, /500\.000|30\.000\.000|Prime|spread/);
} }
fs.writeFileSync( fs.writeFileSync(new URL(title.replaceAll(" ", "-") + "-index.html", out), index);
new URL(title.replaceAll(' ', '-') + '-index.html', out), fs.writeFileSync(new URL(title.replaceAll(" ", "-") + "-detail.html", out), detail);
index,
);
fs.writeFileSync(
new URL(title.replaceAll(' ', '-') + '-detail.html', out),
detail,
);
} }
}); });
test('contact and location deduplication preserves different branches and original records', () => { test("contact and location deduplication preserves different branches and original records", () => {
const moza = records.find((p) => p.title === 'Moza Banco'), const moza = records.find((p) => p.title === "Moza Banco"),
original = JSON.stringify(moza); original = JSON.stringify(moza);
assert.equal( assert.equal(
presentation presentation.publicInstitutionContacts(moza.contacts).filter((c) => c.kind === "phone")
.publicInstitutionContacts(moza.contacts) .length,
.filter((c) => c.kind === 'phone').length,
1,
);
assert.equal(
presentation.publicInstitutionLocations(moza.locations).length,
1, 1,
); );
assert.equal(presentation.publicInstitutionLocations(moza.locations).length, 1);
assert.equal( assert.equal(
presentation.publicInstitutionLocations([ presentation.publicInstitutionLocations([
...moza.locations, ...moza.locations,
{ {
...moza.locations[0], ...moza.locations[0],
role: 'branch', role: "branch",
address: 'Rua dos Desportistas, número 714', address: "Rua dos Desportistas, número 714",
}, },
]).length, ]).length,
2, 2,
@@ -299,10 +248,68 @@ test('contact and location deduplication preserves different branches and origin
}); });
function resolveLocal(name, parent) { function resolveLocal(name, parent) {
if (name === './territory-geometry-preview') return { default: () => null }; if (name === "./territory-geometry-preview") return { default: () => null };
const relative = name.startsWith('@/') ? name.slice(2) : name.startsWith('.') ? path.posix.join(path.posix.dirname(parent), name) : null; const relative = name.startsWith("@/")
if (relative) for (const candidate of [relative, relative + '.tsx', relative + '.ts']) { ? name.slice(2)
if (fs.existsSync(new URL('../../resources/js/' + candidate, import.meta.url))) return load(candidate); : name.startsWith(".")
? path.posix.join(path.posix.dirname(parent), name)
: null;
if (relative)
for (const candidate of [relative, relative + ".tsx", relative + ".ts"]) {
if (fs.existsSync(new URL("../../resources/js/" + candidate, import.meta.url)))
return load(candidate);
} }
return require(name); return require(name);
} }
test("physical presence matches descendants, not a broader province or unknown locations", () => {
const points = [
{
territory_id: "district-a",
territory_path: [
{ id: "province", name: "Province" },
{ id: "district-a", name: "A" },
],
evidence_status: "reported",
},
{
territory_id: "province",
territory_path: [{ id: "province", name: "Province" }],
evidence_status: "reported",
},
{ territory_id: "district-a", evidence_status: "to_confirm" },
{ territory_id: "district-a", evidence_status: "historical" },
{ territory_id: "" },
];
assert.deepEqual(presentation.matchingInstitutionLocations(points, "district-a"), [points[0]]);
assert.deepEqual(
presentation.matchingInstitutionLocations(points, "province"),
points.slice(0, 2),
);
assert.deepEqual(presentation.matchingInstitutionLocations(points, "elsewhere"), []);
});
test("compact institutions show local address and explicitly identify unconfirmed physical presence", () => {
const { InstitutionView } = load("components/funding-institution.tsx");
const value = {
...records[0],
locations: [
{
role: "branch",
address: "Balcão de Tete",
territory_id: "tete",
territory_path: [{ id: "tete", name: "Tete" }],
},
{ role: "headquarters", address: "Sede Maputo", territory_id: "maputo" },
],
};
const render = (territory, compact = true) =>
renderToStaticMarkup(
React.createElement(InstitutionView, { value, compact, physicalTerritory: territory }),
);
assert.match(render("tete"), /Balcão de Tete/);
assert.doesNotMatch(render("tete"), /Sede Maputo|Presença física por confirmar/);
assert.match(render("niassa"), /Presença física por confirmar no local escolhido/);
assert.doesNotMatch(render("niassa"), /Balcão de Tete|Sede Maputo/);
assert.match(render("tete", false), /Sede Maputo/);
assert.match(render("tete", false), /Balcão de Tete/);
});