fix: harmonizar pesquisa e navegacao dos catalogos em QA

This commit is contained in:
2026-10-20 18:53:41 +02:00
parent 1350b4df73
commit fd341b627e
34 changed files with 2311 additions and 1310 deletions
@@ -0,0 +1,140 @@
import { Link, usePage } from '@inertiajs/react';
const labels: Record<string, string> = {
q: 'Pesquisa',
query: 'Pesquisa',
sector: 'Sector',
kind: 'Tipo de ficha',
modality: 'Modalidade',
category: 'Categoria',
physical_category: 'Tipo de espaço',
legal_regime: 'Regime',
development_status: 'Desenvolvimento',
availability_status: 'Disponibilidade',
province_id: 'Província',
district_id: 'Distrito',
admin_post_id: 'Posto administrativo',
locality_id: 'Localidade',
geo_location_id: 'Localização',
territory_id: 'Território',
province: 'Província',
activity: 'Actividade',
document_type: 'Tipo de documento',
topic: 'Tema',
issuer: 'Entidade emissora',
language: 'Idioma',
legal_status: 'Situação documental',
source_confirmation: 'Fonte',
stage: 'Etapa',
module: 'Área',
association_type: 'Associação',
association_target: 'Referência',
association_purpose: 'Relação',
association_state: 'Confirmação',
chain_id: 'Cadeia de valor',
subsector_id: 'Actividade',
authority_id: 'Entidade',
};
const territoryKeys = [
'province_id',
'district_id',
'admin_post_id',
'locality_id',
];
const values: Record<string, string> = {
corridor: 'Corredores',
cluster: 'Clusters',
project: 'Projectos âncora',
zee: 'ZEE',
zfi: 'ZFI',
industrial_park: 'Parque industrial',
investment_project: 'Projecto de investimento',
company_sale: 'Venda de empresa',
company_purchase: 'Compra de empresa',
real_estate: 'Imobiliário',
land_right: 'Direitos fundiários',
turismo: 'Turismo',
agronegocio: 'Agronegócio',
fintech: 'Fintech — especialização do Mercado Financeiro',
'mercado-financeiro': 'Mercado Financeiro',
legislation: 'Legislação',
procedure: 'Procedimento oficial',
official_form: 'Formulário oficial',
guide: 'Guia',
study: 'Estudo',
unknown: 'Por confirmar',
pt: 'Português',
en: 'Inglês',
confirmed: 'Confirmada',
pending: 'Por confirmar',
};
/** 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 active = Object.entries(filters).filter(
([key, value]) =>
!['page', 'per_page', 'sort', 'view', 'publication_state'].includes(
key,
) &&
value !== '' &&
value != null &&
value !== false &&
(!Array.isArray(value) || value.length),
);
if (!active.length) return null;
const describe = (key: string, value: unknown): string => {
const path = page.props.territorySelection as
| { id: string; name: string }[]
| undefined;
const place = path?.find((item) => item.id === value)?.name;
if (place) return place;
if (typeof value !== 'string') return 'seleccionado';
return (
values[value] ??
(['q', 'query', 'province', 'topic', 'issuer'].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;
};
return (
<nav
aria-label="Filtros activos"
className="my-3 flex flex-wrap items-center gap-3"
>
<span className="font-semibold">Filtros activos:</span>
{active.map(([key, value]) => (
<Link
key={key}
href={href(key)}
className="rounded border px-3 py-2 underline"
aria-label={`Remover ${labels[key] ?? 'critério'}`}
>
{labels[key] ?? 'Critério seleccionado'}:{' '}
{describe(key, value)} ×
</Link>
))}
<Link href={href()} className="underline">
Limpar filtros
</Link>
</nav>
);
}
@@ -73,34 +73,32 @@ export default function CatalogueNavigation({
],
};
return (
<nav
className="my-4 grid gap-3 rounded-xl border bg-white p-4 sm:grid-cols-2 lg:grid-cols-4"
aria-label="Explorar dentro do catálogo"
>
{Object.entries(sections).map(([title, items]) => (
<section key={title}>
<h2 className="mb-2 font-semibold">{title}</h2>
<ul className="space-y-2">
{items.map(([label, href]) => (
<li key={label}>
<Link
className="underline"
href={withContext(href)}
>
{label}
</Link>
</li>
))}
</ul>
</section>
))}
<p className="text-sm sm:col-span-2 lg:col-span-4">
Filtros e vistas reutilizam os catálogos existentes.
Comprar/vender continua no consumidor /negocios; não duplica
anúncios nem unifica contagens. Selecionar um parque ou projeto
específico usa os filtros existentes; a ficha relacionada não é
uma oportunidade.
</p>
</nav>
<details className="my-4 rounded-xl border bg-white p-4">
<summary className="cursor-pointer font-semibold">
Catálogos relacionados
</summary>
<nav
className="my-4 grid gap-3 rounded-xl border bg-white p-4 sm:grid-cols-2 lg:grid-cols-4"
aria-label="Explorar dentro do catálogo"
>
{Object.entries(sections).map(([title, items]) => (
<section key={title}>
<h2 className="mb-2 font-semibold">{title}</h2>
<ul className="space-y-2">
{items.map(([label, href]) => (
<li key={label}>
<Link
className="underline"
href={withContext(href)}
>
{label}
</Link>
</li>
))}
</ul>
</section>
))}
</nav>
</details>
);
}
+8 -1
View File
@@ -50,7 +50,14 @@ export default function CountrySelect({
onChange={(event) => setSearch(event.target.value)}
placeholder="Pesquisar nome ou código do país"
/>
{search.trim() && <p role="status" aria-live="polite">{matches.length ? `${matches.length} resultados encontrados` : "Não foram encontrados resultados para esta pesquisa"}</p>}
{search.trim() && (
<p role="status" aria-live="polite">
Países:{' '}
{matches.length
? `${matches.length} opções disponíveis`
: 'Nenhuma opção encontrada'}
</p>
)}
<select
disabled={disabled}
id={id ?? generatedId}
@@ -24,7 +24,9 @@ export default function InvestmentMapPanel({
useEffect(() => {
const controller = new AbortController();
const params = new URLSearchParams(JSON.parse(key));
setPoints(null); setError(''); setMissing([]);
setPoints(null);
setError('');
setMissing([]);
setAreas([]);
fetch(`/api/v1/investment/map?${params}`, {
signal: controller.signal,
@@ -46,13 +48,21 @@ export default function InvestmentMapPanel({
);
})
.catch(() => {
if (!controller.signal.aborted) setError('Não foi possível concluir a pesquisa.');
if (!controller.signal.aborted)
setError('Não foi possível concluir a pesquisa.');
});
return () => controller.abort();
}, [key, retry]);
return (
<section className="space-y-3">
<SearchState loading={points === null && !error} error={error} total={(points?.length ?? 0) + missing.length} retry={() => setRetry(value => value + 1)} />
<SearchState
scope="Registos consultados pelo mapa"
countLabel="registos, incluindo os que não têm coordenadas"
loading={points === null && !error}
error={error}
total={(points?.length ?? 0) + missing.length}
retry={() => setRetry((value) => value + 1)}
/>
<InteractiveInvestmentMap points={points} areas={areas} />
<TerritoryGeometryPreview
territoryId={
@@ -113,9 +113,7 @@ export function ProvinceSelect({
})
.catch(() => {
if (!controller.signal.aborted)
setError(
'Não foi possível concluir a pesquisa.',
);
setError('Não foi possível concluir a pesquisa.');
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false);
@@ -130,7 +128,13 @@ export function ProvinceSelect({
return (
<>
<SearchState loading={loading} error={error} total={options.length} retry={() => setRetry(value => value + 1)} />
<SearchState
scope="Localizações"
loading={loading}
error={error}
total={options.length}
retry={() => setRetry((value) => value + 1)}
/>
<input
className={className}
aria-label={`Pesquisar ${label}`}
@@ -300,9 +304,7 @@ export function TerritoryLevel({
setMore(Boolean(data.next_page_url));
} catch {
if (!controller.signal.aborted)
setError(
'Não foi possível concluir a pesquisa.',
);
setError('Não foi possível concluir a pesquisa.');
} finally {
if (!controller.signal.aborted) setLoading(false);
}
@@ -314,7 +316,15 @@ export function TerritoryLevel({
}, [index, parent, page, enabled, endpoint, retry, search]);
return (
<div className="space-y-2">
{enabled && <SearchState loading={loading} error={error} total={options.length} retry={() => setRetry(value => value + 1)} />}
{enabled && (
<SearchState
scope={labels[index]}
loading={loading}
error={error}
total={options.length}
retry={() => setRetry((value) => value + 1)}
/>
)}
<label htmlFor={id} className="font-medium">
{labels[index]}
</label>
@@ -831,7 +831,11 @@ export function ClassificationSummary({
<h2 className="text-xl font-bold">
Associações territoriais e produtivas
</h2>
<p>{help}</p>
<p>
As relações preliminares permanecem por confirmar. Uma
associação não comprova disponibilidade, incentivos ou direitos
concedidos.
</p>
{Object.entries({
territory: 'Enquadramento territorial',
production: 'Organização produtiva',
@@ -867,10 +871,7 @@ export function ClassificationSummary({
</p>
))
) : (
<p>
Sem informação tipada publicada nesta dimensão;
consulte também as relações anteriores abaixo.
</p>
<p>Sem associações publicadas neste grupo.</p>
)}
</section>
))}
@@ -0,0 +1,480 @@
import { Field, input, button, groupLabels } from '@/pages/investment/shared';
import type { References } from '@/pages/investment/shared';
import { TerritoryLevel, type TerritoryOption } from './investment-territory';
export const modalityLabels: Record<string, string> = {
investment_project: 'Projecto de investimento',
real_estate: 'Imobiliário',
land_rights: 'DUAT e direitos fundiários',
business_sale: 'Venda de negócio',
business_partnership: 'Parceria empresarial',
franchise: 'Franquia',
concession: 'Concessão',
financing: 'Financiamento',
supply: 'Fornecimento',
other: 'Outra modalidade',
};
type Values = Record<string, string | boolean | number[]>;
const labels: Record<string, string> = {
q: 'O que procura',
sector: 'Sector',
category: 'Modalidade da oportunidade',
preparation: 'Estado de preparação',
sort: 'Ordenar',
min_amount: 'Investimento mínimo',
max_amount: 'Investimento máximo',
currency: 'Moeda',
before: 'Data-alvo até',
cluster_id: 'Cluster',
corridor_id: 'Corredor',
project_id: 'Projecto âncora',
zee_id: 'ZEE',
zfi_id: 'ZFI',
park_id: 'Parque industrial',
chain_id: 'Cadeia de valor',
subsector_id: 'Actividade',
include_national: 'Incluir âmbito nacional',
education: 'Educação',
province: 'Província indicada',
district: 'Distrito indicado',
dimension: 'Grupo de oportunidades',
territory_basis: 'Localização considerada',
geo_location_id: 'Localização adicional',
maturity_level: 'Classificação histórica',
association_type: 'Associação herdada',
association_target: 'Referência herdada',
association_purpose: 'Relação indicada',
association_state: 'Critério herdado',
authority_id: 'Entidade',
publication_state: 'Critério herdado',
};
export default function OpportunitySearchFilters({
data,
references,
path,
change,
territory,
submit,
clear,
errors,
}: {
data: Values;
references: References;
path: TerritoryOption[];
change: (values: Values) => void;
territory: (path: TerritoryOption[]) => void;
submit: () => void;
clear: () => void;
errors: Record<string, string>;
}) {
const select = (
key: string,
choices: { value: string; label: string }[],
hint?: string,
) => (
<Field key={key} label={labels[key]}>
<select
className={input}
value={String(data[key] ?? '')}
onChange={(e) =>
change({
[key]: e.target.value,
...(key === 'sector'
? { subsector_id: '', chain_id: '' }
: {}),
})
}
>
<option value="">Todos</option>
{choices.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</select>
{hint && <p className="text-sm text-slate-600">{hint}</p>}
</Field>
);
const zoneChoices = (category: string) =>
(references.zones ?? [])
.filter((z) => z.category === category)
.map((z) => ({ value: z.id, label: z.name }));
const choicesFor = (key: string) => {
if (key === 'sector')
return references.sectors.map((s) => ({
value: s.slug,
label:
s.slug === 'fintech'
? 'Fintech — especialização do Mercado Financeiro'
: s.name,
}));
if (key === 'category')
return (references.categories ?? []).map((c) => ({
value: c,
label: modalityLabels[c] ?? 'Outra modalidade',
}));
if (key === 'preparation') return references.preparationOptions ?? [];
if (key === 'dimension')
return [
{ value: 'cluster', label: 'Clusters' },
{ value: 'corridor', label: 'Corredores' },
{ value: 'zee', label: 'ZEE' },
{ value: 'zfi', label: 'ZFI' },
];
if (['zee_id', 'zfi_id', 'park_id'].includes(key))
return zoneChoices(
(
{
zee_id: 'zee',
zfi_id: 'zfi',
park_id: 'industrial_park',
} as Record<string, string>
)[key],
);
const group = (
{
cluster_id: 'clusters',
corridor_id: 'corridors',
project_id: 'projects',
} as const
)[key as 'cluster_id'];
if (group)
return references[group].map((e) => ({
value: e.id,
label: e.name,
}));
if (key === 'chain_id' || key === 'subsector_id')
return (
references.classification?.targets[
key === 'chain_id' ? 'chain' : 'activity'
] ?? []
).map((e) => ({ value: String(e.id), label: e.label }));
return [];
};
const remove = (key: string) => {
if (key === 'sector')
change({ sector: '', subsector_id: '', chain_id: '' });
else if (key === 'facets') change({ facets: [] });
else change({ [key]: typeof data[key] === 'boolean' ? false : '' });
};
const active = Object.entries(data).filter(
([k, v]) =>
![
'view',
'sort',
'province_id',
'district_id',
'admin_post_id',
'locality_id',
].includes(k) &&
v !== '' &&
v !== false &&
v !== null &&
(!Array.isArray(v) || v.length > 0) &&
!(k === 'territory_basis' && v === 'all'),
);
return (
<form
className="space-y-5 rounded-xl border bg-white p-4 sm:p-6"
onSubmit={(e) => {
e.preventDefault();
submit();
}}
aria-label="Pesquisar oportunidades"
>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
<Field label="O que procura">
<input
className={input}
value={String(data.q)}
placeholder="Palavras do título ou da descrição"
onChange={(e) => change({ q: e.target.value })}
/>
</Field>
{select('sector', choicesFor('sector'))}
{select('category', choicesFor('category'))}
</div>
<fieldset className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<legend className="mb-2 font-semibold">Localização</legend>
{(
[
'province_id',
'district_id',
'admin_post_id',
'locality_id',
] as const
).map((key, index) => (
<TerritoryLevel
key={`${key}-${path[index - 1]?.id ?? ''}`}
index={index}
parent={path[index - 1]?.id ?? ''}
selected={path[index]}
endpoint="/api/v1/investment/territory-options"
onChange={(value) =>
territory([
...path.slice(0, index),
...(value ? [value] : []),
])
}
/>
))}
</fieldset>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<Field label="Estado de preparação">
<select
className={input}
value={String(data.preparation ?? '')}
onChange={(e) =>
change({
preparation: e.target.value,
maturity_level: '',
})
}
>
<option value="">Todos os estados</option>
{[
'Etapas de preparação',
'Classificações históricas',
].map((group) => (
<optgroup key={group} label={group}>
{(references.preparationOptions ?? [])
.filter((o) => o.group === group)
.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</optgroup>
))}
</select>
<p className="text-sm text-slate-600">
Os registos históricos são apresentados separadamente e
conservam a classificação indicada na ficha.
</p>
</Field>
{(['min_amount', 'max_amount'] as const).map((key) => (
<Field key={key} label={labels[key]}>
<input
className={input}
type="number"
min="0"
step="0.01"
value={String(data[key])}
onChange={(e) => change({ [key]: e.target.value })}
/>
</Field>
))}
{select(
'currency',
['MZN', 'USD', 'EUR', 'ZAR'].map((c) => ({
value: c,
label: c,
})),
'Seleccione uma moeda para comparar montantes. Não se efectuam conversões cambiais.',
)}
</div>
<details>
<summary className="cursor-pointer rounded border p-3 font-semibold focus-visible:outline-2">
Mais filtros
</summary>
<div className="mt-4 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{[
'corridor_id',
'cluster_id',
'zee_id',
'zfi_id',
'park_id',
'project_id',
'subsector_id',
'chain_id',
].map((key) => select(key, choicesFor(key)))}
<Field label="Data-alvo até">
<input
className={input}
type="date"
value={String(data.before)}
onChange={(e) => change({ before: e.target.value })}
/>
</Field>
</div>
<p className="my-3 text-sm">
Estes filtros procuram associações documentadas. Estar perto
de um parque ou no mesmo distrito não constitui associação,
nem confirma incentivos ou disponibilidade.
</p>
<label className="flex gap-2">
<input
type="checkbox"
checked={Boolean(data.include_national)}
onChange={(e) =>
change({ include_national: e.target.checked })
}
/>
Incluir oportunidades de âmbito nacional
</label>
<details className="mt-3">
<summary className="cursor-pointer font-medium">
Outras características
</summary>
<div className="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{[
'education',
'infrastructure',
'labour',
'qualification',
'support',
'impact',
'partnership',
]
.filter((group) =>
references.options.some(
(o) => o.group === group,
),
)
.map((group) => (
<fieldset
key={group}
className="rounded border p-3"
>
<legend>{groupLabels[group]}</legend>
{references.options
.filter((o) => o.group === group)
.map((option) => (
<label
key={option.id}
className="flex gap-2 py-1"
>
<input
type="checkbox"
checked={
Array.isArray(
data.facets,
) &&
data.facets.includes(
option.id,
)
}
onChange={(e) => {
const selected =
Array.isArray(
data.facets,
)
? data.facets
: [];
change({
facets: e.target
.checked
? [
...selected,
option.id,
]
: selected.filter(
(id) =>
id !==
option.id,
),
});
}}
/>
{option.label}
</label>
))}
</fieldset>
))}
</div>
</details>
</details>
<section
aria-label="Filtros activos"
className="flex flex-wrap gap-2"
>
{path.map((node, index) => (
<button
className="rounded border px-3 py-2"
type="button"
key={node.id}
aria-label={`Remover localização ${node.name}`}
onClick={() => territory(path.slice(0, index))}
>
{node.name} ×
</button>
))}
{active.flatMap(([key, value]) =>
key === 'facets' && Array.isArray(value)
? value.map((id) => (
<button
key={`facet-${id}`}
type="button"
className="rounded border px-3 py-2"
onClick={() =>
change({
facets: value.filter((x) => x !== id),
})
}
>
{' '}
{references.options.find((o) => o.id === id)
?.label ?? 'Critério adicional'}{' '}
×
</button>
))
: [
<button
key={key}
type="button"
className="rounded border px-3 py-2 text-left"
aria-label={`Remover ${labels[key] ?? 'critério adicional'}`}
onClick={() => remove(key)}
>
{labels[key] ?? 'Critério adicional'}:{' '}
{typeof value === 'boolean'
? 'Sim'
: (choicesFor(key).find(
(o) => o.value === String(value),
)?.label ??
([
'q',
'min_amount',
'max_amount',
'currency',
'before',
'province',
'district',
].includes(key)
? String(value)
: 'seleccionado'))}{' '}
×
</button>,
],
)}
</section>
{Object.entries(errors).map(([key, value]) => (
<p key={key} role="alert">
{value}
</p>
))}
<div className="flex flex-wrap items-end gap-4">
{select('sort', [
{ value: 'recent', label: 'Mais recentes' },
{ value: 'title', label: 'Título' },
{
value: 'amount_asc',
label: 'Montante crescente, por moeda',
},
{
value: 'amount_desc',
label: 'Montante decrescente, por moeda',
},
])}
<button className={button}>Pesquisar</button>
<button
type="button"
className="rounded border px-4 py-2 underline"
onClick={clear}
>
Limpar filtros
</button>
</div>
</form>
);
}
+169 -26
View File
@@ -1,14 +1,45 @@
import { router, usePage } from '@inertiajs/react';
import { useEffect, useRef, useState } from 'react';
import CatalogueFilterContext from './catalogue-filter-context';
// Shared feedback for existing Inertia search consumers; form state is never reset.
const collections = ['results','records','resources','partnerships','opportunities','interests','investors','leads','articles','services','items','entries','documents','requests','batches','users','assignments','zones','matches','businesses'];
const collections = [
'results',
'records',
'resources',
'partnerships',
'opportunities',
'interests',
'investors',
'leads',
'articles',
'services',
'items',
'entries',
'documents',
'requests',
'batches',
'users',
'assignments',
'zones',
'matches',
'businesses',
];
function count(props: Record<string, unknown>): number | null {
if (props.demands && props.capacities) return Number((props.demands as {total:number}).total) + Number((props.capacities as {total:number}).total);
if (props.plan && Array.isArray((props.plan as {rows:unknown[]}).rows)) return (props.plan as {rows:unknown[]}).rows.length;
if (props.demands && props.capacities)
return (
Number((props.demands as { total: number }).total) +
Number((props.capacities as { total: number }).total)
);
if (props.plan && Array.isArray((props.plan as { rows: unknown[] }).rows))
return (props.plan as { rows: unknown[] }).rows.length;
if (typeof props.total === 'number') return props.total;
if (typeof props.match === 'boolean' && Array.isArray(props.articles)) return props.match ? props.articles.length : 0;
if (typeof props.match === 'boolean' && Array.isArray(props.articles))
return props.match ? props.articles.length : 0;
for (const key of collections) {
const value = props[key] as {total?:number; meta?:{total?:number}; data?:unknown[]} | unknown[] | undefined;
const value = props[key] as
| { total?: number; meta?: { total?: number }; data?: unknown[] }
| unknown[]
| undefined;
if (!value) continue;
if (Array.isArray(value)) return value.length;
if (typeof value.total === 'number') return value.total;
@@ -19,28 +50,140 @@ function count(props: Record<string, unknown>): number | null {
}
export default function SearchFeedback() {
const page = usePage();
const [state, setState] = useState<'idle'|'loading'|'error'>('idle');
const latest = useRef<{url: string; data: Record<string, unknown>} | null>(null);
const handledLocally = page.component === 'investment/catalogue';
const [state, setState] = useState<'idle' | 'loading' | 'error'>('idle');
const latest = useRef<{
url: string;
data: Record<string, unknown>;
} | null>(null);
const active = useRef(false);
const searchable = page.props.filters !== undefined || ['portal/legacy','desk/catalogue','investment/zones','partnerships/catalogue','education/index','management/territory-geometry-import'].includes(page.component);
const total = searchable ? count(page.props) : null;
const searchable =
page.props.filters !== undefined ||
[
'portal/legacy',
'desk/catalogue',
'investment/zones',
'partnerships/catalogue',
'education/index',
'management/territory-geometry-import',
].includes(page.component);
// A page may contain several independent catalogues. Never infer a public
// result universe by whichever collection happens to occur first.
const descriptors: Record<string, [string, string]> = {
'portfolio/index': ['records', 'Fichas da carteira'],
'investment/zones': ['records', 'Zonas e parques'],
'investment/business-marketplace': ['results', 'Anúncios de negócios'],
'portal/legacy': ['articles', 'Artigos'],
};
const descriptor =
page.component === 'portal/services'
? page.props.section === 'documents' ||
page.props.section === 'legislation'
? ['resources', 'Documentos']
: page.props.section === 'sectors'
? ['sectors', 'Sectores']
: null
: descriptors[page.component];
const total = descriptor
? page.component === 'portal/legacy' && page.props.match === false
? 0
: count({ results: page.props[descriptor[0]] })
: searchable
? count(page.props)
: null;
const label = descriptor?.[1];
useEffect(() => {
const off = [router.on('before', event => {
const visit = event.detail.visit;
if (visit.method !== 'get') { active.current = false; return; }
const data = visit.data as Record<string, unknown>;
const url = visit.url;
const isSearch = total !== null || ['q','query','search','filter','status','sector'].some(key => key in data || url.searchParams.has(key));
active.current = isSearch;
if (isSearch) { latest.current = {url: url.toString(), data}; setState('loading'); }
}), router.on('success', () => { if (active.current) { active.current = false; setState('idle'); } }),
router.on('error', () => { if (active.current) setState('error'); }),
router.on('httpException', event => { if (active.current) { event.preventDefault(); setState('error'); } }),
router.on('networkError', event => { if (active.current) { event.preventDefault(); setState('error'); } })];
return () => off.forEach(remove => remove());
}, [total]);
if (handledLocally) return;
const off = [
router.on('before', (event) => {
const visit = event.detail.visit;
if (visit.method !== 'get') {
active.current = false;
return;
}
const data = visit.data as Record<string, unknown>;
const url = visit.url;
const isSearch =
total !== null ||
['q', 'query', 'search', 'filter', 'status', 'sector'].some(
(key) => key in data || url.searchParams.has(key),
);
active.current = isSearch;
if (isSearch) {
latest.current = { url: url.toString(), data };
setState('loading');
}
}),
router.on('success', () => {
if (active.current) {
active.current = false;
setState('idle');
}
}),
router.on('error', () => {
if (active.current) setState('error');
}),
router.on('httpException', (event) => {
if (active.current) {
event.preventDefault();
setState('error');
}
}),
router.on('networkError', (event) => {
if (active.current) {
event.preventDefault();
setState('error');
}
}),
];
return () => off.forEach((remove) => remove());
}, [total, handledLocally]);
if (handledLocally) return null;
if (total === null && state === 'idle') return null;
return <aside data-search-feedback role={state === 'error' ? 'alert' : 'status'} aria-live="polite" aria-atomic="true" className="sticky top-0 z-50 border-b bg-white p-3 text-center text-slate-950 shadow">
{state === 'loading' ? 'A pesquisar…' : state === 'error' ? <><span>Não foi possível concluir a pesquisa. Os resultados anteriores mantêm-se abaixo. </span><button type="button" className="underline" onClick={() => { const request = latest.current; if (request) router.get(request.url, request.data as never, {preserveState:true, preserveScroll:true}); }}>Tentar novamente</button></> : total === 0 ? 'Não foram encontrados resultados para esta pesquisa' : `${total} resultados encontrados`}
</aside>;
return (
<>
<aside
data-search-feedback
role={state === 'error' ? 'alert' : 'status'}
aria-live="polite"
aria-atomic="true"
className="border-b bg-white p-3 text-center text-slate-950"
>
{label && <strong>{label}: </strong>}
{state === 'loading' ? (
'A pesquisar…'
) : state === 'error' ? (
<>
<span>
Não foi possível concluir a pesquisa. Os resultados
anteriores mantêm-se abaixo.{' '}
</span>
<button
type="button"
className="underline"
onClick={() => {
const request = latest.current;
if (request)
router.get(
request.url,
request.data as never,
{
preserveState: true,
preserveScroll: true,
},
);
}}
>
Tentar novamente
</button>
</>
) : total === 0 ? (
'Não foram encontrados resultados para esta pesquisa'
) : (
`${total} ${total === 1 ? 'resultado encontrado' : 'resultados encontrados'}`
)}
</aside>
{descriptor && <CatalogueFilterContext />}
</>
);
}
+47 -4
View File
@@ -1,5 +1,48 @@
export default function SearchState({loading, error, total, retry}: {loading:boolean; error?:string; total:number; retry:()=>void}) {
return <div role={error ? 'alert' : 'status'} aria-live="polite" aria-atomic="true" className="my-3 rounded border p-3">
{loading ? 'A pesquisar…' : error ? <>Não foi possível concluir a pesquisa. <button type="button" className="underline" onClick={retry}>Tentar novamente</button></> : total === 0 ? 'Não foram encontrados resultados para esta pesquisa' : `${total} resultados encontrados`}
</div>;
export default function SearchState({
loading,
error,
total,
retry,
scope,
countLabel,
}: {
loading: boolean;
error?: string;
total: number;
retry: () => void;
scope?: string;
countLabel?: string;
}) {
return (
<div
role={error ? 'alert' : 'status'}
aria-live="polite"
aria-atomic="true"
className="my-3 rounded border p-3"
>
{scope && <span className="font-medium">{scope}: </span>}
{loading ? (
'A pesquisar…'
) : error ? (
<>
Não foi possível concluir a pesquisa.{' '}
<button type="button" className="underline" onClick={retry}>
Tentar novamente
</button>
</>
) : total === 0 ? (
scope ? (
'Nenhuma opção encontrada'
) : (
'Não foram encontrados resultados para esta pesquisa'
)
) : countLabel ? (
`${total} ${countLabel}`
) : scope ? (
`${total} ${total === 1 ? 'opção disponível' : 'opções disponíveis'}`
) : (
`${total} ${total === 1 ? 'resultado encontrado' : 'resultados encontrados'}`
)}
</div>
);
}
+12
View File
@@ -0,0 +1,12 @@
/** Only a query string is carried; the return destination is always local. */
export function catalogueDetailHref(path: string, query: string): string {
return query
? `${path}?catalogue_query=${encodeURIComponent(query)}`
: path;
}
export function catalogueReturnHref(base: string, pageUrl: string): string {
const query = new URL(pageUrl, 'https://portal.invalid').searchParams.get(
'catalogue_query',
);
return base + (query ? `?${new URLSearchParams(query).toString()}` : '');
}
+37
View File
@@ -445,6 +445,11 @@ export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
label: 'Descoberta',
children: [
link('home', 'Início', '/'),
link(
'idea-entry',
'Partir de uma ideia',
'/investimentos/iniciar',
),
link(
'why',
'Porquê investir em Moçambique',
@@ -457,6 +462,36 @@ export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
),
link('sectors', 'Sectores de investimento', '/sectores'),
link('locations', 'Localizações', '/oportunidades?view=map'),
{
id: 'related-catalogues',
label: 'Catálogos relacionados',
children: [
link(
'portfolio',
'Carteira, clusters e corredores',
'/carteira',
),
link('zones', 'Zonas e parques', '/zonas'),
...(access.businesses
? [
link(
'business-catalogue',
'Negócios',
'/negocios',
),
]
: []),
...(access.education
? [
link(
'education-catalogue',
'Oportunidades na educação',
'/educacao',
),
]
: []),
],
},
],
},
{
@@ -487,6 +522,8 @@ export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
id: 'support',
label: 'Suporte',
children: [
link('documents', 'Biblioteca de documentos', '/documentos'),
link('legislation', 'Legislação', '/legislacao'),
link(
'services',
'Serviços ao investidor',
@@ -6,7 +6,11 @@ import {
type TerritoryOption,
} from '@/components/investment-territory';
import { businessModalities } from './business-types';
import { ClassificationSummary, classificationStates, type PublicClassification, type ClassificationOptions } from '@/components/opportunity-classification';
import {
ClassificationSummary,
type PublicClassification,
type ClassificationOptions,
} from '@/components/opportunity-classification';
type PublicBusiness = {
multidimensional?: PublicClassification[];
@@ -57,7 +61,22 @@ export default function BusinessMarketplace({
classificationOptions,
authorities = [],
}: Props) {
const [classification, setClassification] = useState<Record<string, string>>(() => Object.fromEntries(['sector', 'association_type', 'association_target', 'association_purpose', 'association_state', 'chain_id', 'authority_id', 'subsector_id'].map((key) => [key, filters[key] ?? ''])));
const [classification, setClassification] = useState<
Record<string, string>
>(() =>
Object.fromEntries(
[
'sector',
'association_type',
'association_target',
'association_purpose',
'association_state',
'chain_id',
'authority_id',
'subsector_id',
].map((key) => [key, filters[key] ?? '']),
),
);
const [query, setQuery] = useState(filters.q ?? '');
const [modality, setModality] = useState(filters.modality ?? '');
const [territory, setTerritory] = useState<Record<string, string>>({
@@ -124,6 +143,35 @@ export default function BusinessMarketplace({
)}
</select>
</label>
{classificationOptions && (
<label className="grid gap-1">
<span>Sector</span>
<select
className={input}
value={classification.sector}
onChange={(event) =>
setClassification((current) => ({
...current,
sector: event.target.value,
subsector_id: '',
chain_id: '',
}))
}
>
<option value="">Todos</option>
{(classificationOptions.targets.sector ?? []).map(
(option) => (
<option
key={option.id}
value={String(option.id)}
>
{option.label}
</option>
),
)}
</select>
</label>
)}
<TerritoryFields
initial={territorySelection}
onChange={(path) =>
@@ -135,22 +183,109 @@ export default function BusinessMarketplace({
})
}
/>
{classificationOptions && <fieldset className="w-full rounded border p-3">
<legend>Classificação multidimensional — filtros combinados</legend>
<p>Critérios diferentes combinam-se por «e». Tipo, referência, finalidade e estado têm de corresponder à mesma relação pública. O setor principal mantém o seu significado.</p>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{([
['sector', 'Setor principal do anúncio', classificationOptions.targets.sector ?? []],
['association_type', 'Tipo de associação', Object.keys(classificationOptions.types).map((id) => ({ id, label: ({ corridor: 'Corredor', location: 'Localização', cluster: 'Cluster', project: 'Projeto âncora', chain: 'Cadeia de valor', park: 'Parque industrial', zone: 'Regime de zona', sector: 'Setor associado', activity: 'Subsector ou atividade' } as Record<string, string>)[id] ?? id }))],
['association_target', 'Referência da associação', classificationOptions.targets[classification.association_type] ?? []],
['association_purpose', 'Finalidade', Object.entries(classificationOptions.purposes).map(([id, label]) => ({ id, label }))],
['association_state', 'Estado da associação', Object.entries(classificationStates).filter(([id]) => !['archived', 'revoked'].includes(id)).map(([id, label]) => ({ id, label }))],
['chain_id', 'Cadeia de valor', classificationOptions.targets.chain ?? []],
['subsector_id', 'Subsector ou atividade', classificationOptions.targets.activity ?? []],
['authority_id', 'Entidade competente', authorities.map((a) => ({ id: a.id, label: a.label_pt_mz }))],
] as [string, string, { id: string | number; label: string }[]][]).map(([key, label, options]) => <label key={key} className="grid gap-1"><span>{label}</span><select className={input} value={classification[key]} onChange={(e) => setClassification((old) => ({ ...old, [key]: e.target.value, ...(key === 'association_type' ? { association_target: '' } : {}) }))}><option value="">Todos</option>{options.map((o) => <option key={o.id} value={String(o.id)}>{o.label}</option>)}</select></label>)}
</div>
</fieldset>}
{classificationOptions && (
<details className="w-full rounded border p-3">
<summary className="cursor-pointer font-semibold">
Mais filtros
</summary>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{(
[
[
'association_type',
'Tipo de associação',
Object.keys(
classificationOptions.types,
).map((id) => ({
id,
label:
(
{
corridor: 'Corredor',
location: 'Localização',
cluster: 'Cluster',
project:
'Projeto âncora',
chain: 'Cadeia de valor',
park: 'Parque industrial',
zone: 'Regime de zona',
sector: 'Setor associado',
activity:
'Subsector ou atividade',
} as Record<string, string>
)[id] ?? id,
})),
],
[
'association_target',
'Referência da associação',
classificationOptions.targets[
classification.association_type
] ?? [],
],
[
'association_purpose',
'Finalidade',
Object.entries(
classificationOptions.purposes,
).map(([id, label]) => ({ id, label })),
],
[
'chain_id',
'Cadeia de valor',
classificationOptions.targets.chain ??
[],
],
[
'subsector_id',
'Subsector ou atividade',
classificationOptions.targets
.activity ?? [],
],
[
'authority_id',
'Entidade competente',
authorities.map((a) => ({
id: a.id,
label: a.label_pt_mz,
})),
],
] as [
string,
string,
{ id: string | number; label: string }[],
][]
).map(([key, label, options]) => (
<label key={key} className="grid gap-1">
<span>{label}</span>
<select
className={input}
value={classification[key]}
onChange={(e) =>
setClassification((old) => ({
...old,
[key]: e.target.value,
...(key === 'association_type'
? { association_target: '' }
: {}),
}))
}
>
<option value="">Todos</option>
{options.map((o) => (
<option
key={o.id}
value={String(o.id)}
>
{o.label}
</option>
))}
</select>
</label>
))}
</div>
</details>
)}
<button className={button}>Pesquisar</button>
</form>
<p role="status">
@@ -192,7 +327,11 @@ export default function BusinessMarketplace({
{record.amount_max ?? '—'} {record.currency}
</p>
)}
{!!record.multidimensional?.length && <ClassificationSummary rows={record.multidimensional} />}
{!!record.multidimensional?.length && (
<ClassificationSummary
rows={record.multidimensional}
/>
)}
{record.objective && (
<p className="mt-3 line-clamp-3">
{record.objective}
File diff suppressed because it is too large Load Diff
+6 -3
View File
@@ -110,7 +110,10 @@ export default function Detail({
Preparar manifestação de interesse
</button>
) : (
<Link className={button} href={`/participar/entrar?return=${encodeURIComponent(page.url)}`}>
<Link
className={button}
href={`/participar/entrar?return=${encodeURIComponent(page.url)}`}
>
Entrar para preparar manifestação
</Link>
)}
@@ -182,9 +185,9 @@ export default function Detail({
['Investimento', money(r)],
['Maturidade', r.maturity_label],
[
'Catálogo de maturidade',
'Classificação da preparação',
r.maturity_catalogue_version === 'spec-v2'
? 'Oito etapas (V2)'
? 'Etapas de preparação'
: r.maturity_catalogue_version === 'legacy-v1'
? 'Histórico — seis níveis'
: 'Versão não registada',
+1
View File
@@ -23,6 +23,7 @@ export type Entity = {
geography?: StructureGeography | null;
};
export type References = {
preparationOptions?: { value: string; label: string; group: string }[];
classification?: import('@/components/opportunity-classification').ClassificationOptions;
authorities?: { id: string; label_pt_mz: string }[];
categories?: string[];
+18 -3
View File
@@ -3,7 +3,8 @@ import ParkDetailsEditor, {
emptyParkDetails,
type ParkDetails,
} from '@/components/investment-zone-operational-details';
import { Link, router, useForm } from '@inertiajs/react';
import { Link, router, useForm, usePage } from '@inertiajs/react';
import { catalogueReturnHref } from '@/lib/catalogue-context';
import InvestmentTerritory from '@/components/investment-territory';
import InvestmentMapPanel from '@/components/investment-map-panel';
import {
@@ -276,6 +277,7 @@ function Editor({
attachments,
opportunities,
}: Props) {
const pageUrl = usePage().url;
const [message, setMessage] = useState('');
const [busy, setBusy] = useState(false);
const [locationPath, setLocationPath] = useState<TerritoryOption[]>([]);
@@ -347,14 +349,27 @@ function Editor({
}
return (
<Frame title={z.name}>
<Link
className="underline"
href={catalogueReturnHref(
management ? '/management/investment/zones' : '/zonas',
pageUrl,
)}
>
Voltar à pesquisa
</Link>
<TerritorialSources sources={territorialSources} />
{!management && z.category === 'industrial_park' && (
<ParkDetailsPublic value={z.operational_details_public} />
)}
{!management && <PartnershipSourceLinks type="zone" id={z.id} />}
<p>
{z.code} · {z.category.toUpperCase()} · {z.validation_status} ·{' '}
{z.province} {z.district}
{z.code} ·{' '}
{z.category === 'industrial_park'
? 'Parque industrial'
: z.category.toUpperCase()}{' '}
{management && `· ${z.validation_status}`} · {z.province}{' '}
{z.district}
</p>
<p>
A ficha é informativa. A associação territorial não atribui
+110 -31
View File
@@ -1,6 +1,9 @@
import InvestmentZoneInstallation, { type ParkInstallationPlan } from '@/components/investment-zone-installation';
import InvestmentZoneInstallation, {
type ParkInstallationPlan,
} from '@/components/investment-zone-installation';
import { Link, router } from '@inertiajs/react';
import { useState } from 'react';
import { catalogueDetailHref } from '@/lib/catalogue-context';
import {
TerritoryFields,
type TerritoryOption,
@@ -41,7 +44,22 @@ type Zone = {
scope_type: string;
}[];
};
const parkLabels: Record<string,string> = { pending:'Por confirmar', general:'Geral', not_applicable:'Não aplicável', unknown:'Não informado', not_informed:'Não informada', announced:'Anunciado', planned:'Planeado', in_development:'Em desenvolvimento', partially_operational:'Parcialmente operacional', operational:'Operacional segundo o cadastro', suspended:'Suspenso', confirmed:'Confirmada segundo o cadastro', unavailable:'Indisponível', reported_unverified:'Declarada, não confirmada' };
const parkLabels: Record<string, string> = {
pending: 'Por confirmar',
general: 'Geral',
not_applicable: 'Não aplicável',
unknown: 'Não informado',
not_informed: 'Não informada',
announced: 'Anunciado',
planned: 'Planeado',
in_development: 'Em desenvolvimento',
partially_operational: 'Parcialmente operacional',
operational: 'Operacional segundo o cadastro',
suspended: 'Suspenso',
confirmed: 'Confirmada segundo o cadastro',
unavailable: 'Indisponível',
reported_unverified: 'Declarada, não confirmada',
};
export default function Zones({
installation,
detailsInstallation,
@@ -105,33 +123,57 @@ export default function Zones({
: 'ZEE, ZFI e parques industriais'
}
>
{management && installation && <InvestmentZoneInstallation initial={installation} />}
{management && detailsInstallation && <InvestmentZoneInstallation initial={detailsInstallation} endpoint="/management/investment/zones/operational-install" title="Complemento operacional L1 dos parques" summary="Uma coluna de detalhes, com dados privados cifrados e projeção pública separada. Sem importação ou publicação de fichas." />}
{management && installation && (
<InvestmentZoneInstallation initial={installation} />
)}
{management && detailsInstallation && (
<InvestmentZoneInstallation
initial={detailsInstallation}
endpoint="/management/investment/zones/operational-install"
title="Complemento operacional L1 dos parques"
summary="Uma coluna de detalhes, com dados privados cifrados e projeção pública separada. Sem importação ou publicação de fichas."
/>
)}
<p>
A informação territorial não atribui benefícios nem substitui
certificados ou decisões das entidades competentes.
</p>
<nav
aria-label="Dimensões de investimento"
className="flex flex-wrap gap-4 underline"
<details className="rounded border p-3">
<summary className="cursor-pointer font-semibold">
Catálogos relacionados
</summary>
<nav
aria-label="Dimensões de investimento"
className="flex flex-wrap gap-4 underline"
>
<Link href="/clusters">Por Cluster</Link>
<Link href="/corredores">Por Corredor</Link>
<Link href="/zonas?category=zee">Por ZEE</Link>
<Link href="/zonas?category=zfi">Por ZFI</Link>
<Link href="/zonas?category=industrial_park">
Parques industriais
</Link>
</nav>
</details>
<form
method="get"
onSubmit={(event) => {
event.preventDefault();
const form = event.currentTarget;
const url = new URL(form.action);
const params = new URLSearchParams();
for (const [name, value] of new FormData(form))
if (typeof value === 'string')
params.append(name, value);
url.search = params.toString();
router.get(
url.toString(),
{},
{ preserveState: true, preserveScroll: true },
);
}}
className={card + ' grid gap-4 md:grid-cols-3'}
>
<Link href="/clusters">Por Cluster</Link>
<Link href="/corredores">Por Corredor</Link>
<Link href="/zonas?category=zee">Por ZEE</Link>
<Link href="/zonas?category=zfi">Por ZFI</Link>
<Link href="/zonas?category=industrial_park">
Parques industriais
</Link>
</nav>
<form method="get" onSubmit={event => {
event.preventDefault();
const form = event.currentTarget;
const url = new URL(form.action);
const params = new URLSearchParams();
for (const [name, value] of new FormData(form)) if (typeof value === 'string') params.append(name, value);
url.search = params.toString();
router.get(url.toString(), {}, {preserveState: true, preserveScroll: true});
}} className={card + ' grid gap-4 md:grid-cols-3'}>
<Field label="Pesquisar por nome ou código">
<input
className={input}
@@ -251,8 +293,7 @@ export default function Zones({
)}
{!records.total && (
<p className={card}>
Sem registos disponíveis para estes filtros. As zonas
aguardam cadastro e validação documental.
Não foram encontrados resultados para esta pesquisa.
</p>
)}
{records.data.map((zone) => (
@@ -260,11 +301,31 @@ export default function Zones({
<h2 className="text-xl font-bold">
<Link
className="underline"
href={`${management ? '/management/investment/zones' : '/zonas'}/${zone.id}`}
href={catalogueDetailHref(
`${management ? '/management/investment/zones' : '/zonas'}/${zone.id}`,
exportParams.toString(),
)}
>
{zone.name}
</Link>
</h2>
<Link
className="underline"
href={catalogueDetailHref(
`${management ? '/management/investment/zones' : '/zonas'}/${zone.id}`,
exportParams.toString(),
)}
>
Consultar ficha
</Link>
{!management && (
<Link
className="ml-4 underline"
href={`/oportunidades?${new URLSearchParams({ [zone.category === 'zee' ? 'zee_id' : zone.category === 'zfi' ? 'zfi_id' : 'park_id']: zone.id })}`}
>
Ver oportunidades associadas
</Link>
)}
<p>
{zone.code} · {zone.category.toUpperCase()} ·{' '}
{[zone.district, zone.province]
@@ -273,19 +334,29 @@ export default function Zones({
</p>
{zone.legal_regime && (
<p>
Regime jurídico: {zone.category === 'industrial_park' ? (parkLabels[zone.legal_regime] ?? zone.legal_regime.toUpperCase()) : zone.legal_regime.toUpperCase()}
Regime jurídico:{' '}
{zone.category === 'industrial_park'
? (parkLabels[zone.legal_regime] ??
zone.legal_regime.toUpperCase())
: zone.legal_regime.toUpperCase()}
</p>
)}
{zoneExtensionsAvailable && zone.development_status && (
<p>
Desenvolvimento:{' '}
{zone.category === 'industrial_park' ? (parkLabels[zone.development_status] ?? 'Por confirmar') : zone.development_status.replaceAll('_', ' ')}
{zone.category === 'industrial_park'
? (parkLabels[zone.development_status] ??
'Por confirmar')
: zone.development_status.replaceAll('_', ' ')}
</p>
)}
{zoneExtensionsAvailable && zone.availability_status && (
<p>
Disponibilidade para instalação:{' '}
{zone.category === 'industrial_park' ? (parkLabels[zone.availability_status] ?? 'Não informada') : zone.availability_status.replaceAll('_', ' ')}
{zone.category === 'industrial_park'
? (parkLabels[zone.availability_status] ??
'Não informada')
: zone.availability_status.replaceAll('_', ' ')}
</p>
)}
{zone.area_value && (
@@ -334,7 +405,15 @@ export default function Zones({
))}
</p>
)}
{zone.category === 'industrial_park' && <p>{zone.resources?.length ? `${zone.resources.length} recursos descritos; consulte o âmbito e a fonte na ficha.` : 'Infraestruturas, serviços, acessos e capacidades: não informados.'} {!zone.activities?.length && 'Atividades: não informadas.'}</p>}
{zone.category === 'industrial_park' && (
<p>
{zone.resources?.length
? `${zone.resources.length} recursos descritos; consulte o âmbito e a fonte na ficha.`
: 'Infraestruturas, serviços, acessos e capacidades: não informados.'}{' '}
{!zone.activities?.length &&
'Atividades: não informadas.'}
</p>
)}
<p>{zone.description}</p>
<p>Validação: {zone.validation_status}</p>
{management && (
+146 -173
View File
@@ -481,32 +481,6 @@ export default function Services(p: Props) {
p.resources?.data.findIndex((resource) =>
formTypes.includes(resource.document_type),
) ?? -1;
const activeFilterNames: Record<string, string> = {
q: 'Texto',
topic: 'Assunto',
category: 'Categoria',
document_type: 'Tipo',
activity: 'Actividade',
stage: 'Etapa',
module: 'Módulo',
issuer: 'Emitente',
language: 'Idioma',
legal_status: 'Situação',
source_confirmation: 'Fonte',
territory_id: 'Território',
};
const activeFilters = Object.entries(filter.data).flatMap(
([key, value]) => {
const text = Array.isArray(value)
? value.join(', ')
: typeof value === 'string'
? value
: '';
return activeFilterNames[key] && text.trim()
? [`${activeFilterNames[key]}: ${text}`]
: [];
},
);
return (
<div className="min-h-screen bg-slate-50 text-slate-900">
<Head title={title} />
@@ -677,63 +651,80 @@ export default function Services(p: Props) {
}
/>
</label>
<label className="block min-w-0">
Tema
<select
className={input}
value={filter.data.topic}
onChange={(e) =>
filter.setData('topic', e.target.value)
}
>
<option value="">Todos</option>
{p.topics?.map((topic) => (
<option key={topic}>{topic}</option>
))}
</select>
</label>
<label className="block min-w-0">
Categoria
<select
className={input}
value={filter.data.category}
onChange={(e) =>
filter.setData(
'category',
e.target.value,
)
}
>
<option value="">Todas</option>
{p.categories?.map((category) => (
<option key={category} value={category}>
{documentTypeLabels[category] ??
category}
</option>
))}
</select>
</label>
<label className="block min-w-0">
Tipo documental
<select
className={input}
value={filter.data.document_type}
onChange={(e) =>
filter.setData(
'document_type',
e.target.value,
)
}
>
<option value="">Todos</option>
{p.documentTypes?.map((type) => (
<option key={type} value={type}>
{documentTypeLabels[type] ??
'Documento'}
</option>
))}
</select>
</label>
{!!(p.topics?.length || filter.data.topic) && (
<label className="block min-w-0">
Tema
<select
className={input}
value={filter.data.topic}
onChange={(e) =>
filter.setData(
'topic',
e.target.value,
)
}
>
<option value="">Todos</option>
{p.topics?.map((topic) => (
<option key={topic}>{topic}</option>
))}
</select>
</label>
)}
{!!(
p.categories?.length || filter.data.category
) && (
<label className="block min-w-0">
Categoria
<select
className={input}
value={filter.data.category}
onChange={(e) =>
filter.setData(
'category',
e.target.value,
)
}
>
<option value="">Todas</option>
{p.categories?.map((category) => (
<option
key={category}
value={category}
>
{documentTypeLabels[category] ??
category}
</option>
))}
</select>
</label>
)}
{!!(
p.documentTypes?.length ||
filter.data.document_type
) && (
<label className="block min-w-0">
Tipo documental
<select
className={input}
value={filter.data.document_type}
onChange={(e) =>
filter.setData(
'document_type',
e.target.value,
)
}
>
<option value="">Todos</option>
{p.documentTypes?.map((type) => (
<option key={type} value={type}>
{documentTypeLabels[type] ??
'Documento'}
</option>
))}
</select>
</label>
)}
{!!p.activities?.length && (
<fieldset className="min-w-0 rounded border p-3">
<legend className="px-1">
@@ -866,62 +857,78 @@ export default function Services(p: Props) {
</div>
</fieldset>
)}
<label className="block min-w-0">
Entidade emitente
<select
className={input}
value={filter.data.issuer}
onChange={(e) =>
filter.setData('issuer', e.target.value)
}
>
<option value="">Todas</option>
{p.issuers?.map((issuer) => (
<option key={issuer}>{issuer}</option>
))}
</select>
</label>
<label className="block min-w-0">
Idioma
<select
className={input}
value={filter.data.language}
onChange={(e) =>
filter.setData(
'language',
e.target.value,
)
}
>
<option value="">Todos</option>
{p.languages?.map((language) => (
<option key={language}>
{language}
</option>
))}
</select>
</label>
<label className="block min-w-0">
Situação jurídica indicada
<select
className={input}
value={filter.data.legal_status}
onChange={(e) =>
filter.setData(
'legal_status',
e.target.value,
)
}
>
<option value="">Todas</option>
{p.legalStatuses?.map((status) => (
<option key={status} value={status}>
{legalStatusLabels[status] ??
'Por confirmar'}
</option>
))}
</select>
</label>
{!!(p.issuers?.length || filter.data.issuer) && (
<label className="block min-w-0">
Entidade emitente
<select
className={input}
value={filter.data.issuer}
onChange={(e) =>
filter.setData(
'issuer',
e.target.value,
)
}
>
<option value="">Todas</option>
{p.issuers?.map((issuer) => (
<option key={issuer}>
{issuer}
</option>
))}
</select>
</label>
)}
{!!(
p.languages?.length || filter.data.language
) && (
<label className="block min-w-0">
Idioma
<select
className={input}
value={filter.data.language}
onChange={(e) =>
filter.setData(
'language',
e.target.value,
)
}
>
<option value="">Todos</option>
{p.languages?.map((language) => (
<option key={language}>
{language}
</option>
))}
</select>
</label>
)}
{!!(
p.legalStatuses?.length ||
filter.data.legal_status
) && (
<label className="block min-w-0">
Situação jurídica indicada
<select
className={input}
value={filter.data.legal_status}
onChange={(e) =>
filter.setData(
'legal_status',
e.target.value,
)
}
>
<option value="">Todas</option>
{p.legalStatuses?.map((status) => (
<option key={status} value={status}>
{legalStatusLabels[status] ??
'Por confirmar'}
</option>
))}
</select>
</label>
)}
<label className="block min-w-0">
Confirmação da fonte
<select
@@ -985,30 +992,6 @@ export default function Services(p: Props) {
Limpar filtros
</Link>
</form>
{activeFilters.length > 0 && (
<section
aria-label="Filtros activos"
className="rounded border bg-white p-3"
>
<h2 className="font-semibold">
Filtros activos
</h2>
<ul className="flex flex-wrap gap-2">
{activeFilters.map((item) => (
<li
key={item}
className="rounded-full bg-slate-100 px-3 py-1 text-sm"
>
{item}
</li>
))}
</ul>
</section>
)}
<p role="status" aria-live="polite">
{p.resources?.total ?? 0} documentos correspondem
aos filtros activos.
</p>
{!!p.topics?.length && (
<nav
aria-label="Navegar por assunto"
@@ -1307,16 +1290,6 @@ export default function Services(p: Props) {
</>
)}
</main>
<footer className="border-t px-5 py-8 text-center text-sm">
Investe Moçambique ·{' '}
<Link href="/apoio" className="underline">
Apoio ao Investidor
</Link>{' '}
·{' '}
<Link href="/documentos" className="underline">
Documentos e Formulários
</Link>
</footer>
</div>
);
}
+30 -3
View File
@@ -1,4 +1,5 @@
import { Link, useForm } from '@inertiajs/react';
import { catalogueDetailHref } from '@/lib/catalogue-context';
import { Management } from '../management/shared';
import type { Paginated } from '../management/shared';
import { Layout, Field, control, button, Pagination, kind } from './shared';
@@ -102,7 +103,14 @@ export default function Index({
<h2 className="text-xl font-semibold">
<Link
className="underline"
href={`${base}/${r.id}`}
href={catalogueDetailHref(
`${base}/${r.id}`,
new URLSearchParams(
Object.entries(filters).filter(
([, value]) => Boolean(value),
) as [string, string][],
).toString(),
)}
>
{r.title}
</Link>
@@ -126,9 +134,28 @@ export default function Index({
</span>
</p>
)}
<Link className="underline" href={`${base}/${r.id}`}>
Explorar relações e próximos passos
<Link
className="underline"
href={catalogueDetailHref(
`${base}/${r.id}`,
new URLSearchParams(
Object.entries(filters).filter(
([, value]) => Boolean(value),
) as [string, string][],
).toString(),
)}
>
Consultar ficha
</Link>
{!management &&
(r.corridor_id || r.cluster_id || r.project_id) && (
<Link
className="ml-4 underline"
href={`/oportunidades?${new URLSearchParams(r.corridor_id ? { corridor_id: r.corridor_id } : r.cluster_id ? { cluster_id: r.cluster_id } : { project_id: r.project_id! })}`}
>
Ver oportunidades associadas
</Link>
)}
</article>
))}
</div>
+1 -11
View File
@@ -1,4 +1,4 @@
import { Head, Link, usePage } from '@inertiajs/react';
import { Head, usePage } from '@inertiajs/react';
import type { ReactNode } from 'react';
export { button, control, Field, Pagination } from '../management/shared';
export type Dossier = {
@@ -47,16 +47,6 @@ export function Layout({
return (
<Container className="mx-auto w-full max-w-6xl min-w-0 space-y-6 p-4 break-words md:p-8">
<Head title={title} />
<nav
className="flex flex-wrap gap-5 text-sm underline"
aria-label="Investimento"
>
<Link href="/">InvestMoz</Link>
<Link href="/carteira?kind=corridor">Corredores</Link>
<Link href="/carteira?kind=cluster">Clusters</Link>
<Link href="/carteira?kind=project">Projectos âncora</Link>
<Link href="/investidor">O meu painel</Link>
</nav>
<h1 className="text-3xl font-semibold">{title}</h1>
{flash?.success && (
<p role="status" className="rounded border p-3">
+8
View File
@@ -1,5 +1,6 @@
import { Link, useForm, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import { catalogueReturnHref } from '@/lib/catalogue-context';
import InvestmentMapPanel from '@/components/investment-map-panel';
import StructureGeographyPanel, {
type StructureGeography,
@@ -76,8 +77,15 @@ function Editor({
const save = useForm({ origin_id: origin?.id ?? null });
const Frame = management ? Management : Layout;
const base = management ? '/management/portfolio' : '/carteira';
const pageUrl = usePage().url;
return (
<Frame title={record.title}>
<Link
className="underline"
href={catalogueReturnHref(base, pageUrl)}
>
Voltar à pesquisa
</Link>
<p>
{kind(record)} · {record.content.code}
</p>