Files
compras/resources/js/components/import-party-selection.tsx
T
nala e709d900d1
tests / ci (push) Waiting to run
commit compras 2711
2026-11-27 13:49:31 +02:00

387 lines
16 KiB
TypeScript

import { Link, useForm } from '@inertiajs/react';
import { useEffect, useRef } from 'react';
import { FormErrors, Panel } from '@/components/procurement';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
type Selection = {
id: number;
version: number;
data: {
role: string;
supplier_id: number;
instruction_document_id: number;
};
snapshot: {
supplier: { name: string; nuit: string; version: number };
instructions: { data: { reference: string } };
};
reason: string;
issues?: string[];
};
type Page<T> = {
data: T[];
prev_page_url: string | null;
next_page_url: string | null;
};
export type ImportPartyWorkspace = {
roles: Record<string, string>;
canSelect: boolean;
search: string;
suppliers: Page<{
id: number;
name: string;
nuit: string;
version: number;
}>;
instructions: Page<{
id: number;
version: number;
data: { reference: string; issuer_reference: string };
}>;
current: Selection[];
history: Page<Selection>;
};
function Pages({
page,
}: {
page: { prev_page_url: string | null; next_page_url: string | null };
}) {
return (
<div className="flex gap-4">
{page.prev_page_url && (
<Link className="underline" href={page.prev_page_url}>
Anterior
</Link>
)}
{page.next_page_url && (
<Link className="underline" href={page.next_page_url}>
Seguinte
</Link>
)}
</div>
);
}
export default function ImportPartySelection({
workspace,
importId,
importKey,
actorId,
tenantId,
}: {
workspace: ImportPartyWorkspace;
importId: number;
importKey: string;
actorId: number;
tenantId: number;
}) {
const current = workspace.current.find((s) => s.data.role === 'broker');
const form = useForm(`import-parties:${tenantId}:${actorId}:${importKey}`, {
operation_key: crypto.randomUUID(),
role: 'broker',
version: current?.version ?? 0,
supplier_id: current ? String(current.data.supplier_id) : '',
supplier_version: current?.snapshot.supplier.version ?? 0,
supplier_label: current?.snapshot.supplier.name ?? '',
instruction_document_id: current
? String(current.data.instruction_document_id)
: '',
instruction_label: current?.snapshot.instructions.data.reference ?? '',
reason: '',
no_conflict: false,
});
const ref = useRef<HTMLFormElement>(null);
useEffect(() => {
const node = ref.current;
window.dispatchEvent(
new CustomEvent('sgc:context-dirty', {
detail: { form: node, dirty: form.isDirty },
}),
);
return () => {
window.dispatchEvent(
new CustomEvent('sgc:context-dirty', {
detail: { form: node, dirty: false },
}),
);
};
}, [form.isDirty]);
const loadRole = (role: string) => {
const selected = workspace.current.find((s) => s.data.role === role);
form.setData({
operation_key: crypto.randomUUID(),
role,
version: selected?.version ?? 0,
supplier_id: selected ? String(selected.data.supplier_id) : '',
supplier_version: selected?.snapshot.supplier.version ?? 0,
supplier_label: selected?.snapshot.supplier.name ?? '',
instruction_document_id: selected
? String(selected.data.instruction_document_id)
: '',
instruction_label:
selected?.snapshot.instructions.data.reference ?? '',
reason: '',
no_conflict: false,
});
};
return (
<Panel title="Despachante e transitário">
<p>
A escolha reutiliza uma entidade elegível do cadastro e as
instruções escritas deste dossiê. O comprador deve ser distinto
dos requisitantes; os conflitos são novamente conferidos antes
de continuar o trânsito ou a libertação.
</p>
<div className="my-4 grid gap-3">
{workspace.current.length === 0 ? (
<p>Sem selecção registada.</p>
) : (
workspace.current.map((selection) => (
<section
key={selection.id}
className="rounded border p-3"
>
<h3 className="font-semibold">
{workspace.roles[selection.data.role]} ·{' '}
{selection.snapshot.supplier.name}
</h3>
<p>
Versão {selection.version} · Instruções:{' '}
{selection.snapshot.instructions.data.reference}
</p>
{selection.issues?.map((issue) => (
<p
key={issue}
className="mt-2 text-amber-800 dark:text-amber-300"
>
{issue}
</p>
))}
</section>
))
)}
</div>
{workspace.canSelect && (
<div className="grid gap-5">
<form
ref={ref}
className="grid gap-3 rounded border p-4"
onSubmit={(event) => {
event.preventDefault();
form.transform(
({
supplier_label: _supplierLabel,
instruction_label: _instructionLabel,
...data
}) => data,
);
form.post(
`/compras/importacoes/${importId}/intervenientes`,
);
}}
>
<FormErrors errors={form.errors} />
<label className="grid gap-1">
Função
<select
value={form.data.role}
className="rounded border p-2"
onChange={(event) =>
loadRole(event.target.value)
}
>
{Object.entries(workspace.roles).map(
([key, label]) => (
<option key={key} value={key}>
{label}
</option>
),
)}
</select>
</label>
<p>
Entidade seleccionada:{' '}
{form.data.supplier_label || 'Por seleccionar'}
</p>
<p>
Instruções seleccionadas:{' '}
{form.data.instruction_label || 'Por seleccionar'}
</p>
<p className="text-sm">
Versão da selecção em conferência:{' '}
{form.data.version}
</p>
<Button
type="button"
variant="outline"
onClick={() => loadRole(form.data.role)}
>
Rever a selecção actual
</Button>
<label className="grid gap-1">
Motivo da selecção ou substituição
<textarea
required
minLength={10}
maxLength={4000}
className="min-h-20 rounded border p-3"
value={form.data.reason}
onChange={(event) =>
form.setData('reason', event.target.value)
}
/>
</label>
<label className="flex items-start gap-2">
<input
type="checkbox"
required
checked={form.data.no_conflict}
onChange={(event) =>
form.setData(
'no_conflict',
event.target.checked,
)
}
/>
Confirmo a ausência de conflito de interesses com
esta entidade nesta selecção.
</label>
<Button
disabled={
form.processing ||
!form.data.supplier_id ||
!form.data.instruction_document_id
}
type="submit"
>
Confirmar entidade e instruções
</Button>
</form>
<section className="grid gap-3 rounded border p-4">
<h3 className="font-semibold">
Escolher a entidade do cadastro
</h3>
<form
method="get"
action={`/compras/importacoes/${importId}/documentos`}
className="flex flex-wrap gap-2"
>
<Input
name="party_search"
aria-label="Pesquisar entidades"
defaultValue={workspace.search}
maxLength={100}
/>
<Button type="submit" variant="outline">
Pesquisar entidades
</Button>
</form>
{workspace.suppliers.data.map((supplier) => (
<div
key={supplier.id}
className="flex flex-wrap items-center justify-between gap-2"
>
<p>
{supplier.name} · {supplier.nuit}
</p>
<Button
type="button"
variant="outline"
onClick={() => {
form.setData(
'supplier_id',
String(supplier.id),
);
form.setData(
'supplier_label',
supplier.name,
);
form.setData(
'supplier_version',
supplier.version,
);
form.setData('no_conflict', false);
}}
>
Escolher entidade
</Button>
</div>
))}
<Pages page={workspace.suppliers} />
</section>
<section className="grid gap-3 rounded border p-4">
<h3 className="font-semibold">
Escolher instruções escritas
</h3>
{workspace.instructions.data.length === 0 ? (
<p>
Registe primeiro as instruções escritas no
dossiê documental.
</p>
) : (
workspace.instructions.data.map((instruction) => (
<div
key={instruction.id}
className="flex flex-wrap items-center justify-between gap-2"
>
<p>
{instruction.data.reference} ·{' '}
{instruction.data.issuer_reference} ·
Versão {instruction.version}
</p>
<Button
type="button"
variant="outline"
onClick={() => {
form.setData(
'instruction_document_id',
String(instruction.id),
);
form.setData(
'instruction_label',
instruction.data.reference,
);
}}
>
Escolher instruções
</Button>
</div>
))
)}
<Pages page={workspace.instructions} />
</section>
</div>
)}
{workspace.history.data.length > 0 && (
<details className="mt-4">
<summary>Histórico de selecções e substituições</summary>
{workspace.history.data.map((selection) => (
<section
key={selection.id}
className="my-3 rounded border p-3"
>
<p>
{workspace.roles[selection.data.role]} ·{' '}
{selection.snapshot.supplier.name} · Versão{' '}
{selection.version}
</p>
<p className="whitespace-pre-wrap">
{selection.reason}
</p>
<a
className="underline"
href={`/compras/importacoes/${importId}/documentos/${selection.data.instruction_document_id}`}
>
Consultar as instruções desta versão
</a>
</section>
))}
<Pages page={workspace.history} />
</details>
)}
</Panel>
);
}