This commit is contained in:
2026-11-02 20:31:15 +02:00
parent 8ddfa93f45
commit 1da273f1f3
131 changed files with 14802 additions and 526 deletions
@@ -0,0 +1,72 @@
import InteractiveInvestmentMap, {
type InvestmentMapArea,
type InvestmentMapFeature,
type InvestmentMapKind,
} from './interactive-investment-map';
import { TerritoryGeometryDetails } from './territory-geometry-preview';
import { useTerritoryGeometry } from './use-territory-geometry';
const noAreas: InvestmentMapArea[] = [];
export default function CatalogueInvestmentMap({
points,
areas = noAreas,
territoryId,
mapKind,
}: {
points: InvestmentMapFeature[] | null;
areas?: InvestmentMapArea[];
territoryId?: string;
mapKind?: InvestmentMapKind;
}) {
const { context, error } = useTerritoryGeometry(territoryId);
return (
<InteractiveInvestmentMap
points={points}
areas={areas}
administrativeAreas={context?.areas}
layerControls
mapKind={mapKind}
administrativeInfo={
territoryId ? (
<TerritoryGeometryDetails
context={context}
error={error}
showSources={false}
/>
) : undefined
}
notice={
territoryId ? (
<>
{error && (
<p role="alert">
{error} Os restantes dados do mapa continuam
disponíveis.
</p>
)}
{!context && !error && (
<p role="status">
A carregar limites administrativos…
</p>
)}
{context && !context.selected_geometry_available && (
<p role="note">
Sem limite administrativo acessível para o
território seleccionado.
{context.areas.length > 0
? ' Os limites de níveis superiores são apenas contexto e não representam a selecção.'
: ''}
</p>
)}
{context?.truncated && (
<p role="alert">
Cobertura administrativa incompleta: são
apresentados até 100 limites.
</p>
)}
</>
) : undefined
}
/>
);
}
@@ -94,9 +94,6 @@ export default function CountrySelect({
{error}
</p>
)}
{matches.length === 0 && (
<p role="status">Nenhum país corresponde à pesquisa.</p>
)}
</div>
);
}
@@ -0,0 +1,228 @@
import { useEffect, useState } from 'react';
import { portalRequest } from '@/lib/portal-api';
import type { Definition, Field } from '@/pages/desk/service-editor';
type Version = {
id: string;
version: number;
status: string;
author_id: number | null;
published_by: number | null;
published_at: string | null;
definition: Definition;
source: { identifier?: string; edition?: string; sha256?: string };
reason: string | null;
};
type History = { page: number; pages: number; total: number; data: Version[] };
const publishedDate = (value: string | null) => {
if (!value) return 'Não indicada';
const date = new Date(value);
return Number.isNaN(date.getTime())
? 'Não indicada'
: date.toLocaleString('pt-MZ');
};
export default function DeskServiceHistory({
code,
formatField,
}: {
code: string;
formatField: (field: Field) => string;
}) {
const [page, setPage] = useState(1);
const [attempt, setAttempt] = useState(0);
const key = JSON.stringify([code, page, attempt]);
const [result, setResult] = useState<{
key: string;
history: History | null;
} | null>(null);
useEffect(() => {
const controller = new AbortController();
void portalRequest<History>(
`/management/balcao/servicos/${encodeURIComponent(code)}/versoes?page=${page}`,
{ signal: controller.signal },
)
.then((history) => {
if (controller.signal.aborted) return;
if (
!history ||
!Array.isArray(history.data) ||
!Number.isSafeInteger(history.page) ||
!Number.isSafeInteger(history.pages) ||
!Number.isSafeInteger(history.total) ||
history.page < 1 ||
history.pages < history.page ||
history.total < 0 ||
history.data.some(
(row) =>
!row ||
typeof row.id !== 'string' ||
!Number.isSafeInteger(row.version) ||
!row.definition ||
typeof row.definition.title !== 'string' ||
!row.definition.fields ||
typeof row.definition.fields !== 'object' ||
Array.isArray(row.definition.fields) ||
Object.values(row.definition.fields).some(
(field) =>
!field ||
typeof field.label !== 'string' ||
typeof field.type !== 'string',
),
)
)
throw new Error('Invalid version history');
setResult({ key, history });
})
.catch(() => {
if (!controller.signal.aborted)
setResult({ key, history: null });
});
return () => controller.abort();
}, [code, page, attempt, key]);
const current = result?.key === key ? result : null;
return (
<section
className="space-y-4 rounded-xl border bg-white p-5 [overflow-wrap:anywhere]"
aria-label="Histórico dos formulários"
aria-busy={!current}
>
<h2 className="text-xl font-bold">Versões anteriores e autoria</h2>
<p>
Consulta das definições guardadas. Esta área não altera versões
nem apresenta respostas dos requerentes.
</p>
{!current ? (
<p role="status">A recuperar versões…</p>
) : !current.history ? (
<div role="alert">
<p>Não foi possível recuperar o histórico.</p>
<button
className="underline"
type="button"
onClick={() => setAttempt((value) => value + 1)}
>
Tentar novamente
</button>
</div>
) : (
<>
<p>
{current.history.total} versões · página{' '}
{current.history.page} de {current.history.pages}
</p>
{current.history.data.length === 0 && (
<p>
Ainda não existem versões guardadas para este
serviço.
</p>
)}
{current.history.data.map((version) => (
<details
key={version.id}
className="rounded border p-3"
>
<summary>
Versão {version.version} —{' '}
{version.definition.title} ·{' '}
{version.status === 'published'
? 'Publicada'
: 'Preparada'}
</summary>
<dl className="mt-3 space-y-2">
<div>
<dt className="font-semibold">
Autor / publicador (identificadores)
</dt>
<dd>
{version.author_id ?? 'Não indicado'} /{' '}
{version.published_by ?? 'Não indicado'}
</dd>
</div>
<div>
<dt className="font-semibold">
Publicação
</dt>
<dd>
{publishedDate(version.published_at)}
</dd>
</div>
<div>
<dt className="font-semibold">
Motivo registado
</dt>
<dd className="whitespace-pre-wrap">
{version.reason ||
'Não disponível nesta versão.'}
</dd>
</div>
<div>
<dt className="font-semibold">
Fonte da definição
</dt>
<dd>
{version.source?.identifier ||
'Não indicada'}
{version.source?.edition
? ` · ${version.source.edition}`
: ''}
</dd>
</div>
</dl>
<h3 className="mt-3 font-semibold">
Identificação e percurso
</h3>
<p>
{version.definition.theme} ·{' '}
{version.definition.profile} ·{' '}
{version.definition.entity} · etapa{' '}
{version.definition.stage}
</p>
<p>{version.definition.result}</p>
<h3 className="mt-3 font-semibold">
Perguntas e regras desta versão
</h3>
<dl className="space-y-2">
{Object.entries(version.definition.fields).map(
([id, field]) => (
<div key={id}>
<dt className="font-semibold">
{id}
</dt>
<dd className="whitespace-pre-wrap">
{formatField(field)}
</dd>
</div>
),
)}
</dl>
</details>
))}
<nav
className="flex gap-4"
aria-label="Páginas do histórico"
>
<button
className="underline disabled:opacity-50"
type="button"
disabled={current.history.page <= 1}
onClick={() => setPage(current.history!.page - 1)}
>
Anterior
</button>
<button
className="underline disabled:opacity-50"
type="button"
disabled={
current.history.page >= current.history.pages
}
onClick={() => setPage(current.history!.page + 1)}
>
Seguinte
</button>
</nav>
</>
)}
</section>
);
}
+1 -1
View File
@@ -485,7 +485,7 @@ export function DossierPrefill(props: Props) {
setReviewed(false);
props.onReview?.(view.context.revision, false);
setMessage(
'Valores selecionados aplicados ao formulário. Os outros valores e os snapshots anteriores foram preservados.',
'Dados seleccionados aplicados. Os restantes campos e as versões anteriores foram conservados.',
);
}}
>
@@ -1,5 +1,10 @@
import { useEffect, useRef, useState } from 'react';
import type { Map as LeafletMap, Marker } from 'leaflet';
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import type {
Map as LeafletMap,
Marker,
LayerGroup,
LayersControlEvent,
} from 'leaflet';
import type { GeoJsonObject } from 'geojson';
import 'leaflet/dist/leaflet.css';
@@ -29,24 +34,87 @@ export type InvestmentMapArea = {
url: string;
};
const noAreas: InvestmentMapArea[] = [];
export type InvestmentMapKind =
| 'investments'
| 'administrative'
| 'documented_locations'
| 'declared_parcel';
export default function InteractiveInvestmentMap({
points,
areas = noAreas,
contextOnly = false,
mapKind = contextOnly ? 'administrative' : 'investments',
administrativeAreas = noAreas,
layerControls = false,
administrativeInfo,
notice,
}: {
points: InvestmentMapFeature[] | null;
areas?: InvestmentMapArea[];
contextOnly?: boolean;
mapKind?: InvestmentMapKind;
administrativeAreas?: InvestmentMapArea[];
layerControls?: boolean;
administrativeInfo?: ReactNode;
notice?: ReactNode;
}) {
const title = {
investments: 'Mapa dos investimentos',
administrative: 'Contexto administrativo',
documented_locations: 'Mapa dos locais documentados',
declared_parcel: 'Perímetro declarado pelo Promotor',
}[mapKind];
const areaDescription = (area: InvestmentMapArea) =>
area.purpose === 'administrative_boundary'
? 'Limite administrativo da edição indicada; não representa um local de investimento'
: area.purpose === 'declared_parcel'
? 'Perímetro declarado pelo Promotor; não é limite administrativo nem comprova disponibilidade legal'
: mapKind === 'documented_locations'
? 'Área documentada na fonte; não confirma implantação de investimento'
: 'Polígono cadastrado; comparação com limite administrativo pendente';
const allAreas = useMemo(() => {
const unique = new Map<string, InvestmentMapArea>();
for (const area of [
...areas,
...administrativeAreas.map((area) => ({
...area,
purpose: 'administrative_boundary',
})),
]) {
const key = JSON.stringify([
area.geometry,
area.purpose,
area.title,
area.source_reference,
area.source_date,
]);
const previous = unique.get(key);
unique.set(key, {
...area,
selected_territory: Boolean(
previous?.selected_territory || area.selected_territory,
),
});
}
return [...unique.values()];
}, [areas, administrativeAreas]);
const element = useRef<HTMLDivElement>(null);
const map = useRef<LeafletMap | null>(null);
const markers = useRef(new Map<number, Marker>());
const pointLayer = useRef<LayerGroup | null>(null);
const visibility = useRef({
points: true,
investments: true,
administrative: true,
});
const [selected, setSelected] = useState<number | null>(null);
const [error, setError] = useState('');
useEffect(() => {
let cancelled = false;
let observer: ResizeObserver | undefined;
setError('');
setSelected(null);
void import('leaflet')
.then((L) => {
if (cancelled || !element.current) return;
@@ -75,8 +143,64 @@ export default function InteractiveInvestmentMap({
})
.addTo(instance);
L.control.scale({ imperial: false }).addTo(instance);
const groups = {
points: L.layerGroup(),
investments: L.layerGroup(),
administrative: L.layerGroup(),
};
pointLayer.current = groups.points;
for (const key of Object.keys(
groups,
) as (keyof typeof groups)[]) {
if (!layerControls || visibility.current[key])
groups[key].addTo(instance);
}
if (layerControls) {
const overlays: Record<string, LayerGroup> = {};
if (points === null || points.length)
overlays[
mapKind === 'investments'
? 'Oportunidades com coordenadas'
: 'Locais documentados com coordenadas'
] = groups.points;
if (
allAreas.some(
(area) =>
area.purpose !== 'administrative_boundary',
)
)
overlays[
mapKind === 'investments'
? 'Áreas de investimento cadastradas'
: 'Áreas documentadas'
] = groups.investments;
if (
allAreas.some(
(area) =>
area.purpose === 'administrative_boundary',
)
)
overlays['Limites administrativos'] =
groups.administrative;
L.control
.layers(undefined, overlays, { collapsed: false })
.addTo(instance);
instance.on('overlayadd overlayremove', (event) => {
const changed = event as LayersControlEvent;
for (const key of Object.keys(
groups,
) as (keyof typeof groups)[]) {
if (changed.layer === groups[key])
visibility.current[key] =
event.type === 'overlayadd';
}
});
}
const bounds: [number, number][] = [];
const hasSelectedBoundary = areas.some(
const selectedBounds: [number, number][] = [];
const opportunityBounds: [number, number][] = [];
const contextBounds: [number, number][] = [];
const hasSelectedBoundary = allAreas.some(
(area) => area.selected_territory,
);
const administrativeLevel: Record<string, number> = {
@@ -85,20 +209,27 @@ export default function InteractiveInvestmentMap({
admin_post: 3,
locality: 4,
};
const closestContextLevel = contextOnly
? Math.max(
0,
...areas.map(
(area) =>
administrativeLevel[
area.location_type ?? ''
] ?? 0,
),
)
: 0;
for (const area of areas) {
const closestContextLevel =
contextOnly || layerControls
? Math.max(
0,
...allAreas
.filter(
(area) =>
area.purpose ===
'administrative_boundary',
)
.map(
(area) =>
administrativeLevel[
area.location_type ?? ''
] ?? 0,
),
)
: 0;
for (const area of allAreas) {
const label = document.createElement('p');
label.textContent = `${area.title} · ${area.purpose === 'administrative_boundary' ? 'Limite administrativo da edição indicada; não representa um local de investimento' : 'Polígono cadastrado, limites oficiais por verificar'} · Fonte: ${area.source_reference ?? 'Não indicada'} · Data: ${area.source_date ?? 'Não documentada'}`;
label.textContent = `${area.title} · ${areaDescription(area)} · Fonte: ${area.source_reference ?? 'Não indicada'} · Data: ${area.source_date ?? 'Não documentada'}`;
const layer = L.geoJSON(
area.geometry,
area.purpose === 'administrative_boundary'
@@ -109,10 +240,21 @@ export default function InteractiveInvestmentMap({
fillOpacity: 0.06,
},
}
: {},
: layerControls
? {
style: {
color: '#b45309',
fillOpacity: 0.16,
},
}
: {},
)
.bindPopup(label)
.addTo(instance);
.addTo(
area.purpose === 'administrative_boundary'
? groups.administrative
: groups.investments,
);
const extent = layer.getBounds();
const focusBoundary = hasSelectedBoundary
? area.selected_territory
@@ -124,6 +266,19 @@ export default function InteractiveInvestmentMap({
[extent.getSouth(), extent.getWest()],
[extent.getNorth(), extent.getEast()],
);
if (extent.isValid()) {
const corners: [number, number][] = [
[extent.getSouth(), extent.getWest()],
[extent.getNorth(), extent.getEast()],
];
if (area.purpose !== 'administrative_boundary')
opportunityBounds.push(...corners);
else {
if (area.selected_territory)
selectedBounds.push(...corners);
if (focusBoundary) contextBounds.push(...corners);
}
}
}
for (const [index, point] of (points ?? []).entries()) {
const [longitude, latitude] = point.geometry.coordinates;
@@ -171,12 +326,20 @@ export default function InteractiveInvestmentMap({
})
.bindPopup(popup, { autoPan: false })
.on('click', () => setSelected(index))
.addTo(instance);
.addTo(groups.points);
markers.current.set(index, marker);
bounds.push([latitude, longitude]);
opportunityBounds.push([latitude, longitude]);
}
if (bounds.length)
instance.fitBounds(bounds, {
const focusBounds = layerControls
? selectedBounds.length
? selectedBounds
: opportunityBounds.length
? opportunityBounds
: contextBounds
: bounds;
if (focusBounds.length)
instance.fitBounds(focusBounds, {
padding: [40, 40],
maxZoom: 14,
animate: false,
@@ -196,29 +359,57 @@ export default function InteractiveInvestmentMap({
map.current?.remove();
map.current = null;
markers.current.clear();
pointLayer.current = null;
};
}, [points, areas]);
}, [points, allAreas, contextOnly, layerControls, mapKind]);
return (
<section
className="space-y-3 rounded-xl border bg-white p-4 text-slate-900"
aria-label={
contextOnly
? 'Mapa dos limites administrativos'
: 'Mapa interactivo dos investimentos'
}
aria-label={title}
>
<h2 className="text-xl font-bold">
{contextOnly
? 'Contexto administrativo'
: 'Mapa dos investimentos'}
</h2>
<h2 className="text-xl font-bold">{title}</h2>
<p>
Arraste para navegar; use +/− para ampliar. Pode seleccionar um
{contextOnly
? 'limite cadastrado para consultar a sua edição.'
: 'investimento na lista para o localizar.'}
Arraste para navegar; use +/− para ampliar.{' '}
{mapKind === 'declared_parcel'
? 'Esta pré-visualização representa a declaração do Promotor, não o limite administrativo.'
: mapKind === 'administrative'
? 'Seleccione um limite cadastrado para consultar a sua edição.'
: 'Seleccione um local na lista para o localizar.'}
</p>
{error && <p role="status">{error}</p>}
{notice}
{layerControls && (
<div
aria-label="Legenda das camadas"
className="flex flex-wrap gap-4 text-sm"
>
<span>
<span
aria-hidden="true"
className="mr-2 inline-block h-3 w-3 rounded-full bg-emerald-800"
/>
{mapKind === 'investments'
? 'Oportunidade com coordenadas confirmadas'
: 'Local documentado com coordenadas'}
</span>
<span>
<span
aria-hidden="true"
className="mr-2 inline-block h-3 w-4 border-2 border-amber-700 bg-amber-100"
/>
{mapKind === 'investments'
? 'Área de investimento cadastrada'
: 'Área documentada'}
</span>
<span>
<span
aria-hidden="true"
className="mr-2 inline-block h-3 w-4 border-2 border-dashed border-blue-600"
/>
Limite administrativo — não indica terreno disponível
</span>
</div>
)}
<div
ref={element}
className="relative z-0 h-[460px] w-full min-w-0 overflow-hidden rounded"
@@ -229,9 +420,11 @@ export default function InteractiveInvestmentMap({
<p role="status">A carregar localizações…</p>
) : (
<p role="status">
{contextOnly
? `${areas.length} limites administrativos disponíveis.`
: `${points.length} locais com coordenadas disponíveis.`}
{mapKind === 'declared_parcel'
? `${allAreas.length} perímetro declarado em pré-visualização.`
: mapKind === 'administrative'
? `${areas.length} limites administrativos disponíveis.`
: `${points.length} locais com coordenadas disponíveis.`}
</p>
)}
<ul className="grid gap-2 md:grid-cols-2">
@@ -251,6 +444,11 @@ export default function InteractiveInvestmentMap({
onClick={() => {
const marker = markers.current.get(index);
if (marker) {
visibility.current.points = true;
if (pointLayer.current)
map.current?.addLayer(
pointLayer.current,
);
map.current?.setView(
marker.getLatLng(),
14,
@@ -278,19 +476,42 @@ export default function InteractiveInvestmentMap({
</li>
))}
</ul>
{areas.map((area, index) => (
<p key={index}>
<a className="underline" href={area.url}>
{area.title}
</a>{' '}
·{' '}
{area.purpose === 'administrative_boundary'
? 'Limite administrativo da edição indicada; não representa um local de investimento'
: 'Polígono cadastrado; comparação com limite administrativo pendente'}{' '}
· Fonte: {area.source_reference ?? 'Não indicada'} · Data:{' '}
{area.source_date ?? 'Não documentada'}
</p>
))}
{layerControls && (
<details className="rounded border p-3">
<summary className="cursor-pointer font-semibold">
Fontes e contexto do mapa
</summary>
<div className="mt-3 space-y-2">
{administrativeInfo}
{allAreas.map((area, index) => (
<p key={index}>
{area.url.startsWith('/') &&
!area.url.startsWith('//') ? (
<a className="underline" href={area.url}>
{area.title}
</a>
) : (
area.title
)}{' '}
· {areaDescription(area)} · Fonte:{' '}
{area.source_reference ?? 'Não indicada'} ·
Edição: {area.source_date ?? 'Não indicada'}
</p>
))}
</div>
</details>
)}
{!layerControls &&
allAreas.map((area, index) => (
<p key={index}>
<a className="underline" href={area.url}>
{area.title}
</a>{' '}
· {areaDescription(area)} · Fonte:{' '}
{area.source_reference ?? 'Não indicada'} · Data:{' '}
{area.source_date ?? 'Não documentada'}
</p>
))}
</section>
);
}
@@ -36,8 +36,10 @@ export default function InvestmentMapCoverage({
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<caption className="text-left">
Registos recebidos para os filtros actuais, incluindo
camadas ocultas.
Registos da pesquisa de investimentos para os filtros
actuais, incluindo camadas ocultas. A cobertura dos
limites administrativos adicionais é apresentada em
«Fontes e contexto do mapa».
</caption>
<thead>
<tr>
@@ -1,8 +1,8 @@
import SearchState from '@/components/search-state';
import { useEffect, useState } from 'react';
import TerritoryGeometryPreview from './territory-geometry-preview';
import TerritorialMap from './catalogue-investment-map';
import InvestmentMapCoverage from './investment-map-coverage';
import InteractiveInvestmentMap, {
import {
type InvestmentMapFeature,
type InvestmentMapArea,
} from './interactive-investment-map';
@@ -23,9 +23,9 @@ export default function InvestmentMapPanel({
const [retry, setRetry] = useState(0);
const [areas, setAreas] = useState<InvestmentMapArea[]>([]);
const [truncated, setTruncated] = useState(false);
const [showPoints, setShowPoints] = useState(true);
const [showAreas, setShowAreas] = useState(true);
const [matched, setMatched] = useState(0);
const [responseKey, setResponseKey] = useState('');
const current = responseKey === key;
useEffect(() => {
const controller = new AbortController();
const params = new URLSearchParams(JSON.parse(key));
@@ -46,6 +46,7 @@ export default function InvestmentMapPanel({
.then((data) => {
if (controller.signal.aborted) return;
setPoints(data.features);
setResponseKey(key);
setAreas(data.areas ?? []);
setMissing(data.unlocated ?? []);
setTruncated(Boolean(data.truncated));
@@ -59,8 +60,10 @@ export default function InvestmentMapPanel({
);
})
.catch(() => {
if (!controller.signal.aborted)
if (!controller.signal.aborted) {
setResponseKey(key);
setError('Não foi possível concluir a pesquisa.');
}
});
return () => controller.abort();
}, [key, retry]);
@@ -69,53 +72,14 @@ export default function InvestmentMapPanel({
<SearchState
scope="Registos consultados pelo mapa"
countLabel="investimentos, incluindo os que não têm coordenadas"
loading={points === null && !error}
error={error}
total={matched}
loading={!current || (points === null && !error)}
error={current ? error : ''}
total={current ? matched : 0}
retry={() => setRetry((value) => value + 1)}
/>
<fieldset className="flex flex-wrap gap-4 rounded border p-3">
<legend className="font-semibold">
Camadas desta consulta
</legend>
<label>
<input
type="checkbox"
checked={showPoints}
onChange={(event) =>
setShowPoints(event.target.checked)
}
/>{' '}
Investimentos com ponto
</label>
<label>
<input
type="checkbox"
checked={showAreas}
onChange={(event) => setShowAreas(event.target.checked)}
/>{' '}
Áreas e limites
</label>
</fieldset>
{!showPoints && !showAreas && (
<p role="status">
Camadas ocultas. Active uma camada para voltar a consultar
os registos no mapa.
</p>
)}
<InteractiveInvestmentMap
points={points === null ? null : showPoints ? points : []}
areas={showAreas ? areas : []}
/>
{points !== null && (
<InvestmentMapCoverage
points={points}
areas={areas}
unlocated={missing.length}
truncated={truncated}
/>
)}
<TerritoryGeometryPreview
<TerritorialMap
points={current ? (error ? [] : points) : null}
areas={current ? areas : []}
territoryId={
territoryId ||
String(
@@ -123,12 +87,20 @@ export default function InvestmentMapPanel({
filters.admin_post_id ||
filters.district_id ||
filters.province_id ||
filters.geo_location_id ||
'',
)
) ||
undefined
}
/>
{missing.length > 0 && (
{current && points !== null && (
<InvestmentMapCoverage
points={points}
areas={areas}
unlocated={missing.length}
truncated={truncated}
/>
)}
{current && missing.length > 0 && (
<div>
<p>
{missing.length} investimentos sem ponto público
@@ -0,0 +1,429 @@
import { useForm } from '@inertiajs/react';
import { modalityLabels } from '@/components/opportunity-search-filters';
import { button, card, input } from '@/pages/investment/shared';
export type AlertPreferences = {
version: number;
enabled: boolean;
frequency: string;
channel: string;
next_run_at: string | null;
criteria_available?: boolean;
sources?: string[];
criteria: {
sector?: string;
province_id?: string;
category?: string;
tender_regime?: string;
funding_certainty?: string;
funding_state?: string;
};
};
export type AlertOptions = {
frequencies: Record<string, string>;
sectors: { slug: string; name: string }[];
provinces: { id: string; name: string }[];
categories: string[];
tendersAvailable?: boolean;
fundingAvailable?: boolean;
tenderRegimes?: Record<string, string>;
tenderActs?: Record<string, string>;
};
export default function OpportunityAlertPreferences({
preferences,
options,
}: {
preferences: AlertPreferences;
options: AlertOptions;
}) {
const form = useForm({
version: preferences.version,
enabled: true,
frequency: preferences.frequency,
channel: 'in_app',
sources: preferences.sources ?? ['opportunities'],
criteria: {
sector: preferences.criteria.sector ?? '',
province_id: preferences.criteria.province_id ?? '',
category: preferences.criteria.category ?? '',
tender_regime: preferences.criteria.tender_regime ?? '',
funding_certainty:
preferences.criteria.funding_certainty ?? 'documented',
funding_state: preferences.criteria.funding_state ?? '',
},
consent: false,
});
const send = (enabled: boolean) => {
form.transform((data) => ({
...data,
enabled,
consent: enabled && data.consent,
}));
form.put('/investidor/alert-preferences', { preserveScroll: true });
};
return (
<section
className={card + ' space-y-3'}
aria-label="Preferências de alertas"
>
<h2 className="text-xl font-bold">
Novidades dos catálogos públicos
</h2>
<p role="status">
{preferences.enabled
? 'Acompanhamento activo.'
: 'Acompanhamento desactivado.'}
</p>
{preferences.enabled &&
preferences.criteria_available === false && (
<p role="alert">
Uma selecção anterior deixou de estar disponível no
catálogo. O acompanhamento das selecções indisponíveis
fica suspenso; os restantes catálogos seleccionados
continuam a ser verificados. Pode escolher outra opção
ou cancelar os alertas a qualquer momento.
</p>
)}
<p>
Escolha os catálogos, critérios e frequência. As novas
disponibilizações compatíveis aparecem nesta área. Não são
enviados emails ou SMS. O acompanhamento de concursos considera
anúncios e actos publicados no catálogo do portal. Fundos e
apoios consideram novas versões do catálogo do portal; não há
recolha automática de fontes externas.
</p>
<p>
Ao activar, reactivar ou alterar os critérios ou catálogos, os
registos já disponíveis estabelecem o ponto de partida e não
geram alertas retroactivos. Uma oportunidade ou versão de acto
não gera alertas repetidos.
</p>
<form
className="space-y-3"
onSubmit={(event) => {
event.preventDefault();
send(true);
}}
>
<fieldset disabled={form.processing} className="space-y-3">
<legend className="font-semibold">
O que pretende acompanhar
</legend>
<fieldset className="space-y-2">
<legend className="font-semibold">Catálogos</legend>
{(['opportunities', 'tenders', 'funding'] as const).map(
(source) => (
<label
key={source}
className="flex items-start gap-2"
>
<input
name={`source-${source}`}
type="checkbox"
checked={form.data.sources.includes(
source,
)}
disabled={
((source === 'tenders' &&
!options.tendersAvailable) ||
(source === 'funding' &&
!options.fundingAvailable)) &&
!form.data.sources.includes(source)
}
onChange={(event) => {
form.setData(
'sources',
event.target.checked
? [
...form.data.sources,
source,
]
: form.data.sources.filter(
(value) =>
value !== source,
),
);
form.setData('consent', false);
}}
/>
{source === 'opportunities'
? 'Oportunidades de investimento'
: source === 'tenders'
? 'Concursos e actos publicados'
: 'Fundos, programas e incentivos publicados'}
</label>
),
)}
{!options.tendersAvailable && (
<p className="text-sm">
O catálogo de concursos não está disponível
neste momento.
</p>
)}
{!options.fundingAvailable && (
<p className="text-sm">
O catálogo de fundos não está disponível neste
momento.
</p>
)}
</fieldset>
<label className="block">
Sector
<select
className={input}
value={form.data.criteria.sector}
onChange={(event) =>
form.setData('criteria', {
...form.data.criteria,
sector: event.target.value,
})
}
>
<option value="">Todos os sectores</option>
{form.data.criteria.sector &&
!options.sectors.some(
(sector) =>
sector.slug ===
form.data.criteria.sector,
) && (
<option value={form.data.criteria.sector}>
Sector anterior indisponível
</option>
)}
{options.sectors.map((sector) => (
<option key={sector.slug} value={sector.slug}>
{sector.name}
</option>
))}
</select>
</label>
<label className="block">
Província
<select
className={input}
value={form.data.criteria.province_id}
onChange={(event) =>
form.setData('criteria', {
...form.data.criteria,
province_id: event.target.value,
})
}
>
<option value="">Todo o território</option>
{form.data.criteria.province_id &&
!options.provinces.some(
(province) =>
province.id ===
form.data.criteria.province_id,
) && (
<option
value={form.data.criteria.province_id}
>
Província anterior indisponível
</option>
)}
{options.provinces.map((province) => (
<option key={province.id} value={province.id}>
{province.name}
</option>
))}
</select>
</label>
<p className="text-sm">
A selecção provincial usa o mesmo âmbito territorial do
catálogo, incluindo locais dos níveis inferiores.
</p>
{form.data.sources.includes('opportunities') && (
<label className="block">
Modalidade
<select
className={input}
value={form.data.criteria.category}
onChange={(event) =>
form.setData('criteria', {
...form.data.criteria,
category: event.target.value,
})
}
>
<option value="">Todas as modalidades</option>
{form.data.criteria.category &&
!options.categories.includes(
form.data.criteria.category,
) && (
<option
value={form.data.criteria.category}
>
Modalidade anterior indisponível
</option>
)}
{options.categories.map((category) => (
<option key={category} value={category}>
{modalityLabels[category] ?? category}
</option>
))}
</select>
</label>
)}
{form.data.sources.includes('tenders') && (
<label className="block">
Regime do concurso
<select
className={input}
value={form.data.criteria.tender_regime}
onChange={(event) =>
form.setData('criteria', {
...form.data.criteria,
tender_regime: event.target.value,
})
}
>
<option value="">Todos os regimes</option>
{form.data.criteria.tender_regime &&
!Object.hasOwn(
options.tenderRegimes ?? {},
form.data.criteria.tender_regime,
) && (
<option
value={
form.data.criteria.tender_regime
}
>
Regime anterior indisponível
</option>
)}
{Object.entries(
options.tenderRegimes ?? {},
).map(([key, label]) => (
<option key={key} value={key}>
{label}
</option>
))}
</select>
</label>
)}
{form.data.sources.includes('funding') && (
<fieldset className="space-y-3">
<legend>Condições para fundos e apoios</legend>
<label className="block">
Âmbitos por confirmar
<select
className={input}
value={form.data.criteria.funding_certainty}
onChange={(event) =>
form.setData('criteria', {
...form.data.criteria,
funding_certainty:
event.target.value,
})
}
>
<option value="documented">
Só âmbito documentado para o sector e
província escolhidos
</option>
<option value="include_unknown">
Incluir e assinalar informação por
confirmar
</option>
</select>
</label>
<label className="block">
Estado de uma janela
<select
className={input}
value={form.data.criteria.funding_state}
onChange={(event) =>
form.setData('criteria', {
...form.data.criteria,
funding_state: event.target.value,
})
}
>
<option value="">Qualquer estado</option>
<option value="open">
Aberta segundo as datas documentadas
</option>
<option value="upcoming">
Abertura futura
</option>
<option value="closed">Encerrada</option>
<option value="unknown">
Por confirmar
</option>
</select>
</label>
<p className="text-sm">
Sector e província referem-se ao programa. Uma
chamada pode ter cobertura mais restrita. O
aviso acompanha novas versões publicadas; uma
mudança de data sem nova publicação não gera
outro aviso.
</p>
</fieldset>
)}
<label className="block">
Frequência
<select
className={input}
value={form.data.frequency}
onChange={(event) =>
form.setData('frequency', event.target.value)
}
>
{Object.entries(options.frequencies).map(
([key, label]) => (
<option key={key} value={key}>
{label}
</option>
),
)}
</select>
</label>
<p>
Canal: notificações no portal. «Na próxima verificação»
depende da execução periódica do acompanhamento.
</p>
<label className="flex items-start gap-2">
<input
type="checkbox"
name="alert-consent"
checked={form.data.consent}
onChange={(event) =>
form.setData('consent', event.target.checked)
}
/>
Quero receber estes alertas no portal e confirmo os
critérios escolhidos.
</label>
{Object.entries(form.errors).map(([key, error]) => (
<p key={key} role="alert">
{error}
</p>
))}
<div className="flex flex-wrap gap-3">
<button type="submit" className={button}>
{preferences.enabled
? 'Guardar preferências'
: 'Activar alertas'}
</button>
{preferences.enabled && (
<button
type="button"
className="underline"
onClick={() => send(false)}
>
Cancelar estes alertas
</button>
)}
</div>
</fieldset>
</form>
<p className="text-sm">
O cancelamento conserva as notificações anteriores e não altera
o acompanhamento das manifestações já apresentadas.
</p>
</section>
);
}
@@ -90,10 +90,9 @@ export default function OpportunityContactForm({
<details className="rounded border p-3">
<summary>Cadastrar contacto do promotor</summary>
<p>
Reutiliza o cadastro de contactos. Indique dados reais e
autorizados do promotor desta oportunidade. O operador do portal
não substitui o promotor real. A gravação não publica o
contacto.
Indique os dados de contacto autorizados pelo promotor desta
oportunidade. O contacto fica guardado para reutilização e não é
publicado.
</p>
<fieldset disabled={disabled || busy} className="space-y-3">
<legend>Dados do contacto</legend>
@@ -142,7 +141,7 @@ export default function OpportunityContactForm({
{organization && investors.length > 1 && (
<div>
<label htmlFor="contact-investor_id">
Cadastro mestre do promotor
Promotor associado ao contacto
</label>
<select
id="contact-investor_id"
@@ -204,6 +204,7 @@ export default function OpportunityParcelGeometry({
<InteractiveInvestmentMap
points={[]}
contextOnly
mapKind="declared_parcel"
areas={[
{
purpose: 'declared_parcel',
@@ -0,0 +1,60 @@
import { Link } from '@inertiajs/react';
export type RelatedOpportunitySearch = {
query: string;
subject: string;
href: string;
items: {
id: number;
slug: string;
title: string;
summary?: string | null;
}[];
};
export default function OpportunityRelatedResults({
related,
loading,
error,
total,
}: {
related: RelatedOpportunitySearch | null;
loading: boolean;
error: string;
total: number;
}) {
if (loading || error || total !== 0 || !related?.items.length) return null;
const context = new URL(related.href, 'https://portal.invalid');
context.searchParams.set('q', related.query);
return (
<section
className="space-y-3 rounded-xl border border-slate-300 bg-white p-5"
aria-label="Fichas relacionadas, sem correspondência completa"
>
<h3 className="text-xl font-bold">
Fichas relacionadas com «{related.subject}»
</h3>
<p>
Não encontrámos fichas que correspondam a todos os termos de «
{related.query}». As fichas abaixo são de actividades
relacionadas e podem corresponder a outras etapas da cadeia.
</p>
<ul className="space-y-3">
{related.items.map((item) => (
<li key={item.id}>
<Link
className="font-semibold underline"
href={`/oportunidades/${encodeURIComponent(item.slug)}${context.search}`}
>
{item.title}
</Link>
{item.summary && <p>{item.summary}</p>}
</li>
))}
</ul>
<Link className="underline" href={related.href}>
Ver a pesquisa relacionada «{related.subject}»
</Link>
</section>
);
}
@@ -4,7 +4,6 @@ import { Link, router, usePage } from '@inertiajs/react';
import {
ChevronDown,
ArrowUpRight,
LayoutDashboard,
LogOut,
Menu,
UserRound,
@@ -13,11 +12,8 @@ import {
import { Fragment, useEffect, useId, useRef, useState } from 'react';
import { useIsMobile } from '@/hooks/use-mobile';
import { useNavigationContext } from '@/components/navigation-context';
import { tempoSocialLinks, useTempoUi } from '@/components/tempo-brand';
import {
TempoLanguageSelector,
TempoWeather,
} from '@/components/tempo-header-tools';
import { useTempoUi } from '@/components/tempo-brand';
import { TempoLanguageSelector } from '@/components/tempo-header-tools';
import {
DropdownMenu,
DropdownMenuContent,
@@ -51,6 +47,7 @@ export function PortalGroupedMenu() {
businessReviewUrl?: string | null;
educationEnabled?: boolean;
procurementEnabled?: boolean;
fundingEnabled?: boolean;
aiEnabled?: boolean;
legacyContentEnabled?: boolean;
profileAccess?: ProfileAccess | null;
@@ -61,7 +58,7 @@ export function PortalGroupedMenu() {
opportunities?: { index: string; create?: string | null };
};
}>();
const { t, language, requestCount } = useTempoUi();
const { t, language } = useTempoUi();
const mobile = useIsMobile();
const navigation = useNavigationContext();
const groups = portalNavigation({
@@ -74,6 +71,7 @@ export function PortalGroupedMenu() {
businessReviewUrl: props.businessReviewUrl,
education: props.educationEnabled,
procurement: props.procurementEnabled,
funding: props.fundingEnabled,
ai: props.aiEnabled,
legacyContent: props.legacyContentEnabled,
opportunityManagement: props.opportunityManagement,
@@ -137,7 +135,6 @@ export function PortalGroupedMenu() {
group.id,
),
);
const panelLabel = `${t('O meu painel')} — ${requestCount} ${t(requestCount === 1 ? 'pedido recebido' : 'pedidos recebidos')}`;
const institutionalCurrent = url.split('?')[0] === '/contacto';
return (
<header
@@ -307,36 +304,6 @@ export function PortalGroupedMenu() {
</DropdownMenuItem>
),
)}
<DropdownMenuSeparator />
<DropdownMenuLabel className="text-xs text-slate-500">
Revista Tempo
</DropdownMenuLabel>
{tempoSocialLinks.map(
({ name, href, icon: Icon }) => (
<DropdownMenuItem
key={name}
asChild
className="tempo-menu-item"
>
<a
href={href}
target="_blank"
rel="noopener noreferrer"
aria-label={`Revista Tempo — ${name}`}
>
<Icon
size={16}
aria-hidden="true"
/>
{name}
<ArrowUpRight
size={12}
aria-hidden="true"
/>
</a>
</DropdownMenuItem>
),
)}
</DropdownMenuContent>
</DropdownMenu>
</li>
@@ -345,31 +312,11 @@ export function PortalGroupedMenu() {
<div id={toolsId} className="tempo-header-extras">
<div className="tempo-header-utilities">
<div className="flex items-center gap-1">
<TempoWeather />
<TempoLanguageSelector />
</div>
</div>
</div>
<div className="tempo-header-actions">
<Link
href="/investidor/manifestacoes"
className="tempo-panel-summary"
aria-label={panelLabel}
title={panelLabel}
>
<LayoutDashboard size={19} aria-hidden="true" />
<span className="tempo-panel-count" aria-hidden="true">
{requestCount}
</span>
</Link>
<span
className="sr-only"
role="status"
aria-live="polite"
aria-atomic="true"
>
{panelLabel}
</span>
{props.auth?.user ? (
<DropdownMenu modal={false}>
<DropdownMenuTrigger className="tempo-login-button">
+24 -5
View File
@@ -1,7 +1,6 @@
import { Link } from '@inertiajs/react';
import { Link, router } from '@inertiajs/react';
import { ArrowRight, Search } from 'lucide-react';
import { useEffect, useState } from 'react';
import type { FormEvent } from 'react';
import type { HomeResponse } from '@/lib/portal-api';
const slides = [
@@ -127,7 +126,6 @@ function HeroAnimatedCopy({
type PortalHeroProps = {
query: string;
setQuery: (value: string) => void;
onSearch: (event: FormEvent<HTMLFormElement>) => void;
stats?: HomeResponse['data']['stats'];
};
@@ -135,7 +133,6 @@ type PortalHeroProps = {
export default function PortalHero({
query,
setQuery,
onSearch,
stats,
}: PortalHeroProps) {
const [currentSlide, setCurrentSlide] = useState(0);
@@ -229,7 +226,20 @@ export default function PortalHero({
</p>
<form
onSubmit={onSearch}
action="/oportunidades"
method="get"
onSubmit={(event) => {
event.preventDefault();
const value = new FormData(event.currentTarget).get(
'q',
);
router.get('/oportunidades', {
q:
typeof value === 'string'
? value.trim()
: query.trim(),
});
}}
role="search"
aria-label="Pesquisar oportunidades"
className="mt-7 w-full max-w-4xl"
@@ -245,6 +255,8 @@ export default function PortalHero({
id="portal-opportunity-search"
type="search"
name="q"
maxLength={120}
aria-describedby="portal-opportunity-search-help"
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder="Ex.: agronegócio, Nampula, energia..."
@@ -258,6 +270,13 @@ export default function PortalHero({
Pesquisar
</button>
</div>
<p
id="portal-opportunity-search-help"
className="mt-2 text-left text-sm text-white/90"
>
Combine palavras-chave, sector e localização. Ex.:
plantio de algodão ou agronegócio Nampula.
</p>
</form>
<div className="mt-4 flex flex-wrap items-center justify-center gap-2">
@@ -0,0 +1,239 @@
import { useEffect, useState } from 'react';
import { Link } from '@inertiajs/react';
import { portalRequest } from '@/lib/portal-api';
type Match = {
id: string;
slug: string;
title: string;
published_at?: string | null;
};
function publicationDate(value?: string | null): string | null {
if (typeof value !== 'string' || !value.trim()) return null;
const date = new Date(value);
return Number.isNaN(date.getTime())
? null
: date.toLocaleDateString('pt-MZ');
}
type Classification = {
target_type: string;
target_id: string;
label: string;
purpose?: string;
purpose_label?: string;
source_reference?: string | null;
};
const classificationKey = (row: Classification) =>
`${row.target_type}:${row.target_id}:${row.purpose ?? ''}`;
type Props = {
currentId: string;
catalogueUrl: string;
criteria: string[];
classifications?: Classification[];
};
export default function SimilarBusinesses({
currentId,
catalogueUrl,
criteria,
classifications = [],
}: Props) {
const [attempt, setAttempt] = useState(0);
const [selection, setSelection] = useState({
recordId: currentId,
value: '',
});
const selected =
selection.recordId === currentId
? classifications.find(
(row) => classificationKey(row) === selection.value,
)
: undefined;
const query = new URL(catalogueUrl, 'https://portal.invalid');
if (selected) {
query.searchParams.set('association_type', selected.target_type);
query.searchParams.set('association_target', selected.target_id);
if (selected.purpose)
query.searchParams.set('association_purpose', selected.purpose);
}
const effectiveCatalogueUrl = query.pathname + query.search;
const key = JSON.stringify([currentId, effectiveCatalogueUrl, attempt]);
const [result, setResult] = useState<{
key: string;
rows: Match[];
error: boolean;
} | null>(null);
useEffect(() => {
const controller = new AbortController();
const params = new URL(effectiveCatalogueUrl, 'https://portal.invalid')
.searchParams;
params.set('per_page', '7');
params.set('page', '1');
void portalRequest<{ data: Match[] }>(
`/api/v1/business-opportunities?${params}`,
{ signal: controller.signal },
)
.then((response) => {
if (controller.signal.aborted) return;
if (!Array.isArray(response.data))
throw new Error('Invalid catalogue response');
const seen = new Set([currentId]);
if (
response.data.some(
(row) =>
!row ||
typeof row.id !== 'string' ||
!row.id.trim() ||
typeof row.slug !== 'string' ||
!row.slug.trim() ||
typeof row.title !== 'string' ||
!row.title.trim(),
)
) {
throw new Error('Invalid catalogue record');
}
const rows = response.data
.filter((row) => {
if (
!row ||
typeof row.id !== 'string' ||
typeof row.slug !== 'string' ||
typeof row.title !== 'string' ||
seen.has(row.id)
)
return false;
seen.add(row.id);
return true;
})
.slice(0, 6);
setResult({ key, rows, error: false });
})
.catch(() => {
if (!controller.signal.aborted)
setResult({ key, rows: [], error: true });
});
return () => controller.abort();
}, [currentId, effectiveCatalogueUrl, key]);
const current = result?.key === key ? result : null;
return (
<section
className="space-y-3 rounded-xl border bg-white p-5"
aria-label="Negócios com critérios semelhantes"
aria-busy={!current}
>
<h2 className="text-xl font-bold">Explorar negócios semelhantes</h2>
<p>
Critérios:{' '}
{[...criteria, ...(selected ? [selected.label] : [])].join(
' · ',
)}
. A consulta compara os dados publicados; não avalia
rentabilidade nem proximidade geográfica.
</p>
{!current ? (
<p role="status">A consultar o catálogo…</p>
) : current.error ? (
<div role="alert">
<p>Não foi possível consultar os negócios semelhantes.</p>
<button
type="button"
className="underline"
onClick={() => setAttempt((value) => value + 1)}
>
Tentar novamente
</button>
</div>
) : current.rows.length ? (
<ul className="space-y-2">
{current.rows.map((row) => (
<li key={row.id}>
<Link
className="underline"
href={`/negocios/${encodeURIComponent(row.slug)}${new URL(effectiveCatalogueUrl, 'https://portal.invalid').search}`}
>
{row.title}
</Link>
<p className="text-sm text-slate-600">
Fonte: catálogo público do InvesteMoz.{' '}
{publicationDate(row.published_at) ? (
<>
Publicado em{' '}
<time
dateTime={
row.published_at ?? undefined
}
>
{publicationDate(row.published_at)}
</time>
.
</>
) : (
'Data de publicação não indicada.'
)}
</p>
</li>
))}
</ul>
) : (
<p>
Não foram encontrados outros negócios públicos com estes
critérios. Isto não demonstra ausência de negócios no
mercado.
</p>
)}
{classifications.length > 0 && (
<label className="block space-y-1">
Comparar também por uma classificação divulgada
<select
className="block w-full rounded border p-2"
value={selected ? classificationKey(selected) : ''}
onChange={(event) =>
setSelection({
recordId: currentId,
value: event.target.value,
})
}
>
<option value="">Sem classificação adicional</option>
{classifications
.filter(
(row, index, all) =>
all.findIndex(
(other) =>
classificationKey(other) ===
classificationKey(row),
) === index,
)
.map((row) => (
<option
key={classificationKey(row)}
value={classificationKey(row)}
>
{row.label}
{row.purpose_label
? ` — ${row.purpose_label}`
: ''}
</option>
))}
</select>
</label>
)}
{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.
</p>
)}
<Link href={effectiveCatalogueUrl} className="underline">
Consultar o catálogo com estes critérios
</Link>
<p className="text-sm">
São apresentados até seis resultados. Pode ajustar os filtros no
catálogo. A data de publicação não indica a data dos dados de
origem.
</p>
</section>
);
}
@@ -209,6 +209,8 @@ export default function StructureGeographyPanel({
</p>
)}
<InteractiveInvestmentMap
mapKind="documented_locations"
layerControls
points={points}
areas={[
...items.flatMap((item) =>
+1 -1
View File
@@ -5,7 +5,7 @@ import { TempoSocialLinks, useTempoUi } from '@/components/tempo-brand';
const navigation = [
['/', 'Início'],
['/apoio', 'Contacto'],
['/apoio', 'Apoio ao investidor'],
];
export function TempoFooter() {
@@ -1,15 +1,10 @@
import { useEffect, useState } from 'react';
import InteractiveInvestmentMap, {
type InvestmentMapArea,
} from './interactive-investment-map';
import InteractiveInvestmentMap from './interactive-investment-map';
import {
useTerritoryGeometry,
type TerritoryGeometryContext,
} from './use-territory-geometry';
const noPoints: [] = [];
type Context = {
selected_geometry_available: boolean;
context_geometry_count: number;
areas: InvestmentMapArea[];
truncated: boolean;
};
export default function TerritoryGeometryPreview({
territoryId,
management = false,
@@ -21,44 +16,37 @@ export default function TerritoryGeometryPreview({
endpoint?: string;
label?: string;
}) {
const [context, setContext] = useState<Context | null>(null);
const [error, setError] = useState('');
useEffect(() => {
setContext(null);
setError('');
if (!territoryId) return;
const controller = new AbortController();
const endpoint =
suppliedEndpoint ??
const { context, error } = useTerritoryGeometry(
territoryId,
suppliedEndpoint ??
(management
? '/management/territory-geometries'
: '/api/v1/investment/territory-geometries');
void fetch(
`${endpoint}?${new URLSearchParams({ territory_id: territoryId })}`,
{
signal: controller.signal,
headers: { Accept: 'application/json' },
},
)
.then(async (response) => {
if (!response.ok)
throw new Error(
'Não foi possível consultar os limites administrativos.',
);
return response.json() as Promise<Context>;
})
.then((data) => {
if (!controller.signal.aborted) setContext(data);
})
.catch((e: unknown) => {
if (!controller.signal.aborted)
setError(
e instanceof Error ? e.message : 'Erro de ligação.',
);
});
return () => controller.abort();
}, [territoryId, management, suppliedEndpoint]);
: '/api/v1/investment/territory-geometries'),
);
if (!territoryId) return null;
return (
<TerritoryGeometryDetails
context={context}
error={error}
label={label}
renderMap
/>
);
}
export function TerritoryGeometryDetails({
context,
error,
label = 'Cobertura cartográfica da selecção',
renderMap = false,
showSources = true,
}: {
context: TerritoryGeometryContext | null;
error: string;
label?: string;
renderMap?: boolean;
showSources?: boolean;
}) {
return (
<section className="space-y-2 md:col-span-full" aria-label={label}>
<p>Território selecionado no cadastro.</p>
@@ -91,26 +79,28 @@ export default function TerritoryGeometryPreview({
incompleta.
</p>
)}
{context.areas.length > 0 && (
{renderMap && context.areas.length > 0 && (
<InteractiveInvestmentMap
points={noPoints}
areas={context.areas}
contextOnly
/>
)}
<ul>
{context.areas.map((area, index) => (
<li key={index}>
{area.title} ·{' '}
{area.selected_territory
? 'Território seleccionado'
: 'Contexto de nível superior'}{' '}
· Fonte:{' '}
{area.source_reference ?? 'Não indicada'} ·
Edição: {area.source_date ?? 'Não indicada'}
</li>
))}
</ul>
{showSources && (
<ul>
{context.areas.map((area, index) => (
<li key={index}>
{area.title} ·{' '}
{area.selected_territory
? 'Território seleccionado'
: 'Contexto de nível superior'}{' '}
· Fonte:{' '}
{area.source_reference ?? 'Não indicada'} ·
Edição: {area.source_date ?? 'Não indicada'}
</li>
))}
</ul>
)}
</>
)}
</section>
@@ -0,0 +1,57 @@
import { useEffect, useState } from 'react';
import type { InvestmentMapArea } from './interactive-investment-map';
export type TerritoryGeometryContext = {
selected_geometry_available: boolean;
context_geometry_count: number;
areas: InvestmentMapArea[];
truncated: boolean;
};
export function useTerritoryGeometry(
territoryId?: string,
endpoint = '/api/v1/investment/territory-geometries',
) {
const key = JSON.stringify([territoryId, endpoint]);
const [result, setResult] = useState<{
key: string;
context: TerritoryGeometryContext | null;
error: string;
}>({ key, context: null, error: '' });
useEffect(() => {
const controller = new AbortController();
setResult({ key, context: null, error: '' });
if (!territoryId) return () => controller.abort();
void fetch(
`${endpoint}?${new URLSearchParams({ territory_id: territoryId })}`,
{
signal: controller.signal,
headers: { Accept: 'application/json' },
},
)
.then(async (response) => {
if (!response.ok)
throw new Error(
'Não foi possível consultar os limites administrativos.',
);
return response.json() as Promise<TerritoryGeometryContext>;
})
.then((context) => {
if (!controller.signal.aborted)
setResult({ key, context, error: '' });
})
.catch((error: unknown) => {
if (!controller.signal.aborted)
setResult({
key,
context: null,
error:
error instanceof Error
? error.message
: 'Erro de ligação.',
});
});
return () => controller.abort();
}, [key, territoryId, endpoint]);
return result.key === key ? result : { key, context: null, error: '' };
}
+18 -10
View File
@@ -29,8 +29,12 @@ export function useInterestDraft<T>(name: string, initial: T) {
setForm,
key: draft.key,
clear: () => {
sessionStorage.removeItem(storage);
sessionStorage.removeItem('investemoz-participation-identity');
try {
sessionStorage.removeItem(storage);
sessionStorage.removeItem('investemoz-participation-identity');
} catch {
/* Storage failure must not turn a confirmed submission into an error. */
}
},
authenticate: () => {
const identity = draft.form as {
@@ -38,14 +42,18 @@ export function useInterestDraft<T>(name: string, initial: T) {
fullName?: string;
email?: string;
};
sessionStorage.setItem(
'investemoz-participation-identity',
JSON.stringify({
name: identity.fullName ?? identity.name ?? '',
email: identity.email ?? '',
}),
);
sessionStorage.setItem(storage, JSON.stringify(draft));
try {
sessionStorage.setItem(
'investemoz-participation-identity',
JSON.stringify({
name: identity.fullName ?? identity.name ?? '',
email: identity.email ?? '',
}),
);
sessionStorage.setItem(storage, JSON.stringify(draft));
} catch {
/* Authentication remains available when browser persistence is blocked. */
}
window.location.assign(
'/participar/entrar?return=' +
encodeURIComponent(location.pathname + location.search),
+20 -1
View File
@@ -1,6 +1,25 @@
import { searchTerritoryHref } from './search-territory.ts';
/** Only a query string is carried; the return destination is always local. */
export function catalogueDetailHref(path: string, query: string): string {
export function catalogueDetailHref(
path: string,
query: string,
pageUrl?: string,
): string {
if (pageUrl) {
const page = new URL(
pageUrl,
'https://portal.invalid',
).searchParams.get('page');
if (
page &&
/^[1-9]\d*$/.test(page) &&
Number.isSafeInteger(Number(page))
) {
const params = new URLSearchParams(query);
params.set('page', page);
query = params.toString();
}
}
return query
? `${path}?catalogue_query=${encodeURIComponent(query)}`
: path;
+23
View File
@@ -0,0 +1,23 @@
type ConditionalField = { when?: { field: string; equals: string } };
export function deskFieldApplies(
key: string,
fields: Record<string, ConditionalField>,
payload: Record<string, unknown>,
ancestors: ReadonlySet<string> = new Set(),
): boolean {
const field = fields[key];
if (!field || ancestors.has(key)) return false;
if (!field.when) return true;
const value = payload[field.when.field];
if (!['string', 'number', 'boolean'].includes(typeof value)) return false;
const answer =
typeof value === 'boolean' ? (value ? '1' : '') : String(value);
if (answer !== field.when.equals) return false;
return deskFieldApplies(
field.when.field,
fields,
payload,
new Set([...ancestors, key]),
);
}
+14 -7
View File
@@ -3,12 +3,19 @@ import type {
PreparationDocument,
} from '@/components/private-investment-preparation';
function csrfToken(): string {
return decodeURIComponent(
document.cookie
.split('; ')
.find((c) => c.startsWith('XSRF-TOKEN='))
?.slice('XSRF-TOKEN='.length) ?? '',
);
try {
return decodeURIComponent(
document.cookie
.split(';')
.map((value) => value.trim())
.find((c) => c.startsWith('XSRF-TOKEN='))
?.slice('XSRF-TOKEN='.length) ?? '',
);
} catch {
throw new Error(
'A sessão não pôde ser validada. Actualize a página e tente novamente.',
);
}
}
export type ContextDocument = {
resource_id: number;
@@ -185,7 +192,7 @@ export async function contextApi<T>(
...(serializedBody === undefined ? {} : { body: serializedBody }),
});
const data = await response.json().catch(() => null);
if (!response.ok)
if (!response.ok || data === null)
throw new Error(
data?.message ||
`Não foi possível recuperar ou guardar o contexto (HTTP ${response.status}).`,
+32
View File
@@ -0,0 +1,32 @@
/** Browser persistence is optional; the current selection remains usable without it. */
const selectionKey = 'investment-opportunity-selection';
export function readOpportunitySelection(): number[] {
try {
const value: unknown = JSON.parse(
sessionStorage.getItem(selectionKey) ?? '[]',
);
if (!Array.isArray(value)) return [];
return [
...new Set(
value.filter(
(id): id is number =>
typeof id === 'number' &&
Number.isSafeInteger(id) &&
id > 0,
),
),
];
} catch {
return [];
}
}
export function persistOpportunitySelection(ids: number[]): boolean {
try {
if (ids.length)
sessionStorage.setItem(selectionKey, JSON.stringify(ids));
else sessionStorage.removeItem(selectionKey);
return true;
} catch {
return false;
}
}
+11 -4
View File
@@ -101,7 +101,9 @@ export class PortalApiError extends Error {
? 'O registo solicitado já não está disponível.'
: status === 422
? 'Verifique os campos assinalados.'
: 'Não foi possível comunicar com o portal. Tente novamente.',
: status === 419
? 'A sessão não pôde ser validada. Actualize a página e tente novamente.'
: 'Não foi possível comunicar com o portal. Tente novamente.',
);
this.status = status;
this.errors = errors;
@@ -122,10 +124,15 @@ export async function portalRequest<T>(
typeof document === 'undefined'
? undefined
: document.cookie
.split('; ')
.split(';')
.map((value) => value.trim())
.find((value) => value.startsWith('XSRF-TOKEN='))
?.slice(11);
if (token) headers.set('X-XSRF-TOKEN', decodeURIComponent(token));
try {
if (token) headers.set('X-XSRF-TOKEN', decodeURIComponent(token));
} catch {
throw new PortalApiError(419);
}
}
const response = await fetch(url, {
...options,
@@ -136,7 +143,7 @@ export async function portalRequest<T>(
if (!response.ok || body === null) {
throw new PortalApiError(
response.status,
response.status === 422 ? body?.errors : undefined,
response.status === 422 ? (body?.errors ?? {}) : undefined,
);
}
return body as T;
+19 -5
View File
@@ -14,6 +14,7 @@ export type PortalNavAccess = {
};
scopedAdministration?: { label: string; href: string }[];
procurement?: boolean;
funding?: boolean;
authenticated: boolean;
manager: boolean;
businesses?: boolean;
@@ -486,11 +487,6 @@ export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
'Porquê investir em Moçambique?',
'/porque-investir',
),
link(
'idea-entry',
'Partir de uma ideia',
'/investimentos/iniciar',
),
link(
'opportunities',
'Consultar oportunidades',
@@ -503,6 +499,24 @@ export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
),
link('sectors', 'Sectores de investimento', '/sectores'),
link('locations', 'Localizações', '/oportunidades?view=map'),
...(access.funding
? [
link(
'funding',
'Fundos e programas de apoio',
'/fundos',
),
...(access.authenticated
? [
link(
'funding-saved',
'Programas que guardei',
'/fundos/guardados',
),
]
: []),
]
: []),
...(access.procurement
? [
link(
+31 -9
View File
@@ -12,29 +12,51 @@ export async function profileJson(
data: object = {},
method: 'GET' | 'POST' = 'POST',
) {
const cookie = document.cookie
.split('; ')
.find((c) => c.startsWith('XSRF-TOKEN='));
let token = '';
if (method !== 'GET') {
const cookie =
typeof document === 'undefined'
? undefined
: document.cookie
.split(';')
.map((value) => value.trim())
.find((value) => value.startsWith('XSRF-TOKEN='));
try {
token = cookie ? decodeURIComponent(cookie.slice(11)) : '';
} catch {
throw new ProfileValidationError(
'A sessão não pôde ser validada. Actualize a página e tente novamente.',
{},
);
}
}
const response = await fetch(url, {
method,
credentials: 'same-origin',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': cookie ? decodeURIComponent(cookie.slice(11)) : '',
...(method === 'GET' ? {} : { 'X-XSRF-TOKEN': token }),
},
...(method === 'GET' ? {} : { body: JSON.stringify(data) }),
});
const result = await response.json();
if (!response.ok)
const result = await response.json().catch(() => null);
const reauthenticate =
response.headers.get('X-Portal-Reauthentication') === 'required';
if (!response.ok || (result === null && response.status !== 204))
throw new ProfileValidationError(
result.message ?? 'A ação não foi concluída.',
typeof result?.message === 'string'
? result.message
: response.status === 419
? 'A sessão expirou. Actualize a página e tente novamente.'
: 'A ação não foi concluída. Tente novamente.',
Object.fromEntries(
Object.entries(result.errors ?? {}).map(([key, value]) => [
Object.entries(result?.errors ?? {}).map(([key, value]) => [
key,
Array.isArray(value) ? value.join(' ') : String(value),
]),
),
response.headers.get('X-Portal-Reauthentication') === 'required',
reauthenticate,
);
return result;
}
@@ -0,0 +1,85 @@
import {
publicRecordOfflineHtml,
downloadOfflineHtml,
offlineValue as display,
} from './public-record-offline.ts';
export type PublicBusinessOffline = {
slug: string;
title: string;
modality: string;
objective?: string | null;
stage?: string | null;
activity_code?: string | null;
amount_min?: string | null;
amount_max?: string | null;
available_percentage?: string | null;
currency?: string | null;
province?: string | null;
district?: string | null;
locality?: string | null;
published_at?: string | null;
sector?: { name: string } | null;
};
/** Fixed public projection: private or future properties are never serialised. */
export function publicBusinessOfflineHtml(
record: PublicBusinessOffline,
modalityLabel: string,
origin: string,
savedAt: Date,
): string {
const rows: [string, string][] = [
['Modalidade', display(modalityLabel)],
['Sector', display(record.sector?.name)],
['Fase', display(record.stage)],
['Actividade', display(record.activity_code)],
[
'Localização divulgada',
[record.locality, record.district, record.province]
.filter(Boolean)
.join(', ') || 'Não indicada',
],
[
'Montante mínimo indicado',
display(record.amount_min) +
(record.currency ? ` ${record.currency}` : ''),
],
[
'Montante máximo indicado',
display(record.amount_max) +
(record.currency ? ` ${record.currency}` : ''),
],
[
'Participação indicada',
record.available_percentage
? `${record.available_percentage}%`
: 'Não indicada',
],
['Publicação no portal', display(record.published_at)],
];
return publicRecordOfflineHtml(
{
title: record.title,
kind: 'Ficha p\u00fablica de neg\u00f3cio',
sourcePath: `/negocios/${encodeURIComponent(record.slug)}`,
rows,
sections: [{ title: 'Objectivo', text: display(record.objective) }],
notice: 'A publica\u00e7\u00e3o n\u00e3o constitui garantia de titularidade, avalia\u00e7\u00e3o, transmissibilidade ou retorno.',
},
origin,
savedAt,
);
}
export function downloadPublicBusinessOffline(
record: PublicBusinessOffline,
modalityLabel: string,
): void {
const html = publicBusinessOfflineHtml(
record,
modalityLabel,
window.location.origin,
new Date(),
);
downloadOfflineHtml(html, 'negocio', record.slug || 'ficha');
}
@@ -0,0 +1,87 @@
import {
publicRecordOfflineHtml,
downloadOfflineHtml,
offlineValue as display,
} from './public-record-offline.ts';
type PublicOpportunity = {
title: string;
slug: string;
reference: string;
summary?: string | null;
description?: string | null;
sector?: { name: string } | null;
province?: string | null;
district?: string | null;
maturity_label?: string | null;
estimated_investment_amount?: string | null;
estimated_investment_currency?: string | null;
financing_modality?: string | null;
expected_impact?: string | null;
last_validated_at?: string | null;
};
export function publicOpportunityOfflineHtml(
record: PublicOpportunity,
origin: string,
savedAt: Date,
): string {
return publicRecordOfflineHtml(
{
title: record.title,
kind: 'Ficha pública de oportunidade',
sourcePath: `/oportunidades/${encodeURIComponent(record.slug)}`,
rows: [
['Referência', display(record.reference)],
['Sector', display(record.sector?.name)],
['Preparação', display(record.maturity_label)],
[
'Contexto territorial indicado na ficha',
[record.district, record.province]
.filter(Boolean)
.join(', ') || 'Não indicado',
],
[
'Investimento estimado',
display(record.estimated_investment_amount) +
(record.estimated_investment_currency
? ` ${record.estimated_investment_currency}`
: ''),
],
[
'Modalidade de financiamento',
display(record.financing_modality),
],
[
'Última validação indicada',
display(record.last_validated_at),
],
],
sections: [
{ title: 'Resumo', text: display(record.summary) },
{ title: 'Descrição', text: display(record.description) },
{
title: 'Impacto esperado',
text: display(record.expected_impact),
},
],
notice: 'O contexto territorial não confirma a implantação. A execução depende das condições e autorizações aplicáveis ao projecto. Esta cópia não inclui mapas, anexos ou dados do dossier privado.',
},
origin,
savedAt,
);
}
export function downloadPublicOpportunityOffline(
record: PublicOpportunity,
): void {
downloadOfflineHtml(
publicOpportunityOfflineHtml(
record,
window.location.origin,
new Date(),
),
'oportunidade',
record.slug || 'ficha',
);
}
+64
View File
@@ -0,0 +1,64 @@
type OfflineContent = {
title: string;
kind: string;
sourcePath: string;
rows: [string, string][];
sections: { title: string; text: string }[];
notice: string;
};
export const offlineValue = (value?: string | null) =>
value?.trim() || 'Não indicado';
const escapeHtml = (value: string) =>
value.replace(
/[&<>"']/g,
(character) =>
({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
})[character]!,
);
/** All content is plain text; assets and executable content are excluded. */
export function publicRecordOfflineHtml(
content: OfflineContent,
origin: string,
savedAt: Date,
): string {
const base = new URL(origin);
if (!['http:', 'https:'].includes(base.protocol))
throw new Error('Origem do portal inválida.');
const source = new URL(content.sourcePath, base.origin);
if (
source.origin !== base.origin ||
!content.sourcePath.startsWith('/') ||
content.sourcePath.startsWith('//')
)
throw new Error('Referência da ficha inválida.');
return `<!doctype html><html lang="pt-MZ"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"><title>${escapeHtml(content.title)} — consulta offline</title><style>body{font:1rem/1.6 system-ui,sans-serif;margin:2rem auto;padding:0 1rem;max-width:55rem;color:#172b23;background:white}h1{line-height:1.2;overflow-wrap:anywhere}dt{font-weight:700}dd{margin:0 0 1rem;white-space:pre-wrap;overflow-wrap:anywhere}p{white-space:pre-wrap;overflow-wrap:anywhere}a{color:#14623d}footer{border-top:1px solid #ccc;margin-top:2rem;padding-top:1rem}</style></head><body><main><h1>${escapeHtml(content.title)}</h1><p>${escapeHtml(content.kind)} — InvesteMoz</p><p>Cópia guardada em ${escapeHtml(savedAt.toISOString())}. Consulte a ficha online para verificar actualizações.</p><dl>${content.rows.map(([label, value]) => `<dt>${escapeHtml(label)}</dt><dd>${escapeHtml(value)}</dd>`).join('')}</dl>${content.sections.map((section) => `<h2>${escapeHtml(section.title)}</h2><p>${escapeHtml(section.text)}</p>`).join('')}<p>${escapeHtml(content.notice)}</p><p><a href="${escapeHtml(source.href)}" rel="noreferrer">Consultar a ficha de origem online</a></p></main><footer>Fonte: ficha pública no portal InvesteMoz. Esta cópia conserva a informação apresentada no momento em que foi guardada.</footer></body></html>`;
}
export function downloadOfflineHtml(
html: string,
prefix: string,
slug: string,
): void {
const url = URL.createObjectURL(
new Blob([html], { type: 'text/html;charset=utf-8' }),
);
const link = document.createElement('a');
link.href = url;
link.download =
`${prefix}-${slug}`.replace(/[^a-zA-Z0-9_-]/g, '-').slice(0, 120) +
'.html';
try {
document.body.appendChild(link);
link.click();
} finally {
link.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
}
}
+4 -10
View File
@@ -749,20 +749,20 @@ function InterestForm({
</Field>
<Field
label="País de origem declarado desta solicitação"
label="País de origem do pedido (opcional)"
error={errors.declared_origin_country_code}
>
<CountrySelect
countries={countries}
label="País de origem declarado desta solicitação"
label="País de origem do pedido (opcional)"
value={form.declared_origin_country_code ?? ''}
onChange={(value) =>
update('declared_origin_country_code', value)
}
/>
<p className="text-sm">
Origem opcional; não é deduzida do país acima nem do
IP.
País de onde apresenta este pedido. Pode ser
diferente do país do requerente.
</p>
</Field>
@@ -971,11 +971,6 @@ export default function PortalInvestidorApp({
router.get('/oportunidades');
}
function handleHeroSearch(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
router.get('/oportunidades', { q: heroQuery.trim() });
}
function handleView(opportunity: Opportunity) {
router.get('/oportunidades/' + encodeURIComponent(opportunity.slug));
}
@@ -999,7 +994,6 @@ export default function PortalInvestidorApp({
<PortalHero
query={heroQuery}
setQuery={setHeroQuery}
onSearch={handleHeroSearch}
stats={home.data?.data.stats}
/>
<InvestmentContextCards />
+15 -3
View File
@@ -156,6 +156,16 @@ export default function Install({
))}
</form>
)}
{baseDeskInstalled && (
<p>
<Link
href="/management/balcao/servicos"
className="underline"
>
Editar formulários e publicar novas versões
</Link>
</p>
)}
{baseDeskInstalled && (
<form
className={card + ' space-y-3'}
@@ -165,11 +175,13 @@ export default function Install({
}}
>
<h2 className="text-xl font-bold">
Publicar serviço de preparação interna
Publicar definição inicial de um serviço
</h2>
<p>
Publicação do catálogo é uma acção separada; não submete
pedidos nem homologa um formulário oficial.
Esta acção usa a definição inicial do código. Para
manter alterações feitas pela interface, utilize o
editor de formulários. A publicação aplica-se a pedidos
futuros.
</p>
<label>
Serviço
+11 -8
View File
@@ -1,5 +1,6 @@
import { DossierPrefill } from '@/components/dossier-prefill';
import { createOperationKey } from '@/lib/operation-key';
import { deskFieldApplies } from '@/lib/desk-field-visibility';
import { Link, useForm } from '@inertiajs/react';
import { Frame, card, input, button } from '@/pages/investment/shared';
import CountrySelect, { type Country } from '@/components/country-select';
@@ -309,11 +310,11 @@ export default function RequestPage({
}
/>
<label className="block" htmlFor="declared-origin-country">
País de origem declarado desta solicitação
País de origem do pedido (opcional)
</label>
<CountrySelect
id="declared-origin-country"
label="País de origem declarado desta solicitação"
label="País de origem do pedido (opcional)"
error={form.errors['payload.declared_origin_country_code']}
countries={countries}
value={form.data.payload.declared_origin_country_code ?? ''}
@@ -333,14 +334,16 @@ export default function RequestPage({
}
/>
<p>
A origem não é deduzida do IP nem do país de residência.
Pedidos antigos sem declaração mantêm “não informado”.
Indique o país de onde apresenta este pedido, se desejar.
Este campo é distinto do país do requerente.
</p>
{Object.entries(definition.fields)
.filter(
([, f]) =>
!f.when ||
form.data.payload[f.when.field] === f.when.equals,
.filter(([key]) =>
deskFieldApplies(
key,
definition.fields,
form.data.payload,
),
)
.map(([key, f]) =>
f.type === 'territory' ? (
+598
View File
@@ -0,0 +1,598 @@
import { Link, useForm } from '@inertiajs/react';
import { useState } from 'react';
import DeskServiceHistory from '@/components/desk-service-history';
import { Frame, card, button, input } from '@/pages/investment/shared';
export type Field = {
label: string;
type: string;
required: boolean;
min?: number;
options?: Record<string, string>;
when?: { field: string; equals: string };
};
export type Definition = {
title: string;
theme: string;
profile: string;
stage: string;
entity: string;
result: string;
fields: Record<string, Field>;
};
type Service = {
code: string;
version: number;
definition: Definition;
fixedTypes?: Record<string, string>;
editable?: boolean;
};
const types: Record<string, string> = {
text: 'Texto curto',
textarea: 'Texto longo',
number: 'Número',
date: 'Data',
select: 'Lista de opções',
territory: 'Localização do cadastro',
email: 'Email',
tel: 'Telefone',
url: 'Ligação web',
};
const labels = {
title: 'Nome do serviço',
theme: 'Tema',
profile: 'Destinatários',
entity: 'Entidade indicada',
result: 'Resultado esperado',
};
function describeField(field: Field | undefined): string {
if (!field) return 'Ausente';
return [
field.label,
types[field.type] ?? field.type,
field.required ? 'Obrigatório' : 'Opcional',
...(field.min !== undefined ? [`Mínimo: ${field.min}`] : []),
...(field.options
? [
`Opções: ${Object.entries(field.options)
.map(([code, label]) => `${label} (${code})`)
.join('; ')}`,
]
: []),
field.when
? `Aplica-se quando ${field.when.field} = ${field.when.equals}`
: 'Sempre aplicável',
].join(' · ');
}
export default function ServiceEditor({ services }: { services: Service[] }) {
const [code, setCode] = useState(services[0]?.code ?? '');
const service = services.find((row) => row.code === code);
return (
<Frame title="Formulários do Balcão — versões">
<Link href="/management/balcao-install" className="underline">
Voltar à administração do Balcão
</Link>
<p>
Prepare a definição, confira as alterações e publique uma nova
versão. Pedidos existentes conservam os campos, respostas e
regras da versão em que foram criados.
</p>
<label className="block">
Serviço
<select
className={input}
value={code}
onChange={(event) => setCode(event.target.value)}
>
{services.map((row) => (
<option key={row.code} value={row.code}>
{row.definition.title} — versão {row.version}
</option>
))}
</select>
</label>
{service && service.editable === false && (
<p>
Este serviço conserva definições históricas fora da
configuração actual. Neste editor estão disponíveis para
consulta.
</p>
)}
{service && service.editable !== false ? (
<Editor
key={`${service.code}:${service.version}`}
service={service}
/>
) : !service ? (
<p>Não existem serviços disponíveis para edição.</p>
) : null}
{service && (
<DeskServiceHistory
key={`history:${service.code}:${service.version}`}
code={service.code}
formatField={describeField}
/>
)}
</Frame>
);
}
function Editor({ service }: { service: Service }) {
const form = useForm(
`desk-service-editor:${service.code}:${service.version}`,
{
base_version: service.version,
definition: structuredClone(service.definition),
reason: '',
confirm: false,
},
);
const [newKey, setNewKey] = useState('');
const [localError, setLocalError] = useState('');
const fields = form.data.definition.fields;
const setFields = (value: Record<string, Field>) =>
form.setData((data) => ({
...data,
confirm: false,
definition: { ...data.definition, fields: value },
}));
const update = (key: string, patch: Partial<Field>) =>
setFields({ ...fields, [key]: { ...fields[key], ...patch } });
const changed = [
...new Set([
...Object.keys(service.definition.fields),
...Object.keys(fields),
]),
].filter(
(key) =>
JSON.stringify(service.definition.fields[key]) !==
JSON.stringify(fields[key]),
);
const metaChanges = (Object.keys(labels) as (keyof typeof labels)[]).filter(
(key) => service.definition[key] !== form.data.definition[key],
);
return (
<form
className="space-y-5"
onSubmit={(event) => {
event.preventDefault();
if (form.processing) return;
form.put(
`/management/balcao/servicos/${encodeURIComponent(service.code)}`,
{ preserveScroll: true },
);
}}
>
<fieldset
disabled={form.processing}
className={card + ' space-y-4'}
>
<legend>Identificação do formulário</legend>
{(Object.keys(labels) as (keyof typeof labels)[]).map((key) => (
<label key={key} className="block">
{labels[key]}
<input
required
maxLength={
key === 'result'
? 2000
: key === 'entity'
? 300
: key === 'profile' || key === 'title'
? 200
: 150
}
className={input}
value={form.data.definition[key]}
onChange={(event) =>
form.setData((data) => ({
...data,
confirm: false,
definition: {
...data.definition,
[key]: event.target.value,
},
}))
}
/>
</label>
))}
<p>
Etapa do percurso existente: {service.definition.stage}.
Este editor não altera a sequência de tramitação.
</p>
</fieldset>
<fieldset disabled={form.processing} className="space-y-4">
<legend className="text-xl font-bold">
Campos e condições de preenchimento
</legend>
{Object.entries(fields).map(([key, field]) => (
<section
key={key}
className={card + ' space-y-3'}
aria-label={`Campo ${key}`}
>
<h3 className="font-bold">
{field.label}{' '}
<span className="font-normal">({key})</span>
</h3>
<label className="block">
Pergunta ou rótulo
<input
required
maxLength={300}
className={input}
value={field.label}
onChange={(event) =>
update(key, { label: event.target.value })
}
/>
</label>
<label className="block">
Tipo de resposta
<select
disabled={Boolean(service.fixedTypes?.[key])}
className={input}
value={field.type}
onChange={(event) => {
const next = {
...field,
type: event.target.value,
};
if (next.type !== 'select')
delete next.options;
else
next.options ??= {
opcao_1: 'Primeira opção',
};
if (next.type !== 'number') delete next.min;
setFields({ ...fields, [key]: next });
}}
>
{Object.entries(types).map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
{service.fixedTypes?.[key] && (
<span className="text-sm">
O tipo deste campo é usado pelo motor de
validação existente. Para outra resposta,
acrescente um novo campo.
</span>
)}
</label>
<label className="flex gap-2">
<input
type="checkbox"
checked={field.required}
onChange={(event) =>
update(key, {
required: event.target.checked,
})
}
/>
Obrigatório ao submeter, quando aplicável
</label>
{field.type === 'number' && (
<label className="block">
Valor mínimo
<input
className={input}
type="number"
min="0"
step="0.01"
value={field.min ?? 0}
onChange={(event) =>
update(key, {
min: Number(event.target.value),
})
}
/>
</label>
)}
{field.type === 'select' && (
<fieldset className="space-y-2">
<legend>Opções de resposta</legend>
{Object.entries(field.options ?? {}).map(
([value, label]) => (
<div key={value} className="flex gap-2">
<label className="flex-1">
Texto da opção ({value})
<input
required
maxLength={300}
className={input}
value={label}
onChange={(event) =>
update(key, {
options: {
...field.options,
[value]:
event.target
.value,
},
})
}
/>
</label>
<button
type="button"
className="underline"
onClick={() => {
const next = {
...field.options,
};
delete next[value];
update(key, {
options: next,
});
}}
>
Remover opção
</button>
</div>
),
)}
<button
type="button"
className="underline"
onClick={() => {
let index = 1;
while (
`opcao_${index}` in
(field.options ?? {})
)
index++;
update(key, {
options: {
...field.options,
[`opcao_${index}`]:
'Nova opção',
},
});
}}
>
Acrescentar opção
</button>
</fieldset>
)}
<label className="block">
Apresentar este campo
<select
className={input}
value={field.when?.field ?? ''}
onChange={(event) => {
const next = { ...field };
if (event.target.value)
next.when = {
field: event.target.value,
equals: '',
};
else delete next.when;
setFields({ ...fields, [key]: next });
}}
>
<option value="">Sempre</option>
{Object.entries(fields)
.filter(
([other, source]) =>
other !== key &&
source.type !== 'number',
)
.map(([other, value]) => (
<option key={other} value={other}>
Quando a resposta a «{value.label}»
for…
</option>
))}
</select>
</label>
{field.when && (
<label className="block">
Resposta que torna o campo aplicável
{fields[field.when.field]?.type === 'select' ? (
<select
required
className={input}
value={field.when.equals}
onChange={(event) =>
update(key, {
when: {
field: field.when!.field,
equals: event.target.value,
},
})
}
>
<option value="">
Seleccionar resposta
</option>
{Object.entries(
fields[field.when.field].options ??
{},
).map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
) : (
<input
required
className={input}
value={field.when.equals}
onChange={(event) =>
update(key, {
when: {
field: field.when!.field,
equals: event.target.value,
},
})
}
/>
)}
</label>
)}
<button
type="button"
className="underline"
onClick={() => {
const next = { ...fields };
delete next[key];
setFields(next);
}}
>
Retirar campo da nova versão
</button>
</section>
))}
<div className={card}>
<label className="block">
Identificador do novo campo
<input
className={input}
pattern="[a-z][a-z0-9_]*"
maxLength={64}
value={newKey}
placeholder="ex.: observacoes_adicionais"
onChange={(event) => setNewKey(event.target.value)}
/>
</label>
<button
type="button"
className="underline"
onClick={() => {
if (
!/^[a-z][a-z0-9_]{0,63}$/.test(newKey) ||
newKey in fields
) {
setLocalError(
'Indique um identificador novo, com letras minúsculas, números ou sublinhado.',
);
return;
}
setFields({
...fields,
[newKey]: {
label: 'Nova pergunta',
type: 'text',
required: false,
},
});
setNewKey('');
setLocalError('');
}}
>
Acrescentar campo
</button>
{localError && <p role="alert">{localError}</p>}
</div>
</fieldset>
<section
className={card + ' space-y-3'}
aria-label="Conferir efeito da publicação"
>
<h2 className="text-xl font-bold">
Conferir nova versão {service.version + 1}
</h2>
<p>
Alterações de identificação:{' '}
{metaChanges.map((key) => labels[key]).join(', ') ||
'nenhuma'}
. Campos acrescentados, alterados ou retirados:{' '}
{changed.join(', ') || 'nenhum'}.
</p>
{(changed.length > 0 || metaChanges.length > 0) && (
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<caption>
Comparação com a versão {service.version}
</caption>
<thead>
<tr>
<th className="p-2">Elemento</th>
<th className="p-2">Versão anterior</th>
<th className="p-2">Nova versão</th>
</tr>
</thead>
<tbody>
{metaChanges.map((key) => (
<tr key={key}>
<th className="p-2">{labels[key]}</th>
<td className="p-2">
{service.definition[key]}
</td>
<td className="p-2">
{form.data.definition[key]}
</td>
</tr>
))}
{changed.map((key) => (
<tr key={key}>
<th className="p-2">{key}</th>
<td className="p-2">
{describeField(
service.definition.fields[key],
)}
</td>
<td className="p-2">
{describeField(fields[key])}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<p>
Aplica-se aos pedidos criados com esta nova versão. Pedidos
e submissões anteriores continuam vinculados à sua definição
original; as respectivas respostas não são reescritas.
</p>
<label className="block">
Motivo da alteração
<textarea
required
minLength={20}
maxLength={2000}
className={input}
value={form.data.reason}
onChange={(event) =>
form.setData('reason', event.target.value)
}
/>
</label>
<label className="flex gap-2">
<input
type="checkbox"
checked={form.data.confirm}
onChange={(event) =>
form.setData('confirm', event.target.checked)
}
/>
Conferi as alterações e o efeito sobre pedidos futuros.
</label>
{Object.entries(form.errors).map(([key, value]) => (
<p key={key} role="alert">
{value}
</p>
))}
<button
className={button}
disabled={
form.processing ||
!form.data.confirm ||
(service.version > 0 &&
changed.length === 0 &&
metaChanges.length === 0)
}
>
{form.processing ? 'A publicar…' : 'Publicar nova versão'}
</button>
</section>
</form>
);
}
+943
View File
@@ -0,0 +1,943 @@
import { Link, router, useForm } from '@inertiajs/react';
import { useState } from 'react';
import type { ReactNode } from 'react';
import { portalRequest, PortalApiError } from '@/lib/portal-api';
import { Frame, card, button, input } from '@/pages/investment/shared';
import type { Criterion } from './shared';
type Choice = { id: string | number; name?: string; title?: string };
type WindowDraft = {
code: string;
title: string;
mode: string;
start_on: string;
end_on: string;
coverage: string;
coverage_text: string;
territory_ids: string[];
source_url: string;
source_reference: string;
checked_on: string;
application_url: string;
criteria: Criterion[];
};
type Draft = {
title: string;
kind: string;
summary: string;
manager_name: string;
manager_organization_id: string;
source_url: string;
source_reference: string;
source_checked_on: string;
source_published_on: string;
source_status: string;
coverage: string;
coverage_text: string;
territory_ids: string[];
sectors_scope: string;
sectors_text: string;
sector_ids: number[];
resource_ids: number[];
criteria: Criterion[];
windows: WindowDraft[];
};
type RecordData = {
id: string;
code: string;
version: number;
draft: Draft;
published: boolean;
};
type Plan = { version: number; hash: string; payload: Draft };
const empty: Draft = {
title: '',
kind: 'fund',
summary: '',
manager_name: '',
manager_organization_id: '',
source_url: '',
source_reference: '',
source_checked_on: '',
source_published_on: '',
source_status: 'unknown',
coverage: 'unknown',
coverage_text: '',
territory_ids: [],
sectors_scope: 'unknown',
sectors_text: '',
sector_ids: [],
resource_ids: [],
criteria: [],
windows: [],
};
const newCode = () => crypto.randomUUID();
function Field({ label, children }: { label: string; children: ReactNode }) {
return (
<label className="my-3 block">
<span className="block font-medium">{label}</span>
{children}
</label>
);
}
function Multi({
label,
options,
values,
onChange,
}: {
label: string;
options: Choice[];
values: (string | number)[];
onChange: (ids: string[]) => void;
}) {
return (
<Field label={label}>
<select
className={input}
multiple
value={values.map(String)}
onChange={(e) =>
onChange(
Array.from(
e.target.selectedOptions,
(option) => option.value,
),
)
}
>
{options.map((option) => (
<option key={option.id} value={option.id}>
{option.name ?? option.title}
</option>
))}
</select>
<span className="text-sm">Pode seleccionar mais de uma opção.</span>
</Field>
);
}
function Criteria({
value,
onChange,
}: {
value: Criterion[];
onChange: (criteria: Criterion[]) => void;
}) {
const update = (index: number, patch: Partial<Criterion>) =>
onChange(
value.map((item, i) =>
i === index ? { ...item, ...patch } : item,
),
);
return (
<section>
<h3 className="font-semibold">Critérios documentados</h3>
{value.map((item, index) => (
<fieldset className={card} key={item.code}>
<legend>Critério {index + 1}</legend>
<Field label="Pergunta">
<input
className={input}
value={item.question ?? ''}
maxLength={500}
onChange={(e) =>
update(index, { question: e.target.value })
}
/>
</Field>
<Field label="Aplica-se a">
<select
className={input}
value={item.applies_to}
onChange={(e) =>
update(index, {
applies_to: e.target
.value as Criterion['applies_to'],
})
}
>
<option value="all">Todos os candidatos</option>
<option value="individual">
Pessoas singulares
</option>
<option value="entity">Entidades</option>
</select>
</Field>
<Field label="Resposta exigida pela fonte">
<select
className={input}
value={item.expected}
onChange={(e) =>
update(index, {
expected: e.target.value as 'yes' | 'no',
})
}
>
<option value="yes">Sim</option>
<option value="no">Não</option>
</select>
</Field>
<Field label="Explicação da condição">
<textarea
className={input}
value={item.explanation ?? ''}
maxLength={2000}
onChange={(e) =>
update(index, { explanation: e.target.value })
}
/>
</Field>
<Field label="Referência exacta na fonte">
<input
className={input}
value={item.source_reference ?? ''}
maxLength={1500}
onChange={(e) =>
update(index, {
source_reference: e.target.value,
})
}
/>
</Field>
<button
type="button"
className="underline"
onClick={() =>
onChange(value.filter((_, i) => i !== index))
}
>
Remover critério
</button>
</fieldset>
))}
<button
type="button"
className="underline"
disabled={value.length >= 30}
onClick={() =>
onChange([
...value,
{
code: newCode(),
question: '',
applies_to: 'all',
expected: 'yes',
source_reference: '',
explanation: '',
},
])
}
>
Acrescentar critério
</button>
</section>
);
}
function Editor({
record,
references,
kinds,
windowModes,
history,
}: {
record: RecordData | null;
references: Record<
'organizations' | 'sectors' | 'territories' | 'documents',
Choice[]
>;
kinds: Record<string, string>;
windowModes: Record<string, string>;
history: { version: number; reason: string; published_at: string }[];
}) {
const form = useForm({
version: record?.version ?? 0,
code: record?.code ?? newCode(),
reason: '',
draft: { ...empty, ...record?.draft },
});
const [plan, setPlan] = useState<Plan | null>(null);
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const [confirmed, setConfirmed] = useState(false);
const draft = form.data.draft;
function change(patch: Partial<Draft>) {
form.setData('draft', { ...draft, ...patch });
setPlan(null);
setConfirmed(false);
}
function text(
key: {
[K in keyof Draft]: Draft[K] extends string ? K : never;
}[keyof Draft],
label: string,
type = 'text',
) {
return (
<Field label={label}>
<input
type={type}
className={input}
value={draft[key] ?? ''}
onChange={(e) => change({ [key]: e.target.value })}
/>
</Field>
);
}
function windowChange(index: number, patch: Partial<WindowDraft>) {
change({
windows: draft.windows.map((item, i) =>
i === index ? { ...item, ...patch } : item,
),
});
}
async function preview() {
if (
!record ||
JSON.stringify(draft) !==
JSON.stringify({ ...empty, ...record?.draft })
) {
setError('Guarde o rascunho antes de conferir a prévia.');
return;
}
setBusy(true);
setError('');
setPlan(null);
setConfirmed(false);
try {
setPlan(
await portalRequest<Plan>(
`/management/fundos/${record.id}/previa`,
{ method: 'POST' },
),
);
} catch (failure) {
setError(
failure instanceof PortalApiError
? Object.values(failure.errors).flat().join(' ') ||
failure.message
: 'Não foi possível preparar a prévia.',
);
} finally {
setBusy(false);
}
}
return (
<Frame
title={
record ? 'Editar fundo ou programa' : 'Novo fundo ou programa'
}
>
<Link className="underline" href="/management/fundos">
Voltar à gestão
</Link>
<p>
Guarde as condições efectivamente documentadas. Uma chamada
local ou encerrada não altera, por si, a cobertura ou existência
do programa.
</p>
<form
onSubmit={(e) => {
e.preventDefault();
const url =
'/management/fundos' + (record ? `/${record.id}` : '');
if (record) form.put(url);
else form.post(url);
}}
>
<section className={card}>
{text('title', 'Nome do programa')}
<Field label="Tipo">
<select
className={input}
value={draft.kind}
onChange={(e) => change({ kind: e.target.value })}
>
{Object.entries(kinds).map(([key, label]) => (
<option key={key} value={key}>
{label}
</option>
))}
</select>
</Field>
<Field label="Resumo">
<textarea
className={input}
value={draft.summary ?? ''}
maxLength={4000}
onChange={(e) =>
change({ summary: e.target.value })
}
/>
</Field>
<Field label="Entidade gestora do cadastro">
<select
className={input}
value={draft.manager_organization_id ?? ''}
onChange={(e) =>
change({
manager_organization_id: e.target.value,
})
}
>
<option value="">Identificar pela fonte</option>
{references.organizations.map((item) => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
</Field>
{!draft.manager_organization_id &&
text('manager_name', 'Gestor indicado pela fonte')}
{text('source_url', 'Endereço da fonte', 'url')}
{text('source_reference', 'Documento, edição e referência')}
{text(
'source_checked_on',
'Data de consulta da fonte',
'date',
)}
{text(
'source_published_on',
'Data de publicação da fonte, se conhecida',
'date',
)}
<Field label="Situação da fonte">
<select
className={input}
value={draft.source_status}
onChange={(e) =>
change({ source_status: e.target.value })
}
>
<option value="unknown">Por identificar</option>
<option value="identified">
Fonte efectiva identificada
</option>
<option value="example">
Conteúdo explicitamente demonstrativo
</option>
</select>
</Field>
</section>
<section className={card}>
<Field label="Cobertura do programa">
<select
className={input}
value={draft.coverage}
onChange={(e) =>
change({
coverage: e.target.value,
territory_ids: [],
})
}
>
<option value="unknown">Por determinar</option>
<option value="national">Nacional</option>
<option value="territorial">Territorial</option>
</select>
</Field>
{draft.coverage === 'territorial' && (
<Multi
label="Locais abrangidos"
options={references.territories}
values={draft.territory_ids}
onChange={(territory_ids) =>
change({ territory_ids })
}
/>
)}
{text('coverage_text', 'Explicação da cobertura')}
<Field label="Sectores abrangidos">
<select
className={input}
value={draft.sectors_scope}
onChange={(e) =>
change({
sectors_scope: e.target.value,
sector_ids: [],
})
}
>
<option value="unknown">Por determinar</option>
<option value="all">Todos, segundo a fonte</option>
<option value="selected">
Sectores documentados
</option>
</select>
</Field>
{draft.sectors_scope === 'selected' && (
<Multi
label="Seleccionar sectores"
options={references.sectors}
values={draft.sector_ids}
onChange={(ids) =>
change({ sector_ids: ids.map(Number) })
}
/>
)}
{text('sectors_text', 'Explicação do âmbito sectorial')}
<Multi
label="Documentos da biblioteca"
options={references.documents}
values={draft.resource_ids}
onChange={(ids) =>
change({ resource_ids: ids.map(Number) })
}
/>
<Criteria
value={draft.criteria}
onChange={(criteria) => change({ criteria })}
/>
</section>
<section className={card}>
<h2 className="text-xl font-semibold">
Janelas de candidatura
</h2>
{draft.windows.map((window, index) => (
<fieldset key={window.code} className={card}>
<legend>Janela {index + 1}</legend>
{(
[
'title',
'source_url',
'source_reference',
'checked_on',
'application_url',
'coverage_text',
] as const
).map((key) => (
<Field
key={key}
label={
{
title: 'Nome da chamada',
source_url: 'Endereço da fonte',
source_reference:
'Referência na fonte',
checked_on: 'Data de consulta',
application_url:
'Canal de candidatura, se documentado',
coverage_text:
'Explicação da cobertura desta chamada',
}[key]
}
>
<input
className={input}
type={
key === 'checked_on'
? 'date'
: key.endsWith('url')
? 'url'
: 'text'
}
value={window[key] ?? ''}
onChange={(e) =>
windowChange(index, {
[key]: e.target.value,
})
}
/>
</Field>
))}
<Field label="Estado documentado">
<select
className={input}
value={window.mode}
onChange={(e) =>
windowChange(index, {
mode: e.target.value,
...(['rolling', 'unknown'].includes(
e.target.value,
)
? { start_on: '', end_on: '' }
: {}),
})
}
>
{Object.entries(windowModes).map(
([key, label]) => (
<option key={key} value={key}>
{label}
</option>
),
)}
</select>
</Field>
{['dated', 'closed'].includes(window.mode) && (
<>
{(['start_on', 'end_on'] as const).map(
(key) => (
<Field
key={key}
label={
key === 'start_on'
? 'Data de abertura'
: 'Data-limite'
}
>
<input
className={input}
type="date"
value={window[key] ?? ''}
onChange={(e) =>
windowChange(index, {
[key]: e.target
.value,
})
}
/>
</Field>
),
)}
</>
)}
<Field label="Cobertura da chamada">
<select
className={input}
value={window.coverage}
onChange={(e) =>
windowChange(index, {
coverage: e.target.value,
territory_ids: [],
})
}
>
<option value="programme">
A mesma do programa
</option>
<option value="unknown">
Por determinar
</option>
<option value="national">Nacional</option>
<option value="territorial">
Territorial
</option>
</select>
</Field>
{window.coverage === 'territorial' && (
<Multi
label="Locais da chamada"
options={references.territories}
values={window.territory_ids ?? []}
onChange={(territory_ids) =>
windowChange(index, { territory_ids })
}
/>
)}
<Criteria
value={window.criteria ?? []}
onChange={(criteria) =>
windowChange(index, { criteria })
}
/>
<button
className="underline"
type="button"
onClick={() =>
change({
windows: draft.windows.filter(
(_, i) => i !== index,
),
})
}
>
Remover janela
</button>
</fieldset>
))}
<button
className="underline"
type="button"
disabled={draft.windows.length >= 20}
onClick={() =>
change({
windows: [
...draft.windows,
{
code: newCode(),
title: '',
mode: 'unknown',
start_on: '',
end_on: '',
coverage: 'programme',
coverage_text: '',
territory_ids: [],
source_url: '',
source_reference: '',
checked_on: '',
application_url: '',
criteria: [],
},
],
})
}
>
Acrescentar janela
</button>
</section>
<Field label="Motivo da alteração">
<textarea
className={input}
value={form.data.reason}
minLength={20}
maxLength={2000}
onChange={(e) => form.setData('reason', e.target.value)}
required
/>
</Field>
{Object.values(form.errors).map((message, index) => (
<p role="alert" key={index}>
{message}
</p>
))}
<button className={button} disabled={form.processing || busy}>
Guardar rascunho
</button>
</form>
{record && (
<section className={card}>
<h2>Publicação</h2>
<p>
A publicação cria uma versão pública; não altera
interesses já guardados, não abre candidaturas nem
activa cálculos fiscais.
</p>
<button
className={button}
disabled={busy || form.processing}
onClick={() => void preview()}
>
Conferir prévia de publicação
</button>
{error && <p role="alert">{error}</p>}
{plan && (
<div>
<h3 className="font-semibold">
{plan.payload.title}
</h3>
<p>{plan.payload.summary}</p>
<p>
Gestor: {plan.payload.manager_name}. Fonte:{' '}
{plan.payload.source_reference}.
</p>
<p>
{plan.payload.criteria.length} critérios gerais;{' '}
{plan.payload.windows.length} janelas.
</p>
<p>
<a
className="underline"
href={plan.payload.source_url}
target="_blank"
rel="noopener noreferrer"
>
Abrir fonte conferida
</a>{' '}
— consulta em {plan.payload.source_checked_on}.
</p>
<p>
Cobertura: {plan.payload.coverage};{' '}
{plan.payload.coverage_text}
</p>
<p>
{references.territories
.filter((item) =>
plan.payload.territory_ids.includes(
String(item.id),
),
)
.map((item) => item.name)
.join(', ')}
</p>
<p>
Sectores:{' '}
{plan.payload.sectors_text ||
(plan.payload.sectors_scope === 'all'
? 'Todos segundo a fonte'
: plan.payload.sectors_scope ===
'unknown'
? 'Por determinar'
: references.sectors
.filter((item) =>
plan.payload.sector_ids.includes(
Number(item.id),
),
)
.map((item) => item.name)
.join(', '))}
</p>
<ul>
{plan.payload.criteria.map((item) => (
<li key={item.code}>
<strong>{item.question}</strong> —{' '}
{item.expected === 'yes'
? 'Sim'
: 'Não'}
;{' '}
{item.applies_to === 'all'
? 'todos os candidatos'
: item.applies_to === 'entity'
? 'entidades'
: 'pessoas singulares'}
. {item.explanation} Fonte:{' '}
{item.source_reference}.
</li>
))}
</ul>
{plan.payload.windows.map((window) => (
<article key={window.code} className={card}>
<h4 className="font-semibold">
{window.title}
</h4>
<p>
{windowModes[window.mode]};{' '}
{window.start_on ||
'Abertura sem data indicada'}
;{' '}
{window.end_on ||
'Sem data-limite indicada'}
.
</p>
<p>{window.coverage_text}</p>
<p>
{references.territories
.filter((item) =>
(
window.territory_ids ?? []
).includes(String(item.id)),
)
.map((item) => item.name)
.join(', ')}
</p>
<a
className="underline"
href={window.source_url}
target="_blank"
rel="noopener noreferrer"
>
{window.source_reference}
</a>
<p>Consulta: {window.checked_on}</p>
{window.application_url && (
<p>
Canal indicado:{' '}
{window.application_url}
</p>
)}
<ul>
{window.criteria.map((item) => (
<li key={item.code}>
{item.question} —{' '}
{item.expected === 'yes'
? 'Sim'
: 'Não'}
; {item.explanation} Fonte:{' '}
{item.source_reference}.
</li>
))}
</ul>
</article>
))}
<ul>
{references.documents
.filter((item) =>
plan.payload.resource_ids.includes(
Number(item.id),
),
)
.map((item) => (
<li key={item.id}>
Documento: {item.title}
</li>
))}
</ul>
<label className="block">
<input
type="checkbox"
checked={confirmed}
onChange={(e) =>
setConfirmed(e.target.checked)
}
/>{' '}
Confirmei as condições, fontes e efeito da
publicação.
</label>
<button
className={button}
disabled={
!confirmed ||
form.processing ||
form.data.reason.length < 20
}
onClick={() =>
router.post(
`/management/fundos/${record.id}/publicar`,
{
version: plan.version,
hash: plan.hash,
reason: form.data.reason,
confirm: true,
},
)
}
>
Publicar versão conferida
</button>
</div>
)}
{record.published && (
<button
className="ml-3 underline"
disabled={
form.data.reason.length < 20 ||
JSON.stringify(draft) !==
JSON.stringify({
...empty,
...record?.draft,
})
}
onClick={() =>
router.post(
`/management/fundos/${record.id}/retirar`,
{
version: record.version,
reason: form.data.reason,
},
)
}
>
Retirar publicação
</button>
)}
</section>
)}
{history.length > 0 && (
<section className={card}>
<h2>Histórico de publicação</h2>
<ul>
{history.map((item) => (
<li key={item.version}>
Versão {item.version} — {item.published_at}:{' '}
{item.reason}
</li>
))}
</ul>
</section>
)}
</Frame>
);
}
export default function Edit(props: Parameters<typeof Editor>[0]) {
return (
<Editor
key={
props.record
? props.record.id + ':' + props.record.version
: 'new'
}
{...props}
/>
);
}
+212
View File
@@ -0,0 +1,212 @@
import { Link, useForm } from '@inertiajs/react';
import { Frame, card, button } from '@/pages/investment/shared';
import { type Programme, windowLabels } from './shared';
export default function Index({
items,
filters,
kinds,
management,
options,
}: {
items: {
data: Programme[];
links: { url: string | null; label: string; active: boolean }[];
};
filters: {
q?: string;
kind?: string;
sector?: string;
territory?: string;
certainty?: string;
state?: string;
};
options: {
sectors: { id: number; name: string }[];
territories: { id: string; name: string }[];
};
kinds: Record<string, string>;
management: boolean;
}) {
const form = useForm({
q: filters.q ?? '',
kind: filters.kind ?? '',
sector: filters.sector ?? '',
territory: filters.territory ?? '',
certainty: filters.certainty ?? 'include_unknown',
state: filters.state ?? '',
});
return (
<Frame title="Fundos e programas de apoio">
{management && (
<Link className={button} href="/management/fundos">
Gerir fundos e programas
</Link>
)}
<Link className="underline" href="/fundos/guardados">
Programas que guardei
</Link>
<p>
Consulte os programas e as condições documentadas. Cada chamada
tem as suas próprias datas e critérios.
</p>
<form
className={`${card} flex flex-wrap gap-4`}
onSubmit={(e) => {
e.preventDefault();
form.get('/fundos');
}}
>
<label>
Palavras-chave
<input
className="block rounded border p-2"
value={form.data.q}
maxLength={150}
onChange={(e) => form.setData('q', e.target.value)}
/>
</label>
<label>
Tipo
<select
className="block rounded border p-2"
value={form.data.kind}
onChange={(e) => form.setData('kind', e.target.value)}
>
<option value="">Todos</option>
{Object.entries(kinds).map(([key, name]) => (
<option key={key} value={key}>
{name}
</option>
))}
</select>
</label>
<button className={button} disabled={form.processing}>
Pesquisar
</button>
<label>
Sector
<select
className="block rounded border p-2"
value={form.data.sector}
onChange={(e) => form.setData('sector', e.target.value)}
>
<option value="">Todos</option>
{options.sectors.map((item) => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
</label>
<label>
Local de interesse
<select
className="block rounded border p-2"
value={form.data.territory}
onChange={(e) =>
form.setData('territory', e.target.value)
}
>
<option value="">Todos</option>
{options.territories.map((item) => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
</label>
<label>
Informação por confirmar
<select
className="block rounded border p-2"
value={form.data.certainty}
onChange={(e) =>
form.setData('certainty', e.target.value)
}
>
<option value="include_unknown">
Incluir e assinalar
</option>
<option value="documented">
Apenas âmbito documentado para os filtros escolhidos
</option>
</select>
</label>
<label>
Estado de uma janela
<select
className="block rounded border p-2"
value={form.data.state}
onChange={(e) => form.setData('state', e.target.value)}
>
<option value="">Qualquer estado</option>
{Object.entries(windowLabels).map(([key, label]) => (
<option key={key} value={key}>
{label}
</option>
))}
</select>
</label>
</form>
<p className="text-sm">
Sector e local filtram o âmbito geral do programa. Cada chamada
pode ter uma cobertura mais restrita. O estado indica que existe
pelo menos uma janela nesse estado; não confirma elegibilidade
nem candidatura aberta no local escolhido.
</p>
{items.data.length === 0 && (
<p>
Não foram encontrados programas publicados para esta
pesquisa.
</p>
)}
{items.data.map((item) => (
<article className={card} key={item.id}>
<h2 className="text-xl font-semibold">
<Link className="underline" href={`/fundos/${item.id}`}>
{item.payload.title}
</Link>
</h2>
<p>{item.payload.summary}</p>
<p>Gestor: {item.payload.manager_name}</p>
{Object.entries(item.filter_explanation ?? {}).map(
([key, message]) => (
<p key={key}>{message}</p>
),
)}
{item.payload.windows.length === 0 ? (
<p>
Não existe uma janela de candidatura confirmada
nesta ficha.
</p>
) : (
<ul>
{item.payload.windows.map((window) => (
<li key={window.code}>
{window.title}: {windowLabels[window.state]}
</li>
))}
</ul>
)}
</article>
))}
<nav aria-label="Páginas do catálogo" className="flex gap-3">
{items.links.map((link, index) =>
link.url ? (
<Link
key={index}
href={link.url}
aria-current={link.active ? 'page' : undefined}
className="underline"
>
{link.label
.replace(/&laquo;/g, '«')
.replace(/&raquo;/g, '»')}
</Link>
) : null,
)}
</nav>
</Frame>
);
}
+64
View File
@@ -0,0 +1,64 @@
import { Link } from '@inertiajs/react';
import { Frame, card, button } from '@/pages/investment/shared';
export default function Manage({
items,
}: {
items: {
data: {
id: string;
title: string;
version: number;
published: boolean;
}[];
links: { url: string | null; label: string; active: boolean }[];
};
}) {
return (
<Frame title="Gerir fundos e programas">
<Link className={button} href="/management/fundos/novo">
Novo programa
</Link>
<Link className="ml-4 underline" href="/fundos">
Catálogo público
</Link>
<Link
className="ml-4 underline"
href="/management/fundos/referencias/fdel"
>
Preparar referência FDEL
</Link>
{items.data.map((item) => (
<article className={card} key={item.id}>
<Link
className="underline"
href={`/management/fundos/${item.id}`}
>
{item.title}
</Link>
<p>
Versão de trabalho {item.version} —{' '}
{item.published
? 'com publicação'
: 'sem publicação pública'}
</p>
</article>
))}
<nav aria-label="Páginas de gestão" className="flex gap-3">
{items.links.map((link, index) =>
link.url ? (
<Link
key={index}
href={link.url}
className="underline"
aria-current={link.active ? 'page' : undefined}
>
{link.label
.replace(/&laquo;/g, '«')
.replace(/&raquo;/g, '»')}
</Link>
) : null,
)}
</nav>
</Frame>
);
}
+121
View File
@@ -0,0 +1,121 @@
import { Link, useForm } from '@inertiajs/react';
import { Frame, card, button } from '@/pages/investment/shared';
import type { Criterion } from './shared';
type Reference = {
code: string;
hash: string;
edition: string;
provenance: { url: string; checked_on: string; reference: string }[];
draft: {
title: string;
summary: string;
manager_name: string;
coverage_text: string;
sectors_text: string;
criteria: Criterion[];
windows: {
code: string;
title: string;
end_on?: string;
coverage_text: string;
criteria: Criterion[];
}[];
};
};
function Criteria({ items }: { items: Criterion[] }) {
return (
<ul>
{items.map((item) => (
<li key={item.code} className="my-3">
<strong>{item.question}</strong>
<p>{item.explanation}</p>
<p>
Resposta indicada:{' '}
{item.expected === 'yes' ? 'Sim' : 'Não'};{' '}
{item.applies_to === 'individual'
? 'pessoas singulares'
: item.applies_to === 'entity'
? 'entidades'
: 'todos os candidatos'}
. Fonte: {item.source_reference}.
</p>
</li>
))}
</ul>
);
}
export default function ReferencePage({ reference }: { reference: Reference }) {
const form = useForm({ hash: reference.hash });
return (
<Frame title="Preparar referência de fundo">
<Link className="underline" href="/management/fundos">
Voltar à gestão
</Link>
<section className={card}>
<h2 className="text-xl font-semibold">
{reference.draft.title}
</h2>
<p>{reference.draft.summary}</p>
<p>Gestão: {reference.draft.manager_name}</p>
<p>{reference.draft.coverage_text}</p>
<p>{reference.draft.sectors_text}</p>
<Criteria items={reference.draft.criteria} />
</section>
<section className={card}>
<h2>Chamadas documentadas</h2>
{reference.draft.windows.map((window) => (
<article key={window.code}>
<h3 className="font-semibold">{window.title}</h3>
{window.end_on && (
<p>
Prazo indicado na fonte: {window.end_on}.
Consulte o estado calculado na ficha; esta data
não é renovada automaticamente.
</p>
)}
<p>{window.coverage_text}</p>
<Criteria items={window.criteria} />
</article>
))}
</section>
<section className={card}>
<h2>Fontes e edições utilizadas</h2>
{reference.provenance.map((source) => (
<p key={source.url}>
<a
className="underline"
href={source.url}
target="_blank"
rel="noopener noreferrer"
>
{source.reference}
</a>{' '}
— consultada em {source.checked_on}
</p>
))}
</section>
<form
onSubmit={(e) => {
e.preventDefault();
form.post(
`/management/fundos/referencias/${reference.code}/preparar`,
);
}}
>
<p>
Prepara um rascunho para edição. A publicação é feita
posteriormente no editor. Se a ficha já existir, será aberta
sem substituir o seu conteúdo.
</p>
{Object.values(form.errors).map((error, index) => (
<p role="alert" key={index}>
{error}
</p>
))}
<button className={button} disabled={form.processing}>
Preparar ou abrir ficha existente
</button>
</form>
</Frame>
);
}
+91
View File
@@ -0,0 +1,91 @@
import { Link, router } from '@inertiajs/react';
import { Frame, card, button } from '@/pages/investment/shared';
type SavedProgramme = {
id: string;
title: string;
saved_version: number;
saved_at: string;
available: boolean;
current_version: number | null;
};
export default function Saved({
items,
}: {
items: {
data: SavedProgramme[];
links: { url: string | null; label: string; active: boolean }[];
};
}) {
return (
<Frame title="Programas que guardei">
<Link className="underline" href="/fundos">
Consultar fundos e programas
</Link>
<p>
Referências privadas aos programas que seleccionou. Guardar
interesse não envia candidatura nem reserva financiamento.
</p>
{items.data.length === 0 && (
<p>Ainda não tem programas guardados.</p>
)}
{items.data.map((item) => (
<article key={item.id} className={card}>
<h2 className="text-xl font-semibold">{item.title}</h2>
<p>Guardado na versão {item.saved_version}.</p>
{item.available ? (
<>
<Link
className="underline"
href={`/fundos/${item.id}`}
>
Consultar ficha publicada
</Link>
{item.current_version !== item.saved_version && (
<p>
Existe uma versão pública diferente:{' '}
{item.current_version}. A referência
guardada conserva a versão que seleccionou.
</p>
)}
</>
) : (
<p>
A ficha já não está disponível publicamente. A sua
referência guardada foi conservada.
</p>
)}
<div className="mt-3">
<button
className={button}
onClick={() =>
router.delete(`/fundos/${item.id}/interesse`)
}
>
Remover da minha lista
</button>
</div>
</article>
))}
<nav
aria-label="Páginas de programas guardados"
className="flex gap-3"
>
{items.links.map((link, index) =>
link.url ? (
<Link
key={index}
href={link.url}
aria-current={link.active ? 'page' : undefined}
className="underline"
>
{link.label
.replace(/&laquo;/g, '«')
.replace(/&raquo;/g, '»')}
</Link>
) : null,
)}
</nav>
</Frame>
);
}
+55
View File
@@ -0,0 +1,55 @@
export type Criterion = {
code: string;
question: string;
applies_to: 'all' | 'individual' | 'entity';
expected: 'yes' | 'no';
source_reference: string;
explanation: string;
};
export type FundingWindow = {
code: string;
title: string;
state: string;
coverage: string;
territory_paths?: { id: string; name: string; type: string }[][];
start_on?: string | null;
end_on?: string | null;
coverage_text?: string | null;
source_url: string;
source_reference: string;
checked_on: string;
application_url?: string | null;
criteria: Criterion[];
};
export type Programme = {
filter_explanation?: Record<string, string>;
id: string;
code: string;
version_id: string;
version: number;
published_at: string;
payload: {
title: string;
kind: string;
summary: string;
manager_name: string;
coverage: string;
coverage_text?: string | null;
territory_paths?: { id: string; name: string; type: string }[][];
sector_snapshots?: { id: number; name: string }[];
sectors_scope: string;
sectors_text?: string | null;
source_url: string;
source_reference: string;
source_checked_on: string;
criteria: Criterion[];
windows: FundingWindow[];
documents: { resource_id: number; title: string; available: boolean }[];
};
};
export const windowLabels: Record<string, string> = {
open: 'Janela aberta segundo as datas documentadas',
closed: 'Janela encerrada',
upcoming: 'Abertura futura',
unknown: 'Janela por confirmar',
};
+332
View File
@@ -0,0 +1,332 @@
import { Link, router } from '@inertiajs/react';
import { useState } from 'react';
import { portalRequest } from '@/lib/portal-api';
import { Frame, card, button } from '@/pages/investment/shared';
import { type Programme, windowLabels } from './shared';
type Assessment = {
notice: string;
criteria: { code: string; status: string }[];
};
const statusLabels: Record<string, string> = {
matches: 'Corresponde à resposta esperada',
does_not_match: 'Não corresponde à resposta esperada',
unknown: 'Informação por confirmar',
not_applicable: 'Não aplicável ao tipo de candidato indicado',
};
export default function Show({
record,
saved,
authenticated,
}: {
record: Programme;
saved: { version: number; saved_at: string } | null;
authenticated: boolean;
}) {
const [kind, setKind] = useState('unknown');
const [windowCode, setWindowCode] = useState('');
const [answers, setAnswers] = useState<Record<string, string>>({});
const [assessment, setAssessment] = useState<Assessment | null>(null);
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const payload = record.payload;
const window = payload.windows.find((item) => item.code === windowCode);
const criteria = [...payload.criteria, ...(window?.criteria ?? [])];
async function assess() {
setBusy(true);
setError('');
setAssessment(null);
try {
setAssessment(
await portalRequest<Assessment>(
`/fundos/${record.id}/criterios`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
version_id: record.version_id,
applicant_kind: kind,
window_code: windowCode || null,
answers: Object.fromEntries(
criteria.map((c) => [
c.code,
answers[c.code] ?? 'unknown',
]),
),
}),
},
),
);
} catch (failure) {
setError(
failure instanceof Error
? failure.message
: 'Não foi possível conferir os critérios.',
);
} finally {
setBusy(false);
}
}
return (
<Frame title={payload.title}>
<Link className="underline" href="/fundos/guardados">
Programas que guardei
</Link>
<Link className="underline" href="/fundos">
Voltar aos fundos e programas
</Link>
<p>{payload.summary}</p>
<p>
Gestor: {payload.manager_name}. Versão publicada:{' '}
{record.version}.
</p>
{(payload.territory_paths ?? []).map((path, index) => (
<p key={index}>
Local abrangido: {path.map((node) => node.name).join(' / ')}
</p>
))}
<p>
Sectores:{' '}
{payload.sectors_text ||
(payload.sectors_scope === 'all'
? 'Todos, segundo a fonte'
: payload.sectors_scope === 'unknown'
? 'Por confirmar'
: (payload.sector_snapshots ?? [])
.map((sector) => sector.name)
.join(', '))}
</p>
<p>
{payload.coverage === 'national'
? 'Cobertura nacional'
: payload.coverage === 'territorial'
? 'Cobertura territorial'
: 'Cobertura por confirmar'}
{payload.coverage_text ? ` — ${payload.coverage_text}` : ''}
</p>
<p>
<a
className="underline"
href={payload.source_url}
target="_blank"
rel="noopener noreferrer"
>
Consultar fonte: {payload.source_reference}
</a>
. Consultada em {payload.source_checked_on}.
</p>
<section className={card}>
<h2 className="text-xl font-semibold">
Janelas de candidatura
</h2>
{payload.windows.length === 0 && (
<p>
Não há uma janela de candidatura confirmada nesta ficha.
</p>
)}
{payload.windows.map((item) => (
<article key={item.code} className="my-4">
<h3 className="font-semibold">{item.title}</h3>
<p>{windowLabels[item.state]}</p>
{item.start_on && <p>Abertura: {item.start_on}</p>}
{item.end_on && <p>Data-limite: {item.end_on}</p>}
{item.coverage_text && <p>{item.coverage_text}</p>}
<p>
{item.coverage === 'programme'
? 'Mesma cobertura do programa'
: item.coverage === 'national'
? 'Chamada nacional'
: item.coverage === 'unknown'
? 'Cobertura da chamada por confirmar'
: 'Chamada territorial'}
</p>
{(item.territory_paths ?? []).map((path, index) => (
<p key={index}>
{path.map((node) => node.name).join(' / ')}
</p>
))}
<a
className="underline"
href={item.source_url}
target="_blank"
rel="noopener noreferrer"
>
{item.source_reference}
</a>
<p>Fonte consultada em {item.checked_on}.</p>
{item.application_url && (
<a
className="underline"
href={item.application_url}
target="_blank"
rel="noopener noreferrer"
>
Consultar o canal indicado pela entidade
</a>
)}
</article>
))}
</section>
<section className={card}>
<h2 className="text-xl font-semibold">
Conferir critérios documentados
</h2>
<p>
Esta consulta não envia candidatura nem concede
financiamento. As respostas não ficam guardadas.
</p>
<label className="block">
Tipo de candidato
<select
disabled={busy}
className="m-2 rounded border p-2"
value={kind}
onChange={(e) => {
setKind(e.target.value);
setAssessment(null);
}}
>
<option value="unknown">Por definir</option>
<option value="individual">Pessoa singular</option>
<option value="entity">Entidade</option>
</select>
</label>
<label className="block">
Janela
<select
disabled={busy}
className="m-2 rounded border p-2"
value={windowCode}
onChange={(e) => {
setWindowCode(e.target.value);
setAssessment(null);
}}
>
<option value="">Apenas critérios gerais</option>
{payload.windows.map((item) => (
<option key={item.code} value={item.code}>
{item.title}
</option>
))}
</select>
</label>
{criteria.length === 0 && (
<p>
Esta ficha não contém critérios suficientes para
conferir a correspondência.
</p>
)}
{criteria.map((criterion) => (
<div key={criterion.code} className="my-4">
<label>
{criterion.question}
<select
disabled={busy}
className="m-2 rounded border p-2"
value={answers[criterion.code] ?? 'unknown'}
onChange={(e) => {
setAnswers({
...answers,
[criterion.code]: e.target.value,
});
setAssessment(null);
}}
>
<option value="unknown">
Não sei / por confirmar
</option>
<option value="yes">Sim</option>
<option value="no">Não</option>
</select>
</label>
<p>{criterion.explanation}</p>
<p>Fonte: {criterion.source_reference}</p>
{assessment && (
<p>
{
statusLabels[
assessment.criteria.find(
(c) => c.code === criterion.code,
)?.status ?? 'unknown'
]
}
</p>
)}
</div>
))}
<button
className={button}
disabled={busy || criteria.length === 0}
onClick={() => void assess()}
>
{busy ? 'A conferir…' : 'Conferir respostas'}
</button>
{error && <p role="alert">{error}</p>}
{assessment && <p role="status">{assessment.notice}</p>}
</section>
{payload.documents.length > 0 && (
<section className={card}>
<h2>Documentos associados</h2>
<ul>
{payload.documents.map((doc) => (
<li key={doc.resource_id}>
{doc.available ? (
<a
className="underline"
href={`/fundos/${record.id}/versoes/${record.version_id}/documentos/${doc.resource_id}`}
>
{doc.title}
</a>
) : (
`${doc.title} — versão indisponível para descarga`
)}
</li>
))}
</ul>
</section>
)}
<section className={card}>
<h2>Guardar interesse</h2>
<p>
Guarda uma referência privada ao programa. Não envia uma
candidatura nem contacta a entidade.
</p>
{saved ? (
<>
<p>
Guardado na versão {saved.version}
{saved.version !== record.version
? '; existe uma versão pública mais recente'
: ''}
.
</p>
<button
className={button}
onClick={() =>
router.delete(`/fundos/${record.id}/interesse`)
}
>
Remover da minha lista
</button>
</>
) : authenticated ? (
<button
className={button}
onClick={() =>
router.put(`/fundos/${record.id}/interesse`, {
version_id: record.version_id,
consent: true,
})
}
>
Guardar programa na minha área privada
</button>
) : (
<Link className="underline" href="/login">
Entrar para guardar interesse
</Link>
)}
</section>
</Frame>
);
}
@@ -5,6 +5,7 @@ import type { FormEvent } from 'react';
import { newSubmissionKey } from '@/lib/portal-api';
import { Frame, Field, button, card, input } from './shared';
import CountrySelect, { type Country } from '@/components/country-select';
import { businessModalities } from './business-types';
type Opportunity = {
id: string;
@@ -190,20 +191,20 @@ export default function BusinessInterest({
) : (
<form className={`${card} space-y-4`} onSubmit={submit}>
<div className="space-y-1 text-sm font-medium">
<span>País de origem declarado desta solicitação</span>
<span>País de origem do pedido (opcional)</span>
<CountrySelect
countries={countries}
id={fieldId('declared_origin_country_code')}
error={fieldErrors.declared_origin_country_code}
value={form.declared_origin_country_code}
label="País de origem declarado desta solicitação"
label="País de origem do pedido (opcional)"
onChange={(value) =>
update('declared_origin_country_code', value)
}
/>
<p className="text-sm">
Origem opcional e independente do país do
investidor.
País de onde apresenta este pedido. Pode ser
diferente do país do requerente.
</p>
</div>
<Field label="Nome ou denominação">
@@ -261,7 +262,9 @@ export default function BusinessInterest({
{fieldError('investorType')}
</Field>
<div className="space-y-1 text-sm font-medium">
<span>País</span>
<label htmlFor={fieldId('country')}>
País do requerente
</label>
<CountrySelect
countries={countries}
required
@@ -296,7 +299,8 @@ export default function BusinessInterest({
>
{modalities.map((modality) => (
<option key={modality} value={modality}>
{modality.replaceAll('_', ' ')}
{businessModalities[modality] ??
modality.replaceAll('_', ' ')}
</option>
))}
</select>
@@ -314,7 +318,7 @@ export default function BusinessInterest({
/>
{fieldError('investmentRange')}
</Field>
<Field label="Motivação e pedido">
<Field label="Como pretende participar nesta oportunidade?">
<textarea
className={input}
required
@@ -2,6 +2,9 @@ import { Link } from '@inertiajs/react';
import { Frame, button, card } from './shared';
import { businessModalities } from './business-types';
import PartnershipSourceLinks from '@/components/partnership-source-links';
import SimilarBusinesses from '@/components/similar-businesses';
import { downloadPublicBusinessOffline } from '@/lib/public-business-offline';
import { useState } from 'react';
import {
ClassificationSummary,
type PublicClassification,
@@ -24,17 +27,21 @@ type Business = {
district?: string | null;
locality?: string | null;
sector?: { name: string; slug: string } | null;
published_at?: string | null;
};
export default function BusinessOpportunity({
record,
returnUrl = '/negocios',
interestUrl = `/negocios/${record.slug}/manifestar-interesse`,
similarCatalogueUrl,
}: {
record: Business;
returnUrl?: string;
interestUrl?: string;
similarCatalogueUrl?: string;
}) {
const [offlineMessage, setOfflineMessage] = useState('');
return (
<Frame title={record.title}>
<Link
@@ -88,7 +95,52 @@ export default function BusinessOpportunity({
<Link className={button} href={interestUrl}>
Manifestar interesse
</Link>
<div className="space-y-2">
<button
type="button"
className="underline"
onClick={() => {
try {
downloadPublicBusinessOffline(
record,
businessModalities[record.modality] ??
record.modality,
);
setOfflineMessage(
'Ficheiro preparado. Guarde-o e abra-o para consultar esta ficha sem rede.',
);
} catch {
setOfflineMessage(
'Não foi possível preparar o ficheiro. Tente novamente.',
);
}
}}
>
Guardar ficha para consulta offline (.html)
</button>
<p role="status" aria-live="polite">
{offlineMessage}
</p>
</div>
</section>
{similarCatalogueUrl && (
<SimilarBusinesses
currentId={record.id}
classifications={record.multidimensional}
catalogueUrl={similarCatalogueUrl}
criteria={[
businessModalities[record.modality] ?? record.modality,
...(record.sector ? [record.sector.name] : []),
...(record.province &&
new URL(
similarCatalogueUrl,
'https://portal.invalid',
).searchParams.has('province_id')
? [record.province]
: []),
]}
/>
)}
</Frame>
);
}
+53 -40
View File
@@ -1,3 +1,7 @@
import {
readOpportunitySelection,
persistOpportunitySelection,
} from '@/lib/opportunity-selection';
import CatalogueGuideLinks from '@/components/catalogue-guide-links';
import OpportunityCorridorGroups, {
type CorridorGroup,
@@ -6,10 +10,12 @@ import { searchTerritoryHref } from '@/lib/search-territory';
import type { EducationalArticle } from '@/components/educational-article-card';
import OpportunitySearchFilters from '@/components/opportunity-search-filters';
import SearchState from '@/components/search-state';
import OpportunityRelatedResults, {
type RelatedOpportunitySearch,
} from '@/components/opportunity-related-results';
import { Link, router, useForm, usePage } from '@inertiajs/react';
import { useEffect, useRef, useState } from 'react';
import Map from '@/components/interactive-investment-map';
import TerritoryGeometryPreview from '@/components/territory-geometry-preview';
import Map from '@/components/catalogue-investment-map';
import type { InvestmentMapArea } from '@/components/interactive-investment-map';
import { type TerritoryOption } from '@/components/investment-territory';
import { Frame, button, card, money, api } from './shared';
@@ -29,7 +35,9 @@ export default function Catalogue({
territorySelection,
catalogueUrl,
corridorGroups = [],
relatedSearch = null,
}: {
relatedSearch?: RelatedOpportunitySearch | null;
guides?: EducationalArticle[];
corridorGroups?: CorridorGroup[];
filters: Record<string, string | string[] | boolean>;
@@ -55,27 +63,19 @@ export default function Catalogue({
const page = usePage<{ auth: { user: unknown } }>();
const { auth } = page.props;
const [investmentSelection, setInvestmentSelection] = useState<number[]>(
() => {
try {
return JSON.parse(
sessionStorage.getItem(
'investment-opportunity-selection',
) ?? '[]',
);
} catch {
return [];
}
},
readOpportunitySelection,
);
const [selectionStorageUnavailable, setSelectionStorageUnavailable] =
useState(false);
function updateInvestmentSelection(next: number[]) {
setInvestmentSelection(next);
setSelectionStorageUnavailable(!persistOpportunitySelection(next));
}
function selectInvestment(id: number, checked: boolean) {
const next = checked
? [...new Set([...investmentSelection, id])]
: investmentSelection.filter((x) => x !== id);
setInvestmentSelection(next);
sessionStorage.setItem(
'investment-opportunity-selection',
JSON.stringify(next),
);
updateInvestmentSelection(next);
}
const form = useForm({
perspective: String(filters.perspective ?? ''),
@@ -427,6 +427,12 @@ export default function Catalogue({
total={results.total}
retry={() => runSearch()}
/>
<OpportunityRelatedResults
related={relatedSearch}
loading={searchLoading}
error={searchError}
total={results.total}
/>
{!searchLoading &&
!searchError &&
results.total === 0 &&
@@ -544,8 +550,8 @@ export default function Catalogue({
<div role={error ? 'alert' : 'status'} aria-live="polite">
{error ? (
<>
Não foi possível apresentar o mapa. A lista
continua disponível.{' '}
Não foi possível carregar as oportunidades no
mapa. A lista continua disponível.{' '}
<button
className="underline"
onClick={() =>
@@ -562,19 +568,20 @@ export default function Catalogue({
)}
</div>
)}
{!searchLoading &&
!searchError &&
['map', 'combined'].includes(view) &&
!error && <Map points={points} areas={areas} />}
{!searchLoading &&
!searchError &&
['map', 'combined'].includes(view) && (
<TerritoryGeometryPreview
<Map
points={error ? [] : points}
areas={areas}
territoryId={
form.data.locality_id ||
form.data.admin_post_id ||
form.data.district_id ||
form.data.province_id
String(
filters.locality_id ||
filters.admin_post_id ||
filters.district_id ||
filters.province_id ||
'',
) || undefined
}
/>
)}
@@ -659,10 +666,7 @@ export default function Catalogue({
selected={investmentSelection}
onSelect={selectInvestment}
onClear={() => {
setInvestmentSelection([]);
sessionStorage.removeItem(
'investment-opportunity-selection',
);
updateInvestmentSelection([]);
}}
onCompare={(ids) =>
void api(
@@ -785,10 +789,10 @@ export default function Catalogue({
aria-label="Paginação"
className={view === 'corridors' ? 'hidden' : 'flex gap-6'}
>
{results.prev_page_url && (
{!searchLoading && !searchError && results.prev_page_url && (
<Link href={results.prev_page_url}>Anterior</Link>
)}
{results.next_page_url && (
{!searchLoading && !searchError && results.next_page_url && (
<Link href={results.next_page_url}>Seguinte</Link>
)}
</nav>
@@ -807,11 +811,23 @@ export default function Catalogue({
Comparar {selected.length} oportunidades
</button>
)}
{selectionStorageUnavailable && (
<p
role="status"
className="my-3 rounded border border-amber-300 p-3 text-sm"
>
O navegador não permitiu guardar a escolha. A selecção
actual continua disponível nesta página; ao sair ou
actualizar, pode recuperar uma escolha anterior ou perdê-la.
</p>
)}
{view !== 'corridors' && !!investmentSelection.length && (
<section className={card}>
<p>
{investmentSelection.length} oportunidades escolhidas,
conservadas ao mudar de página.
{selectionStorageUnavailable
? ' disponíveis nesta página.'
: ' conservadas ao mudar de página.'}
</p>
<Link
className={button}
@@ -827,10 +843,7 @@ export default function Catalogue({
<button
className="ml-4 underline"
onClick={() => {
setInvestmentSelection([]);
sessionStorage.removeItem(
'investment-opportunity-selection',
);
updateInvestmentSelection([]);
}}
>
Limpar escolha
+25
View File
@@ -11,6 +11,7 @@ import type { EducationalArticle } from '@/components/educational-article-card';
import { ClassificationSummary } from '@/components/opportunity-classification';
import { Link, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import { downloadPublicOpportunityOffline } from '@/lib/public-opportunity-offline';
import InvestmentMapPanel from '@/components/investment-map-panel';
import StructureGeographyPanel, {
LocationList,
@@ -42,6 +43,7 @@ export default function Detail({
page.url.split('?')[1] ?? '',
).get('context');
const [sharing, setSharing] = useState('');
const [offlineMessage, setOfflineMessage] = useState('');
return (
<Frame title={r.title}>
{r.maturity_label === 'Em preparação' && (
@@ -114,6 +116,29 @@ export default function Detail({
{r.reference} · {r.sector?.name} · {r.province} {r.district}
</p>
<p className="text-xl">{r.summary}</p>
<div className="space-y-2">
<button
type="button"
className="underline"
onClick={() => {
try {
downloadPublicOpportunityOffline(r);
setOfflineMessage(
'Ficheiro preparado. Guarde-o e abra-o para consultar esta ficha sem rede.',
);
} catch {
setOfflineMessage(
'Não foi possível preparar o ficheiro. Tente novamente.',
);
}
}}
>
Guardar ficha para consulta offline (.html)
</button>
<p role="status" aria-live="polite">
{offlineMessage}
</p>
</div>
<InvestmentComplements items={complements} />
<ClassificationSummary rows={c.classification ?? []} />
<TerritorialSources sources={c.source_evidence} />
+168 -11
View File
@@ -1,16 +1,48 @@
import { Link, router } from '@inertiajs/react';
import { Frame, card, button } from './shared';
import OpportunityAlertPreferences, {
type AlertPreferences,
type AlertOptions,
} from '@/components/opportunity-alert-preferences';
export default function Notifications({
unread,
notifications,
alertPreferences = null,
alertOptions = null,
}: {
alertPreferences?: AlertPreferences | null;
alertOptions?: AlertOptions | null;
unread: number;
notifications: {
data: {
id: string;
submission_id: string;
submission_id: string | null;
opportunity_id?: number | null;
tender_version_id?: string | null;
funding_version_id?: string | null;
kind: string;
payload: { status?: string; reference?: string };
payload: {
status?: string;
reference?: string;
title?: string;
slug?: string;
source?: string;
source_url?: string;
source_reference?: string;
source_checked_on?: string;
preference_version?: number;
tender_id?: string;
programme_id?: string;
scope_explanation?: Record<string, string>;
window_states?: {
title: string;
state: string;
end_on?: string | null;
}[];
publication_version?: number;
act?: string;
published_at?: string | null;
};
read_at: string | null;
created_at: string;
}[];
@@ -24,38 +56,163 @@ export default function Notifications({
contacted: 'Contactado',
closed: 'Encerrado',
};
const fundingStates: Record<string, string> = {
open: 'aberta segundo as datas documentadas',
closed: 'encerrada',
upcoming: 'abertura futura',
unknown: 'por confirmar',
};
return (
<Frame title="Notificações e acompanhamento">
<Link href="/investidor/manifestacoes" className="underline">
Área do investidor
</Link>
<p role="status">{unread} notificações por ler</p>
{alertPreferences && alertOptions && (
<OpportunityAlertPreferences
key={alertPreferences.version}
preferences={alertPreferences}
options={alertOptions}
/>
)}
{notifications.data.map((n) => (
<article key={n.id} className={card + ' space-y-3'}>
<h2 className="text-xl font-bold">
{n.kind === 'received'
? 'Manifestação recebida'
: n.kind === 'status'
? 'Estado actualizado'
: 'Nova mensagem na conversa'}
{n.kind === 'funding_match'
? 'Nova publicação de fundo ou apoio'
: n.kind === 'tender_match'
? 'Novo acto de concurso compatível'
: n.kind === 'opportunity_match'
? 'Nova oportunidade compatível'
: n.kind === 'received'
? 'Manifestação recebida'
: n.kind === 'status'
? 'Estado actualizado'
: 'Nova mensagem na conversa'}
</h2>
<p>
{n.payload.reference ??
{n.payload.title ??
n.payload.reference ??
(n.payload.status
? (states[n.payload.status] ?? n.payload.status)
: 'Consulte o pedido para ler a mensagem.')}
</p>
{(n.kind === 'funding_match' ||
n.kind === 'opportunity_match' ||
n.kind === 'tender_match') && (
<p className="text-sm">
Fonte: {n.payload.source}.{' '}
{n.payload.published_at &&
!Number.isNaN(
new Date(n.payload.published_at).getTime(),
) ? (
<>
Publicação em{' '}
<time dateTime={n.payload.published_at}>
{new Date(
n.payload.published_at,
).toLocaleString('pt-MZ')}
</time>
.{' '}
</>
) : (
'Data de publicação não indicada. '
)}
Correspondência com a versão{' '}
{n.payload.preference_version} das suas
preferências; não representa avaliação de
rentabilidade ou elegibilidade.
</p>
)}
{n.kind === 'tender_match' && (
<p>
{alertOptions?.tenderActs?.[n.payload.act ?? ''] ??
n.payload.act ??
'Acto publicado'}{' '}
· versão {n.payload.publication_version}.
Referência: {n.payload.reference ?? 'Não indicada'}.
Consulte o concurso para verificar o estado e as
condições actuais. Este aviso não apresenta uma
proposta.
</p>
)}
{n.kind === 'funding_match' && (
<div>
{n.payload.source_url && (
<p>
<a
className="underline"
href={n.payload.source_url}
target="_blank"
rel="noopener noreferrer"
>
{n.payload.source_reference ??
'Consultar fonte documentada'}
</a>
{n.payload.source_checked_on
? ` — consultada em ${n.payload.source_checked_on}`
: ''}
</p>
)}
<p>
Versão {n.payload.publication_version}. Consulte
a ficha para conferir as condições actuais. Este
aviso não confirma uma candidatura aberta nem
concessão de financiamento.
</p>
{Object.entries(
n.payload.scope_explanation ?? {},
).map(([key, text]) => (
<p key={key}>{text}</p>
))}
<ul>
{(n.payload.window_states ?? []).map(
(window, index) => (
<li key={index}>
{window.title}:{' '}
{fundingStates[window.state] ??
window.state}
{window.end_on
? `; data-limite ${window.end_on}`
: ''}{' '}
(estado na data do aviso).
</li>
),
)}
</ul>
</div>
)}
<p className="text-sm">
Recebida em{' '}
{new Date(n.created_at).toLocaleString('pt-MZ')}
</p>
<div className="flex flex-wrap gap-4">
<Link
href={
'/investidor/manifestacoes/' + n.submission_id
n.kind === 'funding_match' &&
n.payload.programme_id
? '/fundos/' +
encodeURIComponent(n.payload.programme_id)
: n.kind === 'tender_match' &&
n.payload.tender_id
? '/concursos/' +
encodeURIComponent(n.payload.tender_id)
: n.kind === 'opportunity_match' &&
n.payload.slug
? '/oportunidades/' +
encodeURIComponent(n.payload.slug)
: '/investidor/manifestacoes/' +
n.submission_id
}
className="underline"
>
Abrir manifestação
{n.kind === 'funding_match'
? 'Consultar fundo ou apoio'
: n.kind === 'tender_match'
? 'Consultar concurso'
: n.kind === 'opportunity_match'
? 'Consultar oportunidade'
: 'Abrir manifestação'}
</Link>
{!n.read_at && (
<button
@@ -77,7 +234,7 @@ export default function Notifications({
</article>
))}
{!notifications.data.length && (
<p>Ainda não existem notificações.</p>
<p>Não existem notificações disponíveis nesta consulta.</p>
)}
<nav aria-label="Paginação" className="flex gap-4">
{notifications.prev_page_url && (
+4 -5
View File
@@ -97,7 +97,8 @@ export default function Profile({
, versão{' '}
{company.countrySource.organization_version}. O
valor é uma cópia identificada; não é atualizado
automaticamente quando o cadastro mestre muda.
automaticamente quando o registo da organização
muda.
</p>
)}
<Editor
@@ -173,9 +174,7 @@ export default function Profile({
/>
</section>
)}
<h2 className="text-2xl font-bold">
Organizações representadas — cadastro mestre
</h2>
<h2 className="text-2xl font-bold">Organizações representadas</h2>
<p>
O país de constituição é independente da residência e da origem
da solicitação. Não se associa uma empresa privada a uma
@@ -290,7 +289,7 @@ function OrganizationEditor({
className={button}
disabled={!organization.canEdit || form.processing}
>
Guardar país no cadastro mestre
Guardar país da organização
</button>
</form>
</section>
+22 -9
View File
@@ -174,12 +174,21 @@ export function money(r: Opportunity) {
: `${new Intl.NumberFormat('pt-MZ', { maximumFractionDigits: 2 }).format(Number(r.estimated_investment_amount))} ${r.estimated_investment_currency}`;
}
export async function api(url: string, body?: unknown) {
const token = decodeURIComponent(
document.cookie
.split('; ')
.find((c) => c.startsWith('XSRF-TOKEN='))
?.slice(11) ?? '',
);
const encodedToken =
body === undefined || typeof document === 'undefined'
? ''
: (document.cookie
.split('; ')
.find((c) => c.startsWith('XSRF-TOKEN='))
?.slice(11) ?? '');
let token = '';
try {
token = decodeURIComponent(encodedToken);
} catch {
throw new Error(
'A sessão não pôde ser validada. Actualize a página e tente novamente.',
);
}
const formData =
typeof FormData !== 'undefined' && body instanceof FormData;
const response = await fetch(url, {
@@ -194,10 +203,14 @@ export async function api(url: string, body?: unknown) {
? {}
: { body: formData ? body : JSON.stringify(body) }),
});
const data = await response.json();
if (!response.ok)
const data = await response.json().catch(() => null);
if (!response.ok || (data === null && response.status !== 204))
throw new Error(
data.message ?? 'Não foi possível concluir a operação.',
typeof data?.message === 'string'
? data.message
: response.status === 419
? 'A sessão expirou. Actualize a página e tente novamente.'
: 'Não foi possível concluir a operação. Tente novamente.',
);
return data;
}
+6 -5
View File
@@ -606,7 +606,7 @@ function Editor({
incorporation_country_code:
'País de constituição da entidade',
declared_origin_country_code:
'País de origem declarado desta solicitação',
'País de origem do pedido (opcional)',
}[key]
}
>
@@ -620,7 +620,7 @@ function Editor({
incorporation_country_code:
'País de constituição da entidade',
declared_origin_country_code:
'País de origem declarado desta solicitação',
'País de origem do pedido (opcional)',
}[key]
}
error={
@@ -664,9 +664,10 @@ function Editor({
</p>
)}
<p>
A origem da solicitação é uma declaração
sua; não é deduzida da residência, da
entidade ou do endereço IP.
Indique o país de onde apresenta este
pedido, se desejar. Pode ser diferente do
país de residência ou de constituição da
entidade.
</p>
{option(
'profile_id',
+2
View File
@@ -454,6 +454,7 @@ export default function Zones({
href={catalogueDetailHref(
`${management ? '/management/investment/zones' : '/zonas'}/${zone.id}`,
exportParams.toString(),
pageUrl,
)}
>
{zone.name}
@@ -464,6 +465,7 @@ export default function Zones({
href={catalogueDetailHref(
`${management ? '/management/investment/zones' : '/zonas'}/${zone.id}`,
exportParams.toString(),
pageUrl,
)}
>
Consultar ficha
+2 -2
View File
@@ -476,7 +476,7 @@ export default function LandForm({
</div>
<div className="space-y-1">
<p className="text-sm font-medium">
País de origem declarado da solicitação (opcional)
País de origem do pedido (opcional)
</p>
<CountrySelect
countries={countries}
@@ -484,7 +484,7 @@ export default function LandForm({
onChange={(value) =>
update('declared_origin_country_code', value)
}
label="País de origem declarado da solicitação (opcional)"
label="País de origem do pedido (opcional)"
error={
form.errors[
'payload.declared_origin_country_code'
@@ -1,9 +1,7 @@
import { Link, router } from '@inertiajs/react';
import { useState } from 'react';
import TerritoryGeometryPreview from '@/components/territory-geometry-preview';
import InteractiveInvestmentMap, {
type InvestmentMapFeature,
} from '@/components/interactive-investment-map';
import TerritorialMap from '@/components/catalogue-investment-map';
import type { InvestmentMapFeature } from '@/components/interactive-investment-map';
import {
Frame,
Field,
@@ -159,8 +157,9 @@ export default function Catalogue(
vários locais dos membros; estes pontos não confirmam a
implantação da parceria.
</p>
<InteractiveInvestmentMap points={p.mapPoints} />
<TerritoryGeometryPreview
<TerritorialMap
points={p.mapPoints}
mapKind="documented_locations"
territoryId={p.filters.territory_id}
/>
{!p.mapPoints.length && (
+1 -1
View File
@@ -78,7 +78,7 @@ function Editor(p: Props) {
/>
</Field>
<div className="grid gap-5 md:grid-cols-2">
<Field label="Participação">
<Field label="Organização que representa (opcional)">
<select
className={control}
value={form.data.organization_id}
+4 -4
View File
@@ -249,10 +249,10 @@ function RequestForm({
);
})}
<label className="block">
País de origem declarado desta solicitação
País de origem do pedido (opcional)
<CountrySelect
countries={countries}
label="País de origem declarado desta solicitação"
label="País de origem do pedido (opcional)"
value={form.data.declared_origin_country_code}
onChange={(value) =>
form.setData('declared_origin_country_code', value)
@@ -260,8 +260,8 @@ function RequestForm({
/>
</label>
<p className="text-sm">
Origem opcional e independente do país acima. Sem declaração,
permanece não informado nas estatísticas.
Indique o país de onde apresenta este pedido, se desejar. Pode
ser diferente do país do requerente.
</p>
<label className="block">
Descreva o pedido
+2
View File
@@ -130,6 +130,7 @@ export default function Index({
([, value]) => Boolean(value),
) as [string, string][],
).toString(),
url,
)}
>
{r.title}
@@ -163,6 +164,7 @@ export default function Index({
([, value]) => Boolean(value),
) as [string, string][],
).toString(),
url,
)}
>
Consultar ficha
+4 -3
View File
@@ -97,11 +97,11 @@ function JourneyCard({
allowLegacyValue
/>
</Field>
<Field label="País de origem declarado desta solicitação">
<Field label="País de origem do pedido (opcional)">
<CountrySelect
countries={countries}
value={form.data.declared_origin_country_code}
label="País de origem declarado desta solicitação"
label="País de origem do pedido (opcional)"
error={form.errors.declared_origin_country_code}
onChange={(value) =>
form.setData(
@@ -111,7 +111,8 @@ function JourneyCard({
}
/>
<p className="text-sm">
Origem opcional, independente do país acima.
País de onde apresenta este pedido. Pode ser
diferente do país do requerente.
</p>
</Field>
<Field label="Papel pretendido">
+4 -4
View File
@@ -431,7 +431,7 @@ export default function Edit({
</Field>
{value('guarantee_status') === 'required' &&
input('guarantees')}
<Field label="Fuso horário IANA do procedimento">
<Field label="Fuso horário do procedimento (ex.: Africa/Maputo)">
<input
className={control}
value={value('timezone')}
@@ -440,9 +440,9 @@ export default function Edit({
/>
</Field>
<p>
As datas e horas introduzidas pertencem a este fuso.
Publicação no InvesteMoz é registada separadamente pelo
servidor; não reinicia o prazo.
Use o identificador do fuso, como Africa/Maputo. As
datas e horas do procedimento seguem esse fuso; a
publicação no portal mantém o prazo indicado.
</p>
<Field label="Prazo mínimo documentado em dias (opcional)">
<input
@@ -75,8 +75,8 @@ function OperatorOrganizationForm() {
Organização proprietária e operadora
</h2>
<p>
Reutiliza o cadastro mestre e conserva o histórico. Estes dados
não atribuem representação empresarial nem papéis às contas.
Seleccione a organização responsável pelo portal. As permissões
dos utilizadores são definidas separadamente.
</p>
<form
className="max-w-2xl space-y-3"
+1 -1
View File
@@ -172,7 +172,7 @@ export default function RequestProfile({
</p>
)}
<label className="block">
Explique o seu pedido
Para que actividades precisa do perfil de Promotor?
<textarea
required
minLength={20}
@@ -0,0 +1,11 @@
@foreach($answers as $key => $value)
@php
$field = $definition['fields'][$key] ?? [];
$empty = $value === null || $value === '' || $value === [];
$display = $empty ? 'Não informado' : (is_bool($value) ? ($value ? 'Sim' : 'Não') : (is_scalar($value) ? ($field['options'][(string) $value] ?? (string) $value) : json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)));
if (!$empty && in_array($key, ['investment_amount', 'own_finance', 'other_finance'], true) && is_numeric($value)) {
$display = number_format((float)$value, 2, ',', ' ').' '.(($snapshot['payload']['currency'] ?? '') ?: '(moeda não informada)');
}
@endphp
<tr><th scope="row">{{ $field['label'] ?? \Illuminate\Support\Str::headline($key) }}</th><td>{{ $display }}</td></tr>
@endforeach
+11 -12
View File
@@ -26,24 +26,23 @@ footer { margin-top:28px; border-top:1px solid #cbd8d3; padding-top:12px; }
<h2>Dados submetidos</h2><table><caption>Informação declarada pelo requerente</caption><tbody>
@php
$opportunityScope = json_decode($snapshot['payload']['context_opportunity_snapshot'] ?? '{}', true);
$applicableFields = $applicableFields ?? app(\App\Services\VirtualDesk::class)->applicableFields($snapshot['payload'] ?? [], $definition);
$answers = array_diff_key($snapshot['payload'] ?? [], array_flip(['context_opportunity_snapshot', 'context_opportunity', 'context_reuse']));
$inactiveAnswers = array_intersect_key($answers, array_diff_key($definition['fields'], $applicableFields));
@endphp
@if(data_get($opportunityScope, 'choice.opportunity.key'))
<tr><th>Oportunidade associada</th><td>{{ data_get($opportunityScope, 'choice.opportunity.title') }} · {{ data_get($opportunityScope, 'choice.opportunity.key') }}</td></tr>
<tr><th>Contexto territorial guardado</th><td>{{ data_get($opportunityScope, 'choice.territory.title') ?: 'Por definir' }} · {{ data_get($opportunityScope, 'choice.corridor_name') ?: 'Corredor por definir' }} · {{ data_get($opportunityScope, 'choice.park.title') ?: 'Sem zona/parque seleccionado' }} · Revisão {{ $opportunityScope['revision'] }}</td></tr>
@endif
@foreach(($snapshot['payload'] ?? []) as $key => $value)
@continue(in_array($key, ['context_opportunity_snapshot', 'context_opportunity', 'context_reuse'], true))
@php
$field = $definition['fields'][$key] ?? [];
$empty = $value === null || $value === '' || $value === [];
$display = $empty ? 'Não informado' : (is_bool($value) ? ($value ? 'Sim' : 'Não') : (is_scalar($value) ? ($field['options'][(string) $value] ?? (string) $value) : json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)));
if (!$empty && in_array($key, ['investment_amount', 'own_finance', 'other_finance'], true) && is_numeric($value)) {
$display = number_format((float)$value, 2, ',', ' ').' '.(($snapshot['payload']['currency'] ?? '') ?: '(moeda não informada)');
}
@endphp
<tr><th scope="row">{{ $field['label'] ?? \Illuminate\Support\Str::headline($key) }}</th><td>{{ $display }}</td></tr>
@endforeach
@include('desk.receipt-answers', ['answers' => array_diff_key($answers, $inactiveAnswers)])
</tbody></table>
@if($inactiveAnswers)
<h2>Respostas conservadas de perguntas não aplicáveis</h2>
<p>Estas respostas foram conservadas na submissão, mas as condições do formulário não as tornam aplicáveis. Não entram nas verificações de preparação deste pedido.</p>
<table><caption>Histórico conservado na submissão</caption><tbody>
@include('desk.receipt-answers', ['answers' => $inactiveAnswers])
</tbody></table>
@endif
<h2>Suportes documentais</h2>
@forelse(($snapshot['documents'] ?? []) as $document)
<p>{{ data_get($document, 'source_reference') ?: 'Referência não informada' }} · Versão {{ data_get($document, 'version_no') ?? 'Não informada' }}</p>