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,263 @@
import { Head, Link, useForm, usePage } 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 { money } from '@/types/procurement';
type Source = {
origin: number;
version: number;
plan_hash: string;
allocations: {
allocation_key: string;
line_id: number;
centre_id: number;
subtotal: string;
total: string;
}[];
};
export default function Amendment({
order,
sources,
history,
}: {
order: { id: number; number: string; currency: string };
sources: Source[];
history: {
id: number;
created_at: string;
created_by: number;
reason: string | null;
sources: {
origin: number;
allocations: {
allocation_key: string;
subtotal_minor: number;
total_minor: number;
}[];
}[];
}[];
}) {
const actor = usePage().props.auth?.user;
const form = useForm(
`order-parts-amendment:${actor?.tenant_id}:${actor?.id}:${order.id}:${sources.map((s) => `${s.origin}:${s.version}:${s.plan_hash}`).join(',')}`,
{
operation_key: crypto.randomUUID(),
reason: '',
sources: sources.map((source) => ({
origin: source.origin,
version: source.version,
plan_hash: source.plan_hash,
allocations: source.allocations.map(
({ allocation_key, subtotal, total }) => ({
allocation_key,
subtotal,
total,
}),
),
})),
},
);
const ref = useRef<HTMLFormElement>(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 update = (
origin: number,
allocation: number,
field: 'subtotal' | 'total',
value: string,
) => {
form.setData(
'sources',
form.data.sources.map((source, i) =>
i !== origin
? source
: {
...source,
allocations: source.allocations.map((row, j) =>
j !== allocation
? row
: { ...row, [field]: value },
),
},
),
);
};
return (
<>
<Head title={`Reafectação · ${order.number}`} />
<PageTitle
eyebrow="Compras · Finanças"
title={`Reafectação · ${order.number}`}
description="Confirmação explícita de Finanças para esta ordem."
/>
<Panel title="Imputações actuais em MZN">
<p className="mb-4">
Conserve os montantes de cada artigo e origem. Apenas os
centros já previstos podem ser reafectados. Valores
consumidos, reservas não emitidas e documentos originais são
preservados.
</p>
<form
ref={ref}
className="grid gap-4"
onSubmit={(event) => {
event.preventDefault();
form.post(`/ordens/${order.id}/reafectacao`);
}}
>
<FormErrors errors={form.errors} />
{sources.map((source, i) => (
<fieldset
key={source.origin}
className="grid min-w-0 gap-3 rounded border p-4"
>
<legend className="px-2 font-semibold">
Origem #{source.origin} · Versão{' '}
{source.version}
</legend>
{source.allocations.map((allocation, j) => (
<div
key={allocation.allocation_key}
className="grid gap-3 rounded border p-3 sm:grid-cols-2"
>
<p className="sm:col-span-2">
Artigo #{allocation.line_id} · Centro #
{allocation.centre_id}
</p>
<label className="grid gap-1">
Sem IVA (MZN)
<Input
required
inputMode="decimal"
value={
form.data.sources[i]
.allocations[j].subtotal
}
onChange={(e) =>
update(
i,
j,
'subtotal',
e.target.value,
)
}
/>
</label>
<label className="grid gap-1">
Com IVA (MZN)
<Input
required
inputMode="decimal"
value={
form.data.sources[i]
.allocations[j].total
}
onChange={(e) =>
update(
i,
j,
'total',
e.target.value,
)
}
/>
</label>
</div>
))}
</fieldset>
))}
<label className="grid gap-1">
Motivo
<textarea
required
minLength={10}
maxLength={4000}
className="min-h-24 rounded border p-3"
value={form.data.reason}
onChange={(e) =>
form.setData('reason', e.target.value)
}
/>
</label>
<Button disabled={form.processing} type="submit">
Confirmar reafectação por Finanças
</Button>
<Link className="underline" href={`/ordens/${order.id}`}>
Voltar à ordem
</Link>
</form>
</Panel>
<Panel title="Histórico de reafectações">
{history.length === 0 ? (
<p>Sem reafectações registadas.</p>
) : (
history.map((event) => (
<div key={event.id} className="mb-4 rounded border p-3">
<p>
Reafectação #{event.id} · {event.created_at} ·
Interveniente #{event.created_by}
</p>
{event.reason && (
<p className="whitespace-pre-wrap">
{event.reason}
</p>
)}
<details>
<summary>
Consultar imputações conservadas
</summary>
{event.sources.map((source) => (
<div key={source.origin}>
<p>Origem #{source.origin}</p>
{source.allocations.map((row) => (
<p key={row.allocation_key}>
Centro #
{
sources
.find(
(s) =>
s.origin ===
source.origin,
)
?.allocations.find(
(a) =>
a.allocation_key ===
row.allocation_key,
)?.centre_id
}{' '}
·{' '}
{money(
row.subtotal_minor,
'MZN',
)}{' '}
sem IVA ·{' '}
{money(row.total_minor, 'MZN')}{' '}
com IVA
</p>
))}
</div>
))}
</details>
</div>
))
)}
</Panel>
</>
);
}
+120 -6
View File
@@ -22,6 +22,13 @@ type Financial = {
origin: number;
award_id: number;
requires_adoption: boolean;
approved_reference?: { subtotal_minor: number; total_minor: number };
adoption_lines?: {
line_id: number;
description: string;
subtotal_minor: number;
total_minor: number;
}[];
version?: number;
plan_hash?: string;
allocations: {
@@ -47,6 +54,12 @@ type Preview = {
requisition_number?: string | null;
award_id: number;
currency: string;
reference_amounts?: { subtotal_minor: number; total_minor: number };
exchange_basis?: {
rate: string;
quoted_on: string;
source: string;
} | null;
items: {
description: string;
quotation_item_id: number;
@@ -82,8 +95,28 @@ function useGuard(ref: RefObject<HTMLFormElement | null>, dirty: boolean) {
}, [dirty, ref]);
}
function Adoption({ award }: { award: number }) {
const form = useForm({ operation_key: crypto.randomUUID() });
function Adoption({
source,
currency,
}: {
source: Financial;
currency: string;
}) {
const foreign = currency !== 'MZN';
const form = useForm({
operation_key: crypto.randomUUID(),
...(foreign
? {
reference_lines: (source.adoption_lines ?? []).map(
(line) => ({
line_id: line.line_id,
subtotal: '',
total: '',
}),
),
}
: {}),
});
return (
<div className="grid gap-3 rounded-lg border p-4">
<p>
@@ -96,11 +129,73 @@ function Adoption({ award }: { award: number }) {
da origem. A adopção não cria dotação nem saldo.
</p>
<FormErrors errors={form.errors} />
{foreign && (
<>
<p>
Confira a referência integral aprovada em MZN antes de
transferir a reserva:{' '}
{source.approved_reference
? money(
source.approved_reference.total_minor,
'MZN',
)
: 'Referência por conferir'}
. Indique todos os artigos da proposta, mesmo os que não
serão emitidos nesta parcela.
</p>
{(source.adoption_lines ?? []).map((line, index) => (
<div
key={line.line_id}
className="grid gap-3 rounded border p-3 sm:grid-cols-2"
>
<p className="sm:col-span-2">
{line.description} ·{' '}
{money(line.total_minor, currency)}
</p>
{(['subtotal', 'total'] as const).map((field) => (
<label key={field} className="grid gap-1">
{field === 'subtotal'
? 'Sem IVA (MZN)'
: 'Com IVA (MZN)'}
<Input
inputMode="decimal"
value={
form.data.reference_lines?.[index][
field
] ?? ''
}
onChange={(event) =>
form.setData(
'reference_lines',
(
form.data.reference_lines ??
[]
).map((row, i) =>
i === index
? {
...row,
[field]:
event.target
.value,
}
: row,
),
)
}
/>
</label>
))}
</div>
))}
</>
)}
<Button
type="button"
disabled={form.processing}
onClick={() =>
form.post(`/adjudicacoes/${award}/parcelas/adoptar`)
form.post(
`/adjudicacoes/${source.award_id}/parcelas/adoptar`,
)
}
>
Adoptar a reserva existente
@@ -219,8 +314,28 @@ function Prepared({
{money(line.total_minor, source.currency)}
</p>
))}
{source.reference_amounts &&
source.exchange_basis && (
<p className="text-sm break-words">
Referência desta origem:{' '}
{money(
source.reference_amounts
.total_minor,
'MZN',
)}
{' · '}Taxa:{' '}
{source.exchange_basis.rate}
{' · '}
{source.exchange_basis.quoted_on}
{' · '}
{source.exchange_basis.source}
</p>
)}
{preview.financial[index].requires_adoption ? (
<Adoption award={source.award_id} />
<Adoption
source={preview.financial[index]}
currency={source.currency}
/>
) : (
<>
<p className="text-sm text-muted-foreground">
@@ -354,8 +469,7 @@ function Prepared({
{!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.
emitir.
</p>
)}
<p className="text-sm text-muted-foreground">
+10
View File
@@ -35,12 +35,14 @@ export default function OrderShow({
orderCancellation,
snapshotComplete = true,
orderPartsSources = [],
canAmendOrderParts = false,
}: {
order: PurchaseOrder;
history: History[];
orderCancellation?: OrderCancellationState;
snapshotComplete?: boolean;
orderPartsSources?: OrderPartFrame[];
canAmendOrderParts?: boolean;
}) {
const snapshot = order.snapshot;
if (!snapshotComplete) {
@@ -160,6 +162,14 @@ export default function OrderShow({
' Regras de aprovação provisórias.'}
</div>
<OrderPartsSummary sources={orderPartsSources} />
{canAmendOrderParts && (
<Link
className="underline"
href={`/ordens/${order.id}/reafectacao`}
>
Conferir ou reafectar imputações por Finanças
</Link>
)}
<ImportTariffSummary records={snapshot.import_tariffs} />
<div className="grid gap-6 md:grid-cols-2">
{snapshot.investment_rules && (
@@ -1,4 +1,8 @@
import { Head, Link, useForm } from '@inertiajs/react';
import {
ProcurementPaymentInsights,
type PaymentInsights,
} from '@/components/procurement-payment-insights';
import { Download } from 'lucide-react';
import {
PageTitle,
@@ -48,6 +52,7 @@ export default function ProcurementReports({
generatedAt,
insights,
payableInsights,
paymentInsights,
}: {
records: {
data: Row[];
@@ -63,6 +68,7 @@ export default function ProcurementReports({
generatedAt: string;
insights?: ProcurementInsights;
payableInsights?: PayableInsights | null;
paymentInsights?: PaymentInsights | null;
}) {
const form = useForm({
search: filters.search ?? '',
@@ -113,6 +119,12 @@ export default function ProcurementReports({
exportHref={`/relatorios/obrigacoes.csv?${params}`}
/>
)}
{paymentInsights && (
<ProcurementPaymentInsights
data={paymentInsights}
exportHref={`/relatorios/despesa.csv?${params}`}
/>
)}
<Panel
title="Filtrar requisições"
description="O período refere-se à criação da requisição. Os resultados respeitam o seu acesso à empresa e ao departamento."
+11
View File
@@ -54,7 +54,9 @@ export default function Show({
canRefreshRouting = false,
canPrepareDistributions = false,
importTariffsReady = false,
importEstimatesReady = false,
}: {
importEstimatesReady?: boolean;
importTariffsReady?: boolean;
canPrepareDistributions?: boolean;
requisition: Requisition;
@@ -163,6 +165,15 @@ export default function Show({
}
/>
<FormErrors errors={submission.errors} />
{importEstimatesReady && (
<Button asChild variant="outline">
<Link
href={`/requisicoes/${r.id}/estimativa-importacao`}
>
Estimativa de importação
</Link>
</Button>
)}
{importTariffsReady && (
<Button asChild variant="outline">
<Link
+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