Files
Investidor-V2/resources/js/components/offer-editorial-review.tsx
T

260 lines
12 KiB
TypeScript

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>
);
}