oportunidades 4
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-10 07:03:59 +02:00
parent e662230df7
commit 6ddafc95ba
179 changed files with 22750 additions and 933 deletions
@@ -60,11 +60,13 @@ export default function InterestDetail({
history = [],
assignees = [],
consents = [],
declaredOrigin,
}: {
interest: Interest;
history?: Transition[];
assignees?: Assignee[];
consents?: Consent[];
declaredOrigin: { code: string | null; name: string };
}) {
const form = useForm({
status: interest.status,
@@ -81,6 +83,12 @@ export default function InterestDetail({
['Telefone', interest.phone],
['Tipo de investidor', interest.investor_type],
['País', interest.country],
[
'Origem declarada da solicitação',
declaredOrigin.code
? `${declaredOrigin.name} (${declaredOrigin.code})`
: declaredOrigin.name,
],
['Sector', interest.sector_interest],
['Oportunidade', interest.opportunity_reference],
['Negócio publicado', interest.existing_business_id],
+91 -1
View File
@@ -2,6 +2,7 @@ import { Link, router } from '@inertiajs/react';
import { useState } from 'react';
import { Management, Pagination, button, control, states } from './shared';
import type { Paginated } from './shared';
import CountrySelect, { type Country } from '@/components/country-select';
type Interest = {
id: number;
@@ -15,17 +16,34 @@ type Interest = {
next_action: string | null;
next_action_due_at: string | null;
status: string;
countryName: string | null;
declaredOrigin: { code: string | null; name: string };
};
export default function Interests({
requests,
filters,
countries,
originStatistics,
}: {
requests: Paginated<Interest>;
filters: { q?: string; status?: string; follow_up?: string };
filters: {
q?: string;
status?: string;
follow_up?: string;
country?: string;
origin?: string;
};
countries: Country[];
originStatistics: Record<
string,
{ code: string | null; name: string; count: number }[]
>;
}) {
const [q, setQ] = useState(filters.q ?? '');
const [status, setStatus] = useState(filters.status ?? '');
const [followUp, setFollowUp] = useState(filters.follow_up ?? '');
const [country, setCountry] = useState(filters.country ?? '');
const [origin, setOrigin] = useState(filters.origin ?? '');
return (
<Management title="Manifestações de interesse">
<form
@@ -36,6 +54,8 @@ export default function Interests({
q,
status,
follow_up: followUp,
country,
origin,
});
}}
>
@@ -91,6 +111,29 @@ export default function Interests({
<option value="upcoming">Acções por vencer</option>
<option value="unassigned">Sem responsável</option>
</select>
<CountrySelect
countries={countries}
value={country}
onChange={setCountry}
label="Filtrar país do requerente"
/>
<label>
Origem declarada
<select
aria-label="Filtrar origem declarada"
className={control}
value={origin}
onChange={(e) => setOrigin(e.target.value)}
>
<option value="">Todas as origens</option>
<option value="unknown">Não informada</option>
{countries.map((c) => (
<option key={c.code} value={c.code}>
{c.name} ({c.code})
</option>
))}
</select>
</label>
<button className={button}>Pesquisar</button>
</form>
<div className="overflow-x-auto">
@@ -101,6 +144,8 @@ export default function Interests({
'Referência',
'Nome',
'Email',
'País do requerente',
'Origem declarada',
'Sector',
'Modalidade',
'Responsável',
@@ -129,6 +174,12 @@ export default function Interests({
{item.full_name}
</td>
<td className="border-b p-3">{item.email}</td>
<td className="border-b p-3">
{item.countryName ?? 'Não informado'}
</td>
<td className="border-b p-3">
{item.declaredOrigin.name}
</td>
<td className="border-b p-3">
{item.sector_interest}
</td>
@@ -161,6 +212,45 @@ export default function Interests({
</div>
{!requests.data.length && <p>Nenhum pedido encontrado.</p>}
<Pagination page={requests} />
<details>
<summary>
Estatísticas de solicitações por origem declarada
</summary>
<p>
Contagens por conjunto e filtro de origem; o filtro do país
do requerente aplica-se à lista. Rascunhos de negócios e do
Balcão são excluídos. Apoio fundiário recebido integra
manifestações; não se soma como outro conjunto nem se contam
investidores únicos.
</p>
{Object.entries(originStatistics).map(([group, counts]) => (
<section key={group}>
<h2>
{
(
{
interests:
'Manifestações recebidas, incluindo apoio fundiário',
desk: 'Pedidos do Balcão',
businesses: 'Negócios submetidos',
} as Record<string, string>
)[group]
}
</h2>
{counts.length ? (
<ul>
{counts.map((row) => (
<li key={row.code ?? 'unknown'}>
{row.name}: {row.count}
</li>
))}
</ul>
) : (
<p>Sem solicitações neste conjunto.</p>
)}
</section>
))}
</details>
</Management>
);
}
@@ -1,10 +1,11 @@
import { Link, router } from "@inertiajs/react";
import { useState, useEffect } from "react";
import { Link, router } from '@inertiajs/react';
import TerritoryGeometryPreview from '@/components/territory-geometry-preview';
import { useState, useEffect } from 'react';
import {
TerritoryLevel,
type TerritoryOption,
} from "@/components/investment-territory";
import { Management, Field, button, control } from "./shared";
} from '@/components/investment-territory';
import { Management, Field, button, control } from './shared';
type Values = Record<string, string | number | null>;
type Entry = {
id: number;
@@ -25,6 +26,7 @@ export default function OpportunityDraft({
history,
territoryPath,
resourcesInstalled = false,
maturityCatalogue,
}: {
record: Entry | null;
values: Values;
@@ -36,6 +38,12 @@ export default function OpportunityDraft({
categories: string[];
territoryPath: TerritoryOption[];
resourcesInstalled?: boolean;
maturityCatalogue: {
version: string;
stages: Record<string, string>;
legacyVersion: string;
legacyLabels: Record<string, string>;
};
history: {
id: string;
action: string;
@@ -49,43 +57,43 @@ export default function OpportunityDraft({
});
const [busy, setBusy] = useState(false),
[errors, setErrors] = useState<Record<string, string>>({}),
[message, setMessage] = useState(""),
[reason, setReason] = useState(""),
[message, setMessage] = useState(''),
[reason, setReason] = useState(''),
[confirm, setConfirm] = useState(false),
[token, setToken] = useState(etag);
useEffect(() => setToken(etag), [etag]);
const [path, setPath] = useState(territoryPath);
const unavailable = Boolean(
record?.deleted_at || record?.status === "archived",
record?.deleted_at || record?.status === 'archived',
);
const set = (key: string, value: string) =>
setData((d) => ({ ...d, [key]: value }));
async function send(action: "save" | "delete" | "restore") {
async function send(action: 'save' | 'delete' | 'restore') {
if (busy) return;
setBusy(true);
setErrors({});
setMessage("");
setMessage('');
try {
const cookie = document.cookie
.split("; ")
.find((c) => c.startsWith("XSRF-TOKEN="));
.split('; ')
.find((c) => c.startsWith('XSRF-TOKEN='));
const url =
action === "save"
action === 'save'
? record
? `/management/opportunities/${record.id}/draft`
: "/management/opportunities/drafts"
: '/management/opportunities/drafts'
: `/management/opportunities/${record!.id}/lifecycle`;
const response = await fetch(url, {
method: action === "save" && record ? "PUT" : "POST",
method: action === 'save' && record ? 'PUT' : 'POST',
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-XSRF-TOKEN": cookie
Accept: 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': cookie
? decodeURIComponent(cookie.slice(11))
: "",
: '',
},
body: JSON.stringify(
action === "save"
action === 'save'
? { ...data, etag: token, reason }
: { etag: token, action, reason, confirm },
),
@@ -96,13 +104,13 @@ export default function OpportunityDraft({
Object.fromEntries(
Object.entries(result.errors ?? {}).map(([k, v]) => [
k,
Array.isArray(v) ? v.join(" ") : String(v),
Array.isArray(v) ? v.join(' ') : String(v),
]),
),
);
setMessage(
result.message ??
"Operação falhou; os dados preenchidos foram preservados.",
'Operação falhou; os dados preenchidos foram preservados.',
);
return;
}
@@ -110,15 +118,15 @@ export default function OpportunityDraft({
if (result.etag) setToken(result.etag);
if (!record)
router.visit(`/management/opportunities/${result.id}/edit`);
else if (action !== "save") router.reload();
else if (action !== 'save') router.reload();
} catch {
setMessage(
"Resposta indisponível. Os dados foram preservados; confira o registo no servidor antes de repetir.",
'Resposta indisponível. Os dados foram preservados; confira o registo no servidor antes de repetir.',
);
} finally {
setBusy(false);
requestAnimationFrame(() =>
document.getElementById("opportunity-result")?.focus(),
document.getElementById('opportunity-result')?.focus(),
);
}
}
@@ -126,8 +134,8 @@ export default function OpportunityDraft({
<Management
title={
record
? `${readOnly ? "Ver" : "Editar"} oportunidade ${record.reference}`
: "Nova oportunidade"
? `${readOnly ? 'Ver' : 'Editar'} oportunidade ${record.reference}`
: 'Nova oportunidade'
}
>
<Link href="/management/opportunities">Voltar à gestão</Link>
@@ -145,13 +153,13 @@ export default function OpportunityDraft({
<div
id="opportunity-result"
tabIndex={-1}
role={Object.keys(errors).length ? "alert" : "status"}
role={Object.keys(errors).length ? 'alert' : 'status'}
className="rounded border p-3"
>
{message}
{errors.etag && (
<p>
{errors.etag}{" "}
{errors.etag}{' '}
<a
target="_blank"
rel="noreferrer"
@@ -166,7 +174,7 @@ export default function OpportunityDraft({
className="max-w-3xl space-y-4"
onSubmit={(e) => {
e.preventDefault();
void send("save");
void send('save');
}}
>
<fieldset
@@ -174,6 +182,10 @@ export default function OpportunityDraft({
className="space-y-4"
>
<section aria-label="Localização registada">
<TerritoryGeometryPreview
territoryId={path.at(-1)?.id}
management
/>
<p>
Hierarquia do cadastro territorial existente.
Alterar esta seleção não cria relações com
@@ -181,16 +193,16 @@ export default function OpportunityDraft({
</p>
{(
[
"province_id",
"district_id",
"admin_post_id",
"locality_id",
'province_id',
'district_id',
'admin_post_id',
'locality_id',
] as const
).map((key, index) => (
<TerritoryLevel
key={`${key}-${path[index - 1]?.id ?? ""}`}
key={`${key}-${path[index - 1]?.id ?? ''}`}
index={index}
parent={path[index - 1]?.id ?? ""}
parent={path[index - 1]?.id ?? ''}
selected={path[index]}
endpoint="/management/territory-options"
fieldError={errors[key]}
@@ -202,10 +214,10 @@ export default function OpportunityDraft({
setPath(next);
setData((previous) => ({
...previous,
province_id: next[0]?.id ?? "",
district_id: next[1]?.id ?? "",
admin_post_id: next[2]?.id ?? "",
locality_id: next[3]?.id ?? "",
province_id: next[0]?.id ?? '',
district_id: next[1]?.id ?? '',
admin_post_id: next[2]?.id ?? '',
locality_id: next[3]?.id ?? '',
}));
}}
/>
@@ -217,9 +229,9 @@ export default function OpportunityDraft({
>
<select
className={control}
value={String(data.opportunity_category ?? "")}
value={String(data.opportunity_category ?? '')}
onChange={(e) =>
set("opportunity_category", e.target.value)
set('opportunity_category', e.target.value)
}
>
<option value="">Por indicar</option>
@@ -229,22 +241,22 @@ export default function OpportunityDraft({
</select>
</Field>
{Object.entries({
title: "Título oficial",
summary: "Resumo",
description: "Descrição",
promoter_name: "Promotor",
title: 'Título oficial',
summary: 'Resumo',
description: 'Descrição',
promoter_name: 'Promotor',
}).map(([key, label]) => (
<Field key={key} label={label} error={errors[key]}>
{key === "description" || key === "summary" ? (
{key === 'description' || key === 'summary' ? (
<textarea
className={control}
value={String(data[key] ?? "")}
value={String(data[key] ?? '')}
onChange={(e) => set(key, e.target.value)}
/>
) : (
<input
className={control}
value={String(data[key] ?? "")}
value={String(data[key] ?? '')}
onChange={(e) => set(key, e.target.value)}
/>
)}
@@ -253,8 +265,8 @@ export default function OpportunityDraft({
<Field label="Sector" error={errors.sector_id}>
<select
className={control}
value={String(data.sector_id ?? "")}
onChange={(e) => set("sector_id", e.target.value)}
value={String(data.sector_id ?? '')}
onChange={(e) => set('sector_id', e.target.value)}
>
<option value="">Por indicar</option>
{sectors.map((s) => (
@@ -270,21 +282,21 @@ export default function OpportunityDraft({
>
<select
className={control}
value={String(data.promoter_type ?? "")}
value={String(data.promoter_type ?? '')}
onChange={(e) =>
set("promoter_type", e.target.value)
set('promoter_type', e.target.value)
}
>
<option value="">Por indicar</option>
{values.promoter_type &&
![
"public",
"private",
"ppp",
"cooperative",
"association",
"community",
"other",
'public',
'private',
'ppp',
'cooperative',
'association',
'community',
'other',
].includes(String(values.promoter_type)) && (
<option
value={String(values.promoter_type)}
@@ -294,43 +306,85 @@ export default function OpportunityDraft({
</option>
)}
{[
"public",
"private",
"ppp",
"cooperative",
"association",
"community",
"other",
'public',
'private',
'ppp',
'cooperative',
'association',
'community',
'other',
].map((c) => (
<option key={c}>{c}</option>
))}
</select>
</Field>
<Field
label="Maturidade existente"
error={errors.maturity_level}
label="Etapa de maturidade"
error={errors.maturity_stage ?? errors.maturity_level}
>
<select
className={control}
value={String(data.maturity_level ?? "")}
onChange={(e) =>
set("maturity_level", e.target.value)
value={
data.maturity_catalogue_version ===
maturityCatalogue.version
? String(data.maturity_stage ?? '')
: data.maturity_level
? `legacy:${data.maturity_level}`
: ''
}
onChange={(e) => {
const stage = e.target.value;
if (stage.startsWith('legacy:')) {
setData((d) => ({
...d,
maturity_catalogue_version:
maturityCatalogue.legacyVersion,
maturity_level: Number(stage.slice(7)),
maturity_stage: null,
}));
} else {
setData((d) => ({
...d,
maturity_catalogue_version:
maturityCatalogue.version,
maturity_stage: stage || null,
maturity_level: stage
? Object.keys(
maturityCatalogue.stages,
).indexOf(stage) + 1
: null,
}));
}
}}
>
<option value="">Por indicar</option>
{[
"Ideia identificada",
"Pré-estudo disponível",
"Estudo de viabilidade em curso",
"Projecto estruturado",
"Pronto para investimento",
"Em negociação ou implementação",
].map((c, index) => (
<option key={c} value={index + 1}>
{c}
</option>
))}
{values.maturity_level &&
values.maturity_catalogue_version !==
maturityCatalogue.version && (
<option
value={`legacy:${values.maturity_level}`}
>
{
maturityCatalogue.legacyLabels[
String(values.maturity_level)
]
}{' '}
(catálogo histórico; sem conversão)
</option>
)}
{Object.entries(maturityCatalogue.stages).map(
([code, label], index) => (
<option key={code} value={code}>
{index + 1}. {label}
</option>
),
)}
</select>
<p>
O catálogo de oito etapas é guardado com a sua
versão. Os valores históricos conservam o
significado anterior.
</p>
</Field>
<Field
label="Modalidade de financiamento existente"
@@ -338,9 +392,9 @@ export default function OpportunityDraft({
>
<input
className={control}
value={String(data.financing_modality ?? "")}
value={String(data.financing_modality ?? '')}
onChange={(e) =>
set("financing_modality", e.target.value)
set('financing_modality', e.target.value)
}
/>
</Field>
@@ -350,13 +404,13 @@ export default function OpportunityDraft({
>
<textarea
className={control}
value={String(data.expected_impact ?? "")}
value={String(data.expected_impact ?? '')}
onChange={(e) =>
set("expected_impact", e.target.value)
set('expected_impact', e.target.value)
}
/>
</Field>
{(data.opportunity_category === "investment_project" ||
{(data.opportunity_category === 'investment_project' ||
(!data.opportunity_category &&
data.estimated_investment_amount != null)) && (
<>
@@ -367,11 +421,11 @@ export default function OpportunityDraft({
<input
className={control}
value={String(
data.estimated_investment_amount ?? "",
data.estimated_investment_amount ?? '',
)}
onChange={(e) =>
set(
"estimated_investment_amount",
'estimated_investment_amount',
e.target.value,
)
}
@@ -385,17 +439,17 @@ export default function OpportunityDraft({
className={control}
value={String(
data.estimated_investment_currency ??
"",
'',
)}
onChange={(e) =>
set(
"estimated_investment_currency",
'estimated_investment_currency',
e.target.value,
)
}
>
<option value="">Por indicar</option>
{["MZN", "USD", "EUR", "ZAR"].map((c) => (
{['MZN', 'USD', 'EUR', 'ZAR'].map((c) => (
<option key={c}>{c}</option>
))}
</select>
@@ -403,7 +457,7 @@ export default function OpportunityDraft({
</>
)}
{data.opportunity_category &&
data.opportunity_category !== "investment_project" && (
data.opportunity_category !== 'investment_project' && (
<p>
O módulo especializado desta categoria permanece
pendente. Pode guardar a identificação
@@ -439,11 +493,11 @@ export default function OpportunityDraft({
onChange={(e) =>
setConfirm(e.target.checked)
}
/>{" "}
Confirmo a{" "}
/>{' '}
Confirmo a{' '}
{unavailable
? "restauração"
: "exclusão lógica/arquivo"}
? 'restauração'
: 'exclusão lógica/arquivo'}
, preservando histórico e relações
</label>
<button
@@ -452,15 +506,15 @@ export default function OpportunityDraft({
disabled={busy || !confirm}
onClick={() =>
void send(
unavailable ? "restore" : "delete",
unavailable ? 'restore' : 'delete',
)
}
>
{unavailable
? "Restaurar"
? 'Restaurar'
: closedVersion
? "Arquivar"
: "Excluir rascunho"}
? 'Arquivar'
: 'Excluir rascunho'}
</button>
</>
)}
@@ -472,12 +526,12 @@ export default function OpportunityDraft({
href={
resourcesInstalled
? `/management/opportunities/${record.id}/resources`
: "/management/opportunity-resources-install"
: '/management/opportunity-resources-install'
}
>
{resourcesInstalled
? "Imagens, documentos e localizações"
: "Plano de ativação de imagens, documentos e localizações"}
? 'Imagens, documentos e localizações'
: 'Plano de ativação de imagens, documentos e localizações'}
</Link>
)}
{record && (
@@ -490,7 +544,7 @@ export default function OpportunityDraft({
{history.length ? (
history.map((e) => (
<p key={e.id}>
{e.action} · conta {e.actor_user_id} ·{" "}
{e.action} · conta {e.actor_user_id} ·{' '}
{e.occurred_at}
</p>
))
@@ -1,5 +1,5 @@
import { useForm } from "@inertiajs/react";
import { Management, button } from "./shared";
import { useForm } from '@inertiajs/react';
import { Management, button } from './shared';
export default function Install({
installed,
ready,
@@ -9,7 +9,7 @@ export default function Install({
migration,
backupDate,
rollback,
actionUrl = "/management/opportunity-management-install",
actionUrl = '/management/opportunity-management-install',
imageProcessingAvailable,
}: {
installed: boolean;
@@ -27,8 +27,8 @@ export default function Install({
return (
<Management title="Ativação da Gestão de Oportunidades">
<p>
Base: {target.database}:{target.port} ·{" "}
{installed ? "Instalado" : "Ainda não aplicado"}
Base: {target.database}:{target.port} ·{' '}
{installed ? 'Instalado' : 'Ainda não aplicado'}
</p>
<ul>
{changes.map((c) => (
@@ -36,11 +36,26 @@ export default function Install({
))}
</ul>
<p>Migração: {migration}</p>
{imageProcessingAvailable !== undefined && <section className="rounded border border-amber-500 p-3" aria-label="Limitações dos anexos">
<p>{imageProcessingAvailable ? 'GD/WebP disponível neste servidor; o processamento continua a exigir scan concluído do original.' : 'GD/WebP indisponível neste servidor: guardar imagens é possível; gerar miniaturas permanece pendente.'}</p>
<p>Instalar recursos não confirma scans. Documentos e imagens com scan pendente ficam sem download ou pré-visualização; preparação de rascunhos e localizações continua disponível. ClamD real mantém uma pendência separada.</p>
</section>}
<p>Backup/restauro: {backupDate ?? "Prova ainda por preparar"}</p>
{imageProcessingAvailable !== undefined && (
<section
className="rounded border border-amber-500 p-3"
aria-label="Limitações dos anexos"
>
<p>
{imageProcessingAvailable
? 'GD/WebP disponível neste servidor; o processamento continua a exigir scan concluído do original.'
: 'GD/WebP indisponível neste servidor: guardar imagens é possível; gerar miniaturas permanece pendente.'}
</p>
<p>
Instalar recursos não confirma scans. Documentos e
imagens com scan pendente ficam sem download ou
pré-visualização; preparação de rascunhos e localizações
continua disponível. ClamD real mantém uma pendência
separada.
</p>
</section>
)}
<p>Backup/restauro: {backupDate ?? 'Prova ainda por preparar'}</p>
<p>{rollback}</p>
<p>
Este plano ativa apenas as alterações acima; workflow completo e
@@ -57,9 +72,9 @@ export default function Install({
type="checkbox"
checked={form.data.confirm}
onChange={(e) =>
form.setData("confirm", e.target.checked)
form.setData('confirm', e.target.checked)
}
/>{" "}
/>{' '}
Confirmo a aplicação deste plano
</label>
<button
@@ -1,10 +1,11 @@
import { Link, router } from "@inertiajs/react";
import { useState } from "react";
import { Link, router } from '@inertiajs/react';
import TerritoryGeometryPreview from '@/components/territory-geometry-preview';
import { useState } from 'react';
import {
TerritoryLevel,
type TerritoryOption,
} from "@/components/investment-territory";
import { Management, Field, button, control } from "./shared";
} from '@/components/investment-territory';
import { Management, Field, button, control } from './shared';
type Payload = Record<string, string | number | boolean | null | object>;
type Resource = {
@@ -26,101 +27,101 @@ type Resource = {
sha256: string;
};
};
type Kind = "locations" | "images" | "documents";
type Kind = 'locations' | 'images' | 'documents';
const fields: Record<Kind, string[]> = {
locations: [
"title",
"address",
"operational_unit",
"role_description",
"area_value",
"area_unit",
"allocation_percentage",
"multi_district_rationale",
"source_reference",
"source_date",
'title',
'address',
'operational_unit',
'role_description',
'area_value',
'area_unit',
'allocation_percentage',
'multi_district_rationale',
'source_reference',
'source_date',
],
images: [
"title",
"caption",
"alt_text",
"author_source",
"captured_at",
"rights_valid_until",
"role_description",
"sort_order",
"source_reference",
'title',
'caption',
'alt_text',
'author_source',
'captured_at',
'rights_valid_until',
'role_description',
'sort_order',
'source_reference',
],
documents: [
"title",
"category",
"issuer",
"edition",
"source_date",
"valid_until",
"source_reference",
"section",
"supported_statement",
'title',
'category',
'issuer',
'edition',
'source_date',
'valid_until',
'source_reference',
'section',
'supported_statement',
],
};
const labels: Record<string, string> = {
role: "Papel da localização",
imageRole: "Tipo de imagem",
territorial_purpose: "Natureza da relação territorial",
rights_status: "Direitos de utilização",
visibility: "Âmbito de consulta",
classification: "Classificação documental",
location_id: "Localização associada",
rights_document_id: "Comprovativo de direitos",
title: "Título",
address: "Referência física",
operational_unit: "Unidade operacional",
role_description: "Descrição do papel outro",
area_value: "Área",
area_unit: "Unidade de área",
allocation_percentage: "Distribuição (%)",
multi_district_rationale: "Fundamento multidistrito/interprovincial",
source_reference: "Fonte / referência",
source_date: "Data da fonte",
caption: "Legenda",
alt_text: "Texto alternativo",
author_source: "Autor / fonte",
captured_at: "Data da imagem",
rights_valid_until: "Validade dos direitos",
sort_order: "Ordem",
category: "Categoria documental",
issuer: "Emissor",
edition: "Edição / versão",
valid_until: "Validade",
section: "Página / secção",
supported_statement: "Afirmação fundamentada",
role: 'Papel da localização',
imageRole: 'Tipo de imagem',
territorial_purpose: 'Natureza da relação territorial',
rights_status: 'Direitos de utilização',
visibility: 'Âmbito de consulta',
classification: 'Classificação documental',
location_id: 'Localização associada',
rights_document_id: 'Comprovativo de direitos',
title: 'Título',
address: 'Referência física',
operational_unit: 'Unidade operacional',
role_description: 'Descrição do papel outro',
area_value: 'Área',
area_unit: 'Unidade de área',
allocation_percentage: 'Distribuição (%)',
multi_district_rationale: 'Fundamento multidistrito/interprovincial',
source_reference: 'Fonte / referência',
source_date: 'Data da fonte',
caption: 'Legenda',
alt_text: 'Texto alternativo',
author_source: 'Autor / fonte',
captured_at: 'Data da imagem',
rights_valid_until: 'Validade dos direitos',
sort_order: 'Ordem',
category: 'Categoria documental',
issuer: 'Emissor',
edition: 'Edição / versão',
valid_until: 'Validade',
section: 'Página / secção',
supported_statement: 'Afirmação fundamentada',
};
const choices: Record<string, string[]> = {
role: [
"headquarters",
"production",
"raw_material",
"storage",
"logistics",
"market",
"support",
"other",
'headquarters',
'production',
'raw_material',
'storage',
'logistics',
'market',
'support',
'other',
],
imageRole: [
"cover",
"gallery",
"location",
"asset",
"product",
"plan",
"rendering",
"evidence",
"other",
'cover',
'gallery',
'location',
'asset',
'product',
'plan',
'rendering',
'evidence',
'other',
],
territorial_purpose: ["implementation", "context", "impact", "coverage"],
rights_status: ["owned", "licensed", "authorized", "public_domain"],
visibility: ["internal", "authenticated", "public"],
classification: ["public", "internal", "confidential", "restricted"],
territorial_purpose: ['implementation', 'context', 'impact', 'coverage'],
rights_status: ['owned', 'licensed', 'authorized', 'public_domain'],
visibility: ['internal', 'authenticated', 'public'],
classification: ['public', 'internal', 'confidential', 'restricted'],
};
export default function OpportunityResources({
@@ -143,17 +144,17 @@ export default function OpportunityResources({
assessment: string[];
imageProcessingAvailable: boolean;
}) {
const [kind, setKind] = useState<Kind>("locations");
const [kind, setKind] = useState<Kind>('locations');
const [editing, setEditing] = useState<Resource | null>(null);
const [payload, setPayload] = useState<Payload>({});
const [path, setPath] = useState<TerritoryOption[]>([]);
const [geometry, setGeometry] = useState("");
const [geometry, setGeometry] = useState('');
const [file, setFile] = useState<File | null>(null);
const [reason, setReason] = useState("");
const [reason, setReason] = useState('');
const [confirm, setConfirm] = useState(false);
const [key, setKey] = useState(() => crypto.randomUUID());
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState("");
const [message, setMessage] = useState('');
const [errors, setErrors] = useState<Record<string, string>>({});
const set = (name: string, value: Payload[string]) =>
setPayload((previous) => ({ ...previous, [name]: value }));
@@ -165,57 +166,57 @@ export default function OpportunityResources({
setGeometry(
record?.payload.geometry
? JSON.stringify(record.payload.geometry)
: "",
: '',
);
setFile(null);
setKey(crypto.randomUUID());
setConfirm(false);
setErrors({});
}
async function execute(action: "save" | "delete" | "restore" | "prepare") {
async function execute(action: 'save' | 'delete' | 'restore' | 'prepare') {
if (busy) return;
setBusy(true);
setErrors({});
setMessage("");
setMessage('');
try {
const form = new FormData();
form.set("etag", etag);
form.set("reason", reason);
form.set("creation_key", key);
if (editing) form.set("version", String(editing.version));
if (action === "save") {
form.set('etag', etag);
form.set('reason', reason);
form.set('creation_key', key);
if (editing) form.set('version', String(editing.version));
if (action === 'save') {
const values = { ...payload };
if (kind === "locations") {
if (kind === 'locations') {
[
"province_id",
"district_id",
"admin_post_id",
"locality_id",
'province_id',
'district_id',
'admin_post_id',
'locality_id',
].forEach(
(name, index) =>
(values[name] = path[index]?.id ?? null),
);
values.geometry = geometry ? JSON.parse(geometry) : null;
}
form.set("payload", JSON.stringify(values));
if (file) form.set("file", file);
form.set('payload', JSON.stringify(values));
if (file) form.set('file', file);
} else {
form.set("action", action);
form.set("confirm", confirm ? "1" : "0");
form.set('action', action);
form.set('confirm', confirm ? '1' : '0');
}
const url = `/management/opportunities/${opportunity.id}/resources/${kind}${editing ? `/${editing.id}` : ""}${action === "save" ? "" : action === "prepare" ? "/prepare" : "/lifecycle"}`;
const url = `/management/opportunities/${opportunity.id}/resources/${kind}${editing ? `/${editing.id}` : ''}${action === 'save' ? '' : action === 'prepare' ? '/prepare' : '/lifecycle'}`;
const csrf =
document.cookie
.split("; ")
.find((v) => v.startsWith("XSRF-TOKEN="))
?.split("=")
.split('; ')
.find((v) => v.startsWith('XSRF-TOKEN='))
?.split('=')
.slice(1)
.join("=") ?? "";
.join('=') ?? '';
const result = await fetch(url, {
method: "POST",
method: 'POST',
headers: {
Accept: "application/json",
"X-XSRF-TOKEN": decodeURIComponent(csrf),
Accept: 'application/json',
'X-XSRF-TOKEN': decodeURIComponent(csrf),
},
body: form,
});
@@ -227,7 +228,7 @@ export default function OpportunityResources({
([name, value]) => [
name,
Array.isArray(value)
? value.join(" ")
? value.join(' ')
: String(value),
],
),
@@ -239,30 +240,30 @@ export default function OpportunityResources({
setEditing(null);
setPayload({});
setPath([]);
setGeometry("");
setGeometry('');
setFile(null);
setKey(crypto.randomUUID());
setConfirm(false);
router.reload({
onFinish: () =>
document.getElementById("resource-result")?.focus(),
document.getElementById('resource-result')?.focus(),
});
} catch (error) {
setMessage(
error instanceof Error
? error.message
: "Falha de ligação; preenchimento preservado.",
: 'Falha de ligação; preenchimento preservado.',
);
} finally {
setBusy(false);
setTimeout(
() => document.getElementById("resource-result")?.focus(),
() => document.getElementById('resource-result')?.focus(),
0,
);
}
}
const unavailable =
!!opportunity.deleted_at || opportunity.status === "archived";
!!opportunity.deleted_at || opportunity.status === 'archived';
return (
<Management title="Imagens, documentos e localizações">
<Link href={`/management/opportunities/${opportunity.id}/edit`}>
@@ -280,11 +281,29 @@ export default function OpportunityResources({
className="rounded border p-3"
>
{message ||
"Guardar é independente de validar, submeter e publicar."}
'Guardar é independente de validar, submeter e publicar.'}
{errors.etag && <p>{errors.etag}</p>}
</div>
{kind === 'images' && !imageProcessingAvailable && <p role="status" className="rounded border border-amber-500 p-3">Processamento de imagens indisponível: GD/WebP não está carregado no servidor. Pode guardar o original e os metadados; miniaturas e imagens para divulgação ficam pendentes.</p>}
{kind !== 'locations' && <p className="rounded border p-3">Pode guardar anexos para preparação. Cada ficheiro permanece sem download ou pré-visualização enquanto o seu scan não estiver concluído. ClamD pendente não impede guardar metadados, locais ou rascunhos; testes com scanner simulado não verificam os seus ficheiros.</p>}
{kind === 'images' && !imageProcessingAvailable && (
<p
role="status"
className="rounded border border-amber-500 p-3"
>
Processamento de imagens indisponível: GD/WebP não está
carregado no servidor. Pode guardar o original e os
metadados; miniaturas e imagens para divulgação ficam
pendentes.
</p>
)}
{kind !== 'locations' && (
<p className="rounded border p-3">
Pode guardar anexos para preparação. Cada ficheiro permanece
sem download ou pré-visualização enquanto o seu scan não
estiver concluído. ClamD pendente não impede guardar
metadados, locais ou rascunhos; testes com scanner simulado
não verificam os seus ficheiros.
</p>
)}
<section>
<h2>Conferência e pendências</h2>
<ul>
@@ -304,18 +323,18 @@ export default function OpportunityResources({
</section>
)}
<nav className="flex flex-wrap gap-3">
{(["locations", "images", "documents"] as Kind[]).map((k) => (
{(['locations', 'images', 'documents'] as Kind[]).map((k) => (
<button
className={button}
key={k}
disabled={busy}
onClick={() => select(k)}
>
{k === "locations"
? "Localizações"
: k === "images"
? "Imagens"
: "Documentos"}
{k === 'locations'
? 'Localizações'
: k === 'images'
? 'Imagens'
: 'Documentos'}
</button>
))}
</nav>
@@ -326,21 +345,21 @@ export default function OpportunityResources({
{String(
r.payload.title ??
r.file?.file_name ??
"Recurso incompleto",
)}{" "}
· v{r.version} ·{" "}
'Recurso incompleto',
)}{' '}
· v{r.version} ·{' '}
{r.deleted_at
? "eliminado logicamente"
: "rascunho"}
? 'eliminado logicamente'
: 'rascunho'}
</p>
{r.file && (
<p className="break-all">
Scan: {r.file.malware_scan_status} · motor:{" "}
{r.file.malware_engine ?? "não executado"} ·
Scan: {r.file.malware_scan_status} · motor:{' '}
{r.file.malware_engine ?? 'não executado'} ·
hash: {r.file.sha256}
</p>
)}
{kind === "images" &&
{kind === 'images' &&
!r.deleted_at &&
!!r.derivativePreviews?.length && (
<img
@@ -348,14 +367,14 @@ export default function OpportunityResources({
src={r.derivativePreviews[0].url}
srcSet={r.derivativePreviews
.map((p) => `${p.url} ${p.width}w`)
.join(", ")}
.join(', ')}
alt={String(
r.payload.alt_text ??
"Pré-visualização interna pendente de descrição",
'Pré-visualização interna pendente de descrição',
)}
onError={() =>
setMessage(
"Pré-visualização indisponível ou endereço expirado; recarregue. Dados preservados.",
'Pré-visualização indisponível ou endereço expirado; recarregue. Dados preservados.',
)
}
/>
@@ -366,7 +385,7 @@ export default function OpportunityResources({
>
Ver / editar / restaurar
</button>
{r.file?.malware_scan_status === "clean" &&
{r.file?.malware_scan_status === 'clean' &&
!r.deleted_at && (
<a
href={`/management/opportunities/${opportunity.id}/resources/${kind}/${r.id}/download`}
@@ -380,22 +399,26 @@ export default function OpportunityResources({
<form
onSubmit={(event) => {
event.preventDefault();
void execute("save");
void execute('save');
}}
className="space-y-3"
>
<h2>
{editing
? "Editar recurso / nova versão"
: "Novo recurso incompleto"}
? 'Editar recurso / nova versão'
: 'Novo recurso incompleto'}
</h2>
{kind === "locations" && (
{kind === 'locations' && (
<div>
<TerritoryGeometryPreview
territoryId={path.at(-1)?.id}
management
/>
{[0, 1, 2, 3].map((index) => (
<TerritoryLevel
key={index}
index={index}
parent={path[index - 1]?.id ?? ""}
parent={path[index - 1]?.id ?? ''}
selected={path[index]}
onChange={(value) =>
setPath((previous) =>
@@ -410,10 +433,10 @@ export default function OpportunityResources({
fieldError={
errors[
[
"province_id",
"district_id",
"admin_post_id",
"locality_id",
'province_id',
'district_id',
'admin_post_id',
'locality_id',
][index]
]
}
@@ -421,7 +444,7 @@ export default function OpportunityResources({
))}
</div>
)}
{kind !== "locations" && (
{kind !== 'locations' && (
<Field
label="Original / substituir por nova versão"
error={errors.file}
@@ -431,9 +454,9 @@ export default function OpportunityResources({
aria-label="Original / substituir por nova versão"
type="file"
accept={
kind === "images"
? ".jpg,.jpeg,.png,.webp"
: ".pdf,.docx,.xlsx,.png,.jpg,.jpeg"
kind === 'images'
? '.jpg,.jpeg,.png,.webp'
: '.pdf,.docx,.xlsx,.png,.jpg,.jpeg'
}
onChange={(event) =>
setFile(event.target.files?.[0] ?? null)
@@ -454,13 +477,13 @@ export default function OpportunityResources({
<input
aria-label={labels[name]}
className={control}
value={String(payload[name] ?? "")}
value={String(payload[name] ?? '')}
type={
name.includes("date") ||
name.endsWith("_at") ||
name.endsWith("_until")
? "date"
: "text"
name.includes('date') ||
name.endsWith('_at') ||
name.endsWith('_until')
? 'date'
: 'text'
}
onChange={(event) =>
set(name, event.target.value || null)
@@ -468,19 +491,19 @@ export default function OpportunityResources({
/>
</Field>
))}
{(kind === "locations"
? ["role", "territorial_purpose"]
: kind === "images"
? ["imageRole", "rights_status", "visibility"]
: ["classification", "visibility"]
{(kind === 'locations'
? ['role', 'territorial_purpose']
: kind === 'images'
? ['imageRole', 'rights_status', 'visibility']
: ['classification', 'visibility']
).map((name) => (
<Field
key={name}
label={labels[name] ?? name}
error={
errors[name === "imageRole" ? "role" : name] ??
errors[name === 'imageRole' ? 'role' : name] ??
errors[
`payload.${name === "imageRole" ? "role" : name}`
`payload.${name === 'imageRole' ? 'role' : name}`
]
}
>
@@ -488,12 +511,12 @@ export default function OpportunityResources({
className={control}
aria-label={labels[name] ?? name}
value={String(
payload[name === "imageRole" ? "role" : name] ??
"",
payload[name === 'imageRole' ? 'role' : name] ??
'',
)}
onChange={(event) =>
set(
name === "imageRole" ? "role" : name,
name === 'imageRole' ? 'role' : name,
event.target.value || null,
)
}
@@ -505,7 +528,7 @@ export default function OpportunityResources({
</select>
</Field>
))}
{kind === "locations" && (
{kind === 'locations' && (
<Field
label="GeoJSON documentado (opcional)"
error={errors.geometry}
@@ -523,8 +546,8 @@ export default function OpportunityResources({
</p>
</Field>
)}
{kind === "images" &&
(["location_id", "rights_document_id"] as const).map(
{kind === 'images' &&
(['location_id', 'rights_document_id'] as const).map(
(name) => (
<Field
key={name}
@@ -535,16 +558,16 @@ export default function OpportunityResources({
>
<select
className={control}
value={String(payload[name] ?? "")}
value={String(payload[name] ?? '')}
onChange={(event) =>
set(name, event.target.value || null)
}
>
<option value="">Pendente</option>
{resources[
name === "location_id"
? "locations"
: "documents"
name === 'location_id'
? 'locations'
: 'documents'
]
.filter((r) => !r.deleted_at)
.map((r) => (
@@ -560,30 +583,30 @@ export default function OpportunityResources({
</Field>
),
)}
{kind !== "documents" && (
{kind !== 'documents' && (
<label>
<input
key={key}
type="checkbox"
checked={
!!payload[
kind === "images"
? "is_cover"
: "is_primary"
kind === 'images'
? 'is_cover'
: 'is_primary'
]
}
onChange={(event) =>
set(
kind === "images"
? "is_cover"
: "is_primary",
kind === 'images'
? 'is_cover'
: 'is_primary',
event.target.checked,
)
}
/>
{kind === "images"
? "Selecionar capa de preparação"
: "Localização principal"}
{kind === 'images'
? 'Selecionar capa de preparação'
: 'Localização principal'}
</label>
)}
<Field
@@ -610,12 +633,14 @@ export default function OpportunityResources({
</label>
)}
<div className="flex flex-wrap gap-3">
{kind === "images" && editing && !editing.deleted_at && (
{kind === 'images' && editing && !editing.deleted_at && (
<button
type="button"
className={button}
disabled={busy || unavailable || !imageProcessingAvailable}
onClick={() => void execute("prepare")}
disabled={
busy || unavailable || !imageProcessingAvailable
}
onClick={() => void execute('prepare')}
>
Preparar WebP e miniaturas
</button>
@@ -633,13 +658,13 @@ export default function OpportunityResources({
disabled={busy || unavailable}
onClick={() =>
void execute(
editing.deleted_at ? "restore" : "delete",
editing.deleted_at ? 'restore' : 'delete',
)
}
>
{editing.deleted_at
? "Restaurar recurso"
: "Excluir recurso logicamente"}
? 'Restaurar recurso'
: 'Excluir recurso logicamente'}
</button>
)}
</div>
+3 -1
View File
@@ -60,7 +60,9 @@ export function Management({
>
<Link href="/management/interests">Pedidos de interesse</Link>
<Link href="/management/sectors">Sectores</Link>
<Link href="/management/opportunities">Gestão de Oportunidades</Link>
<Link href="/management/opportunities">
Gestão de Oportunidades
</Link>
<Link href="/management/opportunity-origin">
Revisão da origem das oportunidades
</Link>
@@ -0,0 +1,184 @@
import { router } from "@inertiajs/react";
import { useState } from "react";
import { Management, Field, control, button } from "./shared";
type Plan = {
level: number;
expected: number;
resolved: number;
pending: number;
hash: string;
scan_ready: boolean;
source_sha256: string;
rows: {
external_id: string;
name: string;
parent_name: string | null;
location_id: string | null;
status: string;
}[];
};
export default function GeometryImport({ plan }: { plan: Plan }) {
const [reason, setReason] = useState("");
const [confirmed, setConfirmed] = useState(false);
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState("");
const [batch, setBatch] = useState("");
const [applyKey, setApplyKey] = useState(() => crypto.randomUUID());
const [reverseKey, setReverseKey] = useState(() => crypto.randomUUID());
const execute = async (reverse: boolean) => {
setBusy(true);
try {
const cookie = document.cookie
.split("; ")
.find((v) => v.startsWith("XSRF-TOKEN="))
?.slice(11);
const response = await fetch(
`/management/territory-geometry-import${reverse ? `/${batch}/reverse` : ""}`,
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-XSRF-TOKEN": decodeURIComponent(cookie ?? ""),
},
body: JSON.stringify({
level: plan.level,
hash: plan.hash,
reason,
confirm: confirmed,
idempotency_key: reverse ? reverseKey : applyKey,
}),
},
);
const result = await response.json();
if (!response.ok)
throw new Error(
result.message ??
"Operação recusada. Reveja o plano e a autenticação.",
);
if (!reverse) setBatch(result.batch_id);
setMessage(
reverse
? `Revertidas ${result.reversed}; preservadas ${result.reused_preserved} geometrias reutilizadas.`
: `Criadas ${result.inserted}; reutilizadas ${result.reused}; pendentes ${result.pending}. Lote ${result.batch_id}. Nenhuma camada publicada.`,
);
} catch (e) {
setMessage(e instanceof Error ? e.message : "Erro de ligação.");
} finally {
setBusy(false);
}
};
return (
<Management title="Importação cartográfica">
<p>
Exemplar INE de 07/06/2019 aceite. Correspondência exata de nome
e pai; sem alterações de classificações territoriais,
disponibilidade fundiária ou cálculos.
</p>
<Field label="Nível">
<select
className={control}
value={plan.level}
onChange={(e) => {
setBatch("");
setMessage("");
setConfirmed(false);
setApplyKey(crypto.randomUUID());
setReverseKey(crypto.randomUUID());
router.get("/management/territory-geometry-import", {
level: Number(e.target.value),
});
}}
>
<option value={1}>Províncias</option>
<option value={2}>Distritos</option>
<option value={3}>Postos administrativos</option>
</select>
</Field>
<p>
Esperado: {plan.expected}; resolvido: {plan.resolved}; pendente:{" "}
{plan.pending}. Scan:{" "}
{plan.scan_ready ? "limpo e atual" : "pendente ou inconclusivo"}
.
</p>
<p className="break-all">
SHA-256 do original: {plan.source_sha256}
</p>
<div className="overflow-x-auto">
<table>
<thead>
<tr>
<th>Identificador</th>
<th>Nome</th>
<th>Pai</th>
<th>Correspondência</th>
<th>Ação prevista</th>
</tr>
</thead>
<tbody>
{plan.rows.map((r) => (
<tr key={r.external_id}>
<td>{r.external_id}</td>
<td>{r.name}</td>
<td>{r.parent_name ?? "—"}</td>
<td>{r.location_id ?? "Pendente"}</td>
<td>{r.status}</td>
</tr>
))}
</tbody>
</table>
</div>
<Field label="Fundamento da aplicação ou reversão">
<textarea
className={control}
value={reason}
onChange={(e) => setReason(e.target.value)}
minLength={20}
maxLength={1000}
/>
</Field>
<label>
<input
type="checkbox"
checked={confirmed}
onChange={(e) => setConfirmed(e.target.checked)}
/>{" "}
Confirmei as correspondências. A aplicação mantém geometrias
privadas e publicação separada.
</label>
<button
className={button}
disabled={
busy || !confirmed || reason.length < 20 || !plan.scan_ready
}
onClick={() => execute(false)}
>
Aplicar correspondências
</button>
<Field label="Lote a reverter">
<input
className={control}
value={batch}
onChange={(e) => {
setBatch(e.target.value);
setReverseKey(crypto.randomUUID());
}}
/>
</Field>
<button
className={button}
disabled={busy || !confirmed || reason.length < 20 || !batch}
onClick={() => execute(true)}
>
Reverter apenas geometrias criadas pelo lote
</button>
<p role="status">{message}</p>
<p>
A reversão preserva originais, histórico e geometrias
reutilizadas; recusa alterações ou relações posteriores.
Publicação não é realizada nesta página.
</p>
</Management>
);
}