Aplicar Pint e formatação de frontend; delimitar o âmbito do lint

Só formatação automática (pint, vp check --fix), sem alterar comportamento.
Excluídos da formatação os registos e artefactos com bytes fixos: docs/,
integrations/, storage/, tmp/, output/, resources/data/, tests/Fixtures/,
compras-release.json e AGENTS*.md. Scripts operacionais, integrations e
auxiliares de teste ficam fora do lint (usam new Function; limpeza na fase 2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-30 23:01:42 +02:00
co-authored by Claude Opus 5.5
parent 9f719695e3
commit ec934455e7
148 changed files with 9455 additions and 2413 deletions
+5 -4
View File
@@ -115,10 +115,11 @@ export default function Clients({
onSubmit={(event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
const search = data.get('search');
router.get('/empresa/clientes', {
search: typeof search === 'string' ? search : '',
});
const search = data.get('search');
router.get('/empresa/clientes', {
search:
typeof search === 'string' ? search : '',
});
}}
>
<input
+530 -38
View File
@@ -3,49 +3,541 @@ import { useEffect, useRef, useState, type FormEvent } from 'react';
import { PageTitle, Panel, controlClass } from '@/components/procurement';
import { Button } from '@/components/ui/button';
type Impact = { physical_before: string; physical_after: string; return_quantity_milli: string; not_returned_before: string; not_returned_after: string; original_movement_id: number; item: { code: string; name: string; unit: string }; warehouse: { code: string; name: string } };
type Impact = {
physical_before: string;
physical_after: string;
return_quantity_milli: string;
not_returned_before: string;
not_returned_after: string;
original_movement_id: number;
item: { code: string; name: string; unit: string };
warehouse: { code: string; name: string };
};
type Page = { page: number; last_page: number; total: number };
type Row = { id: number; prepared_id: number; version: number; state: string; reason: string; evidence: string; preparer_id: number; author_id: number; created_at: string; impact: Impact };
type Option = { delivery_event_id: number; line_index: number; delivered_milli: string; item: Impact['item'] };
const milli = (value: string) => { const q = BigInt(value); return `${q / 1000n},${(q % 1000n).toString().padStart(3, '0')}`; };
const states: Record<string,string> = {prepared:'Por confirmar',confirmed:'Confirmada',withdrawn:'Retirada',rejected:'Recusada'};
type Row = {
id: number;
prepared_id: number;
version: number;
state: string;
reason: string;
evidence: string;
preparer_id: number;
author_id: number;
created_at: string;
impact: Impact;
};
type Option = {
delivery_event_id: number;
line_index: number;
delivered_milli: string;
item: Impact['item'];
};
const milli = (value: string) => {
const q = BigInt(value);
return `${q / 1000n},${(q % 1000n).toString().padStart(3, '0')}`;
};
const states: Record<string, string> = {
prepared: 'Por confirmar',
confirmed: 'Confirmada',
withdrawn: 'Retirada',
rejected: 'Recusada',
};
export function WarehouseReturnImpact({ impact: p }: { impact: Impact }) {
return <p>Stock físico: {milli(p.physical_before)} → {milli(p.physical_after)}. Devolução: {milli(p.return_quantity_milli)} {p.item.unit}. Entrega ainda não devolvida: {milli(p.not_returned_before)} → {milli(p.not_returned_after)}. {p.item.code} · {p.warehouse.code} · Saída original #{p.original_movement_id}.</p>;
return (
<p>
Stock físico: {milli(p.physical_before)} → {milli(p.physical_after)}
. Devolução: {milli(p.return_quantity_milli)} {p.item.unit}. Entrega
ainda não devolvida: {milli(p.not_returned_before)} →{' '}
{milli(p.not_returned_after)}. {p.item.code} · {p.warehouse.code} ·
Saída original #{p.original_movement_id}.
</p>
);
}
async function api<T>(url: string, body?: object, signal?: AbortSignal): Promise<T> {
const token = document.cookie.split('; ').find((c) => c.startsWith('XSRF-TOKEN='))?.slice(11);
const response = await fetch(url, { method: body ? 'POST' : 'GET', credentials: 'same-origin', signal, headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', ...(token ? { 'X-XSRF-TOKEN': decodeURIComponent(token) } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) });
const result = await response.json(); if (!response.ok) throw new Error(result.errors ? Object.values(result.errors).flat().join(' ') : result.message || `Pedido recusado (${response.status})`); return result;
async function api<T>(
url: string,
body?: object,
signal?: AbortSignal,
): Promise<T> {
const token = document.cookie
.split('; ')
.find((c) => c.startsWith('XSRF-TOKEN='))
?.slice(11);
const response = await fetch(url, {
method: body ? 'POST' : 'GET',
credentials: 'same-origin',
signal,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
...(token ? { 'X-XSRF-TOKEN': decodeURIComponent(token) } : {}),
},
...(body ? { body: JSON.stringify(body) } : {}),
});
const result = await response.json();
if (!response.ok)
throw new Error(
result.errors
? Object.values(result.errors).flat().join(' ')
: result.message || `Pedido recusado (${response.status})`,
);
return result;
}
export default function WarehouseReturns({ requestId, actorId, canPrepare, canConfirm, canWithdraw=false }: { requestId: number | null; actorId: number; canPrepare: boolean; canConfirm: boolean; canWithdraw?:boolean }) {
const [history, setHistory] = useState<{ rows: Row[]; pagination: Page } | null>(null), [sources, setSources] = useState<{ options: Option[]; pagination: Page } | null>(null);
const [page, setPage] = useState(1), [sourcePage, setSourcePage] = useState(1), [state, setState] = useState('all'), [reload, setReload] = useState(0), [error, setError] = useState(''), [busy, setBusy] = useState(false), [preview, setPreview] = useState<{ id: number; impact: Impact; state?:string } | null>(null);
const generation = useRef(0), command = useRef<{ data: string; key: string } | null>(null);
useEffect(() => { const n = ++generation.current, abort = new AbortController(); setHistory(null); setSources(null); setError('');
Promise.all([api<{ rows: Row[]; pagination: Page }>(`/api/stock-returns?page=${page}&state=${state}`, undefined, abort.signal), requestId ? api<{ options: Option[]; pagination: Page }>(`/api/stock-returns/sources?request_id=${requestId}&source_page=${sourcePage}`, undefined, abort.signal) : Promise.resolve(null)])
.then(([h, s]) => { if (n === generation.current) { setHistory(h); setSources(s); } }).catch((e: Error) => { if (!abort.signal.aborted && n === generation.current) setError(e.message); });
return () => { generation.current++; abort.abort(); };
export default function WarehouseReturns({
requestId,
actorId,
canPrepare,
canConfirm,
canWithdraw = false,
}: {
requestId: number | null;
actorId: number;
canPrepare: boolean;
canConfirm: boolean;
canWithdraw?: boolean;
}) {
const [history, setHistory] = useState<{
rows: Row[];
pagination: Page;
} | null>(null),
[sources, setSources] = useState<{
options: Option[];
pagination: Page;
} | null>(null);
const [page, setPage] = useState(1),
[sourcePage, setSourcePage] = useState(1),
[state, setState] = useState('all'),
[reload, setReload] = useState(0),
[error, setError] = useState(''),
[busy, setBusy] = useState(false),
[preview, setPreview] = useState<{
id: number;
impact: Impact;
state?: string;
} | null>(null);
const generation = useRef(0),
command = useRef<{ data: string; key: string } | null>(null);
useEffect(() => {
const n = ++generation.current,
abort = new AbortController();
setHistory(null);
setSources(null);
setError('');
Promise.all([
api<{ rows: Row[]; pagination: Page }>(
`/api/stock-returns?page=${page}&state=${state}`,
undefined,
abort.signal,
),
requestId
? api<{ options: Option[]; pagination: Page }>(
`/api/stock-returns/sources?request_id=${requestId}&source_page=${sourcePage}`,
undefined,
abort.signal,
)
: Promise.resolve(null),
])
.then(([h, s]) => {
if (n === generation.current) {
setHistory(h);
setSources(s);
}
})
.catch((e: Error) => {
if (!abort.signal.aborted && n === generation.current)
setError(e.message);
});
return () => {
generation.current++;
abort.abort();
};
}, [requestId, actorId, page, sourcePage, state, reload]);
useEffect(() => { setPreview(null); command.current = null; setPage(1); setSourcePage(1); }, [requestId, actorId]);
async function prepare(e: FormEvent<HTMLFormElement>) { e.preventDefault(); const n = generation.current; setBusy(true); setError(''); const fields = Object.fromEntries(new FormData(e.currentTarget)), choice = sources?.options.find((o) => `${o.delivery_event_id}:${o.line_index}` === fields.source);
if (!choice) { setError('Seleccione uma entrega recebida.'); setBusy(false); return; }
const body = { delivery_event_id: choice.delivery_event_id, line_index: choice.line_index, quantity: fields.quantity, declared_unused: fields.declared_unused === 'on', reason: fields.reason, evidence: fields.evidence }, data = JSON.stringify(body);
if (command.current?.data !== data) command.current = { data, key: crypto.randomUUID() };
try { const p = await api<{ id: number; impact: Impact }>('/api/stock-returns/prepare', { ...body, operation_key: command.current.key }); if (n === generation.current) { setPreview(p); setReload((x) => x + 1); } } catch (err) { if (n === generation.current) setError((err as Error).message); } finally { setBusy(false); }
useEffect(() => {
setPreview(null);
command.current = null;
setPage(1);
setSourcePage(1);
}, [requestId, actorId]);
async function prepare(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const n = generation.current;
setBusy(true);
setError('');
const fields = Object.fromEntries(new FormData(e.currentTarget)),
choice = sources?.options.find(
(o) =>
`${o.delivery_event_id}:${o.line_index}` === fields.source,
);
if (!choice) {
setError('Seleccione uma entrega recebida.');
setBusy(false);
return;
}
const body = {
delivery_event_id: choice.delivery_event_id,
line_index: choice.line_index,
quantity: fields.quantity,
declared_unused: fields.declared_unused === 'on',
reason: fields.reason,
evidence: fields.evidence,
},
data = JSON.stringify(body);
if (command.current?.data !== data)
command.current = { data, key: crypto.randomUUID() };
try {
const p = await api<{ id: number; impact: Impact }>(
'/api/stock-returns/prepare',
{ ...body, operation_key: command.current.key },
);
if (n === generation.current) {
setPreview(p);
setReload((x) => x + 1);
}
} catch (err) {
if (n === generation.current) setError((err as Error).message);
} finally {
setBusy(false);
}
}
async function confirm(e: FormEvent<HTMLFormElement>, row: Row) { e.preventDefault(); const n = generation.current; setBusy(true); setError(''); const fields = Object.fromEntries(new FormData(e.currentTarget));
try { await api(`/api/stock-returns/${row.prepared_id}/confirm`, { version: 1, received_in_warehouse: fields.received_in_warehouse === 'on', reason: fields.reason }); if (n === generation.current) { setPreview(null); setReload((x) => x + 1); } } catch (err) { if (n === generation.current) setError((err as Error).message); } finally { setBusy(false); }
async function confirm(e: FormEvent<HTMLFormElement>, row: Row) {
e.preventDefault();
const n = generation.current;
setBusy(true);
setError('');
const fields = Object.fromEntries(new FormData(e.currentTarget));
try {
await api(`/api/stock-returns/${row.prepared_id}/confirm`, {
version: 1,
received_in_warehouse: fields.received_in_warehouse === 'on',
reason: fields.reason,
});
if (n === generation.current) {
setPreview(null);
setReload((x) => x + 1);
}
} catch (err) {
if (n === generation.current) setError((err as Error).message);
} finally {
setBusy(false);
}
}
async function close(e:FormEvent<HTMLFormElement>,row:Row,action:'withdraw'|'reject'){e.preventDefault();const n=generation.current;setBusy(true);setError('');const fields=Object.fromEntries(new FormData(e.currentTarget));try{await api(`/api/stock-returns/${row.prepared_id}/${action}`,{version:1,reason:fields.reason});if(n===generation.current){setPreview(null);setReload(x=>x+1);}}catch(err){if(n===generation.current)setError((err as Error).message);}finally{setBusy(false);}}
return <><Head title="Devoluções de excedentes" /><div className="space-y-6 p-6"><PageTitle eyebrow="Armazém · Material não consumido" title="Devoluções de excedentes" description="Declaração do destinatário e recepção física independente. O original permanece intacto." />
<Link href={requestId ? `/stock/requisicoes/${requestId}` : '/dashboard'}>{requestId ? 'Consultar a requisição de origem' : 'Voltar ao Painel Inicial'}</Link>
{error && <p role="alert">{error}</p>}<Button disabled={busy} onClick={() => setReload((x) => x + 1)}>Actualizar</Button>
{canPrepare && requestId && sources && <Panel title={`Entregas recebidas · RA-${requestId}`}><form onSubmit={prepare} className="space-y-4"><label>Entrega e linha de origem<select name="source" className={controlClass} defaultValue="" required><option value="" disabled>Seleccione a origem</option>{sources.options.map((o) => <option key={`${o.delivery_event_id}:${o.line_index}`} value={`${o.delivery_event_id}:${o.line_index}`}>Entrega #{o.delivery_event_id} · {o.item.code} · {o.item.name} · entregue {milli(o.delivered_milli)} {o.item.unit}</option>)}</select></label>
<label>Quantidade efectivamente devolvida<input name="quantity" className={controlClass} pattern="[0-9]{1,6}(\.[0-9]{1,3})?" required /></label><label>Evidência de excedente e entrega física<textarea name="evidence" className={controlClass} minLength={10} maxLength={1000} required /></label><label>Fundamento<textarea name="reason" className={controlClass} minLength={10} maxLength={1000} required /></label><label><input type="checkbox" name="declared_unused" required />Declaro que esta quantidade não foi consumida</label><Button disabled={busy}>Conferir impacto</Button></form>
<Button disabled={sourcePage <= 1 || busy} onClick={() => setSourcePage((x) => x - 1)}>Entregas anteriores</Button><Button disabled={sourcePage >= sources.pagination.last_page || busy} onClick={() => setSourcePage((x) => x + 1)}>Entregas seguintes</Button></Panel>}
{preview && <Panel title={`Prévia da proposta #${preview.id}`}><WarehouseReturnImpact impact={preview.impact} /><p>{preview.state&&preview.state!=='prepared'?`Decisão já registada: ${states[preview.state]??'Arquivada'}. Sem novo efeito.`:'A preparação não altera stock. Aguarda outra identidade autorizada.'}</p></Panel>}
<Panel title="Histórico e decisões"><label>Estado<select className={controlClass} value={state} onChange={(e) => { setState(e.target.value); setPage(1); }}><option value="all">Todos</option><option value="prepared">Por confirmar</option><option value="confirmed">Confirmados</option><option value="withdrawn">Retirados</option><option value="rejected">Recusados</option></select></label>
{!history ? <p role="status">A consultar decisões…</p> : <>{history.rows.map((r) => <article key={r.id} className="space-y-3 border-b py-4"><h3>Proposta #{r.prepared_id} · v{r.version} · {states[r.state]??'Estado arquivado'}</h3><p>{r.state==="confirmed"?"Entrada efectuada":r.state==="prepared"?"Impacto proposto":"Prévia arquivada, não executada"}</p><WarehouseReturnImpact impact={r.impact} /><p>{r.reason} · Evidência: {r.evidence}</p><p>Preparação #{r.preparer_id} · Autor desta versão #{r.author_id} · {r.created_at}</p>
{r.state === 'prepared' && canConfirm && r.preparer_id !== actorId && <form onSubmit={(e) => confirm(e, r)}><label>Fundamento da recepção<textarea name="reason" className={controlClass} minLength={10} maxLength={1000} required /></label><label><input type="checkbox" name="received_in_warehouse" required />Recebi fisicamente esta quantidade no armazém indicado</label><Button disabled={busy}>Confirmar entrada conferida</Button></form>}<>{r.state==="prepared"&&canWithdraw&&r.preparer_id===actorId&&<details><summary>Retirar proposta sem movimento</summary><form onSubmit={e=>close(e,r,"withdraw")}><label>Fundamento da retirada<textarea name="reason" className={controlClass} minLength={10} maxLength={1000} required/></label><Button disabled={busy}>Retirar proposta</Button></form></details>}{r.state==="prepared"&&canConfirm&&r.preparer_id!==actorId&&<details><summary>Recusar recepção sem movimento</summary><form onSubmit={e=>close(e,r,"reject")}><label>Fundamento da recusa<textarea name="reason" className={controlClass} minLength={10} maxLength={1000} required/></label><Button disabled={busy}>Recusar conferência</Button></form></details>}</></article>)}{!history.rows.length && <p>Sem decisões neste filtro.</p>}<Button disabled={page <= 1 || busy} onClick={() => setPage((x) => x - 1)}>Anterior</Button><Button disabled={page >= history.pagination.last_page || busy} onClick={() => setPage((x) => x + 1)}>Seguinte</Button></>}
</Panel></div></>;
async function close(
e: FormEvent<HTMLFormElement>,
row: Row,
action: 'withdraw' | 'reject',
) {
e.preventDefault();
const n = generation.current;
setBusy(true);
setError('');
const fields = Object.fromEntries(new FormData(e.currentTarget));
try {
await api(`/api/stock-returns/${row.prepared_id}/${action}`, {
version: 1,
reason: fields.reason,
});
if (n === generation.current) {
setPreview(null);
setReload((x) => x + 1);
}
} catch (err) {
if (n === generation.current) setError((err as Error).message);
} finally {
setBusy(false);
}
}
return (
<>
<Head title="Devoluções de excedentes" />
<div className="space-y-6 p-6">
<PageTitle
eyebrow="Armazém · Material não consumido"
title="Devoluções de excedentes"
description="Declaração do destinatário e recepção física independente. O original permanece intacto."
/>
<Link
href={
requestId
? `/stock/requisicoes/${requestId}`
: '/dashboard'
}
>
{requestId
? 'Consultar a requisição de origem'
: 'Voltar ao Painel Inicial'}
</Link>
{error && <p role="alert">{error}</p>}
<Button disabled={busy} onClick={() => setReload((x) => x + 1)}>
Actualizar
</Button>
{canPrepare && requestId && sources && (
<Panel title={`Entregas recebidas · RA-${requestId}`}>
<form onSubmit={prepare} className="space-y-4">
<label>
Entrega e linha de origem
<select
name="source"
className={controlClass}
defaultValue=""
required
>
<option value="" disabled>
Seleccione a origem
</option>
{sources.options.map((o) => (
<option
key={`${o.delivery_event_id}:${o.line_index}`}
value={`${o.delivery_event_id}:${o.line_index}`}
>
Entrega #{o.delivery_event_id} ·{' '}
{o.item.code} · {o.item.name} ·
entregue {milli(o.delivered_milli)}{' '}
{o.item.unit}
</option>
))}
</select>
</label>
<label>
Quantidade efectivamente devolvida
<input
name="quantity"
className={controlClass}
pattern="[0-9]{1,6}(\.[0-9]{1,3})?"
required
/>
</label>
<label>
Evidência de excedente e entrega física
<textarea
name="evidence"
className={controlClass}
minLength={10}
maxLength={1000}
required
/>
</label>
<label>
Fundamento
<textarea
name="reason"
className={controlClass}
minLength={10}
maxLength={1000}
required
/>
</label>
<label>
<input
type="checkbox"
name="declared_unused"
required
/>
Declaro que esta quantidade não foi consumida
</label>
<Button disabled={busy}>Conferir impacto</Button>
</form>
<Button
disabled={sourcePage <= 1 || busy}
onClick={() => setSourcePage((x) => x - 1)}
>
Entregas anteriores
</Button>
<Button
disabled={
sourcePage >= sources.pagination.last_page ||
busy
}
onClick={() => setSourcePage((x) => x + 1)}
>
Entregas seguintes
</Button>
</Panel>
)}
{preview && (
<Panel title={`Prévia da proposta #${preview.id}`}>
<WarehouseReturnImpact impact={preview.impact} />
<p>
{preview.state && preview.state !== 'prepared'
? `Decisão já registada: ${states[preview.state] ?? 'Arquivada'}. Sem novo efeito.`
: 'A preparação não altera stock. Aguarda outra identidade autorizada.'}
</p>
</Panel>
)}
<Panel title="Histórico e decisões">
<label>
Estado
<select
className={controlClass}
value={state}
onChange={(e) => {
setState(e.target.value);
setPage(1);
}}
>
<option value="all">Todos</option>
<option value="prepared">Por confirmar</option>
<option value="confirmed">Confirmados</option>
<option value="withdrawn">Retirados</option>
<option value="rejected">Recusados</option>
</select>
</label>
{!history ? (
<p role="status">A consultar decisões…</p>
) : (
<>
{history.rows.map((r) => (
<article
key={r.id}
className="space-y-3 border-b py-4"
>
<h3>
Proposta #{r.prepared_id} · v{r.version}{' '}
·{' '}
{states[r.state] ?? 'Estado arquivado'}
</h3>
<p>
{r.state === 'confirmed'
? 'Entrada efectuada'
: r.state === 'prepared'
? 'Impacto proposto'
: 'Prévia arquivada, não executada'}
</p>
<WarehouseReturnImpact impact={r.impact} />
<p>
{r.reason} · Evidência: {r.evidence}
</p>
<p>
Preparação #{r.preparer_id} · Autor
desta versão #{r.author_id} ·{' '}
{r.created_at}
</p>
{r.state === 'prepared' &&
canConfirm &&
r.preparer_id !== actorId && (
<form
onSubmit={(e) => confirm(e, r)}
>
<label>
Fundamento da recepção
<textarea
name="reason"
className={controlClass}
minLength={10}
maxLength={1000}
required
/>
</label>
<label>
<input
type="checkbox"
name="received_in_warehouse"
required
/>
Recebi fisicamente esta
quantidade no armazém
indicado
</label>
<Button disabled={busy}>
Confirmar entrada conferida
</Button>
</form>
)}
<>
{r.state === 'prepared' &&
canWithdraw &&
r.preparer_id === actorId && (
<details>
<summary>
Retirar proposta sem
movimento
</summary>
<form
onSubmit={(e) =>
close(
e,
r,
'withdraw',
)
}
>
<label>
Fundamento da
retirada
<textarea
name="reason"
className={
controlClass
}
minLength={10}
maxLength={1000}
required
/>
</label>
<Button disabled={busy}>
Retirar proposta
</Button>
</form>
</details>
)}
{r.state === 'prepared' &&
canConfirm &&
r.preparer_id !== actorId && (
<details>
<summary>
Recusar recepção sem
movimento
</summary>
<form
onSubmit={(e) =>
close(
e,
r,
'reject',
)
}
>
<label>
Fundamento da recusa
<textarea
name="reason"
className={
controlClass
}
minLength={10}
maxLength={1000}
required
/>
</label>
<Button disabled={busy}>
Recusar conferência
</Button>
</form>
</details>
)}
</>
</article>
))}
{!history.rows.length && (
<p>Sem decisões neste filtro.</p>
)}
<Button
disabled={page <= 1 || busy}
onClick={() => setPage((x) => x - 1)}
>
Anterior
</Button>
<Button
disabled={
page >= history.pagination.last_page || busy
}
onClick={() => setPage((x) => x + 1)}
>
Seguinte
</Button>
</>
)}
</Panel>
</div>
</>
);
}