commit melhorias compras3
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-22 10:56:58 +02:00
parent 4fac443dda
commit efd97e265b
130 changed files with 8917 additions and 363 deletions
@@ -0,0 +1,316 @@
import { router } from '@inertiajs/react';
import { useState } from 'react';
import {
ReceiptConversionFields,
type ReceiptConversion,
} from '@/components/receipt-conversion';
import { controlClass, Panel } from '@/components/procurement';
import { convertedQuantity } from '@/components/receipt-conversion';
import type { FrozenOrderAgreement } from '@/types/purchase';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { money } from '@/types/procurement';
export type OrderAgreementOption = {
contract?: {
reference: string;
version: number;
currency: string;
max_order_value_minor: number | null;
} | null;
id: number;
version: number;
reference: string;
stock_item_id: number;
warehouse: string | null;
unit: string;
currency: string;
max_order_value_minor: number | null;
max_order_quantity_milli: number | null;
};
export type OrderAgreementLine = {
id: number;
description: string;
unit: string;
stock_item_id: number | null;
};
export type OrderAgreementBinding = {
requisition_item_id: number;
agreement_id: number;
conversion?: ReceiptConversion;
};
export function AgreementOrderLimitSummary({
bindings,
}: {
bindings?: Record<string, FrozenOrderAgreement>;
}) {
const agreements = Array.from(
new Map(
Object.values(bindings ?? {}).map((row) => [row.agreement_id, row]),
).values(),
);
if (!agreements.length) return null;
return (
<Panel title="Acordos e limites preservados nesta ordem">
<p className="mb-3 text-sm">
Cada ordem pode utilizar o limite completo. A conferência
abrange apenas as linhas expressamente ligadas ao mesmo acordo,
sem acumular outras ordens.
</p>
{Array.from(
new Map(
agreements
.filter((row) => row.contract)
.map((row) => [row.contract!.id, row.contract!]),
).values(),
).map((contract) => (
<div key={contract.id} className="border-t py-3 text-sm">
<p className="font-semibold">
Contrato global: {contract.reference} · versão{' '}
{contract.version}
</p>
<p>
Total com impostos dos artigos ligados:{' '}
{money(
contract.checked_order_value_minor,
contract.currency,
)}{' '}
· Limite global por ordem:{' '}
{contract.max_order_value_minor === null
? 'Não definido'
: money(
contract.max_order_value_minor,
contract.currency,
)}
</p>
</div>
))}
{agreements.map((row) => (
<div
key={row.agreement_id}
className="space-y-2 border-t py-3 text-sm"
>
<p className="font-semibold">
{row.reference} · versão {row.version}
</p>
<p>
Total com impostos conferido:{' '}
{money(row.checked_order_value_minor, row.currency)} ·
Limite por ordem:{' '}
{row.max_order_value_minor === null
? 'Não definido'
: money(row.max_order_value_minor, row.currency)}
</p>
<p>
Quantidade conferida:{' '}
{convertedQuantity(row.checked_order_quantity_milli)}{' '}
{row.unit} · Limite por ordem:{' '}
{row.max_order_quantity_milli === null
? 'Não definido'
: `${convertedQuantity(String(row.max_order_quantity_milli))} ${row.unit}`}
</p>
</div>
))}
</Panel>
);
}
export default function AgreementOrderBindings({
requestId,
lines,
options,
value,
onChange,
initialSearch = '',
}: {
requestId: number;
lines: OrderAgreementLine[];
options: OrderAgreementOption[];
value: OrderAgreementBinding[];
onChange: (value: OrderAgreementBinding[]) => void;
initialSearch?: string;
}) {
const [search, setSearch] = useState(initialSearch);
const change = (line: OrderAgreementLine, id: string) => {
const remaining = value.filter(
(binding) => binding.requisition_item_id !== line.id,
);
const option = options.find((item) => item.id === Number(id));
if (!option) {
onChange(remaining);
return;
}
onChange([
...remaining,
{
requisition_item_id: line.id,
agreement_id: option.id,
...(option.unit.toLowerCase() !== line.unit.toLowerCase()
? {
conversion: {
numerator: '',
denominator: '',
source: '',
version: '',
},
}
: {}),
},
]);
};
return (
<fieldset className="mt-4 space-y-4 rounded border p-4">
<legend className="text-sm font-semibold">
Acordos aplicáveis às linhas desta ordem
</legend>
<p className="text-sm">
A associação é explícita. Cada ordem pode utilizar o limite
completo do acordo. Quantidade e total com impostos são
conferidos apenas nas linhas ligadas, sem somar outras ordens.
</p>
<div className="flex flex-wrap items-end gap-3">
<label className="grid gap-2 text-sm">
Pesquisar referência do acordo
<Input
maxLength={100}
value={search}
onChange={(event) => setSearch(event.target.value)}
/>
</label>
<Button
type="button"
variant="outline"
onClick={() =>
router.get(
`/requisicoes/${requestId}/adjudicacao`,
{
agreement_search: search,
selected_agreement_ids: value.map(
(binding) => binding.agreement_id,
),
},
{
only: ['agreementOptions', 'agreementSearch'],
preserveState: true,
preserveScroll: true,
},
)
}
>
Pesquisar acordos
</Button>
</div>
<p className="text-xs text-muted-foreground">
São apresentados até 100 resultados da pesquisa, mais as
selecções ainda elegíveis. Sem limite definido não é criado um
limite zero.
</p>
{lines.map((line) => {
const binding = value.find(
(item) => item.requisition_item_id === line.id,
);
const selected = options.find(
(item) => item.id === binding?.agreement_id,
);
return (
<div key={line.id} className="space-y-3 border-t pt-3">
<label className="grid gap-2 text-sm">
{line.description} · {line.unit}
<select
className={controlClass}
value={binding?.agreement_id ?? ''}
disabled={line.stock_item_id === null}
onChange={(event) =>
change(line, event.target.value)
}
>
<option value="">Sem acordo associado</option>
{binding && !selected && (
<option
value={binding.agreement_id}
disabled
>
Selecção já não disponível — volte a
conferir o acordo
</option>
)}
{options
.filter(
(item) =>
item.stock_item_id ===
line.stock_item_id,
)
.map((item) => (
<option key={item.id} value={item.id}>
{item.reference} · versão{' '}
{item.version} ·{' '}
{item.warehouse ??
'Local não disponível'}
</option>
))}
</select>
</label>
{line.stock_item_id === null && (
<p className="text-xs text-muted-foreground">
A associação exige identificar o artigo pelo
catálogo; o nome da linha não comprova essa
ligação.
</p>
)}
{selected && (
<p className="text-sm">
Limite de valor por ordem:{' '}
{selected.max_order_value_minor === null
? 'Não definido'
: money(
selected.max_order_value_minor,
selected.currency,
)}{' '}
· Quantidade por ordem:{' '}
{selected.max_order_quantity_milli === null
? 'Não definida'
: `${selected.max_order_quantity_milli / 1000} ${selected.unit}`}
. As versões e os limites ficam preservados na
ordem.
</p>
)}
{selected?.contract && (
<p className="text-sm">
Contrato global {selected.contract.reference} ·
versão {selected.contract.version}: limite por
ordem{' '}
{selected.contract.max_order_value_minor ===
null
? 'Não definido'
: money(
selected.contract
.max_order_value_minor,
selected.contract.currency,
)}
. Soma todos os artigos ligados ao mesmo
contrato nesta ordem.
</p>
)}
{selected && binding?.conversion && (
<ReceiptConversionFields
value={binding.conversion}
documentUnit={line.unit}
stockUnit={selected.unit}
onChange={(conversion) =>
onChange(
value.map((item) =>
item.requisition_item_id === line.id
? { ...item, conversion }
: item,
),
)
}
/>
)}
</div>
);
})}
</fieldset>
);
}
@@ -0,0 +1,330 @@
import { useForm } from '@inertiajs/react';
import { Button } from '@/components/ui/button';
import { FormErrors, Panel, controlClass } from '@/components/procurement';
const identityFields = {
legal_name: 'Denominação social',
nuel: 'NUEL',
address: 'Endereço',
nuit: 'NUIT',
phone: 'Telefone',
email: 'Email',
legal_representative: 'Representante legal',
} as const;
const bankFields = {
bank: 'Banco',
branch: 'Balcão',
account_number: 'Número de conta',
currency: 'Moeda',
nib: 'NIB',
iban: 'IBAN',
nuib: 'NUIB',
account_holder: 'Titular da conta',
} as const;
const locationFields = {
name: 'Designação',
address: 'Endereço',
phone: 'Telefone',
email: 'Email',
} as const;
type Values<T> = Record<keyof T, string | null>;
type Bank = Values<typeof bankFields> & { id: string };
type Establishment = Values<typeof locationFields> & {
id: string;
kind: 'headquarters' | 'branch';
};
export type CompanyDetails = Partial<Values<typeof identityFields>> & {
bank_accounts?: Bank[];
establishments?: Establishment[];
};
function Fields({
fields,
values,
prefix,
change,
}: {
fields: Record<string, string>;
values: Record<string, string | null>;
prefix: string;
change: (key: string, value: string) => void;
}) {
return (
<div className="grid min-w-0 gap-4 sm:grid-cols-2">
{Object.entries(fields).map(([key, label]) => (
<label
className="grid min-w-0 gap-2 text-sm"
key={key}
htmlFor={`${prefix}-${key}`}
>
{label}
<input
id={`${prefix}-${key}`}
className={`${controlClass} w-full min-w-0`}
type={
key === 'email'
? 'email'
: key === 'phone'
? 'tel'
: 'text'
}
maxLength={key === 'address' ? 1000 : 255}
value={values[key] ?? ''}
onChange={(e) => change(key, e.target.value)}
autoComplete="off"
/>
{key === 'currency' && (
<span className="text-muted-foreground">
Código de três letras, por exemplo MZN.
</span>
)}
{key === 'nuit' && (
<span className="text-muted-foreground">
Nove dígitos; conservar os zeros iniciais.
</span>
)}
</label>
))}
</div>
);
}
export function CompanyDetailsSettings({
details,
ready,
version,
}: {
details: CompanyDetails | null;
ready: boolean;
version: number;
}) {
const form = useForm({
...(Object.fromEntries(
Object.keys(identityFields).map((key) => [
key,
details?.[key as keyof typeof identityFields] ?? '',
]),
) as Record<keyof typeof identityFields, string>),
bank_accounts: details?.bank_accounts ?? [],
establishments: details?.establishments ?? [],
version,
reason: '',
});
return (
<Panel
title="Dados da empresa"
description="Identificação institucional, sede, sucursais e várias contas bancárias. Preencha os dados conhecidos. O cadastro bancário não valida contas nem autoriza pagamentos."
>
{!ready ? (
<p>
Instalação dos campos da empresa pendente. Os dados
existentes foram preservados.
</p>
) : (
<form
className="space-y-6"
onSubmit={(e) => {
e.preventDefault();
form.transform((values) => ({ ...values, version }));
form.post(
'/administracao/parametrizacao/company_details',
{ preserveScroll: true },
);
}}
>
<FormErrors errors={form.errors} />
<Fields
fields={identityFields}
values={Object.fromEntries(
Object.keys(identityFields).map((key) => [
key,
form.data[key as keyof typeof identityFields],
]),
)}
prefix="company"
change={(key, value) =>
form.setData(
key as keyof typeof identityFields,
value,
)
}
/>
<section
className="space-y-4"
aria-labelledby="company-establishments"
>
<h3 id="company-establishments" className="font-medium">
Sede e sucursais
</h3>
<p className="text-sm text-muted-foreground">
Identifique a sede uma única vez. Cada sucursal
conserva o seu endereço e contactos.
</p>
{form.data.establishments.length === 0 && (
<p className="text-sm">
Nenhum estabelecimento registado.
</p>
)}
{form.data.establishments.map((row, index) => (
<fieldset
className="min-w-0 space-y-4 rounded border p-4"
key={row.id}
>
<legend className="px-2">
Estabelecimento {index + 1}
</legend>
<label
className="grid gap-2 text-sm"
htmlFor={`establishment-${row.id}-kind`}
>
Tipo
<select
id={`establishment-${row.id}-kind`}
className={controlClass}
value={row.kind}
onChange={(e) =>
form.setData(
'establishments',
form.data.establishments.map(
(r) =>
r.id === row.id
? {
...r,
kind: e.target
.value as Establishment['kind'],
}
: r,
),
)
}
>
<option value="headquarters">
Sede
</option>
<option value="branch">Sucursal</option>
</select>
</label>
<Fields
fields={locationFields}
values={row}
prefix={`establishment-${row.id}`}
change={(key, value) =>
form.setData(
'establishments',
form.data.establishments.map((r) =>
r.id === row.id
? { ...r, [key]: value }
: r,
),
)
}
/>
</fieldset>
))}
<Button
type="button"
variant="outline"
onClick={() =>
form.setData('establishments', [
...form.data.establishments,
{
id: crypto.randomUUID(),
kind: form.data.establishments.some(
(r) => r.kind === 'headquarters',
)
? 'branch'
: 'headquarters',
name: '',
address: '',
phone: '',
email: '',
},
])
}
>
Adicionar estabelecimento
</Button>
</section>
<section
className="space-y-4"
aria-labelledby="company-bank-accounts"
>
<h3 id="company-bank-accounts" className="font-medium">
Contas bancárias da empresa
</h3>
{form.data.bank_accounts.length === 0 && (
<p className="text-sm">Nenhuma conta registada.</p>
)}
{form.data.bank_accounts.map((row, index) => (
<fieldset
className="min-w-0 space-y-4 rounded border p-4"
key={row.id}
>
<legend className="px-2">
Conta {index + 1}
</legend>
<Fields
fields={bankFields}
values={row}
prefix={`bank-${row.id}`}
change={(key, value) =>
form.setData(
'bank_accounts',
form.data.bank_accounts.map((r) =>
r.id === row.id
? { ...r, [key]: value }
: r,
),
)
}
/>
</fieldset>
))}
<Button
type="button"
variant="outline"
onClick={() =>
form.setData('bank_accounts', [
...form.data.bank_accounts,
{
id: crypto.randomUUID(),
bank: '',
branch: '',
account_number: '',
currency: '',
nib: '',
iban: '',
nuib: '',
account_holder: '',
},
])
}
>
Adicionar conta bancária
</Button>
</section>
<label
className="grid gap-2 text-sm"
htmlFor="company-details-reason"
>
Motivo da alteração
<textarea
id="company-details-reason"
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 dados da empresa
</Button>
</form>
)}
</Panel>
);
}
+240
View File
@@ -0,0 +1,240 @@
import { usePage } from '@inertiajs/react';
import { CircleHelp, Search } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@/components/ui/sheet';
import {
helpAudience,
helpForJourney,
searchJourneyHelp,
type JourneyHelp,
} from '@/lib/journey-help';
export function openJourneyHelp(): void {
window.dispatchEvent(new Event('sgc:journey-help'));
}
export function JourneyHelpContent({
topic,
hasErrors = false,
}: {
topic: JourneyHelp;
hasErrors?: boolean;
}) {
return (
<article className="space-y-5" aria-label={`Guia: ${topic.title}`}>
<h2 className="text-lg font-semibold">{topic.title}</h2>
<p className="text-sm text-muted-foreground">{topic.purpose}</p>
{hasErrors && (
<p
role="status"
className="rounded border border-amber-400 bg-amber-50 p-3 text-sm text-amber-950 dark:bg-amber-950 dark:text-amber-100"
>
Há dados por conferir. Leia as mensagens junto do
formulário, corrija os campos indicados e confira o
resultado antes de repetir a confirmação.
</p>
)}
<section aria-label="Passos desta etapa">
<h3 className="mb-2 font-medium">Como fazer</h3>
<ol className="list-decimal space-y-2 pl-5 text-sm">
{topic.steps.map((step) => (
<li key={step}>{step}</li>
))}
</ol>
</section>
<section aria-label="Conferência antes de confirmar">
<h3 className="mb-2 font-medium">Antes de confirmar</h3>
<ul className="list-disc space-y-2 pl-5 text-sm">
{topic.checks.map((check) => (
<li key={check}>{check}</li>
))}
</ul>
</section>
<section>
<h3 className="mb-2 font-medium">
Se algo não correr como esperado
</h3>
<p className="text-sm">{topic.recovery}</p>
</section>
<section>
<h3 className="mb-2 font-medium">Próximo passo</h3>
<p className="text-sm">{topic.next}</p>
</section>
</article>
);
}
export default function JourneyHelpPanel() {
const page = usePage();
const current = helpForJourney(page.component, page.url, page.props.kind);
const audience = helpAudience(page.component);
// A new stage starts on its own guide. The form remains mounted when help opens or closes.
return (
<JourneyHelpStage
key={`${audience}:${current.id}`}
current={current}
audience={audience}
hasErrors={Object.keys(page.props.errors ?? {}).length > 0}
/>
);
}
function JourneyHelpStage({
current,
audience,
hasErrors,
}: {
current: JourneyHelp;
audience: ReturnType<typeof helpAudience>;
hasErrors: boolean;
}) {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState('');
const [browse, setBrowse] = useState(false);
const [selected, setSelected] = useState(current);
useEffect(() => {
const show = () => {
setSelected(current);
setQuery('');
setBrowse(false);
setOpen(true);
};
window.addEventListener('sgc:journey-help', show);
return () => window.removeEventListener('sgc:journey-help', show);
}, [current]);
const results =
query.trim() || browse ? searchJourneyHelp(query, audience) : [];
return (
<Sheet
open={open}
onOpenChange={(next) => {
if (next) {
setSelected(current);
setQuery('');
setBrowse(false);
}
setOpen(next);
}}
>
<SheetTrigger asChild>
<Button
type="button"
variant="outline"
className="fixed right-4 bottom-4 z-40 gap-2 rounded-full border-primary/30 bg-background shadow-lg print:hidden"
aria-label={`Abrir ajuda desta etapa: ${current.title}`}
>
<CircleHelp className="size-4" aria-hidden="true" />
<span>Ajuda</span>
{hasErrors && (
<span
className="size-2 rounded-full bg-amber-500"
aria-label="Há dados por conferir"
/>
)}
</Button>
</SheetTrigger>
<SheetContent className="w-full overflow-y-auto px-5 pb-8 sm:max-w-lg">
<SheetHeader className="px-0 pt-6">
<SheetTitle>Ajuda ao longo do percurso</SheetTitle>
<SheetDescription>
Consulte as orientações sem sair da página nem perder o
que está a preencher.
</SheetDescription>
</SheetHeader>
<label className="grid gap-2 text-sm font-medium">
<span className="flex items-center gap-2">
<Search className="size-4" aria-hidden="true" />
Procurar na ajuda
</span>
<Input
type="search"
value={query}
maxLength={100}
placeholder={
audience === 'candidate'
? 'Ex.: perfil, documentos, candidatura'
: audience === 'auth'
? 'Ex.: acesso, recuperação'
: 'Ex.: moeda, entrega, quantidade'
}
onChange={(event) => setQuery(event.target.value)}
/>
</label>
<button
type="button"
className="text-left text-sm underline"
aria-expanded={browse}
onClick={() => setBrowse(!browse)}
>
{browse ? 'Ocultar temas' : 'Ver todos os temas da ajuda'}
</button>
{(query.trim() || browse) && (
<div>
<p
role="status"
className="mb-2 text-sm text-muted-foreground"
>
{results.length
? `${results.length} tema(s) encontrado(s).`
: 'Sem resultados. Use outra palavra ou consulte a ajuda desta etapa.'}
</p>
<ul className="space-y-1">
{results.map((result) => (
<li key={result.id}>
<button
type="button"
className="w-full rounded border px-3 py-2 text-left text-sm hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring"
aria-pressed={selected.id === result.id}
onClick={() => {
setSelected(result);
setQuery('');
setBrowse(false);
}}
>
{result.title}
</button>
</li>
))}
</ul>
</div>
)}
{selected.id !== current.id && (
<Button
type="button"
variant="outline"
onClick={() => {
setSelected(current);
setQuery('');
}}
>
Voltar à ajuda desta etapa
</Button>
)}
<JourneyHelpContent
topic={selected}
hasErrors={selected.id === current.id && hasErrors}
/>
<p className="border-t pt-4 text-xs text-muted-foreground">
As acções disponíveis dependem do seu perfil e do estado do
processo. A ajuda não submete dados nem toma decisões.
</p>
<Button
type="button"
variant="outline"
onClick={() => setOpen(false)}
>
Fechar ajuda e continuar
</Button>
</SheetContent>
</Sheet>
);
}
@@ -17,6 +17,13 @@ export type ProcurementInsights = {
}[];
};
unapproved_past_needed_date: number;
approval_times?: {
measured: number;
unknown: number;
total_seconds: number;
min_seconds: number | null;
max_seconds: number | null;
};
approved: {
count: number;
without_registered_quotes: number;
@@ -107,6 +114,60 @@ export function ProcurementOperationalInsights({
comparáveis; ausência de ordem visível não comprova
incumprimento.
</p>
{data.approval_times && (
<section
className="space-y-2"
aria-label="Tempos de aprovação"
>
<h3 className="font-medium">
Tempos de aprovação concluída
</h3>
<p>
Da submissão à última decisão aprovada de
todas as etapas, em horas decorridas. Não
representa dias úteis ou cumprimento de um
prazo contratual.
</p>
<p>
{data.approval_times.measured} processos com
datas utilizáveis;{' '}
{data.approval_times.unknown} sem base
completa ou cronologia consistente.
</p>
{data.approval_times.measured > 0 ? (
<p>
Média:{' '}
{(
data.approval_times.total_seconds /
data.approval_times.measured /
3600
).toLocaleString('pt-MZ', {
maximumFractionDigits: 2,
})}{' '}
h · Menor:{' '}
{(
(data.approval_times.min_seconds ??
0) / 3600
).toLocaleString('pt-MZ', {
maximumFractionDigits: 2,
})}{' '}
h · Maior:{' '}
{(
(data.approval_times.max_seconds ??
0) / 3600
).toLocaleString('pt-MZ', {
maximumFractionDigits: 2,
})}{' '}
h
</p>
) : (
<p>
Sem base suficiente para calcular tempos
de aprovação.
</p>
)}
</section>
)}
<div className="flex flex-wrap gap-3">
{withoutQuotesHref &&
data.approved.without_registered_quotes > 0 && (
+22 -1
View File
@@ -2,6 +2,8 @@ import { Link } from '@inertiajs/react';
import { ArrowUpRight, ClipboardList } from 'lucide-react';
import type { ReactNode } from 'react';
import { Badge } from '@/components/ui/badge';
import { openJourneyHelp } from '@/components/journey-help';
import { recoveryHints } from '@/lib/journey-help';
import { date, money, statusLabels } from '@/types/procurement';
import type { Requisition } from '@/types/procurement';
@@ -131,7 +133,7 @@ export function RequisitionTable({ rows }: { rows: Requisition[] }) {
<Status value={r.status} />
</td>
<td className="text-right font-medium whitespace-nowrap">
{money(Number(r.total_minor))}
{money(r.total_minor)}
</td>
<td className="pl-3">
<Link
@@ -150,6 +152,7 @@ export function RequisitionTable({ rows }: { rows: Requisition[] }) {
}
export function FormErrors({ errors }: { errors: Record<string, string> }) {
if (!Object.keys(errors).length) return null;
const hints = recoveryHints(Object.keys(errors));
return (
<div
role="alert"
@@ -161,6 +164,24 @@ export function FormErrors({ errors }: { errors: Record<string, string> }) {
<li key={key}>{value}</li>
))}
</ul>
{hints.length > 0 && (
<div
className="mt-3 space-y-2 text-foreground"
role="note"
aria-label="Orientação para corrigir"
>
{hints.map((hint) => (
<p key={hint}>{hint}</p>
))}
</div>
)}
<button
type="button"
className="mt-3 underline focus-visible:ring-2 focus-visible:ring-ring"
onClick={openJourneyHelp}
>
Consultar ajuda para corrigir e continuar
</button>
</div>
);
}
@@ -303,7 +303,7 @@ export function SgcWorkspaceShell({ children }: { children: ReactNode }) {
);
return (
<div className="min-h-screen bg-slate-50 text-foreground dark:bg-background print:block">
{context?.enforced && <WorkContextChange />}
<WorkContextChange />
{context?.enforced && (
<div
className="border-b bg-background px-5 py-2 text-sm"
@@ -518,7 +518,7 @@ export function SgcWorkspaceShell({ children }: { children: ReactNode }) {
<span className="block truncate text-xs font-medium">
{user.name}
</span>
<span className="block text-[10px] text-muted-foreground">
<span className="block truncate text-[10px] text-muted-foreground">
{(
page.props
.organizationAccess as {
+1 -1
View File
@@ -72,7 +72,7 @@ function SheetContent({
{children}
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
<XIcon className="size-4" />
<span className="sr-only">Close</span>
<span className="sr-only">Fechar</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
+28 -30
View File
@@ -1,6 +1,7 @@
import { router, usePage } from '@inertiajs/react';
import { useEffect, useRef, useState } from 'react';
import { Button } from '@/components/ui/button';
import { protectDepartures } from '@/lib/unsaved-navigation';
import {
Dialog,
DialogContent,
@@ -13,6 +14,7 @@ export function WorkContextChange() {
const dirty = useRef(new Set<HTMLFormElement>());
const pending = useRef(false);
const savingForm = useRef<HTMLFormElement | null>(null);
const destination = useRef<(() => void) | null>(null);
const [open, setOpen] = useState(false);
const [message, setMessage] = useState('');
useEffect(() => {
@@ -38,26 +40,17 @@ export function WorkContextChange() {
if (input.form) dirty.current.add(input.form);
}
};
const click = (event: MouseEvent) => {
if (!(event.target instanceof Element)) return;
const link = event.target.closest('a');
if (
!link ||
new URL(link.href).pathname !== '/dashboard' ||
!dirty.current.size
)
return;
event.preventDefault();
event.stopPropagation();
setMessage('');
setOpen(true);
};
const unload = (event: BeforeUnloadEvent) => {
if (dirty.current.size) {
event.preventDefault();
event.returnValue = '';
}
};
const offDepartures = protectDepartures(
(submittedForm) =>
[...dirty.current].some(
(form) => form.isConnected && form !== submittedForm,
),
(proceed) => {
destination.current = proceed;
setMessage('');
setOpen(true);
},
);
const saved = (event: Event) => {
if (!(event instanceof CustomEvent)) return;
if (event.detail.success) dirty.current.delete(event.detail.form);
@@ -67,7 +60,9 @@ export function WorkContextChange() {
pending.current = false;
dirty.current.clear();
setOpen(false);
router.visit('/dashboard');
const proceed = destination.current;
destination.current = null;
proceed?.();
} else {
pending.current = false;
setOpen(true);
@@ -89,19 +84,16 @@ export function WorkContextChange() {
const offNetwork = router.on('networkError', failure);
document.addEventListener('input', changed);
document.addEventListener('change', changed);
document.addEventListener('click', click, true);
window.addEventListener('beforeunload', unload);
window.addEventListener('sgc:context-save-result', saved);
window.addEventListener('sgc:context-dirty', formChanged);
return () => {
document.removeEventListener('input', changed);
document.removeEventListener('change', changed);
document.removeEventListener('click', click, true);
window.removeEventListener('beforeunload', unload);
window.removeEventListener('sgc:context-save-result', saved);
window.removeEventListener('sgc:context-dirty', formChanged);
offException();
offNetwork();
offDepartures();
};
}, []);
return (
@@ -109,8 +101,8 @@ export function WorkContextChange() {
<DialogContent>
<DialogTitle>Alterações por guardar</DialogTitle>
<DialogDescription>
Guarde as alterações antes de escolher outro contexto, ou
descarte-as.
Existem alterações por guardar. Pode guardar antes de sair,
descartar as alterações ou continuar a editar.
</DialogDescription>
{message && <p role="alert">{message}</p>}
<div className="flex flex-wrap gap-3">
@@ -131,7 +123,10 @@ export function WorkContextChange() {
);
return;
}
if (!forms[0].reportValidity()) {
if (
!forms[0].noValidate &&
!forms[0].reportValidity()
) {
setOpen(false);
return;
}
@@ -149,7 +144,9 @@ export function WorkContextChange() {
dirty.current.clear();
pending.current = false;
setOpen(false);
router.visit('/dashboard');
const proceed = destination.current;
destination.current = null;
proceed?.();
}}
>
Descartar
@@ -158,10 +155,11 @@ export function WorkContextChange() {
variant="outline"
onClick={() => {
pending.current = false;
destination.current = null;
setOpen(false);
}}
>
Cancelar
Continuar a editar
</Button>
</div>
</DialogContent>