feat: integrate opportunity draft management with audited lifecycle
This commit is contained in:
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user