feat(offers): complete phase five operational controls in QA

This commit is contained in:
2026-11-14 18:08:46 +02:00
parent e431de8b42
commit 528a2597ed
33 changed files with 2383 additions and 19 deletions
@@ -0,0 +1,550 @@
import { Link } from '@inertiajs/react';
import { useEffect, useState } from 'react';
import { profileJson } from '@/lib/profile-json';
type Report = {
id: string;
version: number;
status: string;
reason: string;
resolution_reason: string | null;
source_record_version: number;
source_snapshot?: {
title?: string;
summary?: string;
description?: string;
} | null;
};
type Highlight = {
version: number;
status: string;
label: string;
note: string;
starts_at: string | null;
ends_at: string | null;
};
type Operation = {
id: number;
etag: string;
availability: {
state: string;
expires_at: string | null;
policy_pending: boolean;
};
editorial_state: string;
owner: boolean;
reviewer: boolean;
publisher: boolean;
reports: Report[];
highlight: Highlight | null;
history: { id: string; action: string; at: string; cycle: number }[];
};
const labels: Record<string, string> = {
available: 'Disponível',
withdrawn: 'Retirada',
expired: 'Expirada',
revalidation: 'Aguarda nova validação',
unavailable: 'Indisponível',
};
export default function OfferOperations({
id,
onChanged,
}: {
id: number;
onChanged: () => void;
}) {
const [value, setValue] = useState<Operation | null>(null);
const [message, setMessage] = useState('');
const [busy, setBusy] = useState(false);
const [reason, setReason] = useState('');
const [confirm, setConfirm] = useState(false);
const [plan, setPlan] = useState({
label: '',
starts_at: '',
ends_at: '',
note: '',
status: 'draft',
});
const base = `/minhas-oportunidades/ofertas/${id}`;
useEffect(() => {
let active = true;
profileJson(`${base}/operacoes`, {}, 'GET')
.then((result) => {
if (active) {
setValue(result);
if (result.highlight)
setPlan({
label: result.highlight.label,
starts_at: result.highlight.starts_at ?? '',
ends_at: result.highlight.ends_at ?? '',
note: result.highlight.note,
status: result.highlight.status,
});
}
})
.catch((error) => {
if (active) setMessage(error.message);
});
return () => {
active = false;
};
}, [base]);
async function command(path: string, data: object) {
if (busy) return;
setBusy(true);
setMessage('');
try {
const result = await profileJson(`${base}/${path}`, data);
setValue(result);
setConfirm(false);
onChanged();
setMessage(
'Operação guardada em privado. A publicação permanece bloqueada.',
);
} catch (error) {
setMessage(
error instanceof Error
? error.message
: 'Não foi possível concluir.',
);
} finally {
setBusy(false);
}
}
async function refresh(loadPlan = false) {
setBusy(true);
try {
const next: Operation = await profileJson(
`${base}/operacoes`,
{},
'GET',
);
setValue((previous) =>
loadPlan
? next
: { ...next, highlight: previous?.highlight ?? null },
);
if (loadPlan)
setPlan({
label: next.highlight?.label ?? '',
starts_at: next.highlight?.starts_at ?? '',
ends_at: next.highlight?.ends_at ?? '',
note: next.highlight?.note ?? '',
status: next.highlight?.status ?? 'draft',
});
setConfirm(false);
onChanged();
setMessage(
loadPlan
? 'Plano guardado carregado para conferência.'
: 'Disponibilidade e denúncias actualizadas. As observações e o plano local foram preservados.',
);
} catch (error) {
setMessage(
error instanceof Error
? error.message
: 'Não foi possível actualizar.',
);
} finally {
setBusy(false);
}
}
function owner(action: string) {
if (value)
void command('operacoes', {
action,
etag: value.etag,
confirm: true,
reason,
});
}
return (
<section className="space-y-4 rounded-lg border p-4">
<h2 className="font-semibold">Disponibilidade e acompanhamento</h2>
<button
type="button"
className="underline"
disabled={busy}
onClick={() => void refresh()}
>
Actualizar disponibilidade e denúncias
</button>
{value && (
<>
<p>{labels[value.availability.state] ?? 'Indisponível'}</p>
<p className="text-sm">
{value.availability.policy_pending
? 'Prazo de validade por definir.'
: value.availability.expires_at
? `Validade até ${new Date(value.availability.expires_at).toLocaleString('pt-MZ')}.`
: 'A contagem de validade inicia-se com a publicação da versão.'}{' '}
O NDA tem controlo independente.
</p>
{value.owner && (
<div className="space-y-3">
<label className="block">
Observação (opcional)
<textarea
className="block w-full rounded border p-2"
maxLength={1000}
value={reason}
onChange={(event) =>
setReason(event.target.value)
}
/>
</label>
<div className="flex flex-wrap gap-3">
<button
type="button"
className="rounded border p-2"
disabled={
busy ||
value.availability.state === 'withdrawn'
}
onClick={() => owner('withdraw')}
>
Retirar disponibilidade agora
</button>
{['withdrawn', 'expired'].includes(
value.availability.state,
) && (
<button
type="button"
className="rounded border p-2"
disabled={busy}
onClick={() =>
owner('request_reactivation')
}
>
Pedir nova validação para reactivar
</button>
)}
{value.availability.state ===
'revalidation' && (
<button
type="button"
className="rounded border p-2"
disabled={
busy ||
value.editorial_state !== 'approved'
}
onClick={() => owner('reactivate')}
>
Repor disponibilidade após validação
</button>
)}
</div>
</div>
)}
{value.reviewer && (
<div className="space-y-3">
<h3 className="font-semibold">
Denúncias no meu âmbito
</h3>
<label className="block">
Fundamento do tratamento
<textarea
className="block w-full rounded border p-2"
minLength={20}
maxLength={2000}
value={reason}
onChange={(event) =>
setReason(event.target.value)
}
/>
</label>
<label className="flex gap-2">
<input
type="checkbox"
checked={confirm}
onChange={(event) =>
setConfirm(event.target.checked)
}
/>
Confirmo a decisão para a versão consultada.
</label>
{value.reports.map((report) => (
<article
key={report.id}
className="space-y-2 rounded border p-3"
>
<p className="break-words whitespace-pre-line">
{report.reason}
</p>
{report.source_snapshot && (
<details>
<summary>
Conteúdo referido na denúncia
</summary>
<p className="font-semibold">
{report.source_snapshot.title}
</p>
<p className="break-words whitespace-pre-line">
{report.source_snapshot
.summary ??
report.source_snapshot
.description}
</p>
</details>
)}
<p className="text-sm">
Versão denunciada:{' '}
{report.source_record_version} ·{' '}
{
(
{
open: 'Por analisar',
in_review: 'Em análise',
resolved: 'Tratada',
} as Record<string, string>
)[report.status]
}
</p>
{report.resolution_reason && (
<p>{report.resolution_reason}</p>
)}
<div className="flex flex-wrap gap-3">
{(report.status === 'open'
? ['start_review']
: report.status === 'in_review'
? [
'resolve_no_withdrawal',
'resolve_withdrawal',
]
: []
).map((action) => (
<button
type="button"
className="underline"
key={action}
disabled={
busy ||
!confirm ||
reason.trim().length < 20
}
onClick={() =>
void command(
`denuncias/${report.id}`,
{
action,
etag: value.etag,
version:
report.version,
confirm,
reason,
},
)
}
>
{
(
{
start_review:
'Iniciar análise',
resolve_no_withdrawal:
'Concluir sem retirada',
resolve_withdrawal:
'Concluir e retirar disponibilidade',
} as Record<
string,
string
>
)[action]
}
</button>
))}
</div>
</article>
))}
</div>
)}
{value.publisher && (
<details className="space-y-3">
<summary>
Preparação administrativa de destaque
</summary>
<button
type="button"
className="underline"
disabled={busy}
onClick={() => void refresh(true)}
>
Carregar plano guardado (substitui os campos
locais)
</button>
<p>
Registo interno, sem cobrança, pagamento ou
promoção comercial activa.
</p>
<fieldset
disabled={busy}
className="grid gap-3 sm:grid-cols-2"
>
<label>
Designação
<input
className="block w-full rounded border p-2"
maxLength={150}
value={plan.label}
onChange={(event) =>
setPlan({
...plan,
label: event.target.value,
})
}
/>
</label>
<label>
Estado
<select
className="block w-full rounded border p-2"
value={plan.status}
onChange={(event) =>
setPlan({
...plan,
status: event.target.value,
})
}
>
<option value="draft">
Rascunho administrativo
</option>
<option value="archived">
Arquivado
</option>
</select>
</label>
<label>
Início previsto (UTC)
<input
className="block w-full rounded border p-2"
type="datetime-local"
value={plan.starts_at.replace(/Z$/, '')}
onChange={(event) =>
setPlan({
...plan,
starts_at: event.target.value
? `${event.target.value}Z`
: '',
})
}
/>
</label>
<label>
Fim previsto (UTC)
<input
className="block w-full rounded border p-2"
type="datetime-local"
value={plan.ends_at.replace(/Z$/, '')}
onChange={(event) =>
setPlan({
...plan,
ends_at: event.target.value
? `${event.target.value}Z`
: '',
})
}
/>
</label>
<label className="sm:col-span-2">
Fundamento
<textarea
className="block w-full rounded border p-2"
minLength={20}
maxLength={1000}
value={plan.note}
onChange={(event) =>
setPlan({
...plan,
note: event.target.value,
})
}
/>
</label>
<label>
<input
type="checkbox"
checked={confirm}
onChange={(event) =>
setConfirm(event.target.checked)
}
/>
Conferi a preparação administrativa.
</label>
<button
type="button"
className="rounded border p-2"
disabled={
!confirm ||
!plan.label ||
plan.note.trim().length < 20
}
onClick={() =>
void command(
'destaque-administrativo',
{
...plan,
starts_at:
plan.starts_at || null,
ends_at: plan.ends_at || null,
etag: value.etag,
version:
value.highlight?.version ??
0,
confirm,
},
)
}
>
Guardar preparação
</button>
</fieldset>
</details>
)}
<Link
className="inline-block underline"
href={`${base}/denunciar`}
>
Registar denúncia fundamentada
</Link>
<details>
<summary>Histórico de disponibilidade</summary>
<ul className="mt-2 space-y-2">
{value.history
.filter((event) =>
[
'offer_withdrawn',
'offer_reactivation_requested',
'offer_reactivated_privately',
'offer_expired',
].includes(event.action),
)
.map((event) => (
<li key={event.id}>
{
(
{
offer_withdrawn:
'Disponibilidade retirada',
offer_reactivation_requested:
'Nova validação pedida',
offer_reactivated_privately:
'Disponibilidade reposta',
offer_expired:
'Validade terminada',
} as Record<string, string>
)[event.action]
}{' '}
·{' '}
{new Date(event.at).toLocaleString(
'pt-MZ',
)}
</li>
))}
</ul>
</details>
</>
)}
<p role="status">{message}</p>
</section>
);
}
@@ -38,6 +38,12 @@ export default function PublicOfferCard({
Publicada em{' '}
{new Date(offer.published_at).toLocaleDateString('pt-MZ')}
</p>
{offer.expires_at && (
<p className="text-sm text-slate-600">
Validade até{' '}
{new Date(offer.expires_at).toLocaleString('pt-MZ')}
</p>
)}
</article>
);
}
+1
View File
@@ -11,6 +11,7 @@ export type PublicOffer = {
};
status: 'published';
published_at: string;
expires_at?: string | null;
revision: number;
url: string;
};
@@ -41,6 +41,7 @@ export default function EditorialWorkflow({
resourceAccess,
opportunitiesUrl,
offersUrl = null,
offerOperationsUrl = null,
opportunityPending,
clustersUrl,
portfolioUrl,
@@ -56,6 +57,7 @@ export default function EditorialWorkflow({
resourceAccess: boolean;
opportunitiesUrl: string | null;
offersUrl?: string | null;
offerOperationsUrl?: string | null;
opportunityPending: number;
clustersUrl?: string | null;
portfolioUrl?: string | null;
@@ -110,6 +112,7 @@ export default function EditorialWorkflow({
label: 'Ofertas — revisão privada',
href: offersUrl,
},
{ label: 'Ofertas — acompanhamento', href: offerOperationsUrl },
{
label: 'Biblioteca e editores',
href: resourceAccess ? '/management/portal-services' : null,
@@ -12,12 +12,17 @@ export default function OfferPreparations({
title: string | null;
reference: string;
state: string;
availability?: string;
}[];
prev_page_url: string | null;
next_page_url: string | null;
};
canCreate: boolean;
filters?: { state?: string };
filters?: {
state?: string;
operational?: boolean;
pending_reports?: boolean;
};
}) {
return (
<main className="mx-auto w-full max-w-5xl space-y-6 p-4 md:p-8">
@@ -25,7 +30,9 @@ export default function OfferPreparations({
<header className="flex flex-wrap items-center justify-between gap-4">
<div>
<h1 className="text-2xl font-semibold">
As minhas ofertas
{filters.operational || filters.pending_reports
? 'Ofertas — acompanhamento'
: 'As minhas ofertas'}
</h1>
<p className="text-muted-foreground mt-2">
Prepare e guarde as suas ofertas num espaço privado.
@@ -62,6 +69,19 @@ export default function OfferPreparations({
</Link>
))}
</nav>
{filters.operational && (
<nav
className="flex flex-wrap gap-4"
aria-label="Acompanhamento de ofertas"
>
<Link href="/minhas-oportunidades/ofertas?operational=1">
Todas no meu âmbito
</Link>
<Link href="/minhas-oportunidades/ofertas?operational=1&pending_reports=1">
Denúncias pendentes
</Link>
</nav>
)}
{!records.data.length && (
<p>Ainda não existem ofertas neste âmbito.</p>
)}
@@ -77,6 +97,24 @@ export default function OfferPreparations({
<p className="text-muted-foreground mt-1 text-sm">
{record.reference} ·{' '}
{offerStates[record.state] ?? record.state}
{record.availability && (
<>
{' '}
·{' '}
{
(
{
available: 'Disponível',
withdrawn: 'Retirada',
expired: 'Expirada',
revalidation:
'Aguarda nova validação',
unavailable: 'Indisponível',
} as Record<string, string>
)[record.availability]
}
</>
)}
</p>
</li>
))}
+18
View File
@@ -15,6 +15,7 @@ import OfferParticularsFields, {
} from '@/components/offer-particulars';
import OfferPrivateResources from '@/components/offer-private-resources';
import OfferConfidentialAccess from '@/components/offer-confidential-access';
import OfferOperations from '@/components/offer-operations';
type Offer = OfferParticulars & {
price_mode?: string | null;
@@ -196,6 +197,23 @@ export default function OfferPreparation({
<div role="status" aria-live="polite">
{message}
</div>
{saved && (
<OfferOperations
id={saved.id}
onChanged={() => {
void profileJson(
`/minhas-oportunidades/ofertas/${saved.id}`,
{},
'GET',
)
.then((result) => {
setSaved(result.record);
setConfirmed(false);
})
.catch((error) => setMessage(error.message));
}}
/>
)}
{Object.keys(errors).length > 0 && (
<div
role="alert"
@@ -12,6 +12,12 @@ export default function OfferPublicDetail({ offer }: { offer: PublicOffer }) {
Voltar às ofertas
</Link>
<PublicOfferCard offer={offer} detail />
<Link
className="my-4 inline-block underline"
href={`/minhas-oportunidades/ofertas/${offer.id}/denunciar`}
>
Denunciar esta oferta
</Link>
{territoryId && (
<section className="mt-6">
<h2 className="mb-3 text-xl font-semibold">
+80
View File
@@ -0,0 +1,80 @@
import { Head } from '@inertiajs/react';
import { useState } from 'react';
import { profileJson } from '@/lib/profile-json';
import { createOperationKey } from '@/lib/operation-key';
export default function OfferReport({ offerId }: { offerId: number }) {
const [key] = useState(createOperationKey);
const [reason, setReason] = useState('');
const [confirm, setConfirm] = useState(false);
const [busy, setBusy] = useState(false);
const [sent, setSent] = useState(false);
const [message, setMessage] = useState('');
async function submit() {
setBusy(true);
try {
const result = await profileJson(
`/minhas-oportunidades/ofertas/${offerId}/denuncias`,
{ client_key: key, reason, confirm },
);
setSent(true);
setMessage(`Denúncia registada. Referência: ${result.id}.`);
} catch (error) {
setMessage(
error instanceof Error
? error.message
: 'Não foi possível registar a denúncia.',
);
} finally {
setBusy(false);
}
}
return (
<main className="mx-auto w-full max-w-2xl space-y-5 p-4">
<Head title="Denunciar oferta" />
<h1 className="text-2xl font-semibold">Denunciar oferta</h1>
<p>
Explique os factos que justificam a denúncia. A equipa
responsável irá analisá-la em privado.
</p>
<form
onSubmit={(event) => {
event.preventDefault();
void submit();
}}
className="space-y-4"
>
<fieldset disabled={busy || sent} className="space-y-4">
<label className="block">
Fundamento
<textarea
className="mt-2 block w-full rounded border p-3"
required
minLength={20}
maxLength={2000}
value={reason}
onChange={(event) => setReason(event.target.value)}
/>
</label>
<label className="flex gap-2">
<input
type="checkbox"
checked={confirm}
onChange={(event) =>
setConfirm(event.target.checked)
}
/>
Confirmo o envio destes factos para análise da equipa.
</label>
<button
type="submit"
className="rounded border px-4 py-2"
disabled={!confirm || reason.trim().length < 20}
>
Registar denúncia
</button>
</fieldset>
</form>
<p role="status">{message}</p>
</main>
);
}