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
+29 -1
View File
@@ -9,6 +9,9 @@ import {
} from '@/components/procurement';
import { orderPartMinor } from '@/lib/order-parts';
import { money } from '@/types/procurement';
import EstimateReconciliation, {
type EstimateSources,
} from '@/components/import-estimate-reconciliation';
import ImportTariffSummary, {
type FrozenImportTariff,
} from '@/components/import-tariff-summary';
@@ -128,6 +131,7 @@ type Props = {
};
}>;
financialReady: boolean;
estimateSources?: EstimateSources;
financialState: {
revision: number;
native_plan_id: number | null;
@@ -1036,6 +1040,7 @@ function FinancialStage({
financialReady,
url,
historyKey,
estimateSources,
}: Props & { url: string; historyKey: string }) {
const form = useForm(`${historyKey}:financial`, {
operation_key: crypto.randomUUID(),
@@ -1061,7 +1066,15 @@ function FinancialStage({
const eligible = (phase: string) =>
selected.some((origin) => origin.phase === phase);
if (current && !importRecord.context_changed) {
if (!state) {
if (
!state &&
!estimateSources?.data.some(
(source) =>
(source.reserved_minor ?? 0) +
(source.committed_minor ?? 0) >
0,
)
) {
if (
Object.values(latest.snapshot.plan.document_details).some(
(document) =>
@@ -1471,6 +1484,21 @@ export default function ImportCosts(props: Props) {
url={url}
historyKey={key}
/>
{props.estimateSources &&
props.financialReady &&
latest?.state === 'approved' &&
!props.importRecord.context_changed && (
<EstimateReconciliation
key={`${key}:estimate:${latest.id}:${props.financialState?.revision ?? 0}`}
sources={props.estimateSources}
planId={latest.id}
url={url}
historyKey={key}
financialRevision={
props.financialState?.revision ?? 0
}
/>
)}
{props.financialEvents.data.length > 0 && (
<Panel title="Histórico orçamental adicional">
{props.financialEvents.data.map((event) => (
@@ -0,0 +1,351 @@
import { Head, Link, useForm } from '@inertiajs/react';
import { useEffect, useRef } from 'react';
import { FormErrors, PageTitle, Panel } from '@/components/procurement';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import ImportPartySelection, {
type ImportPartyWorkspace,
} from '@/components/import-party-selection';
type Document = {
id: number;
record_key: string;
version: number;
created_at: string;
created_by: number;
current: boolean;
supersedes: number | null;
sha256: string;
reason: string;
data: {
type: string;
reference: string;
issuer_reference: string;
issued_on: string | null;
notes: string | null;
};
};
type Props = {
importRecord: { id: number; version: number; record_key: string };
order: { id: number; number: string };
documents: {
data: Document[];
prev_page_url: string | null;
next_page_url: string | null;
};
types: Record<string, string>;
canWrite: boolean;
actorId: number;
tenantId: number;
parties?: ImportPartyWorkspace;
};
export default function Dossier({
importRecord,
order,
documents,
types,
canWrite,
actorId,
tenantId,
parties,
}: Props) {
const form = useForm(
`import-dossier:${tenantId}:${actorId}:${importRecord.record_key}:${importRecord.version}`,
{
operation_key: crypto.randomUUID(),
record_key: null as string | null,
version: 0,
type: '',
reference: '',
issuer_reference: '',
issued_on: '',
notes: '',
reason: '',
file: null as File | null,
},
);
const ref = useRef<HTMLFormElement>(null);
const fileRef = useRef<HTMLInputElement>(null);
useEffect(() => {
const current = ref.current;
window.dispatchEvent(
new CustomEvent('sgc:context-dirty', {
detail: { form: current, dirty: form.isDirty },
}),
);
return () => {
window.dispatchEvent(
new CustomEvent('sgc:context-dirty', {
detail: { form: current, dirty: false },
}),
);
};
}, [form.isDirty]);
const correction = (document: Document) => {
form.setData({
operation_key: crypto.randomUUID(),
record_key: document.record_key,
version: document.version,
type: document.data.type,
reference: document.data.reference,
issuer_reference: document.data.issuer_reference,
issued_on: document.data.issued_on ?? '',
notes: document.data.notes ?? '',
reason: '',
file: null,
});
if (fileRef.current) fileRef.current.value = '';
ref.current?.scrollIntoView({ block: 'start' });
};
return (
<>
<Head title={`Dossiê de importação · ${order.number}`} />
<div className="mx-auto grid w-full max-w-5xl min-w-0 gap-6 p-5 lg:p-8">
<PageTitle
eyebrow="Compras · Importações"
title={`Dossiê de importação · ${order.number}`}
description="Originais e correcções documentais ligados à mesma ordem."
/>
<p>
Registar um documento conserva a evidência. Não submete
declarações na JUE, não confirma pagamentos nem liberta
mercadoria. Esses factos mantêm os seus percursos e
competências próprios.
</p>
<Link className="underline" href={`/ordens/${order.id}`}>
Consultar a ordem e as suas origens
</Link>
{parties && (
<ImportPartySelection
workspace={parties}
importId={importRecord.id}
importKey={importRecord.record_key}
actorId={actorId}
tenantId={tenantId}
/>
)}
{canWrite && (
<Panel
title={
form.data.record_key
? 'Preparar uma correcção documental'
: 'Registar um documento'
}
>
<form
ref={ref}
className="grid gap-4"
onSubmit={(event) => {
event.preventDefault();
form.post(
`/compras/importacoes/${importRecord.id}/documentos`,
{
forceFormData: true,
onSuccess: () => {
form.reset();
if (fileRef.current)
fileRef.current.value = '';
},
},
);
}}
>
<FormErrors errors={form.errors} />
<label className="grid gap-1">
Tipo de documento
<select
required
disabled={form.data.record_key !== null}
className="rounded border p-2"
value={form.data.type}
onChange={(e) =>
form.setData('type', e.target.value)
}
>
<option value="">Seleccione</option>
{Object.entries(types).map(
([key, label]) => (
<option key={key} value={key}>
{label}
</option>
),
)}
</select>
</label>
<label className="grid gap-1">
Referência
<Input
required
maxLength={180}
value={form.data.reference}
onChange={(e) =>
form.setData(
'reference',
e.target.value,
)
}
/>
</label>
<label className="grid gap-1">
Entidade emitente
<Input
required
maxLength={180}
value={form.data.issuer_reference}
onChange={(e) =>
form.setData(
'issuer_reference',
e.target.value,
)
}
/>
</label>
<label className="grid gap-1">
Data do documento, quando disponível
<Input
type="date"
value={form.data.issued_on}
onChange={(e) =>
form.setData(
'issued_on',
e.target.value,
)
}
/>
</label>
<label className="grid gap-1">
Notas
<textarea
className="min-h-20 rounded border p-3"
maxLength={4000}
value={form.data.notes}
onChange={(e) =>
form.setData('notes', e.target.value)
}
/>
</label>
<label className="grid gap-1">
Motivo do registo ou da correcção
<textarea
required
minLength={10}
maxLength={4000}
className="min-h-20 rounded border p-3"
value={form.data.reason}
onChange={(e) =>
form.setData('reason', e.target.value)
}
/>
</label>
<label className="grid gap-1">
Original privado (PDF, JPG ou PNG, até 2 MB)
<Input
ref={fileRef}
required
type="file"
accept=".pdf,.jpg,.jpeg,.png"
onChange={(e) =>
form.setData(
'file',
e.target.files?.[0] ?? null,
)
}
/>
</label>
<p className="text-sm text-muted-foreground">
Após recarregar a página, volte a seleccionar o
ficheiro. A correcção cria uma nova versão e
conserva o original anterior.
</p>
<Button disabled={form.processing} type="submit">
Guardar documento privado
</Button>
</form>
</Panel>
)}
<Panel title="Documentos e versões conservadas">
{documents.data.length === 0 ? (
<p>Ainda não há documentos neste dossiê.</p>
) : (
documents.data.map((document) => (
<section
key={document.id}
className="mb-4 grid min-w-0 gap-2 rounded border p-4"
>
<h2 className="font-semibold">
{types[document.data.type]} ·{' '}
{document.data.reference}
</h2>
<p>
{document.data.issuer_reference} · Versão{' '}
{document.version}
{document.current
? ' · Actual'
: ' · Histórica'}
</p>
{document.data.issued_on && (
<p>
Data do documento:{' '}
{document.data.issued_on}
</p>
)}
{document.data.notes && (
<p className="whitespace-pre-wrap">
{document.data.notes}
</p>
)}
<p className="whitespace-pre-wrap">
{document.reason}
</p>
<a
className="underline"
href={`/compras/importacoes/${importRecord.id}/documentos/${document.id}`}
>
Descarregar esta versão
</a>
{canWrite && document.current && (
<Button
type="button"
variant="outline"
onClick={() => correction(document)}
>
Preparar correcção
</Button>
)}
<details>
<summary>Rastreabilidade</summary>
<p>
Registo: {document.created_at} ·
Interveniente #{document.created_by}
</p>
<p className="text-xs break-all">
SHA-256: {document.sha256}
</p>
</details>
</section>
))
)}
<div className="flex gap-4">
{documents.prev_page_url && (
<Link
className="underline"
href={documents.prev_page_url}
>
Anterior
</Link>
)}
{documents.next_page_url && (
<Link
className="underline"
href={documents.next_page_url}
>
Seguinte
</Link>
)}
</div>
</Panel>
</div>
</>
);
}
@@ -0,0 +1,418 @@
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: {
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 = {
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),
})),
},
);
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,
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>
<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>
</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>
</>
);
}
+9
View File
@@ -76,6 +76,7 @@ type Projection = {
};
type Props = {
importCostsReady?: boolean;
importDossierReady?: boolean;
orderLimitsReady?: boolean;
linkedAgreementKey?: string | null;
linkedContractKey?: string | null;
@@ -1535,6 +1536,14 @@ export default function SupplyIndex(props: Props) {
Preparar e conferir o custo de aterragem
</Link>
)}
{props.importDossierReady && (
<Link
className="mt-4 block underline"
href={`/compras/importacoes/${record.id}/documentos`}
>
Consultar o dossiê documental da importação
</Link>
)}
<details className="mt-4">
<summary className="cursor-pointer text-sm">
Dados preservados desta versão