commit melhorias compras6
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-23 06:37:16 +02:00
parent db1615fac1
commit dc73540558
73 changed files with 7539 additions and 175 deletions
@@ -0,0 +1,58 @@
import { Panel } from '@/components/procurement';
export type FrozenImportTariff = {
record_id: number;
version: number;
item: { description: string; quantity: string; unit: string };
data: {
proposed_code: string | null;
confirmed_code: string;
source_reference: string | null;
confirmation_source: string;
deviation: boolean;
};
confirmed_by: { name: string };
reason: string;
};
export default function ImportTariffSummary({
records,
}: {
records?: Record<number, FrozenImportTariff>;
}) {
if (!records || !Object.keys(records).length) return null;
return (
<Panel title="Classificação pautal preservada na emissão">
<div className="grid gap-4">
{Object.values(records).map((record) => (
<dl
key={record.record_id}
className="rounded border p-3 text-sm"
>
<dt className="font-medium">
{record.item.description}
</dt>
<dd>
Código confirmado: {record.data.confirmed_code} ·
versão {record.version} · {record.confirmed_by.name}
</dd>
<dt>Proposta e fonte</dt>
<dd>
{record.data.proposed_code ?? 'Não indicada'} ·{' '}
{record.data.source_reference ?? 'Por completar'}
</dd>
<dt>Fonte da confirmação</dt>
<dd>{record.data.confirmation_source}</dd>
<dt>
{record.data.deviation
? 'Justificação do desvio'
: 'Motivo'}
</dt>
<dd className="break-words whitespace-pre-wrap">
{record.reason}
</dd>
</dl>
))}
</div>
</Panel>
);
}
@@ -0,0 +1,142 @@
import { Link } from '@inertiajs/react';
import { Panel } from '@/components/procurement';
import { money, roleLabels } from '@/types/procurement';
export type OrderPartFrame = {
requisition: { id: number; number: string };
department: { name: string };
cost_center: { code: string; name: string };
quotation: { reference: string; currency: string; payment_terms: string };
award: {
delivery_date: string;
delivery_location: string;
justification?: string;
};
native_preparation: {
approved_reference?: { subtotal_minor: number; total_minor: number };
items: {
quotation_item_id: number;
description: string;
quantity_milli: number;
approved_quantity_milli?: number;
total_minor: number;
}[];
};
approval_rules?: { approval_includes_tax: boolean };
final_approvals?: {
id: number;
role: string;
approver_id: number | null;
decision: string;
}[];
};
export function OrderPartsSummary({ sources }: { sources: OrderPartFrame[] }) {
if (sources.length === 0) return null;
return (
<Panel
title={
sources.length === 1
? 'Origem da parcela emitida'
: 'Origens preservadas na ordem'
}
>
<p className="mb-4">
Cada linha conserva a adjudicação original. Quantidades e IVA
usam os arredondamentos cumulativos da origem; o documento
mostra apenas as parcelas emitidas nesta ordem.
</p>
<div className="grid min-w-0 gap-4">
{sources.map((source) => (
<section
key={source.requisition.id}
className="grid min-w-0 gap-2 rounded-lg border p-4"
>
<h3 className="font-semibold">
<Link
href={`/requisicoes/${source.requisition.id}`}
className="underline"
>
{source.requisition.number}
</Link>
</h3>
<p className="break-words">
{source.department.name} · {source.cost_center.code}{' '}
· {source.cost_center.name}
</p>
<p className="break-words">
Proposta {source.quotation.reference} · Pagamento:{' '}
{source.quotation.payment_terms}
</p>
<p className="break-words">
Entrega: {source.award.delivery_date} ·{' '}
{source.award.delivery_location}
</p>
{source.native_preparation.approved_reference && (
<p>
Base aprovada da origem:{' '}
{money(
source.approval_rules
?.approval_includes_tax === false
? source.native_preparation
.approved_reference.subtotal_minor
: source.native_preparation
.approved_reference.total_minor,
'MZN',
)}{' '}
(
{source.approval_rules
?.approval_includes_tax === false
? 'sem IVA'
: 'com IVA'}
).
</p>
)}
{source.award.justification && (
<p className="break-words whitespace-pre-wrap">
Fundamento: {source.award.justification}
</p>
)}
<Link
href={`/requisicoes/${source.requisition.id}/adjudicacao`}
className="underline"
>
Consultar a adjudicação desta origem
</Link>
{(source.final_approvals ?? []).map((step) => (
<p key={step.id} className="text-sm">
{Object.entries(roleLabels).find(
([role]) => role === step.role,
)?.[1] ?? step.role}{' '}
·{' '}
{step.decision === 'approved'
? 'Aprovado'
: step.decision === 'rejected'
? 'Rejeitado'
: 'Pendente'}{' '}
· Interveniente #{step.approver_id}
</p>
))}
{source.native_preparation.items.map((line) => (
<p
key={line.quotation_item_id}
className="break-words"
>
{line.description}: emitido{' '}
{line.quantity_milli / 1000}
{line.approved_quantity_milli === undefined
? ''
: ` de ${line.approved_quantity_milli / 1000} aprovado(s)`}{' '}
·{' '}
{money(
line.total_minor,
source.quotation.currency,
)}
</p>
))}
</section>
))}
</div>
</Panel>
);
}
+58
View File
@@ -37,6 +37,64 @@ function topic(
}
export const journeyHelp: JourneyHelp[] = [
topic(
'import-tariffs',
'Classificar os artigos importados',
['supply/import-tariffs'],
'Conservar o código proposto, a fonte e a confirmação do comprador por artigo.',
[
'Seleccione explicitamente o cadastro do material ou escreva uma proposta manual.',
'Guarde uma proposta mesmo quando o código ainda for desconhecido.',
'O comprador confirma o código e a fonte, justificando qualquer desvio.',
],
[
'Uma nova versão do cadastro não altera confirmações anteriores.',
'A classificação documental não activa imposições, licenças ou submissões JUE.',
],
'Se a origem ou a versão mudou, conserve os seus valores e seleccione o cadastro actual antes de voltar a guardar.',
'Conclua a conferência documental e os restantes requisitos aplicáveis à importação.',
),
topic(
'import-costs',
'Conferir o custo de aterragem',
['supply/import-costs'],
'Reunir os custos da importação conservando cada documento, moeda e credor.',
[
'Registe as imposições documentadas e conserve a evidência privada.',
'Seleccione as facturas já validadas e os documentos adicionais.',
'Identifique cada componente e indique os valores documentais e as referências em MZN.',
'Guarde a preparação para conferência independente de Finanças.',
'Depois da conferência, reserve, comprometa e consuma as origens elegíveis; pode seleccionar uma parte das origens.',
'Para custos tardios, prepare uma nova versão e aplique a alteração conferida. O consumo anterior não se repete.',
],
[
'Não inclua a mesma factura com dois papéis.',
'Não some novamente um encargo já incluído no preço de uma factura; conserve o documento como evidência de consulta.',
'Uma taxa desconhecida não equivale a zero; conserve a taxa, data e fonte explícitas.',
'A conferência documental não cria dívida. A etapa orçamental, após revisão independente, movimenta apenas os custos adicionais e conserva os efeitos nativos das facturas.',
],
'Se uma origem mudou, devolva a preparação e corrija numa nova versão. Os documentos e versões anteriores ficam preservados.',
'Consultar os saldos e o histórico por origem; uma libertação afecta apenas o montante ainda não consumido.',
),
topic(
'order-parts',
'Dividir ou consolidar ordens de compra',
['purchases/parts'],
'Emitir apenas as quantidades necessárias ou reunir origens aprovadas do mesmo fornecedor e moeda, conservando a identidade de cada linha.',
[
'Escolha as origens e as quantidades ainda por emitir.',
'Clique em Conferir para obter os valores nativos e as distribuições.',
'Confira as imputações em MZN; se houver vários centros, indique explicitamente cada parcela.',
'Emita a ordem e acompanhe as recepções e a factura no percurso normal.',
],
[
'As aprovações da origem continuam obrigatórias e são novamente verificadas.',
'A adopção apenas transfere uma reserva adjudicada existente, sem criar saldo ou alterar ordens anteriores.',
'Cancelar uma parcela não autoriza a sua repetição nem encerra a requisição inteira.',
],
'Se a quantidade ou a versão tiver mudado, conserve a preparação e volte a conferir. Consulte o histórico antes de repetir uma emissão incerta.',
'Conferir a ordem emitida e as suas origens; depois registar a recepção e a factura com a validação independente de Finanças.',
),
topic(
'budget-distributions',
'Distribuir um pedido por centros de custo',
+36
View File
@@ -0,0 +1,36 @@
/** Exact transport of explicit monetary input; no price, VAT or exchange calculation. */
export function orderPartMinor(value: string): number | null {
if (!/^\d{1,13}(?:\.\d{1,2})?$/.test(value)) return null;
const [whole, fraction = ''] = value.split('.');
const result = BigInt(whole) * 100n + BigInt(fraction.padEnd(2, '0'));
return result <= 100000000000000n ? Number(result) : null;
}
/** Display-only metadata must not change the identity of a remembered quantity preparation. */
export function orderPartDraftKey(
sources: {
requisition_id: number;
award_id: number;
items: {
quotation_item_id: number;
quantity_milli: number;
quantity_offset_milli: number;
}[];
}[],
): string {
return JSON.stringify(
sources
.map((source): [number, number, [number, number, number][]] => [
source.requisition_id,
source.award_id,
source.items
.map((line): [number, number, number] => [
line.quotation_item_id,
line.quantity_milli,
line.quantity_offset_milli,
])
.sort((a, b) => a[0] - b[0]),
])
.sort((a, b) => a[0] - b[0]),
);
}
+225 -13
View File
@@ -39,6 +39,19 @@ type Line = {
unit_price: string;
tax_rate: string;
};
type OrderPartOption = {
origin: number;
allocation_key: string;
line_id: number;
centre_id: number;
description: string;
};
type OrderPartInput = {
origin: number;
allocation_key: string;
subtotal: string;
total: string;
};
type Invoice = {
id: number;
number: string;
@@ -81,6 +94,8 @@ export default function Invoices({
supplier: string;
items: Source[];
budgetDistributionOptions?: BudgetDistributionOption[] | null;
orderParts?: boolean;
orderPartsBudgetOptions?: OrderPartOption[] | null;
}[];
canManage: boolean;
focusInvoiceId?: number | null;
@@ -139,8 +154,22 @@ export default function Invoices({
})) ?? []) as Line[],
};
const form = useForm(historyKey, initialData);
const [partAllocations, setPartAllocations] = useRemember<OrderPartInput[]>(
(
orders.find((source) => source.id === focusOrderId)
?.orderPartsBudgetOptions ?? []
).map((row) => ({
origin: row.origin,
allocation_key: row.allocation_key,
subtotal: '',
total: '',
})),
`${historyKey}:part-allocations`,
);
const formElement = useRef<HTMLFormElement>(null);
const dirty = hasPreparationChanges(initialData, form.data);
const dirty =
hasPreparationChanges(initialData, form.data) ||
partAllocations.some((row) => row.subtotal !== '' || row.total !== '');
useEffect(() => {
window.dispatchEvent(
new CustomEvent('sgc:context-dirty', {
@@ -157,9 +186,38 @@ export default function Invoices({
(source) => source.id === line.purchase_order_item_id,
)?.requisition_item_id,
);
const activeAllocations = form.data.budget_distribution_preparation.filter(
(row) => activeLineIds.includes(row.line_id),
);
const activeAllocations = (
form.data.budget_distribution_preparation ?? []
).filter((row) => activeLineIds.includes(row.line_id));
const updatePartAmount = (
option: OrderPartOption,
field: 'subtotal' | 'total',
value: string,
) => {
setPartAllocations((rows) =>
rows.some(
(row) =>
row.origin === option.origin &&
row.allocation_key === option.allocation_key,
)
? rows.map((row) =>
row.origin !== option.origin ||
row.allocation_key !== option.allocation_key
? row
: { ...row, [field]: value },
)
: [
...rows,
{
origin: option.origin,
allocation_key: option.allocation_key,
subtotal: '',
total: '',
[field]: value,
},
],
);
};
return (
<>
<Head title="Facturas" />
@@ -245,13 +303,29 @@ export default function Invoices({
e.preventDefault();
form.transform((d) => ({
...d,
budget_distribution_preparation:
d.budget_distribution_preparation.filter(
(row) =>
activeLineIds.includes(
row.line_id,
),
),
...(order?.orderParts
? {
order_part_allocations:
partAllocations.filter(
(row) =>
order.orderPartsBudgetOptions?.some(
(option) =>
option.origin ===
row.origin &&
option.allocation_key ===
row.allocation_key &&
activeLineIds.includes(
option.line_id,
),
),
),
}
: {}),
budget_distribution_preparation: (
d.budget_distribution_preparation ?? []
).filter((row) =>
activeLineIds.includes(row.line_id),
),
items: d.items
.filter((l) => l.quantity !== '')
.map(
@@ -281,6 +355,21 @@ export default function Invoices({
value={orderId}
onChange={(e) => {
setOrderId(e.target.value);
setPartAllocations(
(
orders.find(
(source) =>
String(source.id) ===
e.target.value,
)?.orderPartsBudgetOptions ?? []
).map((row) => ({
origin: row.origin,
allocation_key:
row.allocation_key,
subtotal: '',
total: '',
})),
);
form.setData('reason', '');
form.setData(
'budget_distribution_preparation',
@@ -475,7 +564,11 @@ export default function Invoices({
onChange={(rows) =>
form.setData(
'budget_distribution_preparation',
form.data.budget_distribution_preparation.map(
(
form.data
.budget_distribution_preparation ??
[]
).map(
(row) =>
rows.find(
(changed) =>
@@ -488,7 +581,126 @@ export default function Invoices({
/>
</div>
)}
<Button disabled={!orderId || form.processing}>
{order?.orderParts && (
<fieldset className="grid min-w-0 gap-3 rounded-lg border p-4">
<legend className="px-2 font-semibold">
Imputação pelas origens da ordem
</legend>
<p>
Indique em MZN a parcela de cada linha
efectivamente facturada. A ordem e a
factura mantêm um único documento; o
consumo fica separado pelas origens
aprovadas.
</p>
{order.orderPartsBudgetOptions == null && (
<p role="status">
A preparação de novas facturas desta
ordem está temporariamente
indisponível. Os documentos
anteriores continuam em consulta.
</p>
)}
{(order.orderPartsBudgetOptions ?? [])
.filter((option) =>
activeLineIds.includes(
option.line_id,
),
)
.map((option) => {
const index =
partAllocations.findIndex(
(row) =>
row.origin ===
option.origin &&
row.allocation_key ===
option.allocation_key,
);
const row = partAllocations[index];
return (
<div
key={`${option.origin}:${option.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">
Origem #{option.origin}{' '}
· {option.description} ·
Centro #
{option.centre_id}
</p>
<label className="grid gap-1">
Sem IVA (MZN)
<Input
required
inputMode="decimal"
value={
row?.subtotal ??
''
}
onChange={(event) =>
updatePartAmount(
option,
'subtotal',
event.target
.value,
)
}
/>
</label>
<label className="grid gap-1">
Com IVA (MZN)
<Input
required
inputMode="decimal"
value={
row?.total ?? ''
}
onChange={(event) =>
updatePartAmount(
option,
'total',
event.target
.value,
)
}
/>
</label>
</div>
);
})}
<label className="grid gap-1">
Fundamento da imputação
<textarea
className="rounded-md border p-2"
required
minLength={10}
maxLength={4000}
value={form.data.reason}
onChange={(event) =>
form.setData(
'reason',
event.target.value,
)
}
/>
</label>
<p className="text-sm text-muted-foreground">
Os montantes têm de coincidir com as
linhas nativas e com o compromisso ainda
disponível. Não há compensação
automática. A validação exige outra
pessoa de Finanças.
</p>
</fieldset>
)}
<Button
disabled={
!orderId ||
form.processing ||
(order?.orderParts === true &&
order.orderPartsBudgetOptions == null)
}
>
Registar para conferência independente
</Button>
</form>
+10
View File
@@ -11,9 +11,11 @@ type Page<T> = {
export default function Orders({
orders,
awards,
partsAvailable = false,
}: {
orders: Page<PurchaseOrder>;
awards: Page<PurchaseAward>;
partsAvailable?: boolean;
}) {
return (
<>
@@ -25,6 +27,14 @@ export default function Orders({
description="Acompanhe as aprovações dos valores finais e os documentos emitidos para revisão."
/>
<Panel title="Ordens emitidas">
{partsAvailable && (
<Link
href="/ordens/preparar"
className="mb-4 inline-block underline"
>
Preparar ordens por parcelas ou consolidar origens
</Link>
)}
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<thead className="border-b text-muted-foreground">
+627
View File
@@ -0,0 +1,627 @@
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>
</>
);
}
+34 -5
View File
@@ -8,9 +8,14 @@ import { Button } from '@/components/ui/button';
import { date, money, roleLabels } from '@/types/procurement';
import { ExchangeSummary } from '@/components/quotation-exchange-panel';
import type { PurchaseOrder } from '@/types/purchase';
import ImportTariffSummary from '@/components/import-tariff-summary';
import OrderCancellationRequest, {
type OrderCancellationState,
} from '@/components/order-cancellation-request';
import {
OrderPartsSummary,
type OrderPartFrame,
} from '@/components/order-parts-summary';
type History = {
id: number;
@@ -29,11 +34,13 @@ export default function OrderShow({
history,
orderCancellation,
snapshotComplete = true,
orderPartsSources = [],
}: {
order: PurchaseOrder;
history: History[];
orderCancellation?: OrderCancellationState;
snapshotComplete?: boolean;
orderPartsSources?: OrderPartFrame[];
}) {
const snapshot = order.snapshot;
if (!snapshotComplete) {
@@ -145,11 +152,15 @@ export default function OrderShow({
Documento de desenvolvimento. Não autoriza compras
reais.
</strong>{' '}
Orçamento não verificado. Os dados apresentados foram
congelados na emissão.
{snapshot.budget_checked === true
? 'Controlo orçamental confirmado para as parcelas emitidas. '
: 'Orçamento não verificado. '}{' '}
Os dados apresentados foram congelados na emissão.
{snapshot.approval_rules.rules_provisional &&
' Regras de aprovação provisórias.'}
</div>
<OrderPartsSummary sources={orderPartsSources} />
<ImportTariffSummary records={snapshot.import_tariffs} />
<div className="grid gap-6 md:grid-cols-2">
{snapshot.investment_rules && (
<Panel title="Regra de investimento congelada">
@@ -315,7 +326,13 @@ export default function OrderShow({
<AgreementOrderLimitSummary
bindings={snapshot.agreement_bindings}
/>
<Panel title="Fundamento e matriz congelada">
<Panel
title={
orderPartsSources.length > 1
? 'Fundamento e matriz da referência principal'
: 'Fundamento e matriz congelada'
}
>
{snapshot.comparison_policy && (
<ComparisonPolicySummary
policy={snapshot.comparison_policy}
@@ -359,7 +376,13 @@ export default function OrderShow({
))}
</div>
</Panel>
<Panel title="Aprovações do valor final">
<Panel
title={
orderPartsSources.length > 1
? 'Aprovações da referência principal'
: 'Aprovações do valor final'
}
>
<ol className="space-y-3">
{snapshot.final_approvals.map((step) => (
<li key={step.id} className="text-sm">
@@ -382,7 +405,13 @@ export default function OrderShow({
separadamente.
</p>
</Panel>
<Panel title="Histórico do processo">
<Panel
title={
orderPartsSources.length > 1
? 'Histórico das origens'
: 'Histórico do processo'
}
>
<ol className="space-y-3">
{history.map((event) => (
<li key={event.id} className="text-sm">
+11
View File
@@ -53,7 +53,9 @@ export default function Show({
approvalRouting,
canRefreshRouting = false,
canPrepareDistributions = false,
importTariffsReady = false,
}: {
importTariffsReady?: boolean;
canPrepareDistributions?: boolean;
requisition: Requisition;
canRefreshRouting?: boolean;
@@ -161,6 +163,15 @@ export default function Show({
}
/>
<FormErrors errors={submission.errors} />
{importTariffsReady && (
<Button asChild variant="outline">
<Link
href={`/requisicoes/${r.id}/classificacao-pautal`}
>
Classificação pautal dos artigos importados
</Link>
</Button>
)}
{canPrepareDistributions && (
<Button asChild variant="outline">
<Link href={`/requisicoes/${r.id}/distribuicoes`}>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,461 @@
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>
);
}
+9
View File
@@ -75,6 +75,7 @@ type Projection = {
series?: { date: string; balance_milli: number }[];
};
type Props = {
importCostsReady?: boolean;
orderLimitsReady?: boolean;
linkedAgreementKey?: string | null;
linkedContractKey?: string | null;
@@ -1526,6 +1527,14 @@ export default function SupplyIndex(props: Props) {
/>
)}
<RecordActions record={record} props={props} />
{props.importCostsReady && (
<Link
className="mt-4 inline-block underline"
href={`/compras/importacoes/${record.id}/custos`}
>
Preparar e conferir o custo de aterragem
</Link>
)}
<details className="mt-4">
<summary className="cursor-pointer text-sm">
Dados preservados desta versão
+3
View File
@@ -1,6 +1,7 @@
import type { CommercialTerms } from '@/components/quotation-commercial-terms';
import type { ComparisonPolicy } from '@/components/comparison-policy-summary';
import type { ExchangeBasis } from '@/components/quotation-exchange-panel';
import type { FrozenImportTariff } from '@/components/import-tariff-summary';
export type MatrixRow = {
currency?: string;
@@ -98,6 +99,8 @@ export type PurchaseOrder = {
total_minor: number;
items: OrderItem[];
snapshot: {
import_tariffs?: Record<number, FrozenImportTariff>;
budget_checked?: boolean;
agreement_bindings?: Record<string, FrozenOrderAgreement>;
exchange_basis?: ExchangeBasis;
reference_amounts?: {