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
+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} ·{' '}