feat: integrate private offers with existing editorial workflow

This commit is contained in:
2026-11-14 16:20:30 +02:00
parent 6e302db62e
commit 91c1857368
19 changed files with 1353 additions and 30 deletions
@@ -0,0 +1,259 @@
import { useState } from 'react';
import { router } from '@inertiajs/react';
import {
offerStates,
offerActions,
type OfferEditorialRecord,
} from '@/lib/offer-editorial';
import { profileJson } from '@/lib/profile-json';
const fields: Record<string, string> = {
title: 'Título',
description: 'Descrição',
opportunity_category: 'Categoria',
private_offer: 'Preço',
contact: 'Contacto',
location: 'Localização',
};
export default function OfferEditorialReview<T extends OfferEditorialRecord>({
record,
onChanged,
}: {
record: T;
onChanged: (record: T) => void;
}) {
const [reason, setReason] = useState('');
const [corrections, setCorrections] = useState<string[]>([]);
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState('');
const [assignee, setAssignee] = useState('');
const actions = record.actions.filter((action) => action !== 'submit');
async function decide(action: string) {
if (busy || record.reauthenticationRequired) return;
setBusy(true);
setMessage('');
try {
const result = await profileJson(
`/minhas-oportunidades/ofertas/${record.id}/revisao`,
{
etag: record.etag,
action,
reason,
...(action === 'assign_review'
? { assignee_user_id: Number(assignee) }
: {}),
...(action === 'request_correction'
? { correction_items: corrections }
: {}),
},
);
onChanged(result.record);
setReason('');
setCorrections([]);
setMessage(result.message);
if (action === 'request_revision')
router.visit(`/minhas-oportunidades/ofertas/${record.id}`, {
preserveScroll: true,
});
} catch (error) {
setMessage(
error instanceof Error
? error.message
: 'Não foi possível registar a decisão. O fundamento foi preservado.',
);
} finally {
setBusy(false);
}
}
return (
<section
className="space-y-4 rounded-lg border p-4 md:p-6"
aria-label="Revisão editorial privada"
>
<h2 className="font-semibold">Revisão da oferta</h2>
<p>
{offerStates[record.state] ?? record.state}. A publicação
pública permanece indisponível nesta fase.
</p>
{record.approvalFresh === false && (
<p role="alert">
As referências mudaram desde a aprovação. Prepare nova
revisão; a decisão anterior fica no histórico.
</p>
)}
{record.correctionItems.length > 0 &&
record.state === 'needs_information' && (
<p>
Campos a rever:{' '}
{record.correctionItems
.map((field) => fields[field] ?? field)
.join(', ')}
.
</p>
)}
{record.reauthenticationRequired && (
<p role="alert">
Renove o MFA pela autenticação habitual antes de registar
uma decisão. Os dados guardados permanecem disponíveis.
</p>
)}
{actions.length > 0 && (
<fieldset
className="space-y-3"
disabled={busy || record.reauthenticationRequired}
>
<label className="block">
Fundamento da operação
<textarea
className="bg-background w-full rounded-md border p-2"
value={reason}
onChange={(event) => setReason(event.target.value)}
minLength={20}
maxLength={1000}
rows={3}
/>
</label>
{actions.includes('assign_review') && (
<label className="block">
Responsável pela revisão
<select
className="bg-background w-full rounded-md border p-2"
value={assignee}
onChange={(event) =>
setAssignee(event.target.value)
}
>
<option value="">
Seleccione um validador autorizado
</option>
{record.reviewers.map((reviewer) => (
<option
key={reviewer.id}
value={reviewer.id}
>
{reviewer.name}
</option>
))}
</select>
</label>
)}
{actions.includes('request_correction') && (
<fieldset>
<legend>Campos a corrigir</legend>
<div className="flex flex-wrap gap-3">
{Object.entries(fields).map(
([field, label]) => (
<label
key={field}
className="flex gap-2"
>
<input
type="checkbox"
checked={corrections.includes(
field,
)}
onChange={(event) =>
setCorrections(
(previous) =>
event.target.checked
? [
...previous,
field,
]
: previous.filter(
(value) =>
value !==
field,
),
)
}
/>
{label}
</label>
),
)}
</div>
</fieldset>
)}
<div className="flex flex-wrap gap-3">
{actions.map((action) => (
<button
type="button"
key={action}
className="bg-primary text-primary-foreground rounded-md px-4 py-2 disabled:opacity-50"
disabled={
busy ||
reason.trim().length < 20 ||
(action === 'request_correction' &&
!corrections.length) ||
(action === 'assign_review' && !assignee)
}
onClick={() => void decide(action)}
>
{offerActions[action] ?? action}
</button>
))}
</div>
</fieldset>
)}
<p role="status" aria-live="polite">
{message}
</p>
{record.submittedVersions.length > 0 && (
<details>
<summary className="cursor-pointer font-medium">
Versões submetidas
</summary>
<ul className="mt-3 space-y-3">
{record.submittedVersions.map((version, index) => (
<li key={index} className="rounded border p-3">
<p>
Revisão {version.submission.record_version}:{' '}
{version.submission.payload.title}
</p>
<p>
{version.submission.payload.private_offer
.price_mode === 'negotiable'
? 'A negociar'
: `${version.submission.payload.private_offer.amount} ${version.submission.payload.private_offer.currency}`}
</p>
{version.approval && (
<p>Aprovação: {version.approval.reason}</p>
)}
{version.rejection && (
<p>Rejeição: {version.rejection.reason}</p>
)}
</li>
))}
</ul>
</details>
)}
{record.history.length > 0 && (
<details>
<summary className="cursor-pointer font-medium">
Histórico de revisão
</summary>
<ol className="mt-3 space-y-3">
{record.history.map((event, index) => (
<li key={index} className="rounded border p-3">
<p className="font-medium">
{offerActions[event.action] ?? event.action}{' '}
· {event.actor_name}
</p>
<p>{event.reason}</p>
{event.assignee_name && (
<p>Responsável: {event.assignee_name}</p>
)}
<p className="text-muted-foreground text-sm">
{event.at} · Revisão submetida{' '}
{event.submitted_revision}
</p>
</li>
))}
</ol>
</details>
)}
</section>
);
}
+52
View File
@@ -0,0 +1,52 @@
export const offerStates: Record<string, string> = {
draft: 'Rascunho privado',
submitted: 'Submetida para revisão',
in_review: 'Em revisão',
needs_information: 'Correcções solicitadas',
rejected: 'Rejeitada',
approved: 'Aprovada internamente',
};
export const offerActions: Record<string, string> = {
assign_review: 'Atribuir revisão',
submit: 'Submeter',
start_review: 'Iniciar revisão',
request_correction: 'Solicitar correcção',
reject: 'Rejeitar com fundamento',
approve: 'Aprovar internamente',
request_revision: 'Preparar correcção e reenvio',
};
export type OfferEditorialRecord = {
reviewers: { id: number; name: string }[];
id: number;
etag: string;
state: string;
actions: string[];
reauthenticationRequired: boolean;
approvalFresh: boolean | null;
correctionItems: string[];
history: {
action: string;
actor_name: string;
assignee_name?: string | null;
reason: string;
at: string;
opportunity_version?: number;
submitted_revision?: number;
}[];
submittedVersions: {
submission: {
record_version: number;
at?: string;
payload: {
title: string;
private_offer: {
price_mode: string;
amount?: string;
currency?: string;
};
};
};
approval?: { reason: string; hash: string } | null;
rejection?: { reason: string; hash: string } | null;
}[];
};
@@ -40,6 +40,7 @@ export default function EditorialWorkflow({
filters = {},
resourceAccess,
opportunitiesUrl,
offersUrl = null,
opportunityPending,
clustersUrl,
portfolioUrl,
@@ -54,6 +55,7 @@ export default function EditorialWorkflow({
}: {
resourceAccess: boolean;
opportunitiesUrl: string | null;
offersUrl?: string | null;
opportunityPending: number;
clustersUrl?: string | null;
portfolioUrl?: string | null;
@@ -104,6 +106,10 @@ export default function EditorialWorkflow({
href: opportunitiesUrl,
pending: opportunityPending,
},
{
label: 'Ofertas — revisão privada',
href: offersUrl,
},
{
label: 'Biblioteca e editores',
href: resourceAccess ? '/management/portal-services' : null,
@@ -1,8 +1,10 @@
import { Head, Link } from '@inertiajs/react';
import { offerStates } from '@/lib/offer-editorial';
export default function OfferPreparations({
records,
canCreate,
filters = {},
}: {
records: {
data: {
@@ -15,6 +17,7 @@ export default function OfferPreparations({
next_page_url: string | null;
};
canCreate: boolean;
filters?: { state?: string };
}) {
return (
<main className="mx-auto w-full max-w-5xl space-y-6 p-4 md:p-8">
@@ -37,6 +40,28 @@ export default function OfferPreparations({
</Link>
)}
</header>
<nav
aria-label="Filtrar ofertas por estado"
className="flex flex-wrap gap-3 text-sm"
>
<Link
href="/minhas-oportunidades/ofertas"
aria-current={!filters.state ? 'page' : undefined}
>
Todas
</Link>
{Object.entries(offerStates).map(([state, label]) => (
<Link
key={state}
href={`/minhas-oportunidades/ofertas?state=${state}`}
aria-current={
filters.state === state ? 'page' : undefined
}
>
{label}
</Link>
))}
</nav>
{!records.data.length && (
<p>Ainda não existem ofertas neste âmbito.</p>
)}
@@ -51,9 +76,7 @@ export default function OfferPreparations({
</Link>
<p className="text-muted-foreground mt-1 text-sm">
{record.reference} ·{' '}
{record.state === 'submitted'
? 'Submissão privada registada'
: 'Rascunho privado'}
{offerStates[record.state] ?? record.state}
</p>
</li>
))}
+27 -2
View File
@@ -8,6 +8,8 @@ import OpportunityContactForm from '@/components/opportunity-contact-form';
import { modalityLabels } from '@/components/opportunity-search-filters';
import { createOperationKey } from '@/lib/operation-key';
import { profileJson, ProfileValidationError } from '@/lib/profile-json';
import OfferEditorialReview from '@/components/offer-editorial-review';
import { type OfferEditorialRecord } from '@/lib/offer-editorial';
type Offer = {
price_mode?: string | null;
@@ -20,7 +22,7 @@ type Context = {
organization_name: string | null;
type: string;
};
type RecordData = {
type RecordData = OfferEditorialRecord & {
id: number;
reference: string;
etag: string;
@@ -28,6 +30,7 @@ type RecordData = {
canEdit: boolean;
organization_id: string | null;
territory: TerritoryOption[];
contactLabel?: string | null;
values: {
title?: string;
description?: string;
@@ -76,7 +79,19 @@ export default function OfferPreparation({
},
);
const [territory, setTerritory] = useState(record?.territory ?? emptyPath);
const [contactChoices, setContactChoices] = useState(contacts);
const [contactChoices, setContactChoices] = useState(() => {
const selected = record?.values.private_offer?.contact_id;
return selected && !contacts.some((contact) => contact.id === selected)
? [
...contacts,
{
id: selected,
full_name:
record?.contactLabel ?? 'Contacto indisponível',
},
]
: contacts;
});
const [dirty, setDirty] = useState(!record);
const [busy, setBusy] = useState(false);
const [confirmed, setConfirmed] = useState(false);
@@ -159,6 +174,16 @@ export default function OfferPreparation({
</p>
{saved && <p className="mt-2 text-sm">{saved.reference}</p>}
</header>
{saved && (
<OfferEditorialReview
record={saved}
onChanged={(next) => {
setSaved(next);
setDirty(false);
setConfirmed(false);
}}
/>
)}
<div role="status" aria-live="polite">
{message}
</div>