commit compras1 2911
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-29 05:28:30 +02:00
parent 1ddabbbdcc
commit 448948a487
137 changed files with 9481 additions and 1926 deletions
@@ -107,6 +107,7 @@ export default function AgreementFollowup({
}
>
<form
data-query-form="true"
className="grid gap-4 md:grid-cols-3"
onSubmit={(event) => {
event.preventDefault();
@@ -1,5 +1,5 @@
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
import { Head, Link, router, useForm } from '@inertiajs/react';
import { useEffect, useRef } from 'react';
import {
FormErrors,
PageTitle,
@@ -108,22 +108,7 @@ export default function ImportBankSupport(props: Props) {
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]);
const ref = usePreparationDirty(form.isDirty);
const edit = (record: BankRecord) => {
const label = (id: number | null) =>
record.snapshot.documents.find((doc) => doc.id === id)?.reference ??
+5 -27
View File
@@ -1,5 +1,5 @@
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
import { Head, Link, useForm, useRemember } from '@inertiajs/react';
import { useEffect, useRef, type RefObject } from 'react';
import { Button } from '@/components/ui/button';
import {
ActionBar,
@@ -226,24 +226,6 @@ type DraftComponent = {
values: string[];
};
function useGuard(ref: RefObject<HTMLFormElement | null>, dirty: boolean) {
useEffect(() => {
const element = ref.current;
window.dispatchEvent(
new CustomEvent('sgc:context-dirty', {
detail: { form: element, dirty },
}),
);
return () => {
window.dispatchEvent(
new CustomEvent('sgc:context-dirty', {
detail: { form: element, dirty: false },
}),
);
};
}, [ref, dirty]);
}
function Pagination({
page,
}: {
@@ -295,8 +277,7 @@ function DocumentForm({
reason: '',
file: null as File | null,
}).dontRemember('file');
const ref = useRef<HTMLFormElement>(null);
useGuard(ref, form.isDirty);
const ref = usePreparationDirty(form.isDirty);
return (
<Panel title="Registar documento adicional">
<p className="mb-4">
@@ -548,8 +529,7 @@ function CostPreparation(props: Props & { url: string; historyKey: string }) {
})) ?? ([] as DraftComponent[]),
reason: '',
});
const ref = useRef<HTMLFormElement>(null);
useGuard(ref, form.isDirty);
const ref = usePreparationDirty(form.isDirty);
const selection = () => ({
budget_id: form.data.budget_id,
item_references: form.data.components
@@ -1048,8 +1028,7 @@ function FinancialStage({
reason: '',
sources: [] as string[],
});
const ref = useRef<HTMLFormElement>(null);
useGuard(ref, form.isDirty);
const ref = usePreparationDirty(form.isDirty);
if (!financialReady || !latest) return null;
const current = latest.state === 'approved';
const changed =
@@ -1322,8 +1301,7 @@ export default function ImportCosts(props: Props) {
operation_key: crypto.randomUUID(),
reason: '',
});
const decisionRef = useRef<HTMLFormElement>(null);
useGuard(decisionRef, decision.isDirty);
const decisionRef = usePreparationDirty(decision.isDirty);
return (
<>
<Head title="Custo de aterragem" />
+3 -17
View File
@@ -1,5 +1,6 @@
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
import { Head, Link, useForm } from '@inertiajs/react';
import { useEffect, useRef } from 'react';
import { useRef } from 'react';
import { FormErrors, PageTitle, Panel } from '@/components/procurement';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -69,23 +70,8 @@ export default function Dossier({
file: null as File | null,
},
);
const ref = useRef<HTMLFormElement>(null);
const ref = usePreparationDirty(form.isDirty);
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(),
+2 -17
View File
@@ -1,5 +1,5 @@
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
import { Head, Link, router, useForm } from '@inertiajs/react';
import { useEffect, useRef } from 'react';
import {
FormErrors,
PageTitle,
@@ -139,22 +139,7 @@ export default function ImportEstimate(props: Props) {
})),
},
);
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 ref = usePreparationDirty(form.isDirty);
return (
<>
<Head title="Estimativa de importação" />
+94 -59
View File
@@ -1,5 +1,5 @@
import { Head, Link, useForm } from '@inertiajs/react';
import { useEffect, useRef } from 'react';
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
import {
FormErrors,
PageTitle,
@@ -19,6 +19,18 @@ import {
specificRateMinor,
} from '@/lib/import-legal-specific-rate';
import { date, money } from '@/types/procurement';
import type { InvalidEvent } from 'react';
export function revealInvalidLegalField(event: InvalidEvent<HTMLFormElement>) {
const field = event.currentTarget.querySelector<HTMLElement>(
'input:invalid, select:invalid, textarea:invalid',
);
if (field !== event.target) return;
requestAnimationFrame(() => {
field.focus({ preventScroll: true });
field.scrollIntoView({ block: 'center', behavior: 'instant' });
});
}
type LegalData = {
title: string;
@@ -52,15 +64,20 @@ type Page<T> = {
type Props = {
referenceDraftWarnings?: { source_id: number; message: string }[];
referenceDrafts?: {
label?: string;
match_code?: string;
suggested_code?: string;
source_id: number;
code: string;
description: string;
rate_percent: string;
rate_label?: string;
title: string;
official_reference: string;
official_url: string | null;
citation: string;
valid_from: string;
valid_until?: string | null;
obligations: string;
charges: LegalCharge[];
}[];
@@ -137,23 +154,6 @@ const states: Record<string, string> = {
published: 'Publicada pela área aduaneira',
withdrawn: 'Retirada de novas sugestões',
};
function useDirtyForm(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 Pages({ page }: { page: Page<unknown> }) {
return (
<nav className="flex flex-wrap gap-4" aria-label="Páginas">
@@ -181,7 +181,7 @@ function Proposal({
`legal-proposal:${props.tenantId}:${props.actorId}:${props.requisition.id}:${rule.id}:${JSON.stringify(props.filters)}`,
{ operation_key: '', requisition_item_id: '', reason: '', version: 0 },
);
const ref = useDirtyForm(form.isDirty);
const ref = usePreparationDirty(form.isDirty);
return (
<form
ref={ref}
@@ -280,7 +280,7 @@ function ChargeEstimate({
),
},
);
const ref = useDirtyForm(form.isDirty);
const ref = usePreparationDirty(form.isDirty);
const previous = props.estimates?.find(
(estimate) =>
String(estimate.data.requisition_item_id) ===
@@ -511,7 +511,7 @@ function SourceForm({ url, scope }: { url: string; scope: string }) {
reason: '',
file: null as File | null,
});
const ref = useDirtyForm(form.isDirty);
const ref = usePreparationDirty(form.isDirty);
return (
<form
ref={ref}
@@ -622,23 +622,8 @@ export default function ImportLegal(props: Props) {
reason: '',
},
);
const actionRef = useDirtyForm(action.isDirty);
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 actionRef = usePreparationDirty(action.isDirty);
const ref = usePreparationDirty(form.isDirty);
const edit = (rule: LegalRule) => {
form.setData({
...form.data,
@@ -687,11 +672,47 @@ export default function ImportLegal(props: Props) {
>
Voltar à classificação pautal
</Link>
<details className="rounded-xl border bg-card p-4">
<summary className="cursor-pointer font-medium">
Ir para uma área da base legal
</summary>
<nav
aria-label="Áreas da base legal de importação"
className="mt-4"
>
<ul className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{[
['legal-suggestions', 'Consultar sugestões'],
['legal-rules', 'Regras preparadas e publicadas'],
...(props.canManage
? [['legal-rule-editor', 'Preparar regra']]
: []),
...(props.canManage && action.data.record_key
? [['legal-decision', 'Decisão preparada']]
: []),
['legal-sources', 'Diplomas disponíveis'],
['legal-estimates', 'Estimativas documentadas'],
['legal-history', 'Histórico preservado'],
].map(([id, label]) => (
<li key={id}>
<a
className="font-medium underline underline-offset-4"
href={`#${id}`}
>
{label}
</a>
</li>
))}
</ul>
</nav>
</details>
<Panel
id="legal-suggestions"
title="Consultar sugestões"
description="Não havendo uma correspondência documentada, a regra permanece por determinar. As imposições descritas não são valores calculados nem activam taxas."
>
<form
data-query-form="true"
method="get"
action={url}
className="grid gap-3 sm:grid-cols-2"
@@ -755,6 +776,7 @@ export default function ImportLegal(props: Props) {
))}
</Panel>
<Panel
id="legal-rules"
title="Regras preparadas e publicadas"
description="Uma nova preparação conserva a última publicação até ser validada. Retirar uma regra impede novas sugestões e conserva as decisões anteriores."
>
@@ -787,12 +809,13 @@ export default function ImportLegal(props: Props) {
</a>
{props.canManage && (
<div className="flex flex-wrap gap-3">
<Button
type="button"
variant="outline"
onClick={() => edit(rule)}
>
Preparar nova versão
<Button asChild variant="outline">
<a
href="#legal-rule-editor"
onClick={() => edit(rule)}
>
Preparar nova versão
</a>
</Button>
{rule.state === 'draft' && (
<Button
@@ -835,6 +858,7 @@ export default function ImportLegal(props: Props) {
</Panel>
{props.canManage && action.data.record_key && (
<Panel
id="legal-decision"
title={
action.data.action === 'publish'
? 'Validar e publicar a versão preparada'
@@ -881,6 +905,7 @@ export default function ImportLegal(props: Props) {
)}
{props.canManage && (
<Panel
id="legal-rule-editor"
title={
form.data.record_key
? `Preparar revisão da versão ${form.data.version}`
@@ -902,13 +927,13 @@ export default function ImportLegal(props: Props) {
Preparar a partir do exemplar oficial
</h3>
<p className="text-sm">
Transcrição do anexo da Lei 8/2025, páginas
2180-(4) a (7), com início em 01/01/2026. Inclui
apenas a taxa geral dessa edição; não é uma
pauta consolidada nem determina isenções,
preferências ou outras imposições. A preparação
continua editável e exige gravação e decisão
expressas.
Propostas identificadas por fonte, citação e
período. Cada uma inclui apenas a imposição
demonstrada no respectivo exemplar; não é uma
pauta consolidada nem determina os restantes
impostos ou preferências. Confira as condições
da posição escolhida. A preparação continua
editável e exige gravação e decisão expressas.
</p>
{form.isDirty && (
<p className="text-sm">
@@ -918,7 +943,7 @@ export default function ImportLegal(props: Props) {
</p>
)}
<label className="grid gap-1">
Código do anexo e fonte
Proposta do exemplar e fonte
<select
className={controlClass}
value=""
@@ -954,9 +979,13 @@ export default function ImportLegal(props: Props) {
draft.official_url ?? '',
citation: draft.citation,
valid_from: draft.valid_from,
valid_until: '',
match_code: draft.code,
suggested_code: draft.code,
valid_until:
draft.valid_until ?? '',
match_code:
draft.match_code ?? draft.code,
suggested_code:
draft.suggested_code ??
draft.code,
origin_country: '',
sector: '',
obligations: draft.obligations,
@@ -979,9 +1008,12 @@ export default function ImportLegal(props: Props) {
key={`${draft.source_id}:${draft.code}`}
value={`${draft.source_id}:${draft.code}`}
>
{draft.code} — {draft.description} —
taxa geral {draft.rate_percent}% —
fonte #{draft.source_id}
{draft.label ??
`${draft.code} — ${draft.description}`}{' '}
—
{draft.rate_label ??
`taxa geral ${draft.rate_percent}%`}{' '}
— fonte #{draft.source_id}
</option>
))}
</select>
@@ -991,6 +1023,7 @@ export default function ImportLegal(props: Props) {
<form
ref={ref}
className="space-y-4"
onInvalidCapture={revealInvalidLegalField}
onSubmit={(e) => {
e.preventDefault();
const operation =
@@ -1195,6 +1228,7 @@ export default function ImportLegal(props: Props) {
</Panel>
)}
<Panel
id="legal-sources"
title="Diplomas disponíveis para consulta"
description="Conservar um diploma não publica uma regra nem activa um cálculo. Cada regra usa a citação e o período próprios."
>
@@ -1217,6 +1251,7 @@ export default function ImportLegal(props: Props) {
)}
</Panel>
<Panel
id="legal-estimates"
title="Estimativas documentadas das imposições"
description="Valores calculados pelas taxas e bases preservadas. Não registam dívida, reserva, pagamento ou custo efectivo."
>
@@ -1267,7 +1302,7 @@ export default function ImportLegal(props: Props) {
<Pages page={props.estimateHistory} />
)}
</Panel>
<Panel title="Histórico preservado">
<Panel id="legal-history" title="Histórico preservado">
{props.history.data.map((rule) => (
<p key={rule.id}>
{rule.data.title} · v{rule.version} ·{' '}
+4 -20
View File
@@ -1,5 +1,5 @@
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
import { Head, Link, useForm } from '@inertiajs/react';
import { useEffect, useRef } from 'react';
import { Button } from '@/components/ui/button';
import {
FormErrors,
@@ -64,23 +64,6 @@ type Props = {
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">
@@ -123,7 +106,7 @@ function ItemForm({
'',
reason: '',
});
const ref = useGuard(form.isDirty);
const ref = usePreparationDirty(form.isDirty);
const submit = (action: string) => {
form.transform((data) => ({
...data,
@@ -291,7 +274,7 @@ function MasterForm({
reason: '',
},
);
const ref = useGuard(form.isDirty);
const ref = usePreparationDirty(form.isDirty);
return (
<details className="rounded border p-3">
<summary>
@@ -386,6 +369,7 @@ export default function ImportTariffs(props: Props) {
)}
<Panel title="Localizar material ou código">
<form
data-query-form="true"
method="get"
action={url}
className="flex flex-wrap gap-3"
+70 -40
View File
@@ -140,6 +140,26 @@ const titles: Record<string, string> = {
calendar: 'Reposição e calendário',
imports: 'Importações',
};
const descriptions: Record<string, string> = {
contracts:
'Organize contratos com vários artigos, vigência e limites globais. Consulte os artigos associados e as versões preservadas.',
agreements:
'Defina as condições de fornecimento por artigo, fornecedor e local. Acompanhe a vigência dos acordos e a sua ligação aos contratos.',
calendar:
'Defina os parâmetros de stock por artigo e local e acompanhe as necessidades de reposição e o calendário previsto.',
imports:
'Acompanhe as ordens importadas, desde o embarque e a chegada até à libertação aduaneira e recepção efectiva.',
};
const responsibilities: Record<string, string> = {
contracts:
'Compras prepara os contratos e os artigos associados; o conferente decide de forma independente. A vigência e os limites ficam preservados em cada versão.',
agreements:
'Compras prepara os acordos por artigo, fornecedor e local; o conferente decide de forma independente. As condições aprovadas orientam as políticas de reposição associadas.',
calendar:
'Compras prepara as políticas por artigo e local; o conferente decide de forma independente. O acompanhamento apresenta as necessidades e as datas previstas conforme os parâmetros aprovados.',
imports:
'Logística acompanha embarque e chegada; o responsável aduaneiro comprova a libertação. Armazém confirma a recepção efectiva e Finanças mantém a conferência de facturas e pagamentos nos circuitos existentes.',
};
const quantity = (value: number | undefined) =>
value === undefined
? '—'
@@ -1435,37 +1455,44 @@ export default function SupplyIndex(props: Props) {
<PageTitle
eyebrow="Compras · Fornecimento e reposição"
title={titles[props.view]}
description="Seleccione os cadastros existentes e registe apenas os dados novos desta etapa. A finalidade e a origem são independentes."
description={descriptions[props.view]}
/>
{(props.kind === 'agreement' ||
props.kind === 'policy' ||
props.kind === 'contract') && (
<Link
href={
props.kind === 'contract'
? '/compras/acordos/vigencia?kind=contract'
: '/compras/acordos/vigencia'
}
className="inline-block text-sm underline"
{['agreement', 'policy', 'contract'].includes(props.kind) && (
<nav
aria-label="Consultas e cadastros de fornecimento"
className="flex flex-wrap gap-x-4 gap-y-2"
>
{props.kind === 'contract'
? 'Acompanhar vigência dos contratos globais'
: 'Acompanhar vigência dos acordos'}
</Link>
)}
{props.orderLimitsReady && (
<Link
href={
props.kind === 'contract'
? '/compras/fornecimento?view=agreements'
: '/compras/fornecimento?view=contracts'
}
className="inline-block text-sm underline"
>
{props.kind === 'contract'
? 'Preparar artigos e limites individuais'
: 'Contratos com vários artigos e limite global'}
</Link>
{(props.kind === 'agreement' ||
props.kind === 'policy' ||
props.kind === 'contract') && (
<Link
href={
props.kind === 'contract'
? '/compras/acordos/vigencia?kind=contract'
: '/compras/acordos/vigencia'
}
className="inline-block text-sm underline"
>
{props.kind === 'contract'
? 'Acompanhar vigência dos contratos globais'
: 'Acompanhar vigência dos acordos'}
</Link>
)}
{props.orderLimitsReady && (
<Link
href={
props.kind === 'contract'
? '/compras/fornecimento?view=agreements'
: '/compras/fornecimento?view=contracts'
}
className="inline-block text-sm underline"
>
{props.kind === 'contract'
? 'Preparar artigos e limites individuais'
: 'Contratos com vários artigos e limite global'}
</Link>
)}
</nav>
)}
{props.linkedContractKey && (
<p className="rounded border p-3 text-sm">
@@ -1496,12 +1523,7 @@ export default function SupplyIndex(props: Props) {
)}
<Panel title="Responsabilidades">
<p className="text-sm text-muted-foreground">
Compras prepara os acordos e a reposição; o conferente
decide de forma independente. Logística acompanha
embarque e chegada; o responsável aduaneiro comprova a
libertação. Armazém confirma a recepção efectiva e
Finanças mantém a conferência de facturas e pagamentos
nos circuitos existentes.
{responsibilities[props.view]}
</p>
</Panel>
{props.view === 'calendar' && props.ready && (
@@ -1528,7 +1550,9 @@ export default function SupplyIndex(props: Props) {
? 'Nova política por artigo e local'
: props.kind === 'import'
? 'Acompanhar uma ordem importada'
: 'Novo acordo de fornecimento'
: props.kind === 'contract'
? 'Novo contrato com vários artigos'
: 'Novo acordo de fornecimento'
}
>
<details>
@@ -1575,10 +1599,16 @@ export default function SupplyIndex(props: Props) {
<Panel
key={`${record.record_key}-${record.version}`}
title={
record.snapshot.item
? `${record.snapshot.item.code} · ${record.snapshot.item.name}`
: (record.snapshot.order?.number ??
'Processo de fornecimento')
props.kind === 'contract'
? typeof record.data.reference ===
'string' &&
record.data.reference.trim() !== ''
? `Contrato ${record.data.reference}`
: 'Contrato sem referência indicada'
: record.snapshot.item
? `${record.snapshot.item.code} · ${record.snapshot.item.name}`
: (record.snapshot.order?.number ??
'Processo de fornecimento')
}
description={`${states[record.state]} · Versão ${record.version} · ${record.snapshot.warehouse?.name ?? record.data.jurisdiction ?? ''}`}
>