Mapa de erros: limites administrativos e complementos sem repetição

- Limites administrativos (4.3, 4.4, 4.5): quando o mapa já lista os limites,
  a pré-visualização territorial deixa de repetir a lista e a contagem; a data
  de cada limite passa a chamar-se sempre «Edição» e a advertência fica uma vez.
- Complementos da ficha da carteira (4.3, 4.9): a origem e a descrição dos
  complementos aparecem uma vez por investimento de origem; a referência interna
  ao documento de requisitos (.docx, secção) deixa de ser mostrada ao investidor,
  também na lista de complementos escolhidos do dossier.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jm
This commit is contained in:
Claude
2026-12-04 17:30:39 +02:00
committed by nala
parent 03e54c7a85
commit aff4ccea6c
5 changed files with 369 additions and 80 deletions
@@ -68,6 +68,12 @@ export default function InteractiveInvestmentMap({
documented_locations: 'Mapa dos locais documentados',
declared_parcel: 'Perímetro declarado pelo Promotor',
}[mapKind];
const administrativeRole = (area: InvestmentMapArea) =>
area.selected_territory
? 'Território seleccionado'
: area.child_territory
? 'Subdivisão do território seleccionado'
: 'Contexto de nível superior';
const areaDescription = (area: InvestmentMapArea) =>
area.purpose === 'administrative_boundary'
? `${area.selected_territory ? 'Território seleccionado' : area.child_territory ? 'Subdivisão do território seleccionado' : 'Contexto de nível superior'} · Limite administrativo da edição indicada; não representa um local de investimento`
@@ -512,10 +518,19 @@ export default function InteractiveInvestmentMap({
<a className="underline" href={area.url}>
{area.title}
</a>{' '}
· {areaDescription(area)} · Fonte:{' '}
·{' '}
{mapKind === 'administrative' &&
area.purpose === 'administrative_boundary'
? administrativeRole(area)
: areaDescription(area)}{' '}
· Fonte:{' '}
{publicReference(area.source_reference) ??
'Não indicada'}{' '}
· Data: {area.source_date ?? 'Não documentada'}
·{' '}
{area.purpose === 'administrative_boundary'
? 'Edição'
: 'Data'}
: {area.source_date ?? 'Não documentada'}
</p>
))}
</section>
@@ -90,9 +90,6 @@ export function SelectedComplements({
antes de a utilizar.
</p>
)}
<p className="text-sm">
Fonte: {item.source} · Trecho: {item.excerpt}
</p>
{onRemove && (
<button
type="button"
@@ -108,6 +105,32 @@ export function SelectedComplements({
);
}
/** One heading per investment of origin: its location and source excerpt are shown once, not per complement. */
export function complementGroups(items: ComplementOption[]) {
const groups: {
key: string;
origin: Offer;
territory: string | null;
excerpt: string;
items: ComplementOption[];
}[] = [];
for (const item of items) {
const territory = item.territory?.title ?? null;
const key = [item.origin.key, territory ?? '', item.excerpt].join('|');
const group = groups.find((candidate) => candidate.key === key);
if (group) group.items.push(item);
else
groups.push({
key,
origin: item.origin,
territory,
excerpt: item.excerpt.trim(),
items: [item],
});
}
return groups;
}
export default function InvestmentComplements({
items,
dossierId,
@@ -159,79 +182,102 @@ export default function InvestmentComplements({
Escolha os complementos relevantes para o seu investimento. A
localização e as condições de cada ficha conservam-se.
</p>
{items.map((item) => (
<article
className="space-y-2 border-t pt-3"
key={
item.origin.key + item.code + (item.territory_id ?? '')
}
>
<h3 className="font-semibold">{item.title}</h3>
{complementGroups(items).map((group) => (
<section key={group.key} className="space-y-3 border-t pt-3">
<p>
Investimento de origem: {item.origin.title} ·{' '}
{item.territory?.title ?? 'Localização por definir'}
Investimento de origem: {group.origin.title} ·{' '}
{group.territory ?? 'Localização por definir'}
</p>
<p className="text-sm">
Referência: {item.source} · Trecho: {item.excerpt}
</p>
{[...item.opportunities, ...item.services].map((offer) => (
<div key={offer.key} className="space-y-1">
<p>
<Link
className="underline"
href={consult(item, offer)}
onClick={(event) => {
if (onNavigate) {
event.preventDefault();
onNavigate(consult(item, offer));
}
}}
>
{offer.title}
</Link>{' '}
· {offer.location}
</p>
<Link
className="block underline"
href={prepare(item, offer)}
onClick={(event) => {
if (onNavigate) {
event.preventDefault();
onNavigate(prepare(item, offer));
}
}}
>
Seleccionar esta{' '}
{offer.key.startsWith('opportunity:')
? 'oportunidade'
: 'oferta'}{' '}
para o dossier
</Link>
</div>
))}
{!item.opportunities.length && !item.services.length && (
<>
<p>
Necessidade complementar referida; sem oferta
cadastrada identificada nas relações deste
contexto.
</p>
<Link
className="underline"
href={prepare(item)}
onClick={(event) => {
if (onNavigate) {
event.preventDefault();
onNavigate(prepare(item));
}
}}
>
Iniciar preparação de uma ideia de{' '}
{item.title.toLocaleLowerCase('pt-MZ')}
</Link>
</>
{group.excerpt && (
<p className="text-sm">
Complementos habitualmente associados:{' '}
{group.excerpt}
</p>
)}
</article>
{group.items.map((item) => (
<article
className="space-y-2"
key={
item.origin.key +
item.code +
(item.territory_id ?? '')
}
>
<h3 className="font-semibold">{item.title}</h3>
{[...item.opportunities, ...item.services].map(
(offer) => (
<div key={offer.key} className="space-y-1">
<p>
<Link
className="underline"
href={consult(item, offer)}
onClick={(event) => {
if (onNavigate) {
event.preventDefault();
onNavigate(
consult(
item,
offer,
),
);
}
}}
>
{offer.title}
</Link>{' '}
· {offer.location}
</p>
<Link
className="block underline"
href={prepare(item, offer)}
onClick={(event) => {
if (onNavigate) {
event.preventDefault();
onNavigate(
prepare(item, offer),
);
}
}}
>
Seleccionar esta{' '}
{offer.key.startsWith(
'opportunity:',
)
? 'oportunidade'
: 'oferta'}{' '}
para o dossier
</Link>
</div>
),
)}
{!item.opportunities.length &&
!item.services.length && (
<>
<p>
Necessidade complementar referida;
sem oferta cadastrada identificada
nas relações deste contexto.
</p>
<Link
className="underline"
href={prepare(item)}
onClick={(event) => {
if (onNavigate) {
event.preventDefault();
onNavigate(prepare(item));
}
}}
>
Iniciar preparação de uma ideia de{' '}
{item.title.toLocaleLowerCase(
'pt-MZ',
)}
</Link>
</>
)}
</article>
))}
</section>
))}
</section>
);
@@ -47,6 +47,8 @@ export function TerritoryGeometryDetails({
renderMap?: boolean;
showSources?: boolean;
}) {
// The map lists each boundary and its count itself; a second list repeated every limit.
const mapLists = Boolean(renderMap && context && context.areas.length > 0);
return (
<section className="space-y-2 md:col-span-full" aria-label={label}>
<p>Território selecionado no cadastro.</p>
@@ -68,10 +70,11 @@ export function TerritoryGeometryDetails({
</p>
)}
<p>
{context.context_geometry_count} limites disponíveis na
hierarquia consultada. São contexto administrativo, não
perímetro nem disponibilidade de investimento. A edição
e a atualidade jurídica são informações distintas.
{!mapLists &&
`${context.context_geometry_count} limites disponíveis na hierarquia consultada. `}
São contexto administrativo, não perímetro nem
disponibilidade de investimento. A edição e a
actualidade jurídica são informações distintas.
</p>
{context.child_coverage?.location_type && (
<p role="status">
@@ -97,7 +100,7 @@ export function TerritoryGeometryDetails({
contextOnly
/>
)}
{showSources && (
{showSources && !mapLists && (
<ul>
{context.areas.map((area, index) => (
<li key={index}>
@@ -0,0 +1,117 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { createRequire } from 'node:module';
import { compileFunction } from 'node:vm';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
const root = path.resolve('resources/js');
function load(file) {
const absolute = path.resolve(root, file);
const module = { exports: {} };
const code = ts.transpileModule(fs.readFileSync(absolute, 'utf8'), {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
compileFunction(code, ['require', 'module', 'exports'])(
(id) => {
if (id === '@inertiajs/react')
return {
Link: ({ children, ...props }) =>
React.createElement('a', props, children),
usePage: () => ({ url: '/carteira/x', props: {} }),
};
if (id.startsWith('@/')) {
const base = path.resolve(root, id.slice(2));
const found = [base + '.ts', base + '.tsx'].find((p) =>
fs.existsSync(p),
);
if (found) return load(path.relative(root, found));
}
return require(id);
},
module,
module.exports,
);
return module.exports;
}
const source = 'upgrade do portal de investimentos v4 programacao.docx — 4.5.2';
const excerpt =
'Irrigação, sementes, mecanização, frio, silos, embalagem, certificação, financiamento e compradores.';
const origin = {
key: 'opportunity:1',
title: 'Agro-indústria e segurança alimentar',
href: '/carteira/1',
};
const option = (code, title) => ({
code,
title,
origin,
territory_id: null,
territory: null,
source,
excerpt,
source_sha256: 'a'.repeat(64),
opportunities: [],
services: [],
});
test('complements show the origin and excerpt once, without the internal requirements reference (mapa de erros 4.3)', () => {
const { default: InvestmentComplements } = load(
'components/investment-complements.tsx',
);
const html = renderToStaticMarkup(
React.createElement(InvestmentComplements, {
items: [
option('irrigation', 'Regadio'),
option('storage', 'Silos e armazenagem'),
option('cold', 'Cadeia de frio'),
],
}),
);
assert.doesNotMatch(html, /programacao|\.docx|Referência:|Trecho:/);
assert.doesNotMatch(html, /a{64}/);
assert.equal(html.split('Investimento de origem:').length - 1, 1);
assert.equal(html.split('Irrigação, sementes').length - 1, 1);
for (const title of ['Regadio', 'Silos e armazenagem', 'Cadeia de frio'])
assert.match(html, new RegExp(title));
assert.equal(
html.split('Iniciar preparação de uma ideia de').length - 1,
3,
);
});
test('selected complements in the dossier do not expose the internal source either', () => {
const { SelectedComplements } = load(
'components/investment-complements.tsx',
);
const html = renderToStaticMarkup(
React.createElement(SelectedComplements, {
items: [
{
key: 'k',
code: 'irrigation',
title: 'Regadio',
kind: 'need',
origin,
target: null,
territory_id: null,
territory: null,
source,
excerpt,
source_sha256: 'a'.repeat(64),
},
],
}),
);
assert.doesNotMatch(html, /programacao|\.docx|Fonte:|Trecho:/);
assert.match(html, /Regadio/);
});
@@ -0,0 +1,108 @@
import * as publicPresentation from '../../resources/js/lib/public-presentation.ts';
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
function load(file, mocks = {}) {
const output = ts.transpileModule(
fs
.readFileSync(
new URL('../../resources/js/components/' + file, import.meta.url),
'utf8',
)
.replaceAll('import.meta.env.VITE_MAP_TILE_URL', 'undefined'),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
const module = { exports: {} };
compileFunction(output, ['require', 'module', 'exports'])(
(name) => {
if (name in mocks) return mocks[name];
if (name === '@/lib/public-presentation') return publicPresentation;
if (name.startsWith('./'))
return load(
name.slice(2) +
(fs.existsSync(
new URL(
'../../resources/js/components/' +
name.slice(2) +
'.tsx',
import.meta.url,
),
)
? '.tsx'
: '.ts'),
mocks,
);
return require(name);
},
module,
module.exports,
);
return module.exports;
}
const polygon = (x, y) => ({
type: 'Polygon',
coordinates: [[[x, y], [x + 1, y], [x + 1, y + 1], [x, y + 1], [x, y]]],
});
const area = (title, selected) => ({
geometry: polygon(selected ? 39 : 38, -13),
title,
purpose: 'administrative_boundary',
selected_territory: selected,
location_type: selected ? 'district' : 'province',
url: '/territorio',
source_reference: 'Mozambique INE - Instituto Nacional de Estatistica',
source_date: '2019-06-07',
});
test('each administrative boundary is listed once, with its edition, and the count is not repeated (mapa de erros 4.3–4.5)', () => {
const mocks = { leaflet: {}, 'leaflet/dist/leaflet.css': {} };
const { TerritoryGeometryDetails } = load(
'territory-geometry-preview.tsx',
mocks,
);
const context = {
selected_geometry_available: true,
context_geometry_count: 2,
areas: [area('ANCUABE', true), area('Cabo Delgado', false)],
truncated: false,
child_coverage: null,
};
const html = renderToStaticMarkup(
React.createElement(TerritoryGeometryDetails, {
context,
error: '',
renderMap: true,
}),
);
assert.equal(html.split('>ANCUABE<').length - 1, 1);
assert.equal(html.split('>Cabo Delgado<').length - 1, 1);
assert.doesNotMatch(html, /Data: 2019/);
assert.equal(html.split('Edição: 2019-06-07').length - 1, 2);
assert.doesNotMatch(html, /limites disponíveis na hierarquia/);
assert.equal(html.split('limites administrativos disponíveis').length - 1, 1);
assert.equal(
html.split('não representa um local de investimento').length - 1,
0,
);
assert.match(html, /São contexto administrativo/);
// Without a map the textual list remains the only list, with the count.
const textOnly = renderToStaticMarkup(
React.createElement(TerritoryGeometryDetails, { context, error: '' }),
);
assert.match(textOnly, /2 limites disponíveis na hierarquia consultada/);
assert.equal(textOnly.split('Edição: 2019-06-07').length - 1, 2);
});