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

This commit is contained in:
2026-10-10 14:15:28 +02:00
parent 6ddafc95ba
commit 01405cbf8a
144 changed files with 28903 additions and 1103 deletions
+63 -22
View File
@@ -16,6 +16,10 @@ type Entry = {
opportunity_category: string | null;
updated_at: string;
deleted_at: string | null;
can_edit?: boolean;
working_status?: string;
draft_title?: string;
publication?: { scope: string; label: string; public_catalog: boolean };
};
export default function Opportunities({
records,
@@ -24,10 +28,13 @@ export default function Opportunities({
categories,
sectors,
geographyReviewCount,
basePath = '/management/opportunities',
canCreate = true,
}: {
records: Paginated<Entry>;
filters: {
q?: string;
queue?: string;
status?: string;
category?: string;
deleted?: boolean;
@@ -38,9 +45,12 @@ export default function Opportunities({
categories: string[];
sectors: { id: number; name: string }[];
geographyReviewCount: number;
basePath?: string;
canCreate?: boolean;
}) {
const form = useForm({
q: filters.q ?? '',
queue: filters.queue ?? '',
status: filters.status ?? '',
category: filters.category ?? '',
deleted: Boolean(filters.deleted),
@@ -48,10 +58,18 @@ export default function Opportunities({
geography_scope: filters.geography_scope ?? '',
});
return (
<Management title="Gestão de Oportunidades">
<Link className={button} href="/management/opportunities/create">
Nova oportunidade
</Link>
<Management
title={
basePath === '/minhas-oportunidades'
? 'Minhas oportunidades'
: 'Gestão de Oportunidades'
}
>
{canCreate && (
<Link className={button} href={`${basePath}/create`}>
Nova oportunidade
</Link>
)}
<p>
{geographyReviewCount} registos com âmbito por indicar;
referências existentes permanecem aceites.
@@ -72,7 +90,7 @@ export default function Opportunities({
<Link
className="rounded border p-3"
key={s}
href={`/management/opportunities?status=${s}`}
href={`${basePath}?status=${s}`}
>
{states[s] ?? s}: {counts[s] ?? 0}
</Link>
@@ -82,9 +100,31 @@ export default function Opportunities({
className="flex flex-wrap gap-3"
onSubmit={(e) => {
e.preventDefault();
form.get('/management/opportunities');
form.get(basePath);
}}
>
{basePath === '/minhas-oportunidades' && (
<label>
Fila
<select
className={control}
value={form.data.queue}
onChange={(e) =>
form.setData('queue', e.target.value)
}
>
<option value="">Todas as autorizadas</option>
<option value="assigned">Atribuídas a mim</option>
<option value="review">
Validação e pareceres
</option>
<option value="publication">
Preparação editorial
</option>
<option value="appeal">Recursos pendentes</option>
</select>
</label>
)}
<input
aria-label="Pesquisa global"
placeholder="Título ou referência"
@@ -166,7 +206,7 @@ export default function Opportunities({
{records.data.map((r) => (
<article key={r.id} className="rounded border p-4">
<h2 className="font-semibold">
{r.title ?? 'Rascunho sem título'}
{r.draft_title ?? r.title ?? 'Rascunho sem título'}
</h2>
<p>
ID {r.id} · {r.reference} ·{' '}
@@ -174,24 +214,25 @@ export default function Opportunities({
·{' '}
{r.deleted_at
? 'Eliminado logicamente'
: (states[r.status] ?? r.status)}
: (r.working_status ?? r.status) === 'published'
? 'Versão disponibilizada'
: (states[r.working_status ?? r.status] ??
r.working_status ??
r.status)}
</p>
{r.publication && <p>{r.publication.label}</p>}
<p>Atualizado: {r.updated_at}</p>
<div className="flex flex-wrap gap-4">
<Link
href={`/management/opportunities/${r.id}/view`}
>
Ver
</Link>
<Link
href={`/management/opportunities/${r.id}/edit`}
>
{r.deleted_at || r.status === 'archived'
? 'Restaurar'
: r.status === 'draft'
? 'Continuar preenchimento'
: 'Editar nova versão'}
</Link>
<Link href={`${basePath}/${r.id}/view`}>Ver</Link>
{r.can_edit !== false && (
<Link href={`${basePath}/${r.id}/edit`}>
{r.deleted_at || r.status === 'archived'
? 'Restaurar'
: r.status === 'draft'
? 'Continuar preenchimento'
: 'Editar nova versão'}
</Link>
)}
</div>
</article>
))}
@@ -1,12 +1,16 @@
import { Link, router } from '@inertiajs/react';
import OpportunityProfileActions from '@/components/opportunity-profile-actions';
import OpportunityCanonicalFields, {
type CanonicalOptions,
} from '@/components/opportunity-canonical-fields';
import { Link, router, usePage } 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';
type Values = Record<string, string | number | null>;
import { Management, Field, button, control, states } from './shared';
type Values = Record<string, unknown>;
type Entry = {
id: number;
reference: string;
@@ -51,8 +55,74 @@ export default function OpportunityDraft({
occurred_at: string;
}[];
}) {
const {
basePath = '/management/opportunities',
profileMode = false,
profileOrganization,
profileContext,
profileAccess,
profileActions = [],
canonicalOptions,
workflowState,
workflowTasks = [],
workflowParticipants,
publicationPreview,
publicationState,
auth,
canEditDraft = false,
} = usePage<{
basePath?: string;
profileMode?: boolean;
profileOrganization?: string | null;
profileActions?: string[];
profileContext?: Record<string, unknown> | null;
profileAccess?: {
contexts: { organization_id: string | null; type: string }[];
} | null;
publicationPreview?: {
title: string;
summary: string;
description: string;
};
workflowParticipants?: {
publishers: { id: number; name: string }[];
validators: {
id: number;
name: string;
technical: boolean;
legal: boolean;
}[];
};
canonicalOptions?: CanonicalOptions;
workflowState?: string;
publicationState?: {
scope: string;
label: string;
public_catalog: boolean;
};
workflowTasks?: {
id: string;
title: string;
status: string;
assignee_user_id: number | null;
due_at: string | null;
}[];
auth: { user: { id: number } };
canEditDraft?: boolean;
}>().props;
const [data, setData] = useState<Values>({
...values,
...(profileMode
? {
organization_id: record
? (profileOrganization ?? null)
: (profileAccess?.contexts[0]?.organization_id ?? null),
opportunity_category:
values.opportunity_category ??
profileAccess?.contexts[0]?.type ??
'',
}
: {}),
creation_key: crypto.randomUUID(),
});
const [busy, setBusy] = useState(false),
@@ -66,9 +136,10 @@ export default function OpportunityDraft({
const unavailable = Boolean(
record?.deleted_at || record?.status === 'archived',
);
const archiveAvailable = Boolean(usePage().props.opportunityManagement);
const set = (key: string, value: string) =>
setData((d) => ({ ...d, [key]: value }));
async function send(action: 'save' | 'delete' | 'restore') {
async function send(action: 'save' | 'delete' | 'archive' | 'restore') {
if (busy) return;
setBusy(true);
setErrors({});
@@ -80,9 +151,9 @@ export default function OpportunityDraft({
const url =
action === 'save'
? record
? `/management/opportunities/${record.id}/draft`
: '/management/opportunities/drafts'
: `/management/opportunities/${record!.id}/lifecycle`;
? `${basePath}/${record.id}/draft`
: `${basePath}/drafts`
: `${basePath}/${record!.id}/lifecycle`;
const response = await fetch(url, {
method: action === 'save' && record ? 'PUT' : 'POST',
headers: {
@@ -116,8 +187,7 @@ export default function OpportunityDraft({
}
setMessage(result.message);
if (result.etag) setToken(result.etag);
if (!record)
router.visit(`/management/opportunities/${result.id}/edit`);
if (!record) router.visit(`${basePath}/${result.id}/edit`);
else if (action !== 'save') router.reload();
} catch {
setMessage(
@@ -138,7 +208,61 @@ export default function OpportunityDraft({
: 'Nova oportunidade'
}
>
<Link href="/management/opportunities">Voltar à gestão</Link>
<Link href={basePath}>
{profileMode ? 'Minhas oportunidades' : 'Voltar à gestão'}
</Link>
{profileMode && record && readOnly && canEditDraft && (
<Link
className="block underline"
href={`${basePath}/${record.id}/edit`}
>
Editar proposta privada
</Link>
)}
{profileMode && !record && (
<label className="block">
Organização e tipo autorizados
<select
className={control}
value={`${String(data.organization_id ?? '')}|${String(data.opportunity_category ?? '')}`}
onChange={(e) => {
const [organization, type] =
e.target.value.split('|');
setData((d) => ({
...d,
organization_id: organization || null,
opportunity_category: type,
}));
}}
>
{(profileAccess?.contexts ?? []).map((c) => (
<option
key={`${c.organization_id}|${c.type}`}
value={`${c.organization_id ?? ''}|${c.type}`}
>
{c.organization_id ?? 'Âmbito individual'} —{' '}
{c.type}
</option>
))}
</select>
</label>
)}
{profileMode && record && (
<p>
Estado da preparação:{' '}
{(workflowState ?? record.status) === 'published'
? 'Versão disponibilizada'
: (states[workflowState ?? record.status] ??
workflowState ??
record.status)}
. {publicationState?.label}.{' '}
{profileContext?.request_archive
? 'Pedido de arquivo registado; aguarda decisão independente.'
: ''}{' '}
O Promotor solicita arquivo; não elimina nem restaura
oportunidades.
</p>
)}
<p>
Classificação de origem: {classification}. Esta classificação
não cria associações territoriais.
@@ -147,7 +271,8 @@ export default function OpportunityDraft({
<p>
Versão anterior fechada. As alterações são guardadas numa
nova versão de rascunho; a ficha publicada permanece
intacta. Este incremento não submete, aprova ou publica.
intacta. Guardar não submete: use as ações do workflow para
revisão, aprovação e publicação independentes.
</p>
)}
<div
@@ -163,7 +288,7 @@ export default function OpportunityDraft({
<a
target="_blank"
rel="noreferrer"
href={`/management/opportunities/${record?.id}/view`}
href={`${basePath}/${record?.id}/view`}
>
Abrir versão atual
</a>
@@ -177,119 +302,153 @@ export default function OpportunityDraft({
void send('save');
}}
>
<fieldset
disabled={busy || readOnly || unavailable}
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
projetos/clusters.
</p>
{(
[
'province_id',
'district_id',
'admin_post_id',
'locality_id',
] as const
).map((key, index) => (
<TerritoryLevel
key={`${key}-${path[index - 1]?.id ?? ''}`}
index={index}
parent={path[index - 1]?.id ?? ''}
selected={path[index]}
endpoint="/management/territory-options"
fieldError={errors[key]}
onChange={(value) => {
const next = [
...path.slice(0, index),
...(value ? [value] : []),
];
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 ?? '',
}));
}}
{!profileMode && (
<fieldset
disabled={busy || readOnly || unavailable}
className="space-y-4"
>
<section aria-label="Localização registada">
<TerritoryGeometryPreview
territoryId={path.at(-1)?.id}
management
endpoint={
profileMode
? '/minhas-oportunidades/territory-geometries'
: undefined
}
/>
))}
</section>
<Field
label="Categoria"
error={errors.opportunity_category}
>
<select
className={control}
value={String(data.opportunity_category ?? '')}
onChange={(e) =>
set('opportunity_category', e.target.value)
}
>
<option value="">Por indicar</option>
{categories.map((c) => (
<option key={c}>{c}</option>
<p>
Hierarquia do cadastro territorial existente.
Alterar esta seleção não cria relações com
projetos/clusters.
</p>
{(
[
'province_id',
'district_id',
'admin_post_id',
'locality_id',
] as const
).map((key, index) => (
<TerritoryLevel
key={`${key}-${path[index - 1]?.id ?? ''}`}
index={index}
parent={path[index - 1]?.id ?? ''}
selected={path[index]}
endpoint={
profileMode
? '/minhas-oportunidades/territory-options'
: '/management/territory-options'
}
fieldError={errors[key]}
onChange={(value) => {
const next = [
...path.slice(0, index),
...(value ? [value] : []),
];
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 ?? '',
}));
}}
/>
))}
</select>
</Field>
{Object.entries({
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' ? (
<textarea
className={control}
value={String(data[key] ?? '')}
onChange={(e) => set(key, e.target.value)}
/>
) : (
<input
className={control}
value={String(data[key] ?? '')}
onChange={(e) => set(key, e.target.value)}
/>
)}
</section>
<Field
label="Categoria"
error={errors.opportunity_category}
>
<select
className={control}
value={String(data.opportunity_category ?? '')}
onChange={(e) =>
set('opportunity_category', e.target.value)
}
>
<option value="">Por indicar</option>
{categories.map((c) => (
<option key={c}>{c}</option>
))}
</select>
</Field>
))}
<Field label="Sector" error={errors.sector_id}>
<select
className={control}
value={String(data.sector_id ?? '')}
onChange={(e) => set('sector_id', e.target.value)}
{Object.entries({
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' ? (
<textarea
className={control}
value={String(data[key] ?? '')}
onChange={(e) =>
set(key, e.target.value)
}
/>
) : (
<input
className={control}
value={String(data[key] ?? '')}
onChange={(e) =>
set(key, e.target.value)
}
/>
)}
</Field>
))}
<Field label="Sector" error={errors.sector_id}>
<select
className={control}
value={String(data.sector_id ?? '')}
onChange={(e) =>
set('sector_id', e.target.value)
}
>
<option value="">Por indicar</option>
{sectors.map((s) => (
<option key={s.id} value={s.id}>
{s.name}
</option>
))}
</select>
</Field>
<Field
label="Tipo de promotor"
error={errors.promoter_type}
>
<option value="">Por indicar</option>
{sectors.map((s) => (
<option key={s.id} value={s.id}>
{s.name}
</option>
))}
</select>
</Field>
<Field
label="Tipo de promotor"
error={errors.promoter_type}
>
<select
className={control}
value={String(data.promoter_type ?? '')}
onChange={(e) =>
set('promoter_type', e.target.value)
}
>
<option value="">Por indicar</option>
{values.promoter_type &&
![
<select
className={control}
value={String(data.promoter_type ?? '')}
onChange={(e) =>
set('promoter_type', e.target.value)
}
>
<option value="">Por indicar</option>
{Boolean(values.promoter_type) &&
![
'public',
'private',
'ppp',
'cooperative',
'association',
'community',
'other',
].includes(
String(values.promoter_type),
) && (
<option
value={String(values.promoter_type)}
>
{String(values.promoter_type)}{' '}
(valor existente)
</option>
)}
{[
'public',
'private',
'ppp',
@@ -297,174 +456,170 @@ export default function OpportunityDraft({
'association',
'community',
'other',
].includes(String(values.promoter_type)) && (
<option
value={String(values.promoter_type)}
>
{String(values.promoter_type)} (valor
existente)
</option>
)}
{[
'public',
'private',
'ppp',
'cooperative',
'association',
'community',
'other',
].map((c) => (
<option key={c}>{c}</option>
))}
</select>
</Field>
<Field
label="Etapa de maturidade"
error={errors.maturity_stage ?? errors.maturity_level}
>
<select
className={control}
value={
data.maturity_catalogue_version ===
maturityCatalogue.version
? String(data.maturity_stage ?? '')
: data.maturity_level
? `legacy:${data.maturity_level}`
: ''
].map((c) => (
<option key={c}>{c}</option>
))}
</select>
</Field>
<Field
label="Etapa de maturidade"
error={
errors.maturity_stage ?? errors.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>
{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>
<select
className={control}
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>
{Boolean(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>
),
)}
{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"
error={errors.financing_modality}
>
<input
className={control}
value={String(data.financing_modality ?? '')}
onChange={(e) =>
set('financing_modality', e.target.value)
}
/>
</Field>
<Field
label="Impacto esperado"
error={errors.expected_impact}
>
<textarea
className={control}
value={String(data.expected_impact ?? '')}
onChange={(e) =>
set('expected_impact', e.target.value)
}
/>
</Field>
{(data.opportunity_category === 'investment_project' ||
(!data.opportunity_category &&
data.estimated_investment_amount != null)) && (
<>
<Field
label="Investimento estimado"
error={errors.estimated_investment_amount}
>
<input
className={control}
value={String(
data.estimated_investment_amount ?? '',
)}
onChange={(e) =>
set(
'estimated_investment_amount',
e.target.value,
)
}
/>
</Field>
<Field
label="Moeda"
error={errors.estimated_investment_currency}
>
<select
className={control}
value={String(
data.estimated_investment_currency ??
'',
)}
onChange={(e) =>
set(
'estimated_investment_currency',
e.target.value,
)
}
>
<option value="">Por indicar</option>
{['MZN', 'USD', 'EUR', 'ZAR'].map((c) => (
<option key={c}>{c}</option>
))}
</select>
</Field>
</>
)}
{data.opportunity_category &&
data.opportunity_category !== 'investment_project' && (
</select>
<p>
O módulo especializado desta categoria permanece
pendente. Pode guardar a identificação
incompleta; não será submetida nem publicada.
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"
error={errors.financing_modality}
>
<input
className={control}
value={String(data.financing_modality ?? '')}
onChange={(e) =>
set('financing_modality', e.target.value)
}
/>
</Field>
<Field
label="Impacto esperado"
error={errors.expected_impact}
>
<textarea
className={control}
value={String(data.expected_impact ?? '')}
onChange={(e) =>
set('expected_impact', e.target.value)
}
/>
</Field>
{(data.opportunity_category === 'investment_project' ||
(!data.opportunity_category &&
data.estimated_investment_amount != null)) && (
<>
<Field
label="Investimento estimado"
error={errors.estimated_investment_amount}
>
<input
className={control}
value={String(
data.estimated_investment_amount ??
'',
)}
onChange={(e) =>
set(
'estimated_investment_amount',
e.target.value,
)
}
/>
</Field>
<Field
label="Moeda"
error={errors.estimated_investment_currency}
>
<select
className={control}
value={String(
data.estimated_investment_currency ??
'',
)}
onChange={(e) =>
set(
'estimated_investment_currency',
e.target.value,
)
}
>
<option value="">Por indicar</option>
{['MZN', 'USD', 'EUR', 'ZAR'].map(
(c) => (
<option key={c}>{c}</option>
),
)}
</select>
</Field>
</>
)}
</fieldset>
{Boolean(data.opportunity_category) &&
data.opportunity_category !==
'investment_project' && (
<p>
Guarde o rascunho incompleto e complete o
contrato aplicável abaixo. Submissão e
publicação exigem os documentos e as
revisões desta categoria.
</p>
)}
</fieldset>
)}
{!readOnly && (
<>
<Field
@@ -484,7 +639,7 @@ export default function OpportunityDraft({
Guardar rascunho
</button>
)}
{record && (
{record && !profileMode && (
<>
<label className="block">
<input
@@ -497,7 +652,7 @@ export default function OpportunityDraft({
Confirmo a{' '}
{unavailable
? 'restauração'
: 'exclusão lógica/arquivo'}
: 'operação indicada, preservando o registo'}
, preservando histórico e relações
</label>
<button
@@ -506,16 +661,32 @@ export default function OpportunityDraft({
disabled={busy || !confirm}
onClick={() =>
void send(
unavailable ? 'restore' : 'delete',
unavailable
? 'restore'
: archiveAvailable
? 'archive'
: 'delete',
)
}
>
{unavailable
? 'Restaurar'
: closedVersion
: archiveAvailable || closedVersion
? 'Arquivar'
: 'Excluir rascunho'}
</button>
{archiveAvailable &&
!unavailable &&
!closedVersion && (
<button
type="button"
className={button}
disabled={busy || !confirm}
onClick={() => void send('delete')}
>
Excluir rascunho
</button>
)}
</>
)}
</>
@@ -525,7 +696,7 @@ export default function OpportunityDraft({
<Link
href={
resourcesInstalled
? `/management/opportunities/${record.id}/resources`
? `${basePath}/${record.id}/resources`
: '/management/opportunity-resources-install'
}
>
@@ -534,11 +705,131 @@ export default function OpportunityDraft({
: 'Plano de ativação de imagens, documentos e localizações'}
</Link>
)}
{record && (
<Link href={`/management/opportunities/${record.id}/context`}>
{record && !profileMode && (
<Link href={`${basePath}/${record.id}/context`}>
Consultar projetos, clusters e relações existentes
</Link>
)}
{profileMode && canonicalOptions && (
<section>
<OpportunityCanonicalFields
value={
(data.canonical ?? {}) as Record<string, unknown>
}
onChange={(v) =>
setData((d) => ({ ...d, canonical: v }))
}
options={canonicalOptions}
errors={errors}
category={String(data.opportunity_category ?? '')}
organization={
(data.organization_id ?? null) as string | null
}
actorId={auth.user.id}
sectors={sectors}
disabled={busy || readOnly || unavailable}
/>
{!readOnly && !unavailable && (
<button
type="button"
className={button}
disabled={busy}
onClick={() => void send('save')}
>
Guardar contrato no rascunho
</button>
)}
{Object.entries(errors)
.filter(([key]) => key.startsWith('canonical'))
.map(([key, msg]) => (
<p key={key} role="alert">
{key}: {msg}
</p>
))}
</section>
)}
{profileMode && record && profileActions.includes('publish') && (
<section className="rounded border p-3">
<h2>Pré-visualização da publicação</h2>
<p>
Âmbito solicitado:{' '}
{(data.canonical as Record<string, unknown> | undefined)
?.visibility === 'public'
? 'Catálogo público, após ação do Publicador'
: 'Acesso restrito aos perfis e à organização autorizados'}
</p>
<h3>{publicationPreview?.title}</h3>
<p>{publicationPreview?.summary}</p>
<p>{publicationPreview?.description}</p>
<p>
A ficha partilha apenas título, resumo, proposta, sector
e território. Contactos, avaliações, evidências e
originais conservam o acesso restrito.
</p>
</section>
)}
{profileMode && record && etag && (
<OpportunityProfileActions
participants={workflowParticipants?.validators}
publishers={workflowParticipants?.publishers}
opinions={Object.values(
(profileContext?.opinions ?? {}) as Record<
string,
{
id: string;
gate: string;
recipient_id: number;
status: string;
}
>,
)}
onErrors={setErrors}
id={record.id}
etag={token ?? etag}
actions={profileActions}
publicationVisibility={String(
(data.canonical as Record<string, unknown> | undefined)
?.visibility ?? 'internal',
)}
gates={canonicalOptions?.gates ?? []}
documents={(
canonicalOptions?.resources.documents ?? []
).map((d) => ({
id: d.id,
title: d.payload.title ?? d.file?.file_name ?? d.id,
}))}
approvalHash={
(
profileContext?.approval as
| { hash?: string }
| undefined
)?.hash
}
/>
)}
{profileMode && record && (
<section className="space-y-2 rounded border p-3">
<h2>
Acompanhamento interno —{' '}
{(workflowState ?? record.status) === 'published'
? 'Versão disponibilizada'
: (states[workflowState ?? record.status] ??
workflowState ??
record.status)}
</h2>
<p>
SLA: sem política/prazo aprovado; as tarefas podem ser
preparadas em paralelo.
</p>
{workflowTasks.map((t) => (
<p key={t.id}>
{t.title} — {t.status}; responsável:{' '}
{t.assignee_user_id ?? 'por atribuir'}; prazo:{' '}
{t.due_at ?? 'não definido'}
</p>
))}
</section>
)}
<section aria-label="Histórico de gestão">
<h2>Histórico</h2>
{history.length ? (
@@ -1,4 +1,4 @@
import { Link, router } from '@inertiajs/react';
import { Link, router, usePage } from '@inertiajs/react';
import TerritoryGeometryPreview from '@/components/territory-geometry-preview';
import { useState } from 'react';
import {
@@ -144,9 +144,10 @@ export default function OpportunityResources({
assessment: string[];
imageProcessingAvailable: boolean;
}) {
const { basePath = '/management/opportunities', readOnly = false, countries = [] } = usePage<{basePath?: string; readOnly?: boolean; countries?: {code:string;name:string}[]}>().props;
const [kind, setKind] = useState<Kind>('locations');
const [editing, setEditing] = useState<Resource | null>(null);
const [payload, setPayload] = useState<Payload>({});
const [payload, setPayload] = useState<Payload>({country_code:'MZ'});
const [path, setPath] = useState<TerritoryOption[]>([]);
const [geometry, setGeometry] = useState('');
const [file, setFile] = useState<File | null>(null);
@@ -161,7 +162,7 @@ export default function OpportunityResources({
function select(nextKind: Kind, record: Resource | null = null) {
setKind(nextKind);
setEditing(record);
setPayload(record?.payload ?? {});
setPayload(record?.payload ?? (nextKind === 'locations' ? {country_code:'MZ'} : {}));
setPath(record?.territoryPath ?? []);
setGeometry(
record?.payload.geometry
@@ -174,7 +175,7 @@ export default function OpportunityResources({
setErrors({});
}
async function execute(action: 'save' | 'delete' | 'restore' | 'prepare') {
if (busy) return;
if (busy || readOnly) return;
setBusy(true);
setErrors({});
setMessage('');
@@ -204,7 +205,7 @@ export default function OpportunityResources({
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 = `${basePath}/${opportunity.id}/resources/${kind}${editing ? `/${editing.id}` : ''}${action === 'save' ? '' : action === 'prepare' ? '/prepare' : '/lifecycle'}`;
const csrf =
document.cookie
.split('; ')
@@ -266,7 +267,7 @@ export default function OpportunityResources({
!!opportunity.deleted_at || opportunity.status === 'archived';
return (
<Management title="Imagens, documentos e localizações">
<Link href={`/management/opportunities/${opportunity.id}/edit`}>
<Link href={`${basePath}/${opportunity.id}/edit`}>
Regressar ao rascunho #{opportunity.id}
</Link>
<p>
@@ -327,7 +328,7 @@ export default function OpportunityResources({
<button
className={button}
key={k}
disabled={busy}
disabled={busy || readOnly}
onClick={() => select(k)}
>
{k === 'locations'
@@ -388,7 +389,7 @@ export default function OpportunityResources({
{r.file?.malware_scan_status === 'clean' &&
!r.deleted_at && (
<a
href={`/management/opportunities/${opportunity.id}/resources/${kind}/${r.id}/download`}
href={`${basePath}/${opportunity.id}/resources/${kind}/${r.id}/download`}
>
Consultar original autorizado
</a>
@@ -410,9 +411,12 @@ export default function OpportunityResources({
</h2>
{kind === 'locations' && (
<div>
<Field label="País da localização" error={errors.country_code}><select className={control} disabled={readOnly} value={String(payload.country_code ?? '')} onChange={e=>set('country_code',e.target.value)}><option value="">Por indicar</option>{countries.map(c=><option key={c.code} value={c.code}>{c.name}</option>)}</select></Field>
{payload.country_code !== 'MZ' && <p>A hierarquia abaixo corresponde a Moçambique. Uma localização noutro país requer o seu próprio cadastro; não use territórios moçambicanos para a representar.</p>}
<TerritoryGeometryPreview
territoryId={path.at(-1)?.id}
management
endpoint={basePath === '/minhas-oportunidades' ? '/minhas-oportunidades/territory-geometries' : undefined}
/>
{[0, 1, 2, 3].map((index) => (
<TerritoryLevel
@@ -420,6 +424,7 @@ export default function OpportunityResources({
index={index}
parent={path[index - 1]?.id ?? ''}
selected={path[index]}
endpoint={basePath === '/minhas-oportunidades' ? '/minhas-oportunidades/territory-options' : '/management/territory-options'}
onChange={(value) =>
setPath((previous) =>
value
@@ -638,7 +643,7 @@ export default function OpportunityResources({
type="button"
className={button}
disabled={
busy || unavailable || !imageProcessingAvailable
busy || readOnly || unavailable || !imageProcessingAvailable
}
onClick={() => void execute('prepare')}
>
@@ -647,7 +652,7 @@ export default function OpportunityResources({
)}
<button
className={button}
disabled={busy || unavailable || !!editing?.deleted_at}
disabled={busy || readOnly || unavailable || !!editing?.deleted_at}
>
Guardar recurso
</button>
@@ -655,7 +660,7 @@ export default function OpportunityResources({
<button
type="button"
className={button}
disabled={busy || unavailable}
disabled={busy || readOnly || unavailable}
onClick={() =>
void execute(
editing.deleted_at ? 'restore' : 'delete',
+6 -3
View File
@@ -1,3 +1,4 @@
import ProfileNavigation from '@/components/profile-navigation';
import { Head, Link, usePage } from '@inertiajs/react';
import type { ReactNode } from 'react';
import { cloneElement, isValidElement, useId } from 'react';
@@ -46,7 +47,9 @@ export function Management({
title: string;
children: ReactNode;
}) {
const { flash, educationEnabled, aiEnabled } = usePage<{
const { flash, educationEnabled, aiEnabled, auth, basePath } = usePage<{
auth?: {canManagePortal?: boolean};
basePath?: string;
flash?: { success?: string };
educationEnabled?: boolean;
aiEnabled?: boolean;
@@ -54,7 +57,7 @@ export function Management({
return (
<main className="space-y-6 p-4 md:p-8">
<Head title={title} />
<nav
{auth?.canManagePortal && basePath !== '/minhas-oportunidades' ? <nav
className="flex flex-wrap gap-4 text-sm underline"
aria-label="Gestão do portal"
>
@@ -102,7 +105,7 @@ export function Management({
Referências e formulários
</Link>
<a href="/">Portal público</a>
</nav>
</nav> : <ProfileNavigation />}
<h1 className="text-2xl font-semibold break-words">{title}</h1>
{flash?.success && (
<p
@@ -10,12 +10,14 @@ type Plan = {
hash: string;
scan_ready: boolean;
source_sha256: string;
correspondence_version: string;
rows: {
external_id: string;
name: string;
parent_name: string | null;
location_id: string | null;
status: string;
correspondence: { target_name: string; target_source_code: string; basis: string } | null;
}[];
};
export default function GeometryImport({ plan }: { plan: Plan }) {
@@ -73,7 +75,8 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
<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,
e pai, ou correspondência explícita fundamentada abaixo;
sem alterações de classificações territoriais,
disponibilidade fundiária ou cálculos.
</p>
<Field label="Nível">
@@ -105,6 +108,12 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
<p className="break-all">
SHA-256 do original: {plan.source_sha256}
</p>
<p>Versão das correspondências: {plan.correspondence_version}.</p>
<button className={button} disabled={busy} onClick={() => {
setApplyKey(crypto.randomUUID());
setConfirmed(false);
router.reload({ only: ["plan"] });
}}>Atualizar pré-visualização</button>
<div className="overflow-x-auto">
<table>
<thead>
@@ -113,6 +122,7 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
<th>Nome</th>
<th>Pai</th>
<th>Correspondência</th>
<th>Fundamento</th>
<th>Ação prevista</th>
</tr>
</thead>
@@ -123,6 +133,10 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
<td>{r.name}</td>
<td>{r.parent_name ?? "—"}</td>
<td>{r.location_id ?? "Pendente"}</td>
<td>{r.correspondence ? <>
{r.correspondence.target_name} (código {r.correspondence.target_source_code})
<p>{r.correspondence.basis}</p>
</> : "Nome único sob o pai correspondido"}</td>
<td>{r.status}</td>
</tr>
))}