462 lines
17 KiB
TypeScript
462 lines
17 KiB
TypeScript
import { Head, Link, useForm } from '@inertiajs/react';
|
|
import { useEffect, useRef } from 'react';
|
|
import { Button } from '@/components/ui/button';
|
|
import {
|
|
FormErrors,
|
|
PageTitle,
|
|
Panel,
|
|
controlClass,
|
|
} from '@/components/procurement';
|
|
|
|
type RecordVersion = {
|
|
id: number;
|
|
version: number;
|
|
state: string;
|
|
reason: string;
|
|
data: {
|
|
code?: string;
|
|
proposed_code?: string | null;
|
|
confirmed_code?: string;
|
|
source_reference?: string | null;
|
|
confirmation_source?: string;
|
|
deviation?: boolean;
|
|
requisition_item_id?: number;
|
|
};
|
|
snapshot: {
|
|
item?: { name?: string; description?: string };
|
|
confirmed_by?: { name: string };
|
|
master?: {
|
|
id: number;
|
|
version: number;
|
|
item: { code: string; name: string };
|
|
};
|
|
};
|
|
};
|
|
type Page<T> = {
|
|
data: T[];
|
|
prev_page_url: string | null;
|
|
next_page_url: string | null;
|
|
};
|
|
type Props = {
|
|
requisition: { id: number; number: string };
|
|
items: {
|
|
id: number;
|
|
description: string;
|
|
quantity: string;
|
|
unit: string;
|
|
}[];
|
|
latest: Record<string, RecordVersion> | RecordVersion[];
|
|
history: Page<RecordVersion>;
|
|
masters: Page<RecordVersion>;
|
|
stockItems: Page<{
|
|
id: number;
|
|
code: string;
|
|
name: string;
|
|
unit: string;
|
|
tariff: RecordVersion | null;
|
|
}>;
|
|
canPropose: boolean;
|
|
canConfirm: boolean;
|
|
masterSearch: string;
|
|
actorId: number;
|
|
tenantId: number;
|
|
};
|
|
|
|
function useGuard(dirty: boolean) {
|
|
const ref = useRef<HTMLFormElement>(null);
|
|
useEffect(() => {
|
|
const form = ref.current;
|
|
window.dispatchEvent(
|
|
new CustomEvent('sgc:context-dirty', { detail: { form, dirty } }),
|
|
);
|
|
return () => {
|
|
window.dispatchEvent(
|
|
new CustomEvent('sgc:context-dirty', {
|
|
detail: { form, dirty: false },
|
|
}),
|
|
);
|
|
};
|
|
}, [dirty]);
|
|
return ref;
|
|
}
|
|
function Pagination({ page }: { page: Page<unknown> }) {
|
|
return (
|
|
<nav className="my-3 flex flex-wrap gap-4" aria-label="Páginas">
|
|
{page.prev_page_url && (
|
|
<Link preserveState href={page.prev_page_url}>
|
|
Anterior
|
|
</Link>
|
|
)}
|
|
{page.next_page_url && (
|
|
<Link preserveState href={page.next_page_url}>
|
|
Seguinte
|
|
</Link>
|
|
)}
|
|
</nav>
|
|
);
|
|
}
|
|
function ItemForm({
|
|
item,
|
|
latest,
|
|
props,
|
|
scope,
|
|
url,
|
|
}: {
|
|
item: Props['items'][number];
|
|
latest?: RecordVersion;
|
|
props: Props;
|
|
scope: string;
|
|
url: string;
|
|
}) {
|
|
const form = useForm(`${scope}:item:${item.id}:${latest?.version ?? 0}`, {
|
|
operation_key: crypto.randomUUID(),
|
|
action: 'propose',
|
|
version: latest?.version ?? 0,
|
|
requisition_item_id: item.id,
|
|
master_id: '',
|
|
code: latest?.data.confirmed_code ?? latest?.data.proposed_code ?? '',
|
|
source_reference:
|
|
latest?.data.confirmation_source ??
|
|
latest?.data.source_reference ??
|
|
'',
|
|
reason: '',
|
|
});
|
|
const ref = useGuard(form.isDirty);
|
|
const submit = (action: string) => {
|
|
form.transform((data) => ({
|
|
...data,
|
|
action,
|
|
master_id: action === 'confirm' ? null : data.master_id || null,
|
|
}));
|
|
form.post(url, {
|
|
preserveScroll: true,
|
|
onSuccess: () => {
|
|
form.reset();
|
|
},
|
|
});
|
|
};
|
|
return (
|
|
<Panel title={`${item.description} · ${item.quantity} ${item.unit}`}>
|
|
<p className="mb-3">
|
|
{latest?.state === 'confirmed'
|
|
? `Confirmado: ${latest.data.confirmed_code} · ${latest.snapshot.confirmed_by?.name ?? 'Comprador registado'}`
|
|
: 'Código pautal por confirmar pelo comprador.'}
|
|
</p>
|
|
{latest?.snapshot.master && (
|
|
<p>
|
|
Proposta reutilizada de {latest.snapshot.master.item.code} ·{' '}
|
|
{latest.snapshot.master.item.name}, versão{' '}
|
|
{latest.snapshot.master.version}.
|
|
</p>
|
|
)}
|
|
{(props.canPropose || props.canConfirm) && (
|
|
<form
|
|
ref={ref}
|
|
className="grid gap-3"
|
|
onSubmit={(e) => {
|
|
e.preventDefault();
|
|
submit('propose');
|
|
}}
|
|
>
|
|
<FormErrors errors={form.errors} />
|
|
{props.canPropose && (
|
|
<label>
|
|
Reutilizar cadastro do material (opcional)
|
|
<select
|
|
className={controlClass}
|
|
value={form.data.master_id}
|
|
onChange={(e) => {
|
|
const selected = props.masters.data.find(
|
|
(row) =>
|
|
String(row.id) === e.target.value,
|
|
);
|
|
form.setData((old) => ({
|
|
...old,
|
|
master_id: e.target.value,
|
|
...(selected
|
|
? {
|
|
code:
|
|
selected.data.code ?? '',
|
|
source_reference:
|
|
selected.data
|
|
.source_reference ??
|
|
'',
|
|
}
|
|
: {}),
|
|
}));
|
|
}}
|
|
>
|
|
<option value="">
|
|
Proposta manual / conservar os valores
|
|
escritos
|
|
</option>
|
|
{props.masters.data.map((row) => (
|
|
<option key={row.id} value={row.id}>
|
|
{row.snapshot.item?.name} ·{' '}
|
|
{row.data.code} · v{row.version}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
)}
|
|
<label>
|
|
Código proposto ou a confirmar
|
|
<input
|
|
className={controlClass}
|
|
maxLength={40}
|
|
value={form.data.code}
|
|
onChange={(e) =>
|
|
form.setData('code', e.target.value)
|
|
}
|
|
/>
|
|
</label>
|
|
<label>
|
|
Fonte e versão documental
|
|
<textarea
|
|
className={controlClass}
|
|
maxLength={2000}
|
|
value={form.data.source_reference}
|
|
onChange={(e) =>
|
|
form.setData('source_reference', e.target.value)
|
|
}
|
|
/>
|
|
</label>
|
|
<label>
|
|
Motivo / justificação do desvio
|
|
<textarea
|
|
required
|
|
minLength={10}
|
|
maxLength={4000}
|
|
className={controlClass}
|
|
value={form.data.reason}
|
|
onChange={(e) =>
|
|
form.setData('reason', e.target.value)
|
|
}
|
|
/>
|
|
</label>
|
|
<div className="flex flex-wrap gap-3">
|
|
{props.canPropose && (
|
|
<Button disabled={form.processing}>
|
|
Guardar proposta
|
|
</Button>
|
|
)}
|
|
{props.canConfirm && latest?.state === 'proposed' && (
|
|
<Button
|
|
type="button"
|
|
disabled={form.processing}
|
|
onClick={() => submit('confirm')}
|
|
>
|
|
Confirmar como comprador
|
|
</Button>
|
|
)}
|
|
</div>
|
|
<p className="text-sm text-muted-foreground">
|
|
Pode guardar uma proposta sem código conhecido; a
|
|
confirmação exige código, fonte e motivo. Se alterar a
|
|
proposta confirmada, será criada uma nova versão por
|
|
confirmar. Não são calculadas imposições nem submetida
|
|
uma declaração.
|
|
</p>
|
|
</form>
|
|
)}
|
|
</Panel>
|
|
);
|
|
}
|
|
function MasterForm({
|
|
item,
|
|
scope,
|
|
url,
|
|
}: {
|
|
item: Props['stockItems']['data'][number];
|
|
scope: string;
|
|
url: string;
|
|
}) {
|
|
const form = useForm(
|
|
`${scope}:master:${item.id}:${item.tariff?.version ?? 0}`,
|
|
{
|
|
operation_key: crypto.randomUUID(),
|
|
action: 'master',
|
|
version: item.tariff?.version ?? 0,
|
|
stock_item_id: item.id,
|
|
code: item.tariff?.data.code ?? '',
|
|
source_reference: item.tariff?.data.source_reference ?? '',
|
|
reason: '',
|
|
},
|
|
);
|
|
const ref = useGuard(form.isDirty);
|
|
return (
|
|
<details className="rounded border p-3">
|
|
<summary>
|
|
{item.code} · {item.name} ·{' '}
|
|
{item.tariff?.data.code ?? 'Sem código pautal'}
|
|
</summary>
|
|
<form
|
|
ref={ref}
|
|
className="mt-3 grid gap-3"
|
|
onSubmit={(e) => {
|
|
e.preventDefault();
|
|
form.post(url, { preserveScroll: true });
|
|
}}
|
|
>
|
|
<FormErrors errors={form.errors} />
|
|
<label>
|
|
Código pautal do material
|
|
<input
|
|
required
|
|
maxLength={40}
|
|
className={controlClass}
|
|
value={form.data.code}
|
|
onChange={(e) => form.setData('code', e.target.value)}
|
|
/>
|
|
</label>
|
|
<label>
|
|
Fonte e versão documental
|
|
<textarea
|
|
required
|
|
maxLength={2000}
|
|
className={controlClass}
|
|
value={form.data.source_reference}
|
|
onChange={(e) =>
|
|
form.setData('source_reference', e.target.value)
|
|
}
|
|
/>
|
|
</label>
|
|
<label>
|
|
Motivo da actualização
|
|
<textarea
|
|
required
|
|
minLength={10}
|
|
maxLength={4000}
|
|
className={controlClass}
|
|
value={form.data.reason}
|
|
onChange={(e) => form.setData('reason', e.target.value)}
|
|
/>
|
|
</label>
|
|
<Button disabled={form.processing}>
|
|
Guardar versão do cadastro
|
|
</Button>
|
|
</form>
|
|
</details>
|
|
);
|
|
}
|
|
export default function ImportTariffs(props: Props) {
|
|
const url = `/requisicoes/${props.requisition.id}/classificacao-pautal`;
|
|
const scope = `import-tariffs:${props.tenantId}:${props.actorId}:${props.requisition.id}`;
|
|
return (
|
|
<div className="space-y-5">
|
|
<Head title="Classificação pautal" />
|
|
<PageTitle
|
|
eyebrow="Importação directa"
|
|
description="Proposta por artigo, cadastro do material e confirmação do comprador."
|
|
title={`Classificação pautal · ${props.requisition.number}`}
|
|
/>
|
|
<Link href={`/requisicoes/${props.requisition.id}`}>
|
|
Voltar à requisição
|
|
</Link>
|
|
<Panel title="Código por artigo e confirmação do comprador">
|
|
<p>
|
|
Associe explicitamente cada artigo importado ao cadastro do
|
|
material ou prepare a sua classificação manual. A
|
|
confirmação conserva a proposta e identifica o comprador e o
|
|
motivo; alterações futuras do cadastro não reescrevem
|
|
decisões anteriores.
|
|
</p>
|
|
<p className="mt-2">
|
|
O cadastro documental não certifica vigência legal, activa
|
|
taxas ou substitui a conferência das fontes aplicáveis.
|
|
Licenças e documentos aduaneiros continuam no respectivo
|
|
percurso.
|
|
</p>
|
|
</Panel>
|
|
<Panel title="Localizar material ou código">
|
|
<form
|
|
method="get"
|
|
action={url}
|
|
className="flex flex-wrap gap-3"
|
|
>
|
|
<label>
|
|
Pesquisa
|
|
<input
|
|
name="search"
|
|
maxLength={100}
|
|
defaultValue={props.masterSearch}
|
|
className={controlClass}
|
|
/>
|
|
</label>
|
|
<Button>Pesquisar</Button>
|
|
</form>
|
|
<Pagination page={props.masters} />
|
|
</Panel>
|
|
{props.items.map((item) => {
|
|
const latest = Object.values(props.latest).find(
|
|
(row) => row.data.requisition_item_id === item.id,
|
|
);
|
|
return (
|
|
<ItemForm
|
|
key={`${scope}:${item.id}:${latest?.version ?? 0}`}
|
|
item={item}
|
|
latest={latest}
|
|
props={props}
|
|
scope={scope}
|
|
url={url}
|
|
/>
|
|
);
|
|
})}
|
|
{props.canConfirm && (
|
|
<Panel title="Cadastro pautal dos materiais">
|
|
<p className="mb-3">
|
|
A actualização beneficia novas propostas. Para associar
|
|
um material, seleccione-o explicitamente no artigo da
|
|
requisição.
|
|
</p>
|
|
<div className="grid gap-3">
|
|
{props.stockItems.data.map((item) => (
|
|
<MasterForm
|
|
key={`${scope}:${item.id}:${item.tariff?.version ?? 0}`}
|
|
item={item}
|
|
scope={scope}
|
|
url={url}
|
|
/>
|
|
))}
|
|
</div>
|
|
<Pagination page={props.stockItems} />
|
|
</Panel>
|
|
)}
|
|
<Panel title="Histórico preservado">
|
|
{props.history.data.map((row) => (
|
|
<details key={row.id} className="my-3 rounded border p-3">
|
|
<summary>
|
|
{row.snapshot.item?.description} · v{row.version} ·{' '}
|
|
{row.state === 'confirmed'
|
|
? 'Confirmado'
|
|
: 'Proposto'}
|
|
</summary>
|
|
<p>
|
|
Proposta:{' '}
|
|
{row.data.proposed_code ?? 'Por completar'}
|
|
</p>
|
|
<p>
|
|
Fonte:{' '}
|
|
{row.data.source_reference ?? 'Por completar'}
|
|
</p>
|
|
{row.data.confirmed_code && (
|
|
<p>
|
|
Confirmado: {row.data.confirmed_code} ·{' '}
|
|
{row.snapshot.confirmed_by?.name} · Fonte:{' '}
|
|
{row.data.confirmation_source}
|
|
</p>
|
|
)}
|
|
<p>
|
|
{row.data.deviation
|
|
? 'Desvio justificado: '
|
|
: 'Motivo: '}
|
|
{row.reason}
|
|
</p>
|
|
</details>
|
|
))}
|
|
<Pagination page={props.history} />
|
|
</Panel>
|
|
</div>
|
|
);
|
|
}
|