feat: integrate opportunity draft management with audited lifecycle

This commit is contained in:
2026-10-09 08:16:51 +02:00
parent ebfc188240
commit 7ecfe3d543
20 changed files with 1459 additions and 22 deletions
+5 -1
View File
@@ -52,7 +52,11 @@ export default function Dashboard({ summary }: { summary: Summary | null }) {
</div>
</section>
<section className="space-y-4">
<h2 className="text-lg font-semibold">Catálogo</h2>
<h2 className="text-lg font-semibold">
<Link href="/management/opportunities">
Gestão de Oportunidades
</Link>
</h2>
<div className="grid gap-4 sm:grid-cols-3">
{[
{
@@ -0,0 +1,203 @@
import { Link, useForm } from '@inertiajs/react';
import {
Management,
Pagination,
button,
control,
states,
type Paginated,
} from './shared';
type Entry = {
id: number;
reference: string;
title: string | null;
status: string;
opportunity_category: string | null;
updated_at: string;
deleted_at: string | null;
};
export default function Opportunities({
records,
filters,
counts,
categories,
sectors,
geographyReviewCount,
}: {
records: Paginated<Entry>;
filters: {
q?: string;
status?: string;
category?: string;
deleted?: boolean;
sector_id?: string;
geography_scope?: string;
};
counts: Record<string, number>;
categories: string[];
sectors: { id: number; name: string }[];
geographyReviewCount: number;
}) {
const form = useForm({
q: filters.q ?? '',
status: filters.status ?? '',
category: filters.category ?? '',
deleted: Boolean(filters.deleted),
sector_id: String(filters.sector_id ?? ''),
geography_scope: filters.geography_scope ?? '',
});
return (
<Management title="Gestão de Oportunidades">
<Link className={button} href="/management/opportunities/create">
Nova oportunidade
</Link>
<p>
{geographyReviewCount} registos com âmbito por indicar;
referências existentes permanecem aceites.
</p>
<section
aria-label="Indicadores autorizados"
className="grid gap-3 sm:grid-cols-3"
>
{[
'draft',
'submitted',
'returned',
'approved',
'published',
'suspended',
'archived',
].map((s) => (
<Link
className="rounded border p-3"
key={s}
href={`/management/opportunities?status=${s}`}
>
{states[s] ?? s}: {counts[s] ?? 0}
</Link>
))}
</section>
<form
className="flex flex-wrap gap-3"
onSubmit={(e) => {
e.preventDefault();
form.get('/management/opportunities');
}}
>
<input
aria-label="Pesquisa global"
placeholder="Título ou referência"
className={control}
value={form.data.q}
onChange={(e) => form.setData('q', e.target.value)}
/>
<select
aria-label="Estado"
className={control}
value={form.data.status}
onChange={(e) => form.setData('status', e.target.value)}
>
<option value="">Todos os estados</option>
{Object.keys(counts).map((s) => (
<option key={s} value={s}>
{states[s] ?? s}
</option>
))}
</select>
<select
aria-label="Categoria"
className={control}
value={form.data.category}
onChange={(e) => form.setData('category', e.target.value)}
>
<option value="">Todas as categorias</option>
{categories.map((s) => (
<option key={s}>{s}</option>
))}
</select>
<label>
<input
type="checkbox"
checked={form.data.deleted}
onChange={(e) =>
form.setData('deleted', e.target.checked)
}
/>{' '}
Rascunhos eliminados logicamente
</label>
<select
aria-label="Sector"
className={control}
value={form.data.sector_id}
onChange={(e) => form.setData('sector_id', e.target.value)}
>
<option value="">Todos os sectores</option>
{sectors.map((s) => (
<option key={s.id} value={s.id}>
{s.name}
</option>
))}
</select>
<select
aria-label="Âmbito geográfico"
className={control}
value={form.data.geography_scope}
onChange={(e) =>
form.setData('geography_scope', e.target.value)
}
>
<option value="">Todos os âmbitos</option>
{[
'unspecified',
'specific',
'multiple',
'national',
'digital',
].map((s) => (
<option key={s}>{s}</option>
))}
</select>
<button className={button} disabled={form.processing}>
Pesquisar
</button>
</form>
<div className="space-y-3">
{records.data.map((r) => (
<article key={r.id} className="rounded border p-4">
<h2 className="font-semibold">
{r.title ?? 'Rascunho sem título'}
</h2>
<p>
ID {r.id} · {r.reference} ·{' '}
{r.opportunity_category ?? 'Categoria por indicar'}{' '}
·{' '}
{r.deleted_at
? 'Eliminado logicamente'
: (states[r.status] ?? r.status)}
</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>
</div>
</article>
))}
</div>
{!records.data.length && <p>Nenhum registo encontrado.</p>}
<Pagination page={records} />
</Management>
);
}
@@ -0,0 +1,488 @@
import { Link, router } from '@inertiajs/react';
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>;
type Entry = {
id: number;
reference: string;
status: string;
deleted_at: string | null;
management_version: number;
};
export default function OpportunityDraft({
record,
values,
etag,
readOnly,
closedVersion,
classification,
sectors,
categories,
history,
territoryPath,
}: {
record: Entry | null;
values: Values;
etag: string | null;
readOnly: boolean;
closedVersion: boolean;
classification: string;
sectors: { id: number; name: string }[];
categories: string[];
territoryPath: TerritoryOption[];
history: {
id: string;
action: string;
actor_user_id: number;
occurred_at: string;
}[];
}) {
const [data, setData] = useState<Values>({
...values,
creation_key: crypto.randomUUID(),
});
const [busy, setBusy] = useState(false),
[errors, setErrors] = useState<Record<string, string>>({}),
[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',
);
const set = (key: string, value: string) =>
setData((d) => ({ ...d, [key]: value }));
async function send(action: 'save' | 'delete' | 'restore') {
if (busy) return;
setBusy(true);
setErrors({});
setMessage('');
try {
const cookie = document.cookie
.split('; ')
.find((c) => c.startsWith('XSRF-TOKEN='));
const url =
action === 'save'
? record
? `/management/opportunities/${record.id}/draft`
: '/management/opportunities/drafts'
: `/management/opportunities/${record!.id}/lifecycle`;
const response = await fetch(url, {
method: action === 'save' && record ? 'PUT' : 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': cookie
? decodeURIComponent(cookie.slice(11))
: '',
},
body: JSON.stringify(
action === 'save'
? { ...data, etag: token, reason }
: { etag: token, action, reason, confirm },
),
});
const result = await response.json();
if (!response.ok) {
setErrors(
Object.fromEntries(
Object.entries(result.errors ?? {}).map(([k, v]) => [
k,
Array.isArray(v) ? v.join(' ') : String(v),
]),
),
);
setMessage(
result.message ??
'Operação falhou; os dados preenchidos foram preservados.',
);
return;
}
setMessage(result.message);
if (result.etag) setToken(result.etag);
if (!record)
router.visit(`/management/opportunities/${result.id}/edit`);
else if (action !== 'save') router.reload();
} catch {
setMessage(
'Resposta indisponível. Os dados foram preservados; confira o registo no servidor antes de repetir.',
);
} finally {
setBusy(false);
requestAnimationFrame(() =>
document.getElementById('opportunity-result')?.focus(),
);
}
}
return (
<Management
title={
record
? `${readOnly ? 'Ver' : 'Editar'} oportunidade ${record.reference}`
: 'Nova oportunidade'
}
>
<Link href="/management/opportunities">Voltar à gestão</Link>
<p>
Classificação de origem: {classification}. Esta classificação
não cria associações territoriais.
</p>
{closedVersion && (
<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.
</p>
)}
<div
id="opportunity-result"
tabIndex={-1}
role={Object.keys(errors).length ? 'alert' : 'status'}
className="rounded border p-3"
>
{message}
{errors.etag && (
<p>
{errors.etag}{' '}
<a
target="_blank"
rel="noreferrer"
href={`/management/opportunities/${record?.id}/view`}
>
Abrir versão atual
</a>
</p>
)}
</div>
<form
className="max-w-3xl space-y-4"
onSubmit={(e) => {
e.preventDefault();
void send('save');
}}
>
<fieldset
disabled={busy || readOnly || unavailable}
className="space-y-4"
>
<section aria-label="Localização registada">
<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 ?? '',
}));
}}
/>
))}
</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>
{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}
>
<select
className={control}
value={String(data.promoter_type ?? '')}
onChange={(e) =>
set('promoter_type', e.target.value)
}
>
<option value="">Por indicar</option>
{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',
'cooperative',
'association',
'community',
'other',
].map((c) => (
<option key={c}>{c}</option>
))}
</select>
</Field>
<Field
label="Maturidade existente"
error={errors.maturity_level}
>
<select
className={control}
value={String(data.maturity_level ?? '')}
onChange={(e) =>
set('maturity_level', e.target.value)
}
>
<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>
))}
</select>
</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' && (
<p>
O módulo especializado desta categoria permanece
pendente. Pode guardar a identificação
incompleta; não será submetida nem publicada.
</p>
)}
</fieldset>
{!readOnly && (
<>
<Field
label="Motivo da alteração"
error={errors.reason}
>
<textarea
className={control}
value={reason}
onChange={(e) => setReason(e.target.value)}
minLength={20}
maxLength={1000}
/>
</Field>
{!unavailable && (
<button className={button} disabled={busy}>
Guardar rascunho
</button>
)}
{record && (
<>
<label className="block">
<input
type="checkbox"
checked={confirm}
onChange={(e) =>
setConfirm(e.target.checked)
}
/>{' '}
Confirmo a{' '}
{unavailable
? 'restauração'
: 'exclusão lógica/arquivo'}
, preservando histórico e relações
</label>
<button
type="button"
className={button}
disabled={busy || !confirm}
onClick={() =>
void send(
unavailable ? 'restore' : 'delete',
)
}
>
{unavailable
? 'Restaurar'
: closedVersion
? 'Arquivar'
: 'Excluir rascunho'}
</button>
</>
)}
</>
)}
</form>
{record && (
<Link href={`/management/opportunities/${record.id}/context`}>
Consultar projetos, clusters e relações existentes
</Link>
)}
<section aria-label="Histórico de gestão">
<h2>Histórico</h2>
{history.length ? (
history.map((e) => (
<p key={e.id}>
{e.action} · conta {e.actor_user_id} ·{' '}
{e.occurred_at}
</p>
))
) : (
<p>Sem eventos deste incremento.</p>
)}
</section>
</Management>
);
}
@@ -0,0 +1,84 @@
import { useForm } from '@inertiajs/react';
import { Management, button } from './shared';
export default function Install({
installed,
ready,
target,
hash,
changes,
migration,
backupDate,
rollback,
}: {
installed: boolean;
ready: boolean;
target: { database: string; port: number };
hash: string;
changes: string[];
migration: string;
backupDate: string | null;
rollback: string;
}) {
const form = useForm({ hash, confirm: false });
return (
<Management title="Ativação da Gestão de Oportunidades">
<p>
Base: {target.database}:{target.port} ·{' '}
{installed ? 'Instalado' : 'Ainda não aplicado'}
</p>
<ul>
{changes.map((c) => (
<li key={c}>{c}</li>
))}
</ul>
<p>Migração: {migration}</p>
<p>Backup/restauro: {backupDate ?? 'Prova ainda por preparar'}</p>
<p>{rollback}</p>
<p>
Este plano ativa apenas o primeiro incremento; workflow
completo, imagens e módulos especializados permanecem no
backlog.
</p>
<form
onSubmit={(e) => {
e.preventDefault();
form.post('/management/opportunity-management-install');
}}
>
<label>
<input
type="checkbox"
checked={form.data.confirm}
onChange={(e) =>
form.setData('confirm', e.target.checked)
}
/>{' '}
Confirmo a aplicação deste plano
</label>
<button
className={button}
disabled={
installed ||
!ready ||
!form.data.confirm ||
form.processing
}
>
Aplicar plano de gestão
</button>
{!ready && (
<p>
Aplicação indisponível até comprovar QA,
backup/restauro, compatibilidade e reversão da versão
atual.
</p>
)}
{Object.values(form.errors).map((e) => (
<p role="alert" key={e}>
{e}
</p>
))}
</form>
</Management>
);
}
+4 -1
View File
@@ -34,6 +34,9 @@ export const states: Record<string, string> = {
draft: 'Rascunho',
published: 'Publicado',
archived: 'Arquivado',
returned: 'Devolvida',
approved: 'Aprovada internamente',
suspended: 'Suspensa',
};
export function Management({
@@ -57,7 +60,7 @@ export function Management({
>
<Link href="/management/interests">Pedidos de interesse</Link>
<Link href="/management/sectors">Sectores</Link>
<Link href="/management/opportunities">Oportunidades</Link>
<Link href="/management/opportunities">Gestão de Oportunidades</Link>
<Link href="/management/opportunity-origin">
Revisão da origem das oportunidades
</Link>