fix: correct V13 and public presentation patterns in isolated QA

This commit is contained in:
2026-11-21 12:36:28 +02:00
parent 1950bb69ec
commit e239a31a76
66 changed files with 3977 additions and 278 deletions
@@ -1,3 +1,4 @@
import { catalogueFilterHref } from '@/lib/catalogue-context';
import { Link, usePage } from '@inertiajs/react';
const labels: Record<string, string> = {
@@ -71,8 +72,17 @@ const values: Record<string, string> = {
/** Name each active criterion without exposing IDs or taxonomy codes. */
export default function CatalogueFilterContext() {
const page = usePage();
const filters = page.props.filters as Record<string, unknown> | undefined;
if (!filters) return null;
const supplied = page.props.filters as Record<string, unknown> | undefined;
const path = page.props.territorySelection as
| { id: string; name: string; location_type?: string }[]
| undefined;
const filters: Record<string, unknown> = { ...supplied };
path?.forEach((place, index) => {
const key = place.location_type
? territoryKeys.find((name) => name === `${place.location_type}_id`)
: territoryKeys[index];
if (key && !filters[key]) filters[key] = place.id;
});
const active = Object.entries(filters).filter(
([key, value]) =>
!['page', 'per_page', 'sort', 'view', 'publication_state'].includes(
@@ -93,28 +103,15 @@ export default function CatalogueFilterContext() {
if (typeof value !== 'string') return 'seleccionado';
return (
values[value] ??
(['q', 'query', 'province', 'topic', 'issuer'].includes(key)
(['q', 'query', 'province', 'topic', 'issuer', 'activity'].includes(
key,
)
? value
: 'seleccionado')
);
};
const href = (remove?: string) => {
const url = new URL(page.url, 'https://portal.invalid');
const keys = remove
? [
remove,
...territoryKeys
.slice(territoryKeys.indexOf(remove) + 1)
.filter(() => territoryKeys.includes(remove)),
]
: Object.keys(filters);
for (const key of keys) {
url.searchParams.delete(key);
url.searchParams.delete(`${key}[]`);
}
url.searchParams.delete('page');
return url.pathname + url.search;
};
const href = (remove?: string) =>
catalogueFilterHref(page.url, Object.keys(filters), remove);
return (
<nav
aria-label="Filtros activos"
@@ -85,7 +85,7 @@ export default function FintechInvestment({
{
version: 'Versão do dossier',
'profile.model': 'Natureza do modelo',
'profile.activity_basis': 'Fundamento das atividades',
'profile.activity_basis': 'Fundamento das actividades',
} as Record<string, string>
)[field] ?? 'Caracterização'
);
@@ -179,7 +179,7 @@ export default function FintechInvestment({
</option>
<option value="technology_provider">
Fornecedor de tecnologia, sem presumir
atividade financeira reservada
actividade financeira reservada
</option>
<option value="financial_operator">
Operador de serviços financeiros declarado,
@@ -248,7 +248,7 @@ export default function FintechInvestment({
</p>
<fieldset className="grid gap-3 md:grid-cols-2">
<legend className="font-semibold">
Atividades pretendidas, ainda sujeitas a
Actividades pretendidas, ainda sujeitas a
enquadramento
</legend>
{Object.entries(data.activities).map(
@@ -285,7 +285,7 @@ export default function FintechInvestment({
)}
</fieldset>
<label className="grid gap-1">
Fundamento e limites da declaração de atividades
Fundamento e limites da declaração de actividades
<textarea
rows={3}
maxLength={3000}
@@ -375,7 +375,7 @@ export default function FintechInvestment({
className="mt-5 space-y-3"
>
<h3 className="font-semibold">
Aplicabilidade por atividade e ação
Aplicabilidade por actividade e acção
</h3>
<p>
Quem prepara: promotor. Quem confere: responsável
@@ -1,3 +1,4 @@
import { publicReference } from '@/lib/public-presentation';
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import type {
Map as LeafletMap,
@@ -231,7 +232,7 @@ export default function InteractiveInvestmentMap({
: 0;
for (const area of allAreas) {
const label = document.createElement('p');
label.textContent = `${area.title} · ${areaDescription(area)} · Fonte: ${area.source_reference ?? 'Não indicada'} · Data: ${area.source_date ?? 'Não documentada'}`;
label.textContent = `${area.title} · ${areaDescription(area)} · Fonte: ${publicReference(area.source_reference) ?? 'Não indicada'} · Data: ${area.source_date ?? 'Não documentada'}`;
const layer = L.geoJSON(
area.geometry,
area.purpose === 'administrative_boundary'
@@ -299,7 +300,7 @@ export default function InteractiveInvestmentMap({
for (const text of [
p.category,
p.location,
`Fonte: ${p.source_reference ?? 'Não indicada'} · Data: ${p.source_date ?? 'Não documentada'}`,
`Fonte: ${publicReference(p.source_reference) ?? 'Não indicada'} · Data: ${p.source_date ?? 'Não documentada'}`,
`Corredor: ${p.corridors?.join(', ') || 'Não associado'}`,
`Cluster: ${p.clusters?.join(', ') || 'Não associado'}`,
`Projecto âncora: ${p.projects?.join(', ') || 'Não associado'}`,
@@ -468,8 +469,9 @@ export default function InteractiveInvestmentMap({
</p>
<p>
Fonte:{' '}
{p.properties.source_reference ?? 'Não indicada'} ·
Data:{' '}
{publicReference(p.properties.source_reference) ??
'Não indicada'}{' '}
· Data:{' '}
{p.properties.source_date ?? 'Não documentada'}
</p>
<a className="underline" href={p.properties.url}>
@@ -496,8 +498,9 @@ export default function InteractiveInvestmentMap({
area.title
)}{' '}
· {areaDescription(area)} · Fonte:{' '}
{area.source_reference ?? 'Não indicada'} ·
Edição: {area.source_date ?? 'Não indicada'}
{publicReference(area.source_reference) ??
'Não indicada'}{' '}
· Edição: {area.source_date ?? 'Não indicada'}
</p>
))}
</div>
@@ -510,8 +513,9 @@ export default function InteractiveInvestmentMap({
{area.title}
</a>{' '}
· {areaDescription(area)} · Fonte:{' '}
{area.source_reference ?? 'Não indicada'} · Data:{' '}
{area.source_date ?? 'Não documentada'}
{publicReference(area.source_reference) ??
'Não indicada'}{' '}
· Data: {area.source_date ?? 'Não documentada'}
</p>
))}
</section>
@@ -22,7 +22,10 @@ export function InvestmentReportTables({
</h4>
<ul className="list-disc space-y-2 pl-5">
{issues.map((issue) => (
<li key={issue.message}>
<li
key={issue.message}
data-correction-message={issue.message}
>
<p>{issue.message}</p>
<p className="text-xs">
Tabelas afectadas: {issue.tables.join('; ')}
@@ -75,7 +75,7 @@ export function ProvinceSelect({
setGeometrySelection({ value, id: matches[0].id });
else
setGeometryFeedback(
'Seleção guardada preservada; sem correspondência cartográfica inequívoca neste cadastro.',
'Selecção guardada preservada; sem correspondência cartográfica inequívoca neste cadastro.',
);
})
.catch((cause: unknown) => {
@@ -577,7 +577,9 @@ export function ParkIntegralPublic({ value }: { value?: ParkIntegral }) {
<p>
Fonte:{' '}
{String(
item.source_reference || 'Não informada',
publicReference(
String(item.source_reference ?? ''),
) || 'Referência pública não disponível',
)}{' '}
· data:{' '}
{String(item.source_date || 'Não informada')} ·
@@ -590,3 +592,4 @@ export function ParkIntegralPublic({ value }: { value?: ParkIntegral }) {
</section>
);
}
import { publicReference } from '@/lib/public-presentation';
@@ -1,3 +1,5 @@
import PublicReference from './public-reference';
import { publicReference } from '@/lib/public-presentation';
import ParkIntegralEditor, {
ParkIntegralPublic,
type ParkIntegral,
@@ -175,8 +177,14 @@ export function ParkDetailsPublic({ value }: { value?: Partial<ParkDetails> }) {
)}
<p>
Fonte:{' '}
{item.source_reference || 'Não informada'} ·
data: {item.source_date || 'Não informada'} ·
{publicReference(item.source_reference) ? (
<PublicReference
value={item.source_reference}
/>
) : (
'Referência pública não disponível'
)}{' '}
· data: {item.source_date || 'Não informada'} ·
âmbito: {item.scope || 'Não informado'}
</p>
</article>
@@ -192,15 +200,25 @@ export function ParkDetailsPublic({ value }: { value?: Partial<ParkDetails> }) {
<div key={k}>
<dt>{reviewLabels[k]}</dt>
<dd>
{k === 'confidence'
? ({
unknown: 'Não informada',
reported: 'Declarada',
documented: 'Documentada',
disputed: 'Divergente',
}[value.review?.[k] ?? ''] ??
'Não informada')
: value.review?.[k] || 'Não informado'}
{k === 'confidence' ? (
({
unknown: 'Não informada',
reported: 'Declarada',
documented: 'Documentada',
disputed: 'Divergente',
}[value.review?.[k] ?? ''] ??
'Não informada')
) : k === 'source_reference' ? (
publicReference(value.review?.[k]) ? (
<PublicReference
value={value.review?.[k]}
/>
) : (
'Referência pública não disponível'
)
) : (
value.review?.[k] || 'Não informado'
)}
</dd>
</div>
))}
@@ -276,7 +294,7 @@ export default function ParkDetailsEditor({
<h2 className="font-semibold">Complemento operacional</h2>
<p>
Uma entidade pode exercer várias funções. Guardar prepara em
privado; divulgar exige seleção por detalhe e publicação
privado; divulgar exige selecção por detalhe e publicação
expressa. Contactos pessoais, notas e suporte permanecem
privados.
</p>
@@ -71,7 +71,7 @@ const labels: Record<string, string> = {
internal_contact_id: 'Contacto interno',
sector_id: 'Sector',
subsector_id: 'Subsector',
economic_activity_id: 'Atividade económica',
economic_activity_id: 'Actividade económica',
location_mode: 'Uma ou várias localizações',
geographic_scope: 'Âmbito geográfico',
multi_district_rationale: 'Justificação territorial',
@@ -94,7 +94,7 @@ const labels: Record<string, string> = {
real_estate: 'Imobiliário',
land_rights: 'DUAT e direitos fundiários',
business_transaction: 'Negócio',
module_profile_version: 'Versão do contrato QA (seleção explícita)',
module_profile_version: 'Versão do contrato QA (selecção explícita)',
module_details: 'Condições do módulo',
mode: 'Percurso: procura, oferta ou modalidade',
conditions_status: 'Condições propostas ou compromisso documentado',
@@ -1156,7 +1156,7 @@ export default function OpportunityCanonicalFields({
}
>
<option value="">
Contrato original / por selecionar
Contrato original / por seleccionar
</option>
{current && current !== version && (
<option value={current}>
@@ -2,6 +2,8 @@ import { useEffect, useRef, useState } from 'react';
import { router } from '@inertiajs/react';
import { control, button } from '@/pages/management/shared';
import { valueText } from '@/lib/value-text';
import PublicReference from './public-reference';
import { publicReference } from '@/lib/public-presentation';
type Classification = {
target_type: string;
@@ -49,11 +51,11 @@ const typeLabels: Record<string, string> = {
corridor: 'Corredor',
location: 'Localização',
cluster: 'Cluster',
project: 'Projeto âncora',
project: 'Projecto âncora',
chain: 'Cadeia de valor',
zone: 'Zona ou parque',
sector: 'Setor',
activity: 'Subsector ou atividade',
sector: 'Sector',
activity: 'Subsector ou actividade',
};
export const classificationStates: Record<string, string> = {
draft: 'Rascunho',
@@ -67,8 +69,8 @@ export const classificationStates: Record<string, string> = {
const externalLabels: Record<string, string> = {
not_assessed: 'Não determinado',
pending: 'Pendente',
documented_granted: 'Ato de concessão documentado',
documented_denied: 'Ato de recusa documentado',
documented_granted: 'Acto de concessão documentado',
documented_denied: 'Acto de recusa documentado',
expired: 'Caducado',
};
const help =
@@ -211,7 +213,7 @@ export function ClassificationEditor({
}
>
<option value="">
Selecionar referência
Seleccionar referência
</option>
{row.related_id &&
!(
@@ -295,7 +297,7 @@ export function ClassificationEditor({
}
>
<option value="">
Selecionar finalidade
Seleccionar finalidade
</option>
{Object.entries(
options.purposes,
@@ -840,7 +842,7 @@ export function ClassificationSummary({
territory: 'Enquadramento territorial',
production: 'Organização produtiva',
regulation: 'Regime regulatório',
activity: 'Atividade económica',
activity: 'Actividade económica',
}).map(([dimension, label]) => (
<section key={dimension}>
<h3 className="font-semibold">{label}</h3>
@@ -861,9 +863,15 @@ export function ClassificationSummary({
{classificationStates[r.state] ??
'Por determinar'}{' '}
· {r.purpose_label ?? r.purpose} ·{' '}
{r.source_reference || 'Fonte por indicar'}{' '}
{r.citation} {r.production_stage} · Ato
externo:{' '}
{publicReference(r.source_reference) ? (
<PublicReference
value={r.source_reference}
/>
) : (
'Referência pública não disponível'
)}{' '}
{publicReference(r.citation)}{' '}
{r.production_stage} · Acto externo:{' '}
{externalLabels[r.external_status] ??
'Não determinado'}
. Benefício ou capacidade disponível: não
@@ -935,7 +943,7 @@ export function ClassificationFilters({
},
{
key: 'subsector_id',
label: 'Subsector ou atividade publicada',
label: 'Subsector ou actividade publicada',
choices: (options.targets.activity ?? []).map((r) => [
String(r.id),
r.label,
@@ -962,7 +970,7 @@ export function ClassificationFilters({
<legend>Classificação multidimensional — filtros combinados</legend>
<p>
Os filtros combinam-se por «e». Tipo, referência e finalidade
identificam a mesma associação; cadeia, atividade e entidade
identificam a mesma associação; cadeia, actividade e entidade
podem constar de outras associações da mesma oportunidade. A
pesquisa inclui apenas publicações públicas. Os vínculos
anteriores continuam nos filtros próprios.
@@ -160,7 +160,7 @@ export default function OpportunityContactForm({
: undefined
}
>
<option value="">Por selecionar</option>
<option value="">Por seleccionar</option>
{investors.map((investor) => (
<option key={investor.id} value={investor.id}>
{investor.legal_name}
@@ -213,7 +213,7 @@ export default function OpportunityContactForm({
type="button"
onClick={() => void save()}
>
Guardar contacto e selecionar
Guardar contacto e seleccionar
</button>
</fieldset>
<p id="contact-result" role="status" tabIndex={-1}>
@@ -0,0 +1,226 @@
import { useEffect, useRef, useState } from 'react';
import {
correctionFieldHints,
fieldLabelMatches,
revealCorrectionTarget,
} from '@/lib/field-corrections';
type Correction = { message: string; targets: { id: string; label: string }[] };
let nextId = 0;
function labelOf(
control: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement,
) {
const label = control.labels?.[0];
if (label) {
const copy = label.cloneNode(true) as HTMLElement;
copy.querySelectorAll(
'input,select,textarea,button,[role="alert"],.sr-only',
).forEach((n) => n.remove());
return (
copy.textContent?.replace(/\s+/g, ' ').trim() ||
control.getAttribute('aria-label') ||
''
);
}
return control.getAttribute('aria-label') || '';
}
/** Maps live, existing messages to real controls; no inferred financial validations. */
export default function PortalCorrections() {
const marker = useRef<HTMLDivElement>(null);
const [items, setItems] = useState<Correction[]>([]);
const previous = useRef('');
useEffect(() => {
const root = marker.current?.closest('#portal-content');
if (!root) return;
let pending = 0;
const collect = () => {
pending = 0;
const controls = [
...root.querySelectorAll<
HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement
>('input:not([type="hidden"]),select,textarea'),
].filter(
(c) =>
!c.disabled && !c.closest('[hidden],[aria-hidden="true"]'),
);
const names = controls.map((c) => ({
control: c,
label: labelOf(c),
}));
const target = (c: (typeof controls)[number], label: string) => {
if (!c.id) c.id = `portal-correction-field-${++nextId}`;
const group = c.closest('fieldset,[role="group"]');
const context =
group?.querySelector('legend')?.textContent?.trim() ||
group?.getAttribute('aria-label') ||
'';
return {
id: c.id,
label: context ? `${label} — ${context}` : label,
};
};
const grouped = new Map<string, Correction>();
const add = (message: string, targets: Correction['targets']) => {
if (!message || !targets.length) return;
const item = grouped.get(message) ?? { message, targets: [] };
for (const t of targets)
if (!item.targets.some((a) => a.id === t.id))
item.targets.push(t);
grouped.set(message, item);
};
for (const { control, label } of names) {
if (control.getAttribute('aria-invalid') !== 'true') continue;
const messages = (
control.getAttribute('aria-describedby') ?? ''
)
.split(/\s+/)
.map((id) =>
document.getElementById(id)?.textContent?.trim(),
)
.filter(Boolean);
const local = control
.closest('label')
?.querySelector('[role="alert"]')
?.textContent?.trim();
add(
messages.join(' ') || local || 'Confira o valor indicado.',
[target(control, label || 'Campo indicado')],
);
}
for (const node of root.querySelectorAll<HTMLElement>(
'[data-correction-message],[role="alert"]',
)) {
if (
node.closest(
'[data-correction-summary],[hidden],[aria-hidden="true"]',
)
)
continue;
const message =
node.dataset.correctionMessage ||
node.textContent?.replace(/\s+/g, ' ').trim() ||
'';
if (!message) continue;
const hints = correctionFieldHints(message);
const matches = names.filter(
({ label }) =>
label && hints.some((h) => fieldLabelMatches(label, h)),
);
// Restrict explicit product/parcel diagnostics to the matching real group, if present.
const index = /produto\s+(\d+)|parcela\s+(\d+)/i.exec(message);
const indexed = index
? matches.filter(({ control }) => {
const group = control.closest(
'fieldset,[role="group"],[aria-label]',
);
const name =
group?.getAttribute('aria-label') ||
group?.querySelector('legend')?.textContent ||
'';
return new RegExp(
`(?:produto|parcela)\\s+${index[1] || index[2]}\\b`,
'i',
).test(name);
})
: [];
add(
message,
(indexed.length ? indexed : matches).map(
({ control, label }) => target(control, label),
),
);
}
const next = [...grouped.values()];
const serial = JSON.stringify(next);
if (serial !== previous.current) {
previous.current = serial;
setItems(next);
}
};
const schedule = () => {
if (!pending) pending = requestAnimationFrame(collect);
};
const observer = new MutationObserver((records) => {
if (
records.some(
(r) =>
!(
r.target instanceof Element
? r.target
: r.target.parentElement
)?.closest('[data-correction-summary]'),
)
)
schedule();
});
observer.observe(root, {
subtree: true,
childList: true,
characterData: true,
attributes: true,
attributeFilter: ['aria-invalid', 'aria-describedby', 'hidden'],
});
root.addEventListener('input', schedule);
root.addEventListener('change', schedule);
collect();
return () => {
observer.disconnect();
root.removeEventListener('input', schedule);
root.removeEventListener('change', schedule);
if (pending) cancelAnimationFrame(pending);
};
}, []);
return (
<div
ref={marker}
data-correction-summary
className="mx-auto max-w-6xl px-4 print:hidden"
>
{items.length > 0 && (
<section
id="portal-corrections"
aria-label="Falta preencher ou corrigir"
className="my-3 space-y-3 rounded border border-amber-500 bg-amber-50 p-4 text-sm"
>
<h2 className="font-semibold">
Falta preencher ou corrigir
</h2>
<p>
Use as ligações para abrir a secção e chegar ao campo
indicado.
</p>
<ul className="space-y-3">
{items.map((item) => (
<li key={item.message}>
<p>{item.message}</p>
<div className="flex flex-wrap gap-2">
{item.targets.map((t) => (
<a
key={t.id}
className="min-h-11 rounded border bg-white px-3 py-2 underline"
href={`#${t.id}`}
onClick={(e) => {
const node =
document.getElementById(
t.id,
);
if (node) {
e.preventDefault();
revealCorrectionTarget(
node,
);
}
}}
>
{t.label}
</a>
))}
</div>
</li>
))}
</ul>
</section>
)}
</div>
);
}
@@ -0,0 +1,17 @@
import { publicReference } from '@/lib/public-presentation';
export default function PublicReference({ value }: { value?: string | null }) {
const text = publicReference(value);
if (!text) return null;
if (/^https?:\/\//i.test(text))
return (
<a
className="underline"
href={text}
target="_blank"
rel="noreferrer"
>
Consultar fonte — {new URL(text).hostname}
</a>
);
return <>{text}</>;
}
@@ -0,0 +1,64 @@
import EvidenceDetails from './evidence-details';
import { publicReference, publicSourceHref } from '@/lib/public-presentation';
type Source = {
title?: string | null;
url?: string | null;
source_date?: string | null;
supports?: string | null;
};
export default function PublicSourceList({ sources }: { sources?: Source[] }) {
const rows = new Map<
string,
{
title: string;
url?: string;
date?: string | null;
supports: string[];
}
>();
for (const source of sources ?? []) {
const url = publicSourceHref(source.url),
title =
publicReference(source.title) ||
(url ? new URL(url).hostname : null);
if (!title) continue;
const key = JSON.stringify([url || title, source.source_date || '']);
const row = rows.get(key) ?? {
title,
url,
date: source.source_date,
supports: [],
};
const support = publicReference(source.supports);
if (support && !row.supports.includes(support))
row.supports.push(support);
rows.set(key, row);
}
if (!rows.size) return null;
return (
<EvidenceDetails title="Fontes e datas">
<ul className="space-y-2">
{[...rows.entries()].map(([key, row]) => (
<li key={key}>
{row.url ? (
<a
className="underline"
href={row.url}
target="_blank"
rel="noreferrer"
>
{row.title}
</a>
) : (
<span>{row.title}</span>
)}
{row.date && <> · {row.date}</>}
{row.supports.map((text) => (
<p key={text}>{text}</p>
))}
</li>
))}
</ul>
</EvidenceDetails>
);
}
+1 -1
View File
@@ -60,7 +60,7 @@ export default function SectorEntry({
/>
),
)}
<nav aria-label="Ações no setor" className="flex flex-wrap gap-3">
<nav aria-label="Acções no sector" className="flex flex-wrap gap-3">
{data.start_href ? (
<Link
className="rounded bg-emerald-800 px-4 py-3 text-white"
@@ -1,3 +1,4 @@
import { publicReference } from '@/lib/public-presentation';
import { useEffect, useState } from 'react';
import { Link } from '@inertiajs/react';
import { portalRequest } from '@/lib/portal-api';
@@ -86,7 +87,7 @@ export function GeographicCoverage({
</p>
<p>
Fonte de origem da localização:{' '}
{coverage.origin_source_reference ||
{publicReference(coverage.origin_source_reference) ||
'referência não divulgada ou não indicada'}
. Data da fonte:{' '}
{publicationDate(coverage.origin_source_date) ?? 'desconhecida'}
@@ -149,7 +150,7 @@ export function BusinessLocationSource({
return (
<p className="text-sm">
Fonte de origem da localização:{' '}
{record.location_source_reference ||
{publicReference(record.location_source_reference) ||
'referência não divulgada ou não indicada'}
. Data da fonte:{' '}
{publicationDate(record.location_source_date) ?? 'desconhecida'}.
@@ -445,9 +446,10 @@ export default function SimilarBusinesses({
{selected && (
<p className="text-sm">
Fonte da classificação na ficha de origem:{' '}
{selected.source_reference || 'não indicada'}. A relação
documental não comprova implantação, propriedade ou
capacidade.
{publicReference(selected.source_reference) ||
'não indicada'}
. A relação documental não comprova implantação, propriedade
ou capacidade.
</p>
)}
<Link href={effectiveCatalogueUrl} className="underline">
+5 -8
View File
@@ -1,3 +1,4 @@
import { focusCorrectionId } from '@/lib/field-corrections';
import FiscalOperationPicker from './fiscal-operation-picker';
import { SimulationIrpcAnnual } from '@/components/simulation-irpc-annual';
import DemographicContext from '@/components/demographic-context';
@@ -5124,13 +5125,9 @@ export function SimulationForm() {
),
),
);
window.requestAnimationFrame(
() =>
document
.getElementById(
`field-${item.key}`,
)
?.focus(),
setOpenedTool(null);
focusCorrectionId(
`field-${item.key}`,
);
}}
>
@@ -5225,7 +5222,7 @@ export function SimulationForm() {
{draft.purpose === 'simulate_only' && (
<div
className="space-y-2 rounded border p-3"
aria-label="Ações do simulador"
aria-label="Acções do simulador"
>
<p>
Abrir cálculo apresenta as ferramentas financeiras
+100 -25
View File
@@ -1,3 +1,5 @@
import PublicReference from './public-reference';
import { publicReference, uniquePresentation } from '@/lib/public-presentation';
import { Link } from '@inertiajs/react';
import DemographicContext from './demographic-context';
import TerritorialSources, {
@@ -98,38 +100,97 @@ export function LocationList({
</dl>
<DemographicContext
key={location.id}
territoryId={location.path
.filter((t) => ['province', 'district'].includes(t.location_type))
.at(-1)?.id}
territoryId={
location.path
.filter((t) =>
['province', 'district'].includes(
t.location_type,
),
)
.at(-1)?.id
}
/>
{location.coordinates.map((point) => (
<p key={point.geometry_id}>
{uniquePresentation(location.coordinates, (p) =>
JSON.stringify([
p.geometry_id,
p.source_reference,
p.source_date,
]),
).map((point) => (
<p
key={JSON.stringify([
point.geometry_id,
point.source_reference,
point.source_date,
])}
>
Coordenadas documentadas (
{location.location_type === 'site'
? 'local cadastrado; não confirma a implantação da oportunidade'
: 'referência territorial; não representa a implantação'}
): {point.geometry.coordinates[1]},{' '}
{point.geometry.coordinates[0]} · Fonte:{' '}
{point.source_reference ?? 'Não indicada'}
{' · Data da fonte: '}
{point.source_date ?? 'Não documentada'}
{point.geometry.coordinates[0]}
{publicReference(point.source_reference) && (
<>
{' '}
· Fonte:{' '}
<PublicReference
value={point.source_reference}
/>
</>
)}
{point.source_date && (
<> · Data: {point.source_date}</>
)}
</p>
))}
{!location.coordinates.length && (
<p>Coordenadas não documentadas.</p>
)}
<p className="text-sm">
Fonte da relação:{' '}
{location.source_reference ?? 'Não indicada'}
{' · Data da fonte: '}
{location.source_date ?? 'Não documentada'}
</p>
{location.boundaries?.map((boundary) => (
<p key={boundary.geometry_id}>
Polígono cadastrado · Fonte:{' '}
{boundary.source_reference ?? 'Não indicada'} ·
Data: {boundary.source_date ?? 'Não documentada'}. O
cadastro não certifica limites oficiais.
{(publicReference(location.source_reference) ||
location.source_date) && (
<p className="text-sm">
{publicReference(location.source_reference) && (
<>
Fonte da relação:{' '}
<PublicReference
value={location.source_reference}
/>
</>
)}
{location.source_date && (
<> · Data: {location.source_date}</>
)}
</p>
)}
{uniquePresentation(location.boundaries ?? [], (b) =>
JSON.stringify([
b.geometry_id,
b.source_reference,
b.source_date,
]),
).map((boundary) => (
<p
key={JSON.stringify([
boundary.geometry_id,
boundary.source_reference,
boundary.source_date,
])}
>
Polígono cadastrado
{publicReference(boundary.source_reference) && (
<>
{' '}
· Fonte:{' '}
<PublicReference
value={boundary.source_reference}
/>
</>
)}
{boundary.source_date && (
<> · Data: {boundary.source_date}</>
)}
. O cadastro não certifica limites oficiais.
</p>
))}
{!location.boundaries?.length && (
@@ -251,7 +312,7 @@ export default function StructureGeographyPanel({
className="underline"
href={`/carteira/${member.dossier_id}?from=${dossierId}`}
>
{member.code} · {member.title}
{member.title}
</Link>
</h3>
<p>
@@ -259,7 +320,15 @@ export default function StructureGeographyPanel({
{member.validation_status === 'validated'
? 'validada no cadastro'
: 'documental de planeamento; validação pendente'}{' '}
· Fonte: {member.source_reference}
{publicReference(member.source_reference) && (
<>
{' '}
· Fonte:{' '}
<PublicReference
value={member.source_reference}
/>
</>
)}
</p>
<LocationList locations={member.locations} />
{!member.locations.length && (
@@ -282,7 +351,13 @@ export default function StructureGeographyPanel({
{item.validation_status === 'validated'
? 'validada no cadastro'
: 'relação documental de planeamento; validação pendente'}{' '}
· Fonte: {item.source_reference}
{publicReference(item.source_reference) && (
<>
{' '}
· Fonte:{' '}
<PublicReference value={item.source_reference} />
</>
)}
</p>
))}
{cluster && (
@@ -292,7 +367,7 @@ export default function StructureGeographyPanel({
</h3>
{geography.chains?.map((chain) => (
<p key={chain.id}>
{chain.code} · {chain.name} ·{' '}
{chain.name} ·{' '}
{(
{
input: 'Insumos',
@@ -1,3 +1,6 @@
import { publicReference, uniquePresentation } from '@/lib/public-presentation';
import PublicReference from './public-reference';
import { usePage } from '@inertiajs/react';
import EvidenceDetails from './evidence-details';
export type TerritorialSourceEvidence = {
@@ -15,28 +18,68 @@ export default function TerritorialSources({
}: {
sources?: TerritorialSourceEvidence[];
}) {
if (!sources?.length) return null;
const management = usePage().url.startsWith('/management/');
const visible = uniquePresentation(
(sources ?? []).filter(
(row) =>
management ||
publicReference(row.source_reference) ||
publicReference(row.source_quote) ||
publicReference(row.supports),
),
(row) =>
JSON.stringify([
row.association,
row.role,
management
? row.source_reference
: publicReference(row.source_reference),
publicReference(row.source_quote),
publicReference(row.supports),
...(management ? [row.traceability] : []),
]),
);
if (!visible.length) return null;
return (
<EvidenceDetails title="Fontes das relações territoriais">
{sources.map((source, i) => (
{visible.map((source, i) => (
<article className="border-t pt-3" key={i}>
<h3 className="font-semibold">
{source.role} — {source.association}
</h3>
<p>
Fonte:{' '}
{source.source_reference ??
'ligação ao exemplar por recuperar'}
</p>
<p>{source.source_quote ?? source.supports}</p>
{(management ||
publicReference(source.source_reference)) && (
<p>
Fonte:{' '}
{management ? (
source.source_reference
) : (
<PublicReference
value={source.source_reference}
/>
)}
</p>
)}
{(publicReference(source.source_quote) ||
publicReference(source.supports)) && (
<p>
{publicReference(source.source_quote) ||
publicReference(source.supports)}
</p>
)}
<EvidenceDetails title="Proveniência e versão da referência">
<p>
{source.official_source_accepted
? 'Fonte oficial identificada.'
: 'Ligação ao exemplar oficial por recuperar.'}
</p>
<p>{source.traceability}</p>
{source.existing_validation && (
{(management ||
publicReference(source.traceability)) && (
<p>{source.traceability}</p>
)}
{(management
? source.existing_validation
: publicReference(source.existing_validation)) && (
<p>{source.existing_validation}</p>
)}
</EvidenceDetails>