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

685 lines
38 KiB
TypeScript

import { Head, Link, router, useForm } from '@inertiajs/react';
import { useEffect, useRef } from 'react';
import {
FormErrors,
PageTitle,
Panel,
controlClass,
} from '@/components/procurement';
import { Button } from '@/components/ui/button';
import { estimateMinor, estimateMoney } from '@/lib/import-estimate-money';
const labels: Record<string, string> = {
freight: 'Frete',
insurance: 'Seguro',
duty: 'Direitos aduaneiros',
ice: 'ICE',
vat: 'IVA da importação',
other: 'Outros encargos',
};
type Component = {
key: string;
kind: string;
status: string;
basis: string;
subtotal_minor: number | null;
tax_minor: number | null;
total_minor: number | null;
};
type Version = {
id: number;
version: number;
state: string;
reason: string;
data: { budget_id: number; components: Component[] };
snapshot: {
legal_sources?: Record<
string,
{
estimate_id: number;
estimate_version: number;
charge_key: string;
}
>;
plan: {
complete: boolean;
budget_amount_minor: number | null;
known_total_minor: number;
unknown: string[];
};
};
};
type Page<T> = {
data: T[];
prev_page_url: string | null;
next_page_url: string | null;
};
type Props = {
legalAmounts?: {
id: number;
version: number;
snapshot: {
item: { description: string };
legal_rule: { data: { official_reference: string } };
result: {
lines: {
key: string;
kind: string;
label: string;
method: string;
amount_minor: number | null;
}[];
};
};
}[];
requisition: {
id: number;
number: string;
status: string;
total_minor: number | null;
};
latest: Version | null;
nativeChanged: boolean;
history: Page<Version>;
budgets: Page<{ id: number; includes_tax: boolean }>;
canPrepare: boolean;
actorId: number;
tenantId: number;
};
function Pages({ page }: { page: Page<unknown> }) {
return (
<nav className="mt-3 flex 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>
);
}
export default function ImportEstimate(props: Props) {
const { requisition, latest, canPrepare } = props;
const components =
latest?.data.components ??
Object.keys(labels).map((kind) => ({
key: kind,
kind,
status: 'unknown',
basis: '',
subtotal_minor: null,
tax_minor: null,
total_minor: null,
}));
const form = useForm(
`import-estimate:${props.tenantId}:${props.actorId}:${requisition.id}:${latest?.version ?? 0}`,
{
operation_key: '',
version: latest?.version ?? 0,
budget_id: latest ? String(latest.data.budget_id) : '',
reason: '',
components: components.map((row) => ({
key: row.key,
kind: row.kind,
status: row.status,
basis: row.basis,
subtotal: estimateMoney(row.subtotal_minor),
tax: estimateMoney(row.tax_minor),
total: estimateMoney(row.total_minor),
legal_estimate_id:
latest?.snapshot.legal_sources?.[row.key]?.estimate_id ??
(null as number | null),
legal_charge_key:
latest?.snapshot.legal_sources?.[row.key]?.charge_key ??
(null as string | null),
})),
},
);
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]);
return (
<>
<Head title="Estimativa de importação" />
<main className="mx-auto max-w-5xl space-y-5 px-5 py-8">
<PageTitle
eyebrow="Preparação da importação"
title="Estimativa de importação"
description={`Requisição ${requisition.number}. Pressupostos antes das facturas e documentos aduaneiros.`}
/>
<Link
className="underline"
href={`/requisicoes/${requisition.id}`}
>
Voltar à requisição
</Link>
<Panel
title="Base da preparação"
description="Os bens conservam os valores da requisição. Indique apenas encargos adicionais, sem repetir custos já incluídos nos bens. Não são aplicadas taxas legais ou isenções automaticamente."
>
<p>
Bens:{' '}
{requisition.total_minor === null
? 'Por completar'
: `${estimateMoney(requisition.total_minor)} MZN`}
.
</p>
<p>
Guardar conserva os pressupostos; a submissão usa a
estimativa completa para determinar as aprovações e
reservar os custos adicionais.
</p>
{props.nativeChanged && (
<p role="alert">
A requisição mudou. Reveja os pressupostos e guarde
uma nova versão antes de submeter.
</p>
)}
{latest && (
<p>
{latest.snapshot.plan.complete
? `Estimativa completa: ${estimateMoney(latest.snapshot.plan.budget_amount_minor)} MZN, segundo a base do orçamento escolhido.`
: `Estimativa incompleta. Parcela conhecida: ${estimateMoney(latest.snapshot.plan.known_total_minor)} MZN; o total permanece indeterminado.`}
</p>
)}
</Panel>
{canPrepare && (
<Panel
title="Pressupostos dos encargos"
description="Para cada família, indique um valor conhecido, informação ainda em falta ou não aplicabilidade fundamentada. Montantes em MZN; não substitua valores desconhecidos por zero."
>
<form
ref={ref}
className="space-y-5"
onSubmit={(event) => {
event.preventDefault();
const operation =
form.data.operation_key ||
crypto.randomUUID();
form.setData('operation_key', operation);
form.transform((data) => ({
...data,
legal_sources: Object.fromEntries(
data.components
.filter(
(row) =>
row.legal_estimate_id !==
null &&
row.legal_charge_key !==
null,
)
.map((row) => [
row.key,
{
estimate_id:
row.legal_estimate_id,
charge_key:
row.legal_charge_key,
},
]),
),
operation_key: operation,
components: data.components.map((row) => ({
key: row.key,
kind: row.kind,
status: row.status,
basis: row.basis,
subtotal_minor:
row.status === 'known'
? estimateMinor(row.subtotal)
: null,
tax_minor:
row.status === 'known'
? estimateMinor(row.tax)
: null,
total_minor:
row.status === 'known'
? estimateMinor(row.total)
: null,
})),
}));
form.post(
`/requisicoes/${requisition.id}/estimativa-importacao`,
{
preserveScroll: true,
onSuccess: () => {
form.reset();
router.visit(
`/requisicoes/${requisition.id}/estimativa-importacao`,
{
preserveState: false,
preserveScroll: true,
},
);
},
},
);
}}
>
<FormErrors errors={form.errors} />
<label className="grid gap-1">
Orçamento aprovado dos encargos
<select
className={controlClass}
required
value={form.data.budget_id}
onChange={(e) =>
form.setData(
'budget_id',
e.target.value,
)
}
>
<option value="">Seleccione</option>
{props.budgets.data.map((budget) => (
<option
key={budget.id}
value={budget.id}
>
Orçamento {budget.id} ·{' '}
{budget.includes_tax
? 'Inclui imposto'
: 'Sem imposto'}
</option>
))}
</select>
</label>
<Pages page={props.budgets} />
{form.data.components.map((row, index) => (
<fieldset
key={row.key}
className="space-y-3 rounded border p-4"
>
<legend>
{labels[row.kind] ?? row.kind}
</legend>
{((props.legalAmounts?.length ?? 0) > 0 ||
row.legal_estimate_id !== null) && (
<label className="grid gap-1">
Reutilizar uma imposição calculada
<select
className={controlClass}
value={
row.legal_estimate_id ===
null
? ''
: `${row.legal_estimate_id}:${row.legal_charge_key}`
}
onChange={(event) => {
const candidates = (
props.legalAmounts ?? []
).flatMap((estimate) =>
estimate.snapshot.result.lines
.filter(
(line) =>
line.kind ===
row.kind,
)
.map((line) => ({
estimate,
line,
value: `${estimate.id}:${line.key}`,
})),
);
const selected =
candidates.find(
(candidate) =>
candidate.value ===
event.target
.value,
);
form.setData(
'components',
form.data.components.map(
(component, at) =>
at !== index
? component
: selected
? {
...component,
legal_estimate_id:
selected
.estimate
.id,
legal_charge_key:
selected
.line
.key,
status:
selected
.line
.amount_minor ===
null
? 'unknown'
: selected
.line
.method ===
'not_applicable'
? 'not_applicable'
: 'known',
basis: `Estimativa legal #${selected.estimate.id}, versão ${selected.estimate.version}; ${selected.line.label}. Fonte: ${selected.estimate.snapshot.legal_rule.data.official_reference}.`,
total: estimateMoney(
selected
.line
.amount_minor,
),
subtotal:
selected
.line
.amount_minor ===
0
? '0.00'
: '',
tax:
selected
.line
.amount_minor ===
0
? '0.00'
: '',
}
: {
...component,
legal_estimate_id:
null,
legal_charge_key:
null,
},
),
);
}}
>
<option value="">
Pressuposto manual / retirar
ligação e conservar os
valores
</option>
{row.legal_estimate_id !==
null &&
!(
props.legalAmounts ?? []
).some(
(estimate) =>
estimate.id ===
row.legal_estimate_id,
) && (
<option
value={`${row.legal_estimate_id}:${row.legal_charge_key}`}
>
Versão preservada da
estimativa #
{
row.legal_estimate_id
}
</option>
)}
{(
props.legalAmounts ?? []
).flatMap((estimate) =>
estimate.snapshot.result.lines
.filter(
(line) =>
line.kind ===
row.kind,
)
.map((line) => (
<option
key={`${estimate.id}:${line.key}`}
value={`${estimate.id}:${line.key}`}
>
{
estimate
.snapshot
.item
.description
}{' '}
· {line.label} ·
estimativa #
{estimate.id} v
{
estimate.version
}{' '}
·{' '}
{line.amount_minor ===
null
? 'Por determinar'
: `${estimateMoney(line.amount_minor)} MZN`}
</option>
)),
)}
</select>
{row.legal_estimate_id !== null && (
<span>
O total conserva a fonte
seleccionada. Indique
explicitamente a divisão
entre base e imposto segundo
o orçamento. Para alterar o
montante, retire primeiro a
ligação.
</span>
)}
</label>
)}
<label className="grid gap-1">
Situação
<select
className={controlClass}
value={row.status}
onChange={(e) =>
form.setData(
'components',
form.data.components.map(
(r, i) =>
i === index
? {
...r,
status: e
.target
.value,
}
: r,
),
)
}
>
<option value="unknown">
Ainda desconhecido
</option>
<option value="known">
Valor conhecido
</option>
<option value="not_applicable">
Não aplicável
</option>
</select>
</label>
{row.status === 'known' && (
<div className="grid gap-3 sm:grid-cols-3">
{(
[
'subtotal',
'tax',
'total',
] as const
).map((field) => (
<label
key={field}
className="grid gap-1"
>
{field === 'subtotal'
? 'Base'
: field === 'tax'
? 'Imposto'
: 'Total'}{' '}
(MZN)
<input
className={controlClass}
inputMode="decimal"
required
value={row[field]}
onChange={(e) =>
form.setData(
'components',
form.data.components.map(
(r, i) =>
i ===
index
? {
...r,
[field]:
e
.target
.value,
}
: r,
),
)
}
/>
</label>
))}
</div>
)}
<label className="grid gap-1">
Fonte ou fundamento
<textarea
className={controlClass}
required
minLength={3}
maxLength={4000}
value={row.basis}
onChange={(e) =>
form.setData(
'components',
form.data.components.map(
(r, i) =>
i === index
? {
...r,
basis: e
.target
.value,
}
: r,
),
)
}
/>
</label>
<div className="flex flex-wrap gap-3">
<Button
type="button"
variant="outline"
disabled={
form.data.components.length >=
100
}
onClick={() =>
form.setData('components', [
...form.data.components,
{
key: crypto.randomUUID(),
kind: row.kind,
status: 'unknown',
basis: '',
subtotal: '',
tax: '',
total: '',
legal_estimate_id: null,
legal_charge_key: null,
},
])
}
>
Acrescentar parcela desta família
</Button>
{form.data.components.filter(
(component) =>
component.kind === row.kind,
).length > 1 && (
<Button
type="button"
variant="outline"
onClick={() =>
form.setData(
'components',
form.data.components.filter(
(_, at) =>
at !== index,
),
)
}
>
Retirar parcela da preparação
</Button>
)}
</div>
</fieldset>
))}
<label className="grid gap-1">
Motivo desta versão
<textarea
className={controlClass}
required
minLength={10}
maxLength={4000}
value={form.data.reason}
onChange={(e) =>
form.setData('reason', e.target.value)
}
/>
</label>
<Button disabled={form.processing}>
Guardar estimativa
</Button>
</form>
</Panel>
)}
<Panel title="Histórico preservado">
{props.history.data.map((record) => (
<article key={record.id} className="border-b py-3">
<p>
Versão {record.version} ·{' '}
{record.snapshot.plan.complete
? 'Completa'
: 'Incompleta'}
</p>
<p>{record.reason}</p>
{record.data.components.map((row) => (
<p key={row.key}>
{labels[row.kind]}:{' '}
{row.status === 'known'
? `${estimateMoney(row.total_minor)} MZN`
: row.status === 'unknown'
? 'Desconhecido'
: 'Não aplicável'}{' '}
· {row.basis}
</p>
))}
</article>
))}
<Pages page={props.history} />
</Panel>
</main>
</>
);
}