commit compras 2711
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-27 13:49:31 +02:00
parent dc73540558
commit e709d900d1
81 changed files with 5352 additions and 107 deletions
@@ -0,0 +1,182 @@
import { Link, useForm } from '@inertiajs/react';
import { useEffect, useRef } from 'react';
import { FormErrors, Panel, controlClass } from '@/components/procurement';
import { Button } from '@/components/ui/button';
import { estimateMinor, estimateMoney } from '@/lib/import-estimate-money';
export type EstimateSources = {
data: {
id: number;
version: number;
requisition_id: number;
budget_id: number;
revision: number | null;
reserved_minor: number | null;
committed_minor: number | null;
}[];
prev_page_url: string | null;
next_page_url: string | null;
};
export default function EstimateReconciliation({
sources,
planId,
url,
historyKey,
financialRevision,
}: {
sources: EstimateSources;
planId: number;
url: string;
historyKey: string;
financialRevision: number;
}) {
const form = useForm(
`${historyKey}:estimate-reconciliation:${planId}:${financialRevision}`,
{
operation_key: '',
actual_operation_key: '',
estimate_id: '',
amount: '',
reason: '',
},
);
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]);
if (
sources.data.length === 0 &&
!sources.prev_page_url &&
!sources.next_page_url
)
return null;
const selected = sources.data.find(
(source) => String(source.id) === form.data.estimate_id,
);
return (
<Panel
title="Reconciliar a estimativa anterior"
description="Seleccione a estimativa aprovada de uma origem desta ordem e a parcela que corresponde aos documentos conferidos. A mesma operação liberta essa parcela e aplica os custos efectivos; conserva o saldo para as restantes ordens. As facturas mantêm o seu principal nativo."
>
<form
ref={ref}
className="space-y-3"
onSubmit={(event) => {
event.preventDefault();
if (!selected) return;
const operation =
form.data.operation_key || crypto.randomUUID();
const actual =
form.data.actual_operation_key || crypto.randomUUID();
form.setData((data) => ({
...data,
operation_key: operation,
actual_operation_key: actual,
}));
form.transform((data) => ({
operation_key: operation,
actual_operation_key: actual,
action: 'reconcile_estimate',
financial_revision: financialRevision,
estimate_id: selected.id,
estimate_revision: selected.revision,
estimate_release_minor: estimateMinor(data.amount),
sources: [],
reason: data.reason,
}));
form.post(`${url}/${planId}/orcamento`, {
preserveScroll: true,
onSuccess: () => form.reset(),
});
}}
>
<FormErrors errors={form.errors} />
<label className="grid gap-1">
Estimativa da origem
<select
className={controlClass}
required
value={form.data.estimate_id}
onChange={(e) =>
form.setData('estimate_id', e.target.value)
}
>
<option value="">Seleccione</option>
{sources.data.map((source) => (
<option
key={source.id}
value={source.id}
disabled={
source.revision === null ||
(source.reserved_minor ?? 0) +
(source.committed_minor ?? 0) ===
0
}
>
Requisição {source.requisition_id} · versão{' '}
{source.version} · orçamento {source.budget_id}{' '}
· saldo{' '}
{source.reserved_minor === null ||
source.committed_minor === null
? 'indeterminado'
: estimateMoney(
source.reserved_minor +
source.committed_minor,
)}{' '}
MZN
</option>
))}
</select>
</label>
<label className="grid gap-1">
Parcela estimada a reconciliar (MZN)
<input
className={controlClass}
required
inputMode="decimal"
value={form.data.amount}
onChange={(e) => form.setData('amount', e.target.value)}
/>
</label>
<label className="grid gap-1">
Motivo e diferença face aos custos efectivos
<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 || !selected}>
Reconciliar com os documentos conferidos
</Button>
</form>
<nav className="mt-3 flex gap-4">
{sources.prev_page_url && (
<Link preserveState href={sources.prev_page_url}>
Anterior
</Link>
)}
{sources.next_page_url && (
<Link preserveState href={sources.next_page_url}>
Seguinte
</Link>
)}
</nav>
</Panel>
);
}
@@ -0,0 +1,386 @@
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>
);
}
@@ -13,6 +13,12 @@ export type OrderPartFrame = {
justification?: string;
};
native_preparation: {
exchange_basis?: {
rate: string;
quoted_on: string;
source: string;
} | null;
reference_amounts?: { total_minor: number };
approved_reference?: { subtotal_minor: number; total_minor: number };
items: {
quotation_item_id: number;
@@ -97,6 +103,33 @@ export function OrderPartsSummary({ sources }: { sources: OrderPartFrame[] }) {
Fundamento: {source.award.justification}
</p>
)}
{source.native_preparation.exchange_basis &&
source.native_preparation.reference_amounts && (
<p className="break-words">
Taxa desta origem:{' '}
{
source.native_preparation.exchange_basis
.rate
}{' '}
MZN
{' · '}
{
source.native_preparation.exchange_basis
.quoted_on
}
{' · '}
{
source.native_preparation.exchange_basis
.source
}
{' · '}Referência da parcela:{' '}
{money(
source.native_preparation
.reference_amounts.total_minor,
'MZN',
)}
</p>
)}
<Link
href={`/requisicoes/${source.requisition.id}/adjudicacao`}
className="underline"
@@ -0,0 +1,59 @@
import { Panel } from '@/components/procurement';
export type PaymentInsights = {
from: string | null;
to: string | null;
coverage: {
invoices: number;
indeterminate: number;
confirmed_payments: number;
};
currencies: { currency: string; count: number; amount_minor: string }[];
};
export function ProcurementPaymentInsights({
data,
exportHref,
}: {
data: PaymentInsights;
exportHref?: string;
}) {
return (
<Panel
title="Despesa por período"
description="Pagamentos externos confirmados, pela data de confirmação. O período seleccionado aplica-se à confirmação, independentemente da data de criação da requisição. Cópias importadas não se somam aos originais."
>
<p className="text-sm text-muted-foreground">
{data.from ?? 'Desde o início'} —{' '}
{data.to ?? 'Até à data actual'}.{' '}
{data.coverage.confirmed_payments} pagamentos confirmados.
</p>
{data.coverage.indeterminate > 0 && (
<p role="status">
{data.coverage.indeterminate} facturas com histórico
indeterminado excluídas dos totais. Os valores apresentados
são parciais.
</p>
)}
{data.currencies.map((row) => {
const digits = row.amount_minor.padStart(3, '0');
return (
<p key={row.currency} className="mt-2 font-medium">
{digits.slice(0, -2)},{digits.slice(-2)} {row.currency}{' '}
· {row.count} pagamentos
</p>
);
})}
{data.currencies.length === 0 && (
<p className="mt-2">
Nenhum pagamento confirmado determinado neste período.
</p>
)}
{exportHref && (
<a href={exportHref} className="mt-3 inline-block underline">
Exportar despesa CSV
</a>
)}
</Panel>
);
}