373 lines
16 KiB
TypeScript
373 lines
16 KiB
TypeScript
import { Link, router, useForm } from '@inertiajs/react';
|
|
import { useState } from 'react';
|
|
import { Management, button, control } from './shared';
|
|
|
|
type Preview = {
|
|
id: string;
|
|
file_name: string;
|
|
sha256: string;
|
|
publication_version: string;
|
|
status: string;
|
|
report: {
|
|
record_count: number;
|
|
issue_counts: Record<string, number>;
|
|
issues: { code: string; sheet: string; cell: string; delta?: string }[];
|
|
};
|
|
matches: {
|
|
key: string;
|
|
province: string;
|
|
territory: string;
|
|
level: string;
|
|
geo_location_id: string | null;
|
|
state: string;
|
|
}[];
|
|
territory_options: {
|
|
id: string;
|
|
name: string;
|
|
location_type: string;
|
|
parent_id: string | null;
|
|
}[];
|
|
events: {
|
|
id: number;
|
|
action: string;
|
|
reason: string;
|
|
created_at: string;
|
|
}[];
|
|
};
|
|
export default function DemographyManagement({
|
|
batches,
|
|
preview,
|
|
qa = true,
|
|
editorialEnabled = false,
|
|
editorialRevision = 0,
|
|
}: {
|
|
editorialEnabled?: boolean;
|
|
editorialRevision?: number;
|
|
qa?: boolean;
|
|
batches: {
|
|
id: string;
|
|
file_name: string;
|
|
publication_version: string;
|
|
status: string;
|
|
}[];
|
|
preview: Preview | null;
|
|
}) {
|
|
const [file, setFile] = useState<File | null>(null);
|
|
const [version, setVersion] = useState('');
|
|
const [year, setYear] = useState('');
|
|
const [reason, setReason] = useState('');
|
|
const [mapping, setMapping] = useState<Record<string, string>>({});
|
|
const [message, setMessage] = useState('');
|
|
const [busy, setBusy] = useState(false);
|
|
const review = useForm({ expected_revision: editorialRevision });
|
|
async function execute(path: string, body: FormData | object) {
|
|
setBusy(true);
|
|
setMessage('');
|
|
try {
|
|
const token =
|
|
document.cookie
|
|
.split('; ')
|
|
.find((c) => c.startsWith('XSRF-TOKEN='))
|
|
?.split('=')
|
|
.slice(1)
|
|
.join('=') ?? '';
|
|
const response = await fetch(path, {
|
|
method: 'POST',
|
|
headers: {
|
|
Accept: 'application/json',
|
|
'X-XSRF-TOKEN': decodeURIComponent(token),
|
|
...(body instanceof FormData
|
|
? {}
|
|
: { 'Content-Type': 'application/json' }),
|
|
},
|
|
body: body instanceof FormData ? body : JSON.stringify(body),
|
|
});
|
|
const data = await response.json().catch(() => null);
|
|
if (!data)
|
|
throw new Error(
|
|
'O servidor não confirmou a operação. Confira o estado guardado antes de repetir.',
|
|
);
|
|
if (!response.ok)
|
|
throw new Error(
|
|
data.message ?? 'Não foi possível executar a operação.',
|
|
);
|
|
setMapping({});
|
|
router.get('/management/demography', { batch: data.id });
|
|
} catch (error) {
|
|
setMessage(
|
|
error instanceof Error ? error.message : 'Erro de comunicação.',
|
|
);
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
return (
|
|
<Management
|
|
title={
|
|
qa ? 'Dados demográficos INE — QA' : 'Dados demográficos INE'
|
|
}
|
|
>
|
|
<p>
|
|
Preparar não grava observações. Confirmar importa para consulta
|
|
administrativa.{' '}
|
|
{editorialEnabled
|
|
? 'A revisão, a aprovação e a publicação dos novos lotes são operações distintas. Os lotes anteriormente disponibilizados permanecem preservados.'
|
|
: 'Aprovar disponibiliza a série nas análises deste ambiente; desactivar conserva dados e histórico.'}
|
|
</p>
|
|
<form
|
|
className="space-y-3"
|
|
onSubmit={(e) => {
|
|
e.preventDefault();
|
|
if (!file) return;
|
|
const body = new FormData();
|
|
body.append('file', file);
|
|
body.append('publication_version', version);
|
|
if (year) body.append('baseline_year', year);
|
|
void execute('/management/demography/prepare', body);
|
|
}}
|
|
>
|
|
<label className="block">
|
|
Excel original
|
|
<input
|
|
type="file"
|
|
accept=".xlsx"
|
|
required
|
|
className={control}
|
|
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
|
|
/>
|
|
</label>
|
|
<label className="block">
|
|
Publicação / identificação do exemplar
|
|
<input
|
|
required
|
|
maxLength={255}
|
|
className={control}
|
|
value={version}
|
|
onChange={(e) => setVersion(e.target.value)}
|
|
/>
|
|
</label>
|
|
<label className="block">
|
|
Ano de referência, apenas para folha sem ano
|
|
<input
|
|
type="number"
|
|
min="1900"
|
|
max="2100"
|
|
className={control}
|
|
value={year}
|
|
onChange={(e) => setYear(e.target.value)}
|
|
/>
|
|
</label>
|
|
<button className={button} disabled={busy}>
|
|
Preparar e verificar
|
|
</button>
|
|
</form>
|
|
{message && <p role="alert">{message}</p>}
|
|
<h2 className="text-xl font-semibold">Importações anteriores</h2>
|
|
<ul>
|
|
{batches.map((b) => (
|
|
<li key={b.id}>
|
|
<a
|
|
className="underline"
|
|
href={`/management/demography?batch=${b.id}`}
|
|
>
|
|
{b.file_name} · {b.publication_version} · {b.status}
|
|
</a>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
{preview && (
|
|
<section key={preview.id} className="space-y-4">
|
|
<h2 className="text-xl font-semibold">
|
|
{preview.file_name} — {preview.status}
|
|
</h2>
|
|
<p>
|
|
{preview.report.record_count} observações extraídas.
|
|
SHA256: {preview.sha256}
|
|
</p>
|
|
<details>
|
|
<summary>Erros e advertências</summary>
|
|
<pre>
|
|
{JSON.stringify(
|
|
preview.report.issue_counts,
|
|
null,
|
|
2,
|
|
)}
|
|
</pre>
|
|
<div className="max-h-72 overflow-auto">
|
|
<ul>
|
|
{preview.report.issues.map((i, n) => (
|
|
<li key={n}>
|
|
{i.sheet}!{i.cell}: {i.code}{' '}
|
|
{i.delta ?? ''}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</div>
|
|
</details>
|
|
<h3 className="font-semibold">
|
|
Correspondências territoriais
|
|
</h3>
|
|
{preview.matches.map((m) => (
|
|
<label className="block" key={m.key}>
|
|
{m.province} / {m.territory} ({m.level}) — {m.state}
|
|
<select
|
|
className={control}
|
|
disabled={preview.status !== 'prepared'}
|
|
value={
|
|
mapping[m.key] ?? m.geo_location_id ?? ''
|
|
}
|
|
onChange={(e) =>
|
|
setMapping({
|
|
...mapping,
|
|
[m.key]: e.target.value,
|
|
})
|
|
}
|
|
>
|
|
<option value="">Por resolver</option>
|
|
{preview.territory_options
|
|
.filter((t) => t.location_type === m.level)
|
|
.map((t) => (
|
|
<option value={t.id} key={t.id}>
|
|
{t.name} (
|
|
{preview.territory_options.find(
|
|
(p) => p.id === t.parent_id,
|
|
)?.name ?? 'Província'}
|
|
)
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
))}
|
|
<label className="block">
|
|
Motivo e tratamento das advertências
|
|
<textarea
|
|
className={control}
|
|
minLength={10}
|
|
maxLength={2000}
|
|
value={reason}
|
|
onChange={(e) => setReason(e.target.value)}
|
|
/>
|
|
</label>
|
|
<div className="flex flex-wrap gap-3">
|
|
{preview.status === 'prepared' ? (
|
|
<button
|
|
disabled={busy || reason.length < 10}
|
|
className={button}
|
|
onClick={() =>
|
|
void execute(
|
|
`/management/demography/${preview.id}/confirm`,
|
|
{
|
|
sha256: preview.sha256,
|
|
mapping,
|
|
reason,
|
|
},
|
|
)
|
|
}
|
|
>
|
|
Confirmar importação
|
|
</button>
|
|
) : (
|
|
<>
|
|
{editorialEnabled && (
|
|
<div className="space-y-2">
|
|
{editorialRevision > 0 && (
|
|
<Link
|
|
className="underline"
|
|
href={`/management/editorial/demography/${preview.id}`}
|
|
>
|
|
Continuar revisão e consultar
|
|
versões
|
|
</Link>
|
|
)}
|
|
{preview.status === 'approved' ? (
|
|
<p>
|
|
{editorialRevision
|
|
? 'Lote publicado; consulte a edição e o histórico.'
|
|
: 'Lote anteriormente disponibilizado, preservado sem nova aprovação.'}
|
|
</p>
|
|
) : (
|
|
<button
|
|
type="button"
|
|
className={button}
|
|
disabled={
|
|
busy || review.processing
|
|
}
|
|
onClick={() => {
|
|
review.transform(() => ({
|
|
expected_revision:
|
|
editorialRevision,
|
|
}));
|
|
review.post(
|
|
`/management/editorial/demography/${preview.id}/drafts`,
|
|
);
|
|
}}
|
|
>
|
|
{editorialRevision
|
|
? 'Preparar nova edição de revisão'
|
|
: 'Preparar revisão para publicação'}
|
|
</button>
|
|
)}
|
|
</div>
|
|
)}
|
|
{!editorialEnabled &&
|
|
preview.status !== 'approved' && (
|
|
<button
|
|
disabled={
|
|
busy || reason.length < 10
|
|
}
|
|
className={button}
|
|
onClick={() =>
|
|
void execute(
|
|
`/management/demography/${preview.id}/transition`,
|
|
{
|
|
action: 'approved',
|
|
reason,
|
|
},
|
|
)
|
|
}
|
|
>
|
|
{qa
|
|
? 'Aprovar utilização em QA'
|
|
: 'Aprovar utilização'}
|
|
</button>
|
|
)}
|
|
{preview.status !== 'disabled' &&
|
|
(!editorialEnabled ||
|
|
editorialRevision === 0) && (
|
|
<button
|
|
disabled={
|
|
busy || reason.length < 10
|
|
}
|
|
className={button}
|
|
onClick={() =>
|
|
void execute(
|
|
`/management/demography/${preview.id}/transition`,
|
|
{
|
|
action: 'disabled',
|
|
reason,
|
|
},
|
|
)
|
|
}
|
|
>
|
|
Desactivar série
|
|
</button>
|
|
)}
|
|
</>
|
|
)}
|
|
</div>
|
|
<details>
|
|
<summary>Histórico</summary>
|
|
<ul>
|
|
{preview.events.map((e) => (
|
|
<li key={e.id}>
|
|
{e.created_at}: {e.action} — {e.reason}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</details>
|
|
</section>
|
|
)}
|
|
</Management>
|
|
);
|
|
}
|