628 lines
34 KiB
TypeScript
628 lines
34 KiB
TypeScript
import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
|
import { useEffect, useRef, type RefObject } from 'react';
|
|
import { Button } from '@/components/ui/button';
|
|
import { Input } from '@/components/ui/input';
|
|
import { FormErrors, PageTitle, Panel } from '@/components/procurement';
|
|
import { orderPartDraftKey, orderPartMinor } from '@/lib/order-parts';
|
|
import { money } from '@/types/procurement';
|
|
|
|
type Selection = {
|
|
award_id: number;
|
|
items: { quotation_item_id: number; quantity: string }[];
|
|
};
|
|
type Candidate = {
|
|
id: number;
|
|
requisition_id: number;
|
|
number: string;
|
|
supplier: string;
|
|
currency: string;
|
|
items: { id: number; description: string; remaining: string }[];
|
|
};
|
|
type Financial = {
|
|
origin: number;
|
|
award_id: number;
|
|
requires_adoption: boolean;
|
|
version?: number;
|
|
plan_hash?: string;
|
|
allocations: {
|
|
allocation_key: string;
|
|
line_id: number;
|
|
centre_id: number;
|
|
description: string;
|
|
subtotal: string;
|
|
total: string;
|
|
}[];
|
|
};
|
|
type Preview = {
|
|
selection: { sources: Selection[] };
|
|
can_issue: boolean;
|
|
financial: Financial[];
|
|
prepared: {
|
|
fingerprint: string;
|
|
currency: string;
|
|
subtotal_minor: number;
|
|
total_minor: number;
|
|
sources: {
|
|
requisition_id: number;
|
|
requisition_number?: string | null;
|
|
award_id: number;
|
|
currency: string;
|
|
items: {
|
|
description: string;
|
|
quotation_item_id: number;
|
|
quantity_offset_milli: number;
|
|
quantity_milli: number;
|
|
total_minor: number;
|
|
}[];
|
|
}[];
|
|
};
|
|
};
|
|
type Props = {
|
|
candidates: {
|
|
data: Candidate[];
|
|
prev_page_url: string | null;
|
|
next_page_url: string | null;
|
|
};
|
|
preview: Preview | null;
|
|
};
|
|
|
|
function useGuard(ref: RefObject<HTMLFormElement | null>, dirty: boolean) {
|
|
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, ref]);
|
|
}
|
|
|
|
function Adoption({ award }: { award: number }) {
|
|
const form = useForm({ operation_key: crypto.randomUUID() });
|
|
return (
|
|
<div className="grid gap-3 rounded-lg border p-4">
|
|
<p>
|
|
Esta origem ainda não tem distribuição para parcelas. Pode
|
|
adoptar a reserva já adjudicada, conservando o centro, os
|
|
valores e o histórico. Uma ordem anterior não é alterada.
|
|
</p>
|
|
<p className="text-sm text-muted-foreground">
|
|
Se não existir reserva, complete primeiro o controlo orçamental
|
|
da origem. A adopção não cria dotação nem saldo.
|
|
</p>
|
|
<FormErrors errors={form.errors} />
|
|
<Button
|
|
type="button"
|
|
disabled={form.processing}
|
|
onClick={() =>
|
|
form.post(`/adjudicacoes/${award}/parcelas/adoptar`)
|
|
}
|
|
>
|
|
Adoptar a reserva existente
|
|
</Button>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function Prepared({
|
|
preview,
|
|
historyKey,
|
|
}: {
|
|
preview: Preview;
|
|
historyKey: string;
|
|
}) {
|
|
const initial = {
|
|
order_key: crypto.randomUUID(),
|
|
operation_key: crypto.randomUUID(),
|
|
budget_sources: preview.financial.map((source) => ({
|
|
origin: source.origin,
|
|
version: source.version ?? 0,
|
|
plan_hash: source.plan_hash ?? '',
|
|
allocations: source.allocations.map((row) => ({
|
|
allocation_key: row.allocation_key,
|
|
subtotal: row.subtotal,
|
|
total: row.total,
|
|
})),
|
|
})),
|
|
};
|
|
const form = useForm(historyKey, initial);
|
|
const ref = useRef<HTMLFormElement>(null);
|
|
const changed = form.data.budget_sources.some((source, i) =>
|
|
source.allocations.some(
|
|
(row, j) =>
|
|
row.subtotal !==
|
|
initial.budget_sources[i]?.allocations[j]?.subtotal ||
|
|
row.total !== initial.budget_sources[i]?.allocations[j]?.total,
|
|
),
|
|
);
|
|
useGuard(ref, changed);
|
|
return (
|
|
<div id="order-parts-review" tabIndex={-1} className="scroll-mt-24">
|
|
<Panel title="Conferir e emitir a ordem">
|
|
<p className="mb-4">
|
|
As origens mantêm as suas aprovações. Só as quantidades
|
|
indicadas são emitidas; a reserva restante fica disponível
|
|
para as próximas parcelas. Cancelar uma parcela não autoriza
|
|
a sua repetição.
|
|
</p>
|
|
<form
|
|
ref={ref}
|
|
className="grid min-w-0 gap-5"
|
|
onSubmit={(event) => {
|
|
event.preventDefault();
|
|
const invalid = form.data.budget_sources.some(
|
|
(source) =>
|
|
source.allocations.some(
|
|
(row) =>
|
|
orderPartMinor(row.subtotal) === null ||
|
|
orderPartMinor(row.total) === null,
|
|
),
|
|
);
|
|
if (invalid) {
|
|
form.setError(
|
|
'budget_sources',
|
|
'Indique montantes válidos, com até duas casas decimais.',
|
|
);
|
|
return;
|
|
}
|
|
form.transform((data) => ({
|
|
order_key: data.order_key,
|
|
operation_key: data.operation_key,
|
|
sources: preview.selection.sources,
|
|
fingerprint: preview.prepared.fingerprint,
|
|
budget_sources: data.budget_sources.map(
|
|
(source) => ({
|
|
origin: source.origin,
|
|
version: source.version,
|
|
plan_hash: source.plan_hash,
|
|
allocations: source.allocations.map(
|
|
(row) => ({
|
|
allocation_key: row.allocation_key,
|
|
subtotal_minor: orderPartMinor(
|
|
row.subtotal,
|
|
),
|
|
total_minor: orderPartMinor(
|
|
row.total,
|
|
),
|
|
}),
|
|
),
|
|
}),
|
|
),
|
|
}));
|
|
form.post('/ordens/parcelas/emitir');
|
|
}}
|
|
>
|
|
<FormErrors errors={form.errors} />
|
|
{preview.prepared.sources.map((source, index) => (
|
|
<fieldset
|
|
key={source.requisition_id}
|
|
className="grid min-w-0 gap-3 rounded-lg border p-4"
|
|
>
|
|
<legend className="px-2 font-semibold">
|
|
<Link
|
|
href={`/requisicoes/${source.requisition_id}/adjudicacao`}
|
|
className="underline"
|
|
>
|
|
{source.requisition_number ??
|
|
`Origem #${source.requisition_id}`}
|
|
</Link>
|
|
</legend>
|
|
{source.items.map((line, i) => (
|
|
<p key={i} className="break-words">
|
|
{line.description}:{' '}
|
|
{line.quantity_milli / 1000} —{' '}
|
|
{money(line.total_minor, source.currency)}
|
|
</p>
|
|
))}
|
|
{preview.financial[index].requires_adoption ? (
|
|
<Adoption award={source.award_id} />
|
|
) : (
|
|
<>
|
|
<p className="text-sm text-muted-foreground">
|
|
Confira a imputação em MZN por centro.
|
|
Quando há vários centros, indique
|
|
explicitamente os montantes; o sistema
|
|
não distribui diferenças
|
|
automaticamente.
|
|
</p>
|
|
{preview.financial[index].allocations.map(
|
|
(row, position) => (
|
|
<div
|
|
key={row.allocation_key}
|
|
className="grid min-w-0 gap-3 rounded border p-3 sm:grid-cols-2"
|
|
>
|
|
<p className="break-words sm:col-span-2">
|
|
{row.description} · Centro #
|
|
{row.centre_id}
|
|
</p>
|
|
<label className="grid gap-1">
|
|
Sem IVA (MZN)
|
|
<Input
|
|
inputMode="decimal"
|
|
required
|
|
value={
|
|
form.data
|
|
.budget_sources[
|
|
index
|
|
].allocations[
|
|
position
|
|
].subtotal
|
|
}
|
|
onChange={(event) => {
|
|
form.setData(
|
|
'budget_sources',
|
|
form.data.budget_sources.map(
|
|
(
|
|
entry,
|
|
i,
|
|
) =>
|
|
i !==
|
|
index
|
|
? entry
|
|
: {
|
|
...entry,
|
|
allocations:
|
|
entry.allocations.map(
|
|
(
|
|
part,
|
|
j,
|
|
) =>
|
|
j !==
|
|
position
|
|
? part
|
|
: {
|
|
...part,
|
|
subtotal:
|
|
event
|
|
.target
|
|
.value,
|
|
},
|
|
),
|
|
},
|
|
),
|
|
);
|
|
}}
|
|
/>
|
|
</label>
|
|
<label className="grid gap-1">
|
|
Com IVA (MZN)
|
|
<Input
|
|
inputMode="decimal"
|
|
required
|
|
value={
|
|
form.data
|
|
.budget_sources[
|
|
index
|
|
].allocations[
|
|
position
|
|
].total
|
|
}
|
|
onChange={(event) => {
|
|
form.setData(
|
|
'budget_sources',
|
|
form.data.budget_sources.map(
|
|
(
|
|
entry,
|
|
i,
|
|
) =>
|
|
i !==
|
|
index
|
|
? entry
|
|
: {
|
|
...entry,
|
|
allocations:
|
|
entry.allocations.map(
|
|
(
|
|
part,
|
|
j,
|
|
) =>
|
|
j !==
|
|
position
|
|
? part
|
|
: {
|
|
...part,
|
|
total: event
|
|
.target
|
|
.value,
|
|
},
|
|
),
|
|
},
|
|
),
|
|
);
|
|
}}
|
|
/>
|
|
</label>
|
|
</div>
|
|
),
|
|
)}
|
|
</>
|
|
)}
|
|
</fieldset>
|
|
))}
|
|
<p className="font-semibold">
|
|
Total documental:{' '}
|
|
{money(
|
|
preview.prepared.total_minor,
|
|
preview.prepared.currency,
|
|
)}
|
|
</p>
|
|
{!preview.can_issue && (
|
|
<p role="status">
|
|
Complete a distribuição de todas as origens antes de
|
|
emitir. A emissão multimoeda por parcelas ainda não
|
|
está disponível.
|
|
</p>
|
|
)}
|
|
<p className="text-sm text-muted-foreground">
|
|
Na emissão voltam a ser verificadas aprovações,
|
|
quantidades, versões e orçamento. Se a origem tiver
|
|
mudado, conserve os valores e volte a conferir.
|
|
</p>
|
|
<Button
|
|
type="submit"
|
|
disabled={form.processing || !preview.can_issue}
|
|
>
|
|
Emitir uma ordem com estas parcelas
|
|
</Button>
|
|
</form>
|
|
</Panel>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export default function Parts({ candidates, preview }: Props) {
|
|
const actor = usePage().props.auth?.user;
|
|
const historyKey = `order-parts:${actor?.tenant_id}:${actor?.id}`;
|
|
const form = useForm<{ sources: Selection[] }>(`${historyKey}:selection`, {
|
|
sources: [],
|
|
});
|
|
const ref = useRef<HTMLFormElement>(null);
|
|
useGuard(ref, form.data.sources.length > 0);
|
|
useEffect(() => {
|
|
if (preview) {
|
|
const review = document.getElementById('order-parts-review');
|
|
review?.scrollIntoView({ block: 'start' });
|
|
review?.focus({ preventScroll: true });
|
|
}
|
|
}, [preview]);
|
|
const draftKey = preview ? orderPartDraftKey(preview.prepared.sources) : '';
|
|
return (
|
|
<>
|
|
<Head title="Preparar ordens por parcelas" />
|
|
<div className="mx-auto grid w-full max-w-5xl min-w-0 gap-6 p-5 lg:p-8">
|
|
<PageTitle
|
|
eyebrow="Compras"
|
|
title="Preparar ordens por parcelas"
|
|
description="Divida uma adjudicação ou reúna origens aprovadas da mesma empresa, fornecedor e moeda. Cada origem conserva a sua identidade."
|
|
/>
|
|
<Link href="/ordens" className="underline">
|
|
Voltar às adjudicações e ordens
|
|
</Link>
|
|
<Panel title="Escolher origens e quantidades">
|
|
<form
|
|
ref={ref}
|
|
className="grid min-w-0 gap-4"
|
|
onSubmit={(event) => {
|
|
event.preventDefault();
|
|
form.post('/ordens/preparar', {
|
|
preserveState: true,
|
|
preserveScroll: true,
|
|
});
|
|
}}
|
|
>
|
|
<p>
|
|
Escolha apenas as linhas a emitir agora. O saldo de
|
|
quantidade já inclui as parcelas anteriores, mesmo
|
|
canceladas. As aprovações e os prazos serão
|
|
novamente conferidos.
|
|
</p>
|
|
<p className="text-sm text-muted-foreground">
|
|
As escolhas ficam conservadas neste navegador para o
|
|
seu utilizador e empresa. Depois de actualizar a
|
|
página, volte a conferir para recuperar a preparação
|
|
actual.
|
|
</p>
|
|
<FormErrors errors={form.errors} />
|
|
{candidates.data.map((candidate) => {
|
|
const selected = form.data.sources.find(
|
|
(source) => source.award_id === candidate.id,
|
|
);
|
|
return (
|
|
<fieldset
|
|
key={candidate.id}
|
|
className="grid min-w-0 gap-3 rounded-lg border p-4"
|
|
>
|
|
<legend className="px-2 font-semibold break-words">
|
|
{candidate.number} ·{' '}
|
|
{candidate.supplier} ·{' '}
|
|
{candidate.currency}
|
|
</legend>
|
|
{candidate.items.map((line) => {
|
|
const value = selected?.items.find(
|
|
(item) =>
|
|
item.quotation_item_id ===
|
|
line.id,
|
|
);
|
|
return (
|
|
<div
|
|
key={line.id}
|
|
className="grid gap-2"
|
|
>
|
|
<label className="flex items-start gap-3 break-words">
|
|
<input
|
|
type="checkbox"
|
|
checked={
|
|
value !== undefined
|
|
}
|
|
disabled={
|
|
!value &&
|
|
Number(
|
|
line.remaining,
|
|
) <= 0
|
|
}
|
|
onChange={(event) => {
|
|
const items = event
|
|
.target.checked
|
|
? [
|
|
...(selected?.items ??
|
|
[]),
|
|
{
|
|
quotation_item_id:
|
|
line.id,
|
|
quantity:
|
|
line.remaining,
|
|
},
|
|
]
|
|
: (
|
|
selected?.items ??
|
|
[]
|
|
).filter(
|
|
(item) =>
|
|
item.quotation_item_id !==
|
|
line.id,
|
|
);
|
|
form.setData(
|
|
'sources',
|
|
[
|
|
...form.data.sources.filter(
|
|
(
|
|
source,
|
|
) =>
|
|
source.award_id !==
|
|
candidate.id,
|
|
),
|
|
...(items.length ===
|
|
0
|
|
? []
|
|
: [
|
|
{
|
|
award_id:
|
|
candidate.id,
|
|
items,
|
|
},
|
|
]),
|
|
],
|
|
);
|
|
}}
|
|
/>
|
|
{line.description} · Por
|
|
emitir: {line.remaining}
|
|
</label>
|
|
{value && (
|
|
<label className="grid gap-1">
|
|
Quantidade desta parcela
|
|
<Input
|
|
inputMode="decimal"
|
|
required
|
|
value={
|
|
value.quantity
|
|
}
|
|
onChange={(event) =>
|
|
form.setData(
|
|
'sources',
|
|
form.data.sources.map(
|
|
(
|
|
source,
|
|
) =>
|
|
source.award_id !==
|
|
candidate.id
|
|
? source
|
|
: {
|
|
...source,
|
|
items: source.items.map(
|
|
(
|
|
item,
|
|
) =>
|
|
item.quotation_item_id !==
|
|
line.id
|
|
? item
|
|
: {
|
|
...item,
|
|
quantity:
|
|
event
|
|
.target
|
|
.value,
|
|
},
|
|
),
|
|
},
|
|
),
|
|
)
|
|
}
|
|
/>
|
|
</label>
|
|
)}
|
|
</div>
|
|
);
|
|
})}
|
|
<Link
|
|
href={`/requisicoes/${candidate.requisition_id}/adjudicacao`}
|
|
className="underline"
|
|
>
|
|
Consultar a adjudicação
|
|
</Link>
|
|
</fieldset>
|
|
);
|
|
})}
|
|
{candidates.data.length === 0 && (
|
|
<p>
|
|
Não há adjudicações aprovadas disponíveis nesta
|
|
página.
|
|
</p>
|
|
)}
|
|
<p>
|
|
{form.data.sources.length}{' '}
|
|
{form.data.sources.length === 1
|
|
? 'origem seleccionada'
|
|
: 'origens seleccionadas'}
|
|
, incluindo escolhas de outras páginas.
|
|
</p>
|
|
<Button
|
|
disabled={
|
|
form.processing ||
|
|
form.data.sources.length === 0
|
|
}
|
|
>
|
|
Conferir as parcelas seleccionadas
|
|
</Button>
|
|
</form>
|
|
<nav
|
|
aria-label="Páginas de adjudicações"
|
|
className="mt-4 flex flex-wrap gap-4"
|
|
>
|
|
{candidates.prev_page_url && (
|
|
<Link
|
|
preserveState
|
|
href={candidates.prev_page_url}
|
|
className="underline"
|
|
>
|
|
Anterior
|
|
</Link>
|
|
)}
|
|
{candidates.next_page_url && (
|
|
<Link
|
|
preserveState
|
|
href={candidates.next_page_url}
|
|
className="underline"
|
|
>
|
|
Seguinte
|
|
</Link>
|
|
)}
|
|
</nav>
|
|
</Panel>
|
|
{preview && (
|
|
<Prepared
|
|
key={`${draftKey}:${preview.financial.map((source) => `${source.plan_hash}:${source.version}`).join(':')}`}
|
|
preview={preview}
|
|
historyKey={`${historyKey}:issue:${draftKey}:${preview.financial.map((source) => source.version).join(':')}`}
|
|
/>
|
|
)}
|
|
</div>
|
|
</>
|
|
);
|
|
}
|