Files
Investidor-V2/resources/js/pages/management/opportunity-origin.tsx
T

234 lines
8.5 KiB
TypeScript

import { router } from '@inertiajs/react';
import { useState } from 'react';
import { Management } from './shared';
type RecordState = {
id: number;
reference: string;
title: string;
description: string;
classification: string;
snapshot_hash: string;
history: {
id: string;
classification: string;
reason: string;
author: number;
date: string;
}[];
};
const labels: Record<string, string> = {
real: 'Oportunidade real',
example: 'Exemplo demonstrativo',
undetermined: 'Origem ainda indeterminada',
};
type Preview = {
current: RecordState;
classification: string;
reason: string;
effect: string;
ready: boolean;
};
function Review({ record, ready }: { record: RecordState; ready: boolean }) {
const [classification, setClassification] = useState(record.classification);
const [reason, setReason] = useState('');
const [preview, setPreview] = useState<Preview | null>(null);
const [error, setError] = useState('');
const [processing, setProcessing] = useState(false);
const [confirmed, setConfirmed] = useState(false);
const [result, setResult] = useState('');
async function request(apply: boolean) {
setProcessing(true);
setError('');
try {
const xsrf = document.cookie
.split('; ')
.find((cookie) => cookie.startsWith('XSRF-TOKEN='))
?.split('=')
.slice(1)
.join('=');
const response = await fetch(
'/management/opportunity-origin/' +
(apply ? 'apply' : 'preview'),
{
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'X-XSRF-TOKEN': decodeURIComponent(xsrf ?? ''),
},
body: JSON.stringify({
id: record.id,
classification,
reason,
snapshot_hash: preview?.current.snapshot_hash,
confirm: confirmed,
}),
},
);
const data = await response.json();
if (!response.ok)
throw new Error(
Object.values(data.errors ?? {})
.flat()
.join(' ') ||
data.message ||
'Operação recusada.',
);
if (apply) {
setPreview(null);
setResult(
'Decisão registada. Classificação separada das associações; histórico preservado.',
);
router.reload({ only: ['records', 'ready'] });
} else {
setPreview(data);
setConfirmed(false);
}
} catch (exception) {
setError(
exception instanceof Error
? exception.message
: 'Falha de comunicação; dados preservados.',
);
} finally {
setProcessing(false);
}
}
return (
<article className="space-y-3 rounded border p-4">
<h2 className="text-lg font-bold">
ID {record.id} — {record.title}
</h2>
<p>{record.reference}</p>
<p>{record.description}</p>
<p>
Classificação atual: {labels[record.classification]}.{' '}
{record.classification === 'example' &&
'Exemplo de demonstração — não constitui oportunidade real. Consulta autenticada preservada.'}
</p>
<label className="block">
Classificação
<select
aria-label="Classificação"
className="block rounded border p-2"
value={classification}
onChange={(event) => {
setClassification(event.target.value);
setPreview(null);
}}
>
{Object.entries(labels).map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
</label>
<label className="block">
Fundamento da decisão
<textarea
aria-label="Fundamento da decisão"
className="block w-full rounded border p-2"
value={reason}
maxLength={2000}
onChange={(event) => {
setReason(event.target.value);
setPreview(null);
}}
/>
</label>
<button
className="rounded border p-2"
disabled={processing || !reason.trim()}
onClick={() => request(false)}
>
Pré-visualizar decisão
</button>
{preview && (
<section
className="space-y-2 rounded border p-3"
aria-label="Pré-visualização da classificação"
>
<p>
{labels[preview.current.classification]} →{' '}
{labels[preview.classification]}
</p>
<p>{preview.reason}</p>
<p>{preview.effect}</p>
<p>
IDs, relações, interações e histórico preservados. Não
associa projetos/clusters nem valida informação
jurídica.
</p>
<label className="block">
<input
type="checkbox"
checked={confirmed}
onChange={(event) =>
setConfirmed(event.target.checked)
}
/>{' '}
Confirmo esta decisão de classificação
</label>
<button
className="rounded border p-2"
disabled={
processing || !confirmed || !ready || !preview.ready
}
onClick={() => request(true)}
>
Aplicar decisão de classificação
</button>
</section>
)}
{!ready && (
<p>
Aplicação indisponível até prova atual de backup/restauro e
reversão; a revisão e pré-visualização continuam
disponíveis.
</p>
)}
{error && <p role="alert">{error}</p>}
{result && <p role="status">{result}</p>}
<h3 className="font-bold">Histórico da classificação</h3>
{record.history.length ? (
record.history.map((event) => (
<p key={event.id}>
{labels[event.classification]} · {event.reason} · conta{' '}
{event.author} · {event.date}
</p>
))
) : (
<p>
Sem decisão registada; ausência de prova não significa
exemplo nem oportunidade real.
</p>
)}
</article>
);
}
export default function OpportunityOrigin({
records,
ready,
}: {
records: RecordState[];
ready: boolean;
}) {
return (
<Management title="Revisão da origem das oportunidades">
<p>
O seeder documenta valores de código; não prova a realidade do
investimento. A classificação é independente de publicação,
situação jurídica e associações territoriais. Exemplos decididos
ficam separados do catálogo público e disponíveis aqui para
consulta autenticada.
</p>
{records.map((record) => (
<Review key={record.id} record={record} ready={ready} />
))}
</Management>
);
}