Files
compras/resources/js/pages/supply/import-dossier.tsx
T
nala 930064269e
tests / ci (push) Waiting to run
commit compras2 2711
2026-11-27 18:11:02 +02:00

372 lines
16 KiB
TypeScript

import { Head, Link, useForm } from '@inertiajs/react';
import { useEffect, useRef } from 'react';
import { FormErrors, PageTitle, Panel } from '@/components/procurement';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import ImportPartySelection, {
type ImportPartyWorkspace,
} from '@/components/import-party-selection';
type Document = {
id: number;
record_key: string;
version: number;
created_at: string;
created_by: number;
current: boolean;
supersedes: number | null;
sha256: string;
reason: string;
data: {
type: string;
reference: string;
issuer_reference: string;
issued_on: string | null;
notes: string | null;
};
};
type Props = {
importRecord: { id: number; version: number; record_key: string };
order: { id: number; number: string };
documents: {
data: Document[];
prev_page_url: string | null;
next_page_url: string | null;
};
types: Record<string, string>;
canWrite: boolean;
actorId: number;
tenantId: number;
parties?: ImportPartyWorkspace;
bankSupportReady?: boolean;
readinessReady?: boolean;
};
export default function Dossier({
importRecord,
order,
documents,
types,
canWrite,
actorId,
tenantId,
parties,
bankSupportReady = false,
readinessReady = false,
}: Props) {
const form = useForm(
`import-dossier:${tenantId}:${actorId}:${importRecord.record_key}:${importRecord.version}`,
{
operation_key: crypto.randomUUID(),
record_key: null as string | null,
version: 0,
type: '',
reference: '',
issuer_reference: '',
issued_on: '',
notes: '',
reason: '',
file: null as File | null,
},
);
const ref = useRef<HTMLFormElement>(null);
const fileRef = useRef<HTMLInputElement>(null);
useEffect(() => {
const current = ref.current;
window.dispatchEvent(
new CustomEvent('sgc:context-dirty', {
detail: { form: current, dirty: form.isDirty },
}),
);
return () => {
window.dispatchEvent(
new CustomEvent('sgc:context-dirty', {
detail: { form: current, dirty: false },
}),
);
};
}, [form.isDirty]);
const correction = (document: Document) => {
form.setData({
operation_key: crypto.randomUUID(),
record_key: document.record_key,
version: document.version,
type: document.data.type,
reference: document.data.reference,
issuer_reference: document.data.issuer_reference,
issued_on: document.data.issued_on ?? '',
notes: document.data.notes ?? '',
reason: '',
file: null,
});
if (fileRef.current) fileRef.current.value = '';
ref.current?.scrollIntoView({ block: 'start' });
};
return (
<>
<Head title={`Dossiê de importação · ${order.number}`} />
<div className="mx-auto grid w-full max-w-5xl min-w-0 gap-6 p-5 lg:p-8">
<PageTitle
eyebrow="Compras · Importações"
title={`Dossiê de importação · ${order.number}`}
description="Originais e correcções documentais ligados à mesma ordem."
/>
<p>
Registar um documento conserva a evidência. Não submete
declarações na JUE, não confirma pagamentos nem liberta
mercadoria. Esses factos mantêm os seus percursos e
competências próprios.
</p>
<Link className="underline" href={`/ordens/${order.id}`}>
Consultar a ordem e as suas origens
</Link>
{readinessReady && (
<Link
className="underline"
href={`/compras/importacoes/${importRecord.id}/acompanhamento`}
>
Consultar alertas e próximos passos
</Link>
)}
{bankSupportReady && (
<Link
className="underline"
href={`/compras/importacoes/${importRecord.id}/suporte-bancario`}
>
Acompanhar termo e suporte bancário
</Link>
)}
{parties && (
<ImportPartySelection
workspace={parties}
importId={importRecord.id}
importKey={importRecord.record_key}
actorId={actorId}
tenantId={tenantId}
/>
)}
{canWrite && (
<Panel
title={
form.data.record_key
? 'Preparar uma correcção documental'
: 'Registar um documento'
}
>
<form
ref={ref}
className="grid gap-4"
onSubmit={(event) => {
event.preventDefault();
form.post(
`/compras/importacoes/${importRecord.id}/documentos`,
{
forceFormData: true,
onSuccess: () => {
form.reset();
if (fileRef.current)
fileRef.current.value = '';
},
},
);
}}
>
<FormErrors errors={form.errors} />
<label className="grid gap-1">
Tipo de documento
<select
required
disabled={form.data.record_key !== null}
className="rounded border p-2"
value={form.data.type}
onChange={(e) =>
form.setData('type', e.target.value)
}
>
<option value="">Seleccione</option>
{Object.entries(types).map(
([key, label]) => (
<option key={key} value={key}>
{label}
</option>
),
)}
</select>
</label>
<label className="grid gap-1">
Referência
<Input
required
maxLength={180}
value={form.data.reference}
onChange={(e) =>
form.setData(
'reference',
e.target.value,
)
}
/>
</label>
<label className="grid gap-1">
Entidade emitente
<Input
required
maxLength={180}
value={form.data.issuer_reference}
onChange={(e) =>
form.setData(
'issuer_reference',
e.target.value,
)
}
/>
</label>
<label className="grid gap-1">
Data do documento, quando disponível
<Input
type="date"
value={form.data.issued_on}
onChange={(e) =>
form.setData(
'issued_on',
e.target.value,
)
}
/>
</label>
<label className="grid gap-1">
Notas
<textarea
className="min-h-20 rounded border p-3"
maxLength={4000}
value={form.data.notes}
onChange={(e) =>
form.setData('notes', e.target.value)
}
/>
</label>
<label className="grid gap-1">
Motivo do registo ou da correcção
<textarea
required
minLength={10}
maxLength={4000}
className="min-h-20 rounded border p-3"
value={form.data.reason}
onChange={(e) =>
form.setData('reason', e.target.value)
}
/>
</label>
<label className="grid gap-1">
Original privado (PDF, JPG ou PNG, até 2 MB)
<Input
ref={fileRef}
required
type="file"
accept=".pdf,.jpg,.jpeg,.png"
onChange={(e) =>
form.setData(
'file',
e.target.files?.[0] ?? null,
)
}
/>
</label>
<p className="text-sm text-muted-foreground">
Após recarregar a página, volte a seleccionar o
ficheiro. A correcção cria uma nova versão e
conserva o original anterior.
</p>
<Button disabled={form.processing} type="submit">
Guardar documento privado
</Button>
</form>
</Panel>
)}
<Panel title="Documentos e versões conservadas">
{documents.data.length === 0 ? (
<p>Ainda não há documentos neste dossiê.</p>
) : (
documents.data.map((document) => (
<section
key={document.id}
className="mb-4 grid min-w-0 gap-2 rounded border p-4"
>
<h2 className="font-semibold">
{types[document.data.type]} ·{' '}
{document.data.reference}
</h2>
<p>
{document.data.issuer_reference} · Versão{' '}
{document.version}
{document.current
? ' · Actual'
: ' · Histórica'}
</p>
{document.data.issued_on && (
<p>
Data do documento:{' '}
{document.data.issued_on}
</p>
)}
{document.data.notes && (
<p className="whitespace-pre-wrap">
{document.data.notes}
</p>
)}
<p className="whitespace-pre-wrap">
{document.reason}
</p>
<a
className="underline"
href={`/compras/importacoes/${importRecord.id}/documentos/${document.id}`}
>
Descarregar esta versão
</a>
{canWrite && document.current && (
<Button
type="button"
variant="outline"
onClick={() => correction(document)}
>
Preparar correcção
</Button>
)}
<details>
<summary>Rastreabilidade</summary>
<p>
Registo: {document.created_at} ·
Interveniente #{document.created_by}
</p>
<p className="text-xs break-all">
SHA-256: {document.sha256}
</p>
</details>
</section>
))
)}
<div className="flex gap-4">
{documents.prev_page_url && (
<Link
className="underline"
href={documents.prev_page_url}
>
Anterior
</Link>
)}
{documents.next_page_url && (
<Link
className="underline"
href={documents.next_page_url}
>
Seguinte
</Link>
)}
</div>
</Panel>
</div>
</>
);
}