Preserve published territories during private editorial review
This commit is contained in:
@@ -42,6 +42,7 @@ export default function EditorialWorkflow({
|
||||
portfolioPending = 0,
|
||||
demographyUrl,
|
||||
demographyPending = 0,
|
||||
territorialUrl,
|
||||
}: {
|
||||
resourceAccess: boolean;
|
||||
opportunitiesUrl: string | null;
|
||||
@@ -51,6 +52,7 @@ export default function EditorialWorkflow({
|
||||
portfolioPending?: number;
|
||||
demographyUrl?: string | null;
|
||||
demographyPending?: number;
|
||||
territorialUrl?: string | null;
|
||||
filters?: { state?: string; kind?: string };
|
||||
items: { data: Item[]; current_page: number; last_page: number };
|
||||
notices: {
|
||||
@@ -76,6 +78,11 @@ export default function EditorialWorkflow({
|
||||
Demografia: {demographyPending} lotes pendentes
|
||||
</Link>
|
||||
)}
|
||||
{territorialUrl && (
|
||||
<Link className="underline" href={territorialUrl}>
|
||||
Conteúdos territoriais
|
||||
</Link>
|
||||
)}
|
||||
{portfolioUrl && (
|
||||
<Link className="underline" href={portfolioUrl}>
|
||||
Carteira: {portfolioPending} fichas pendentes
|
||||
|
||||
@@ -0,0 +1,493 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { portalRequest, PortalApiError } from '@/lib/portal-api';
|
||||
import { Field, Management, button, control } from './shared';
|
||||
|
||||
type Row = {
|
||||
id: string;
|
||||
name: string;
|
||||
code: string;
|
||||
status: string;
|
||||
version_no: number;
|
||||
private_revision?: boolean;
|
||||
public_version_no?: number | null;
|
||||
};
|
||||
type State = {
|
||||
location: {
|
||||
id: string;
|
||||
name: string;
|
||||
code: string;
|
||||
location_type: string;
|
||||
parent_id: string | null;
|
||||
version_no: number;
|
||||
};
|
||||
profile: {
|
||||
source_id: string;
|
||||
valid_from: string;
|
||||
valid_to: string | null;
|
||||
status: string;
|
||||
editor_id: string;
|
||||
reviewer_id: string | null;
|
||||
};
|
||||
fresh: boolean;
|
||||
baseline_changed: boolean;
|
||||
public_version_no: number | null;
|
||||
_editorial?: { private: boolean; contributors?: string[] };
|
||||
};
|
||||
type Preview = {
|
||||
working: State;
|
||||
public: State;
|
||||
history: {
|
||||
id: string;
|
||||
version_no: number;
|
||||
reason: string;
|
||||
snapshot: State;
|
||||
}[];
|
||||
};
|
||||
const titles: Record<string, string> = {
|
||||
draft: 'Rascunho',
|
||||
pending_review: 'Submetido',
|
||||
in_review: 'Em revisão',
|
||||
approved: 'Aprovado',
|
||||
published: 'Publicado',
|
||||
rejected: 'Devolvido com fundamento',
|
||||
archived: 'Arquivado',
|
||||
};
|
||||
|
||||
export default function TerritorialEditorial({
|
||||
roles,
|
||||
actorId,
|
||||
}: {
|
||||
roles: string[];
|
||||
actorId: string;
|
||||
}) {
|
||||
const [rows, setRows] = useState<Row[]>([]);
|
||||
const [next, setNext] = useState<string | null>(null);
|
||||
const [preview, setPreview] = useState<Preview | null>(null);
|
||||
const [form, setForm] = useState({
|
||||
name: '',
|
||||
code: '',
|
||||
source_id: '',
|
||||
valid_from: '',
|
||||
valid_to: '',
|
||||
reason: '',
|
||||
confirm_baseline_change: false,
|
||||
});
|
||||
const [sources, setSources] = useState<
|
||||
{ id: string; name: string; source_version: string }[]
|
||||
>([]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [errors, setErrors] = useState<Record<string, string[]>>({});
|
||||
const fail = (error: unknown) => {
|
||||
setErrors(error instanceof PortalApiError ? error.errors : {});
|
||||
setMessage(
|
||||
error instanceof PortalApiError && error.status === 409
|
||||
? 'A versão, fonte ou autoridade mudou. Consulte o estado guardado antes de continuar.'
|
||||
: error instanceof PortalApiError && error.status === 403
|
||||
? 'Confirme a sua função e renove o MFA na sessão habitual. Os dados guardados mantêm-se.'
|
||||
: error instanceof Error
|
||||
? error.message
|
||||
: 'Operação não confirmada. Consulte o estado guardado antes de repetir.',
|
||||
);
|
||||
};
|
||||
const list = async (
|
||||
url = '/api/v1/geo/drafts?limit=30',
|
||||
append = false,
|
||||
) => {
|
||||
const data = await portalRequest<{
|
||||
data: Row[];
|
||||
next_page_url: string | null;
|
||||
}>(url);
|
||||
setRows((current) => (append ? [...current, ...data.data] : data.data));
|
||||
setNext(data.next_page_url);
|
||||
};
|
||||
useEffect(() => {
|
||||
void Promise.all([
|
||||
list(),
|
||||
portalRequest<{ data: typeof sources }>(
|
||||
'/api/v1/geo/sources?limit=100',
|
||||
).then((data) => setSources(data.data)),
|
||||
]).catch(fail);
|
||||
}, []);
|
||||
const open = async (id: string) => {
|
||||
setBusy(true);
|
||||
setMessage('');
|
||||
setErrors({});
|
||||
try {
|
||||
const data = await portalRequest<Preview>(
|
||||
`/api/v1/geo/drafts/${id}`,
|
||||
);
|
||||
setPreview(data);
|
||||
const { location, profile } = data.working;
|
||||
setForm({
|
||||
name: location.name,
|
||||
code: location.code,
|
||||
source_id: profile.source_id,
|
||||
valid_from: profile.valid_from,
|
||||
valid_to: profile.valid_to ?? '',
|
||||
reason: '',
|
||||
confirm_baseline_change: false,
|
||||
});
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const write = async (action?: string) => {
|
||||
if (!preview) return;
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
setMessage('');
|
||||
const { location } = preview.working;
|
||||
try {
|
||||
await portalRequest(
|
||||
`/api/v1/geo/territories/${location.id}${action ? '/transitions' : ''}`,
|
||||
{
|
||||
method: action ? 'POST' : 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Idempotency-Key': crypto.randomUUID(),
|
||||
},
|
||||
body: JSON.stringify(
|
||||
action
|
||||
? {
|
||||
action,
|
||||
version_no: location.version_no,
|
||||
reason: form.reason,
|
||||
}
|
||||
: {
|
||||
...form,
|
||||
valid_to: form.valid_to || null,
|
||||
location_type: location.location_type,
|
||||
parent_id: location.parent_id,
|
||||
version_no: location.version_no,
|
||||
},
|
||||
),
|
||||
},
|
||||
);
|
||||
await open(location.id);
|
||||
await list();
|
||||
setMessage(
|
||||
action === 'published'
|
||||
? 'Versão publicada.'
|
||||
: action === 'withdrawn'
|
||||
? 'Publicação retirada; proposta privada preservada.'
|
||||
: 'Operação guardada.',
|
||||
);
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const state = preview?.working;
|
||||
const changed = Boolean(
|
||||
state &&
|
||||
(form.name !== state.location.name ||
|
||||
form.code !== state.location.code ||
|
||||
form.source_id !== state.profile.source_id ||
|
||||
form.valid_from !== state.profile.valid_from ||
|
||||
form.valid_to !== (state.profile.valid_to ?? '')),
|
||||
);
|
||||
const contributor = state?._editorial?.contributors?.includes(actorId);
|
||||
const canReview = roles.includes('reviewers') && !contributor;
|
||||
const canPublish =
|
||||
roles.includes('publishers') &&
|
||||
!contributor &&
|
||||
state?.profile.reviewer_id !== actorId;
|
||||
const actionButton = (action: string, title: string, allowed: boolean) =>
|
||||
allowed && (
|
||||
<button
|
||||
key={action}
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
busy ||
|
||||
form.reason.trim().length < 10 ||
|
||||
Boolean(action && changed)
|
||||
}
|
||||
onClick={() => void write(action)}
|
||||
>
|
||||
{title}
|
||||
</button>
|
||||
);
|
||||
return (
|
||||
<Management title="Revisão dos conteúdos territoriais">
|
||||
<Link href="/management/editorial" className="underline">
|
||||
Circuito editorial
|
||||
</Link>
|
||||
<p>
|
||||
Edite e reveja uma proposta privada. A versão pública mantém-se
|
||||
até à publicação expressa.
|
||||
</p>
|
||||
{message && <p role="status">{message}</p>}
|
||||
<ul className="space-y-2">
|
||||
{rows.map((row) => (
|
||||
<li key={row.id}>
|
||||
<button
|
||||
className="text-left underline"
|
||||
disabled={busy || changed}
|
||||
onClick={() => void open(row.id)}
|
||||
>
|
||||
{row.name} · {titles[row.status] ?? row.status} ·
|
||||
versão {row.version_no}
|
||||
{row.private_revision ? ' · proposta privada' : ''}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{next && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
setBusy(true);
|
||||
void list(next, true)
|
||||
.catch(fail)
|
||||
.finally(() => setBusy(false));
|
||||
}}
|
||||
>
|
||||
Ver seguintes
|
||||
</button>
|
||||
)}
|
||||
{state && preview && (
|
||||
<section
|
||||
className="space-y-4 rounded-lg border p-4"
|
||||
aria-label="Proposta territorial"
|
||||
>
|
||||
<h2 className="text-xl font-semibold">
|
||||
{state.location.name} —{' '}
|
||||
{titles[state.profile.status] ?? state.profile.status}
|
||||
</h2>
|
||||
<p>
|
||||
Versão pública:{' '}
|
||||
{state.public_version_no ?? 'sem publicação'} ·
|
||||
proposta: {state.location.version_no}. Publicação
|
||||
actual: {preview.public.location.name} (
|
||||
{titles[preview.public.profile.status]}).
|
||||
</p>
|
||||
{!state.fresh && (
|
||||
<p role="alert">
|
||||
O contexto foi alterado. Compare a publicação actual
|
||||
e reveja os dados antes de guardar e pedir nova
|
||||
aprovação.
|
||||
</p>
|
||||
)}
|
||||
<fieldset
|
||||
disabled={busy || !roles.includes('editors')}
|
||||
className="grid gap-4 sm:grid-cols-2"
|
||||
>
|
||||
<Field
|
||||
label="Designação"
|
||||
error={errors.name?.join(' ')}
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
value={form.name}
|
||||
onChange={(event) =>
|
||||
setForm({
|
||||
...form,
|
||||
name: event.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Código" error={errors.code?.join(' ')}>
|
||||
<input
|
||||
className={control}
|
||||
value={form.code}
|
||||
onChange={(event) =>
|
||||
setForm({
|
||||
...form,
|
||||
code: event.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label="Fonte e versão"
|
||||
error={errors.source_id?.join(' ')}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={form.source_id}
|
||||
onChange={(event) =>
|
||||
setForm({
|
||||
...form,
|
||||
source_id: event.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
{!sources.some(
|
||||
(source) => source.id === form.source_id,
|
||||
) && (
|
||||
<option value={form.source_id}>
|
||||
Fonte actual — {form.source_id}
|
||||
</option>
|
||||
)}
|
||||
{sources.map((source) => (
|
||||
<option key={source.id} value={source.id}>
|
||||
{source.name} · {source.source_version}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
label="Aplicável desde"
|
||||
error={errors.valid_from?.join(' ')}
|
||||
>
|
||||
<input
|
||||
type="date"
|
||||
className={control}
|
||||
value={form.valid_from}
|
||||
onChange={(event) =>
|
||||
setForm({
|
||||
...form,
|
||||
valid_from: event.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label="Aplicável até (opcional)"
|
||||
error={errors.valid_to?.join(' ')}
|
||||
>
|
||||
<input
|
||||
type="date"
|
||||
className={control}
|
||||
value={form.valid_to}
|
||||
onChange={(event) =>
|
||||
setForm({
|
||||
...form,
|
||||
valid_to: event.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
</fieldset>
|
||||
{sources.length === 100 && (
|
||||
<p>
|
||||
São apresentadas as primeiras 100 fontes do catálogo
|
||||
existente.
|
||||
</p>
|
||||
)}
|
||||
{state.baseline_changed && (
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.confirm_baseline_change}
|
||||
onChange={(event) =>
|
||||
setForm({
|
||||
...form,
|
||||
confirm_baseline_change:
|
||||
event.target.checked,
|
||||
})
|
||||
}
|
||||
/>
|
||||
Conferi a publicação alterada e reconciliei esta
|
||||
proposta.
|
||||
</label>
|
||||
)}
|
||||
<Field
|
||||
label="Fundamento da operação (pelo menos 10 caracteres)"
|
||||
error={errors.reason?.join(' ')}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.reason}
|
||||
onChange={(event) =>
|
||||
setForm({ ...form, reason: event.target.value })
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{changed && (
|
||||
<p>
|
||||
Guarde as alterações antes de efectuar uma decisão
|
||||
sobre a versão.
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{actionButton(
|
||||
'',
|
||||
'Guardar proposta privada',
|
||||
roles.includes('editors'),
|
||||
)}
|
||||
{actionButton(
|
||||
'pending_review',
|
||||
'Submeter à revisão',
|
||||
state._editorial?.private === true &&
|
||||
['draft', 'rejected'].includes(
|
||||
state.profile.status,
|
||||
) &&
|
||||
state.profile.editor_id === actorId &&
|
||||
roles.includes('editors') &&
|
||||
state.fresh,
|
||||
)}
|
||||
{actionButton(
|
||||
'in_review',
|
||||
'Iniciar revisão',
|
||||
state.profile.status === 'pending_review' &&
|
||||
canReview,
|
||||
)}
|
||||
{actionButton(
|
||||
'approved',
|
||||
'Aprovar esta versão',
|
||||
state.profile.status === 'in_review' &&
|
||||
canReview &&
|
||||
state.fresh,
|
||||
)}
|
||||
{actionButton(
|
||||
'rejected',
|
||||
'Devolver com fundamento',
|
||||
['pending_review', 'in_review'].includes(
|
||||
state.profile.status,
|
||||
) && canReview,
|
||||
)}
|
||||
{actionButton(
|
||||
'published',
|
||||
'Publicar versão aprovada',
|
||||
state.profile.status === 'approved' &&
|
||||
canPublish &&
|
||||
state.fresh,
|
||||
)}
|
||||
{actionButton(
|
||||
'archived',
|
||||
state._editorial?.private
|
||||
? 'Arquivar proposta privada'
|
||||
: 'Arquivar publicação',
|
||||
roles.includes('publishers') &&
|
||||
(state._editorial?.private === true ||
|
||||
preview.public.profile.status ===
|
||||
'published'),
|
||||
)}
|
||||
{actionButton(
|
||||
'withdrawn',
|
||||
'Retirar publicação actual',
|
||||
roles.includes('publishers') &&
|
||||
preview.public.profile.status === 'published' &&
|
||||
state._editorial?.private === true,
|
||||
)}
|
||||
</div>
|
||||
<details>
|
||||
<summary className="cursor-pointer underline">
|
||||
Histórico (últimas 100 operações)
|
||||
</summary>
|
||||
<ol>
|
||||
{preview.history.map((item) => (
|
||||
<li key={item.id}>
|
||||
Versão {item.version_no} ·{' '}
|
||||
{item.snapshot.location.name} ·{' '}
|
||||
{titles[item.snapshot.profile.status] ??
|
||||
item.snapshot.profile.status}
|
||||
: {item.reason}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</details>
|
||||
</section>
|
||||
)}
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user