commit de armazens
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-04 09:40:26 +02:00
parent e753f7a0a4
commit 63d20b10fc
245 changed files with 10847 additions and 230 deletions
+7
View File
@@ -0,0 +1,7 @@
# Cartografia administrativa fornecida
`cartografia-moz.json` conserva as oito colunas de cada linha da fonte, além do diagnóstico e da ligação explícita ao pai quando única. Códigos são texto. Não normalizar nomes, eliminar duplicados ou inserir localidades sem uma fonte aprovada.
Preparador: `scripts/prepare-geography-catalogue.py SOURCE.xlsx DESTINATION.json`. Leitura apenas do XLSX. A mesma fonte produz o mesmo conteúdo; outra fonte exige novo destino. A configuração da aplicação fixa os hashes e permanece desligada no piloto.
Fonte/edição, integração e limitações: `docs/divisao-administrativa-sgc.md`.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,253 @@
import { useEffect, useId, useState } from 'react';
import { useForm } from '@inertiajs/react';
import { Button } from '@/components/ui/button';
import { FormErrors, controlClass } from '@/components/procurement';
export type GeographyReference = {
country: string;
catalogue: string;
record_id: string;
};
type Node = {
id: string;
name: string;
level: number;
parent_id: string | null;
};
export type GeographyDescription = {
reference: GeographyReference;
path: Node[];
requires_review: boolean;
} | null;
const levels = [
'Província',
'Distrito',
'Posto administrativo',
'Localidade',
'Bairro urbano',
'Aldeia / quarteirão',
];
export function AdministrativeLocation({
value,
initial = null,
onChange,
endpoint = '/api/divisao-administrativa',
maxLevel = 6,
legend = 'Localização administrativa de Moçambique (opcional)',
hint = 'Escolha apenas até ao nível conhecido. A morada mantém-se. Para endereços estrangeiros, deixe esta referência vazia.',
}: {
value: GeographyReference | null;
initial?: GeographyDescription;
endpoint?: string;
maxLevel?: number;
legend?: string;
hint?: string;
onChange: (
value: GeographyReference | null,
description?: GeographyDescription,
) => void;
}) {
const id = useId();
const [path, setPath] = useState<Node[]>(initial?.path ?? []);
const [options, setOptions] = useState<Node[]>([]);
const [page, setPage] = useState(1);
const [more, setMore] = useState(false);
const [catalogue, setCatalogue] = useState(value?.catalogue ?? '');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const activePath = value ? path : [];
const parent = activePath.at(-1)?.id ?? '';
const atLastLevel = (activePath.at(-1)?.level ?? 0) >= maxLevel;
const queryPage = value ? page : 1;
const [retry, setRetry] = useState(0);
useEffect(() => {
if (atLastLevel) {
setOptions([]);
setMore(false);
setLoading(false);
setError('');
return;
}
const controller = new AbortController();
setLoading(true);
setError('');
fetch(
`${endpoint}?${new URLSearchParams({ parent, page: String(queryPage) })}`,
{
headers: { Accept: 'application/json' },
signal: controller.signal,
},
)
.then(async (response) => {
if (!response.ok)
throw new Error(
'Não foi possível carregar as localidades. Tente novamente.',
);
return response.json() as Promise<{
data: Node[];
has_more: boolean;
catalogue: string;
}>;
})
.then((result) => {
if (controller.signal.aborted) return;
setOptions((previous) =>
queryPage === 1
? result.data
: [...previous, ...result.data],
);
setMore(result.has_more);
setCatalogue(result.catalogue);
})
.catch((failure: Error) => {
if (!controller.signal.aborted) setError(failure.message);
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false);
});
return () => controller.abort();
}, [parent, queryPage, retry, endpoint, atLastLevel]);
const select = (next: Node[]) => {
setPath(next);
setOptions([]);
setPage(1);
const node = next.at(-1);
onChange(
node ? { country: 'MZ', catalogue, record_id: node.id } : null,
node
? {
reference: {
country: 'MZ',
catalogue,
record_id: node.id,
},
path: next,
requires_review: false,
}
: null,
);
};
return (
<fieldset className="space-y-3 rounded-lg border p-4">
<legend className="px-2 font-medium">{legend}</legend>
<p className="text-sm text-muted-foreground">{hint}</p>
<p className="text-sm">
{activePath.map((node) => node.name).join(' / ') ||
'Sem referência administrativa'}
</p>
{initial?.requires_review && (
<p role="status">
A referência anterior precisa de revisão. Escolha um
percurso confirmado.
</p>
)}
<label htmlFor={id} className="block text-sm">
{levels[options[0]?.level - 1] ?? 'Próximo nível'}
</label>
<select
id={id}
className={controlClass}
value=""
disabled={loading || !!error || options.length === 0}
onChange={(event) => {
const node = options.find(
(option) => option.id === event.target.value,
);
if (node) select([...activePath, node]);
}}
>
<option value="">
{loading
? 'A carregar…'
: options.length
? 'Escolher localização'
: 'Sem níveis adicionais confirmados'}
</option>
{options.map((node) => (
<option key={node.id} value={node.id}>
{node.name}
</option>
))}
</select>
{error && (
<Button
type="button"
variant="outline"
onClick={() => setRetry(retry + 1)}
>
Tentar novamente
</Button>
)}
{error && (
<p role="alert" className="text-sm text-red-700">
{error}
</p>
)}
<div className="flex flex-wrap gap-2">
{more && (
<Button
type="button"
variant="outline"
disabled={loading}
onClick={() => setPage(page + 1)}
>
Mais localidades
</Button>
)}
{activePath.length > 0 && (
<Button
type="button"
variant="outline"
onClick={() => select(activePath.slice(0, -1))}
>
Voltar um nível
</Button>
)}
{value && (
<Button
type="button"
variant="outline"
onClick={() => select([])}
>
Retirar referência
</Button>
)}
</div>
</fieldset>
);
}
export function CompanyAdministrativeLocation({
geography,
}: {
geography: GeographyDescription;
}) {
const form = useForm({
geography_reference:
geography?.reference ?? (null as GeographyReference | null),
expected_reference: geography?.reference ?? null,
});
useEffect(() => {
form.setData('expected_reference', geography?.reference ?? null);
}, [geography]);
return (
<form
className="space-y-4"
onSubmit={(event) => {
event.preventDefault();
form.post('/empresa/localizacao', { preserveScroll: true });
}}
>
<FormErrors errors={form.errors} />
<AdministrativeLocation
value={form.data.geography_reference}
initial={geography}
onChange={(value) => form.setData('geography_reference', value)}
/>
<Button disabled={form.processing}>
Guardar localização da sede
</Button>
</form>
);
}
@@ -0,0 +1,57 @@
import { useState } from 'react';
import { AdministrativeLocation } from '@/components/administrative-location';
import type {
GeographyReference,
GeographyDescription,
} from '@/components/administrative-location';
import { Button } from '@/components/ui/button';
export function CandidateLocationPicker({
companyId,
apply,
label = 'Escolher a disponibilidade principal no catálogo',
}: {
companyId: number;
label?: string;
apply: (
reference: GeographyReference,
location: { province: string; district: string; locality: string },
) => void;
}) {
const [selection, setSelection] = useState<GeographyReference | null>(null);
const [description, setDescription] = useState<GeographyDescription>(null);
const province = description?.path.find((node) => node.level === 1)?.name;
const district = description?.path.find((node) => node.level === 2)?.name;
const locality = description?.path.find((node) => node.level === 4)?.name;
return (
<details className="space-y-3 rounded-lg border p-4">
<summary className="cursor-pointer font-medium">{label}</summary>
<AdministrativeLocation
endpoint={`/candidaturas/${companyId}/divisao-administrativa`}
maxLevel={4}
value={selection}
onChange={(value, detail) => {
setSelection(value);
setDescription(detail ?? null);
}}
legend="Local de disponibilidade"
hint="Complete o percurso até à localidade. Ao aplicar, os três campos de disponibilidade serão preenchidos com as designações da fonte."
/>
<Button
type="button"
variant="outline"
disabled={!selection || !province || !district || !locality}
onClick={() => {
if (selection && province && district && locality)
apply(selection, { province, district, locality });
}}
>
Usar esta localidade
</Button>
<p className="text-sm text-muted-foreground">
O preenchimento manual continua disponível para locais ausentes,
estrangeiros ou pendentes de revisão.
</p>
</details>
);
}
@@ -0,0 +1,91 @@
import { Link, useForm } from '@inertiajs/react';
import { Panel, FormErrors, controlClass } from '@/components/procurement';
import { Button } from '@/components/ui/button';
export type OrderCancellationState = {
enabled: boolean;
state: string;
canRequest: boolean;
};
export default function OrderCancellationRequest({
orderId,
state,
}: {
orderId: number;
state: OrderCancellationState;
}) {
const form = useForm({
operation_key: crypto.randomUUID(),
reason: '',
evidence: '',
});
if (!state.enabled && state.state === 'issued') return null;
return (
<Panel title="Estado operacional e cancelamento">
<p>
{state.state === 'cancelled'
? 'Ordem cancelada. O documento emitido e as suas aprovações são preservados.'
: state.state === 'cancellation_pending'
? 'Cancelamento pendente. Novas recepções e facturas estão bloqueadas.'
: 'Ordem emitida. Cancelamento sujeito a política própria publicada e decisão independente de Finanças.'}
</p>
{state.enabled && (
<Link
className="mt-3 block underline"
href="/ordens/cancelamentos"
>
Acompanhar pedidos e política de cancelamento
</Link>
)}
{state.enabled && state.canRequest && state.state === 'issued' && (
<details className="mt-4 rounded border p-3">
<summary>Pedir cancelamento integral</summary>
<form
className="mt-4 space-y-4"
onSubmit={(event) => {
event.preventDefault();
form.post(`/ordens/${orderId}/cancelamento`);
}}
>
<FormErrors errors={form.errors} />
<p className="text-sm">
Só para ordens sem qualquer recepção, factura ou
pagamento. O pedido suspende nova execução até à
decisão.
</p>
<label className="block">
Fundamento
<textarea
className={controlClass}
minLength={10}
maxLength={4000}
required
value={form.data.reason}
onChange={(event) =>
form.setData('reason', event.target.value)
}
/>
</label>
<label className="block">
Referência e descrição da documentação de suporte
<textarea
className={controlClass}
minLength={10}
maxLength={4000}
required
value={form.data.evidence}
onChange={(event) =>
form.setData('evidence', event.target.value)
}
/>
</label>
<Button disabled={form.processing}>
Submeter pedido de cancelamento
</Button>
</form>
</details>
)}
</Panel>
);
}
@@ -51,12 +51,15 @@ export function SgcWorkspaceShell({ children }: { children: ReactNode }) {
procurementNavigation(
context?.permissions ?? [],
page.props.payablesAvailable === true,
undefined,
page.props.orderCancellationAvailable === true,
).flatMap((group) => group.entries.map((entry) => entry.id)),
);
const groups = procurementNavigation(
access?.active ? access.permissions : (user?.purchasing_role ?? ''),
page.props.payablesAvailable === true,
publicNavigation?.paths,
page.props.orderCancellationAvailable === true,
)
.map((group) => ({
...group,
@@ -0,0 +1,53 @@
import { router } from '@inertiajs/react';
import { useState } from 'react';
import { AdministrativeLocation } from '@/components/administrative-location';
import type {
GeographyDescription,
GeographyReference,
} from '@/components/administrative-location';
import { Button } from '@/components/ui/button';
import { FormErrors } from '@/components/procurement';
export function TerritorialFilter({
target,
initial = null,
extra = {},
endpoint,
maxLevel = 6,
}: {
target: string;
endpoint?: string;
maxLevel?: number;
initial?: GeographyDescription;
extra?: Record<string, string>;
}) {
const [location, setLocation] = useState<GeographyReference | null>(
initial?.reference ?? null,
);
const [errors, setErrors] = useState<Record<string, string>>({});
return (
<form
className="space-y-3"
onSubmit={(event) => {
event.preventDefault();
setErrors({});
router.get(
target,
{ ...extra, location: location?.record_id ?? '' },
{ preserveState: 'errors', onError: setErrors },
);
}}
>
<FormErrors errors={errors} />
<AdministrativeLocation
endpoint={endpoint}
maxLevel={maxLevel}
hint="Escolha uma província ou outro nível para consultar os respectivos registos."
value={location}
initial={initial}
onChange={setLocation}
/>
<Button variant="outline">Aplicar filtro territorial</Button>
</form>
);
}
+29 -1
View File
@@ -32,6 +32,7 @@ export function procurementNavigation(
role: string | string[],
payables: boolean,
publicPaths?: string[],
orderCancellation = false,
): ProcurementGroup[] {
const groups: ProcurementGroup[] = [
{
@@ -108,6 +109,18 @@ export function procurementNavigation(
path: '/ordens',
roles: readers,
},
{
id: 'issued_order_cancellations',
label: 'Cancelamento de ordens',
path: '/ordens/cancelamentos',
roles: [
'admin',
'procurement',
'finance',
'requester',
'department_head',
],
},
{
id: 'purchase_review',
label: 'Revisão e cancelamento',
@@ -472,6 +485,19 @@ export function procurementNavigation(
},
],
},
{
id: 'audit',
label: 'Auditoria',
icon: ShieldCheck,
entries: [
{
id: 'audit_metadata',
label: 'Eventos dos módulos',
path: '/auditoria/eventos',
roles: ['audit_metadata_read'],
},
],
},
{
id: 'reports',
label: 'Relatórios',
@@ -535,7 +561,9 @@ export function procurementNavigation(
? publicPaths.includes(
new URL(entry.path, 'http://local').pathname,
)
: (entry.id !== 'new_request' ||
: (entry.id !== 'issued_order_cancellations' ||
orderCancellation) &&
(entry.id !== 'new_request' ||
!Array.isArray(role) ||
role.includes('requester')) &&
(!entry.roles ||
+201
View File
@@ -0,0 +1,201 @@
import { Head, Link, useForm } from '@inertiajs/react';
import {
PageTitle,
Panel,
FormErrors,
controlClass,
} from '@/components/procurement';
import { Button } from '@/components/ui/button';
type Props = {
filters: {
action?: string;
actor_id?: number | string;
from?: string;
to?: string;
page?: number;
};
events: {
data: {
id: number;
action: string;
created_at: string;
user_id: number | null;
}[];
total: number;
current_page: number;
last_page: number;
prev_page_url: string | null;
next_page_url: string | null;
};
};
export default function AuditMetadata({ filters, events }: Props) {
const form = useForm({
action: filters.action ?? '',
actor_id: String(filters.actor_id ?? ''),
from: filters.from ?? '',
to: filters.to ?? '',
});
const query = new URLSearchParams(
Object.entries(filters)
.filter(
([key, value]) =>
key !== 'page' && value !== null && value !== '',
)
.map(([key, value]) => [key, String(value)]),
);
return (
<>
<Head title="Eventos dos módulos" />
<div className="mx-auto flex w-full max-w-6xl flex-col gap-6 p-5 lg:p-8">
<PageTitle
eyebrow="Auditoria"
title="Eventos dos módulos"
description="Metadados registados na empresa. Esta consulta não concede acesso ao conteúdo dos processos."
/>
<Panel title="Consulta e exportação">
<p className="text-sm">
Os eventos são apresentados pela ordem de registo,
incluindo os mais antigos. A exportação inclui todos os
resultados dos filtros, sem conteúdos privados,
documentos ou valores anteriores e posteriores.
</p>
<details className="my-4 rounded border p-3">
<summary>Filtrar eventos</summary>
<form
className="mt-4 grid gap-4 sm:grid-cols-2"
onSubmit={(event) => {
event.preventDefault();
form.get('/auditoria/eventos', {
preserveState: true,
});
}}
>
<FormErrors errors={form.errors} />
<label>
Acção exacta
<input
className={controlClass}
maxLength={100}
value={form.data.action}
onChange={(event) =>
form.setData(
'action',
event.target.value,
)
}
/>
</label>
<label>
Utilizador (id)
<input
className={controlClass}
type="number"
min="1"
value={form.data.actor_id}
onChange={(event) =>
form.setData(
'actor_id',
event.target.value,
)
}
/>
</label>
<label>
Desde
<input
className={controlClass}
type="date"
value={form.data.from}
onChange={(event) =>
form.setData('from', event.target.value)
}
/>
</label>
<label>
Até
<input
className={controlClass}
type="date"
value={form.data.to}
onChange={(event) =>
form.setData('to', event.target.value)
}
/>
</label>
<Button disabled={form.processing}>
Aplicar filtros
</Button>
<Link href="/auditoria/eventos">
Limpar filtros
</Link>
</form>
</details>
<a
className="text-sm underline"
href={`/auditoria/eventos.csv?${query.toString()}`}
>
Descarregar metadados filtrados em CSV
</a>
</Panel>
<Panel title={`${events.total} eventos encontrados`}>
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<thead>
<tr>
<th className="p-2">Registo</th>
<th className="p-2">Data</th>
<th className="p-2">Acção</th>
<th className="p-2">Utilizador (id)</th>
</tr>
</thead>
<tbody>
{events.data.map((event) => (
<tr key={event.id} className="border-t">
<td className="p-2">{event.id}</td>
<td className="p-2">
{event.created_at}
</td>
<td className="p-2 break-all">
{event.action}
</td>
<td className="p-2">
{event.user_id ?? '—'}
</td>
</tr>
))}
</tbody>
</table>
</div>
{events.data.length === 0 && (
<p className="mt-4">Sem eventos para estes filtros.</p>
)}
<nav
aria-label="Páginas de eventos"
className="mt-5 flex flex-wrap gap-4 text-sm"
>
<span>
Página {events.current_page} de {events.last_page}
</span>
{events.prev_page_url && (
<Link href={events.prev_page_url} preserveScroll>
Anterior
</Link>
)}
{events.next_page_url && (
<Link href={events.next_page_url} preserveScroll>
Seguinte
</Link>
)}
</nav>
</Panel>
</div>
</>
);
}
AuditMetadata.layout = {
breadcrumbs: [{ title: 'Auditoria', href: '/auditoria/eventos' }],
};
+203 -16
View File
@@ -1,3 +1,9 @@
import { useState } from 'react';
import { CandidateLocationPicker } from '@/components/candidate-location-picker';
import type {
GeographyReference,
GeographyDescription,
} from '@/components/administrative-location';
import { Head, Link, router, useForm } from '@inertiajs/react';
import { FormErrors, controlClass } from '@/components/procurement';
import { Button } from '@/components/ui/button';
@@ -7,10 +13,14 @@ type Data = {
phone: string | null;
summary: string;
availability: { province: string; district: string; locality: string };
availability_reference?: GeographyReference | null;
additional_availability?: Data['availability'][];
additional_availability_references?: (GeographyReference | null)[];
};
export default function Profile({
companyId,
geographyEnabled = false,
availabilityGeography = null,
email,
profile,
emailVerified = false,
@@ -23,6 +33,8 @@ export default function Profile({
submissionPagination,
}: {
companyId: number;
geographyEnabled?: boolean;
availabilityGeography?: GeographyDescription;
email: string;
profile: { version: number; data: Data };
emailVerified?: boolean;
@@ -46,10 +58,21 @@ export default function Profile({
const form = useForm({
version: profile.version,
...profile.data,
availability_reference: profile.data.availability_reference ?? null,
phone: profile.data.phone ?? '',
additional_availability: profile.data.additional_availability ?? [],
additional_availability_references:
profile.data.additional_availability_references ??
(profile.data.additional_availability ?? []).map(
() => null as GeographyReference | null,
),
reason: '',
});
const [locationKeys, setLocationKeys] = useState(() =>
(profile.data.additional_availability ?? []).map(() =>
crypto.randomUUID(),
),
);
return (
<>
<Head title="O meu perfil" />
@@ -184,6 +207,20 @@ export default function Profile({
className="space-y-4"
onSubmit={(e) => {
e.preventDefault();
form.transform((data) => {
const {
availability_reference,
additional_availability_references,
...rest
} = data;
return geographyEnabled
? {
...rest,
availability_reference,
additional_availability_references,
}
: rest;
});
form.post(`/candidaturas/${companyId}/perfil`, {
preserveScroll: true,
preserveState: false,
@@ -233,6 +270,48 @@ export default function Profile({
Local de disponibilidade para trabalhar ou prestar
serviço
</legend>
{geographyEnabled &&
!form.data.availability_reference && (
<CandidateLocationPicker
companyId={companyId}
apply={(reference, location) => {
form.setData('availability', location);
form.setData(
'availability_reference',
reference,
);
}}
/>
)}
{geographyEnabled &&
form.data.availability_reference && (
<div className="space-y-2 rounded-lg border p-3 text-sm">
<p>
Disponibilidade principal associada ao
catálogo.
</p>
{availabilityGeography?.requires_review && (
<p>
A edição da referência precisa de
revisão. As designações registadas
foram preservadas.
</p>
)}
<Button
type="button"
variant="outline"
onClick={() =>
form.setData(
'availability_reference',
null,
)
}
>
Alterar selecção ou preencher
manualmente
</Button>
</div>
)}
{(['province', 'district', 'locality'] as const).map(
(key) => (
<label className="grid gap-2" key={key}>
@@ -248,6 +327,10 @@ export default function Profile({
required
maxLength={150}
value={form.data.availability[key]}
readOnly={
geographyEnabled &&
!!form.data.availability_reference
}
onChange={(e) =>
form.setData('availability', {
...form.data.availability,
@@ -262,12 +345,82 @@ export default function Profile({
{form.data.additional_availability.map(
(location, index) => (
<fieldset
key={index}
className="grid gap-3 sm:grid-cols-3"
key={locationKeys[index]}
className="grid gap-3 rounded-lg border p-4 sm:grid-cols-3"
>
<legend>
Outro local de disponibilidade {index + 1}
</legend>
{geographyEnabled &&
!form.data
.additional_availability_references[
index
] && (
<div className="sm:col-span-3">
<CandidateLocationPicker
companyId={companyId}
label="Escolher este local no catálogo"
apply={(
reference,
selected,
) => {
form.setData((data) => ({
...data,
additional_availability:
data.additional_availability.map(
(
item,
position,
) =>
position ===
index
? selected
: item,
),
additional_availability_references:
data.additional_availability_references.map(
(
item,
position,
) =>
position ===
index
? reference
: item,
),
}));
}}
/>
</div>
)}
{geographyEnabled &&
form.data
.additional_availability_references[
index
] && (
<div className="space-y-2 text-sm sm:col-span-3">
<p>Local associado ao catálogo.</p>
<Button
type="button"
variant="outline"
onClick={() =>
form.setData(
'additional_availability_references',
form.data.additional_availability_references.map(
(item, position) =>
position ===
index
? null
: item,
),
)
}
>
Alterar selecção ou preencher
manualmente
</Button>
</div>
)}
{(
[
'province',
@@ -288,7 +441,14 @@ export default function Profile({
required
maxLength={150}
value={location[key]}
onChange={(e) =>
readOnly={
geographyEnabled &&
!!form.data
.additional_availability_references[
index
]
}
onChange={(event) =>
form.setData(
'additional_availability',
form.data.additional_availability.map(
@@ -296,7 +456,7 @@ export default function Profile({
position === index
? {
...item,
[key]: e
[key]: event
.target
.value,
}
@@ -310,15 +470,27 @@ export default function Profile({
<Button
type="button"
variant="outline"
onClick={() =>
form.setData(
'additional_availability',
form.data.additional_availability.filter(
onClick={() => {
form.setData((data) => ({
...data,
additional_availability:
data.additional_availability.filter(
(_, position) =>
position !== index,
),
additional_availability_references:
data.additional_availability_references.filter(
(_, position) =>
position !== index,
),
}));
setLocationKeys((keys) =>
keys.filter(
(_, position) =>
position !== index,
),
)
}
);
}}
>
Retirar este local
</Button>
@@ -331,12 +503,27 @@ export default function Profile({
disabled={
form.data.additional_availability.length >= 20
}
onClick={() =>
form.setData('additional_availability', [
...form.data.additional_availability,
{ province: '', district: '', locality: '' },
])
}
onClick={() => {
form.setData((data) => ({
...data,
additional_availability: [
...data.additional_availability,
{
province: '',
district: '',
locality: '',
},
],
additional_availability_references: [
...data.additional_availability_references,
null,
],
}));
setLocationKeys((keys) => [
...keys,
crypto.randomUUID(),
]);
}}
>
Adicionar local de disponibilidade
</Button>
@@ -0,0 +1,212 @@
import { Head, Link, router } from '@inertiajs/react';
import { useState } from 'react';
import { PageTitle, Panel, controlClass } from '@/components/procurement';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
type GeoRow = {
id: string;
source_row: number;
name: string;
codes: string[];
issues: string[];
};
const base = '/administracao/divisao-administrativa';
export default function GeographyReview({
records,
total,
filters,
issues,
manifest,
}: {
records: GeoRow[];
total: number;
filters: { search: string; issue: string; page: number };
issues: Record<string, string>;
manifest: {
source_file: string;
records: number;
selectable: number;
edition: string | null;
};
}) {
const [search, setSearch] = useState(filters.search);
const [issue, setIssue] = useState(filters.issue);
const query = new URLSearchParams({
search: filters.search,
issue: filters.issue,
});
const pageLink = (page: number) => `${base}?${query}&page=${page}`;
return (
<>
<Head title="Revisão da divisão administrativa" />
<main className="mx-auto flex w-full max-w-7xl flex-col gap-6 p-5 lg:p-8">
<PageTitle
eyebrow="Parametrização"
title="Divisão administrativa por rever"
description="Consulta da fonte e dos registos que ainda não podem ser seleccionados nos cadastros."
action={
<Button asChild variant="outline">
<Link href="/administracao/parametrizacao">
Voltar à parametrização
</Link>
</Button>
}
/>
<Panel title="Fonte preservada">
<p className="text-sm">
{manifest.source_file} · Edição{' '}
{manifest.edition ?? 'por confirmar'}.
</p>
<p className="mt-2 text-sm">
{manifest.records.toLocaleString('pt-PT')} registos
conservados;{' '}
{manifest.selectable.toLocaleString('pt-PT')}{' '}
disponíveis para selecção;{' '}
{(
manifest.records - manifest.selectable
).toLocaleString('pt-PT')}{' '}
por rever.
</p>
<p className="mt-2 text-sm text-muted-foreground">
Esta consulta não corrige ou cria localidades. Um código
pode ter vários diagnósticos. Os registos permanecem
indisponíveis até existir uma fonte esclarecida. Pode
usar um nível superior confirmado no cadastro.
</p>
</Panel>
<Panel title="Pendências da cartografia">
<form
className="mb-5 flex flex-wrap items-end gap-3"
onSubmit={(event) => {
event.preventDefault();
router.get(
base,
{ search, issue },
{ preserveState: true },
);
}}
>
<label className="space-y-2 text-sm">
Designação ou ID da fonte
<Input
value={search}
maxLength={120}
onChange={(event) =>
setSearch(event.target.value)
}
/>
</label>
<label className="space-y-2 text-sm">
Diagnóstico
<select
className={controlClass}
value={issue}
onChange={(event) =>
setIssue(event.target.value)
}
>
<option value="">Todos os diagnósticos</option>
{Object.entries(issues).map(([key, label]) => (
<option key={key} value={key}>
{label}
</option>
))}
</select>
</label>
<Button>Pesquisar</Button>
<Button asChild variant="outline">
<a href={`${base}.csv?${query}`}>
Exportar resultados CSV
</a>
</Button>
</form>
<p className="mb-4 text-sm">
{total.toLocaleString('pt-PT')} resultados · Página{' '}
{filters.page} de {Math.max(1, Math.ceil(total / 50))}
</p>
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<thead className="border-b">
<tr>
{[
'Linha / ID da fonte',
'Designação original',
'Códigos por nível',
'Diagnósticos',
].map((label) => (
<th className="p-3" key={label}>
{label}
</th>
))}
</tr>
</thead>
<tbody>
{records.map((record) => (
<tr
className="border-b align-top"
key={record.id}
>
<td className="p-3">
{record.source_row} / {record.id}
</td>
<td className="p-3">
{record.name ||
'(designação vazia na fonte)'}
</td>
<td className="p-3 font-mono whitespace-nowrap">
{record.codes
.map((code) => code || '—')
.join(' / ')}
</td>
<td className="p-3">
{record.issues
.map((code) => issues[code])
.join('; ')}
</td>
</tr>
))}
</tbody>
</table>
</div>
{records.length === 0 && (
<p className="py-5 text-sm">
Não existem pendências para estes filtros.
</p>
)}
<p className="mt-3 text-xs text-muted-foreground">
Ordem dos códigos: província, distrito, posto
administrativo, localidade, bairro urbano e
aldeia/quarteirão. O CSV exporta todos os resultados
filtrados; ao abrir numa folha de cálculo, importe os
códigos como texto para conservar zeros iniciais.
</p>
<div className="mt-5 flex gap-3">
{filters.page > 1 && (
<Button asChild variant="outline">
<Link href={pageLink(filters.page - 1)}>
Anterior
</Link>
</Button>
)}
{filters.page * 50 < total && (
<Button asChild variant="outline">
<Link href={pageLink(filters.page + 1)}>
Seguinte
</Link>
</Button>
)}
</div>
</Panel>
</main>
</>
);
}
GeographyReview.layout = {
breadcrumbs: [
{ title: 'Parametrização', href: '/administracao/parametrizacao' },
{ title: 'Divisão administrativa', href: base },
],
};
+17
View File
@@ -1,3 +1,5 @@
import { CompanyAdministrativeLocation } from '@/components/administrative-location';
import type { GeographyDescription } from '@/components/administrative-location';
import { Head, Link, useForm } from '@inertiajs/react';
import { AiPlanSettings } from '@/components/ai-plan-settings';
import type { AiPlan } from '@/components/ai-plan-settings';
@@ -166,6 +168,8 @@ function Assignment({
}
export default function Parameters({
ready,
geographyEnabled = false,
geography = null,
active,
version,
permissions,
@@ -188,6 +192,8 @@ export default function Parameters({
enabledWorkContexts = [],
}: {
ready: boolean;
geographyEnabled?: boolean;
geography?: GeographyDescription;
comparisonPolicy: ComparisonPolicy;
intelligencePolicy?: IntelligencePolicy;
intelligenceReady?: boolean;
@@ -257,6 +263,17 @@ export default function Parameters({
return (
<>
<Head title="Parametrização da aplicação" />
{geographyEnabled && (
<div className="mx-auto w-full max-w-7xl p-5">
<CompanyAdministrativeLocation geography={geography} />
<Link
className="mt-4 inline-block font-semibold underline"
href="/administracao/divisao-administrativa"
>
Consultar inconsistências da divisão administrativa
</Link>
</div>
)}
<Link
href="/administracao/candidaturas/formularios"
className="m-5 inline-block font-semibold underline"
+63
View File
@@ -1,3 +1,9 @@
import { AdministrativeLocation } from '@/components/administrative-location';
import type {
GeographyDescription,
GeographyReference,
} from '@/components/administrative-location';
import { TerritorialFilter } from '@/components/territorial-filter';
import { Head, useForm, Link } from '@inertiajs/react';
import { useState } from 'react';
import { InventoryNotice, InventoryPagination } from '@/components/inventory';
@@ -20,6 +26,7 @@ type Level = {
is_critical: boolean;
};
type Asset = {
geography_reference?: GeographyReference | null;
id: number;
code: string;
description: string;
@@ -57,6 +64,9 @@ type History = {
};
};
type Props = {
geographyEnabled?: boolean;
equipmentGeography?: Record<number, GeographyDescription>;
geographyFilter?: GeographyDescription;
equipment: Asset[];
parts: Part[];
levels: Level[];
@@ -98,6 +108,9 @@ export default function EquipmentPage({
canManage,
canConfigure,
demo = false,
geographyEnabled = false,
equipmentGeography = {},
geographyFilter = null,
}: Props) {
const [message, setMessage] = useState('');
const category = useForm({
@@ -107,6 +120,7 @@ export default function EquipmentPage({
is_critical: '',
});
const asset = useForm({
geography_reference: null as GeographyReference | null,
id: '',
version: '',
code: '',
@@ -143,6 +157,14 @@ export default function EquipmentPage({
description="Cadastro, peças compatíveis, mínimos explícitos e rastreabilidade das saídas."
/>
<InventoryNotice />
{geographyEnabled && !demo && (
<Panel title="Localização dos equipamentos">
<TerritorialFilter
target="/equipamentos"
initial={geographyFilter}
/>
</Panel>
)}
{demo && (
<p className="rounded-lg border bg-teal-50 p-4 text-sm text-teal-900">
Dados fictícios para revisão sem login. Formulários
@@ -179,6 +201,12 @@ export default function EquipmentPage({
<strong>
{e.code} · {e.description}
</strong>
<Link
className="mt-2 block underline"
href={`/equipamentos/${e.id}`}
>
Acompanhar compras e movimentos
</Link>
<p className="mt-2">
{e.area} ·{' '}
{
@@ -193,6 +221,14 @@ export default function EquipmentPage({
Criticidade:{' '}
{criticality(e.criticality_level_id)?.name}
</p>
{equipmentGeography[e.id]?.path.length ? (
<p className="text-muted-foreground">
Localização actual:{' '}
{equipmentGeography[e.id]?.path
.map((node) => node.name)
.join(' / ')}
</p>
) : null}
{e.stock_item_id && (
<p>
Artigo: {stock(e.stock_item_id)?.code}
@@ -220,6 +256,9 @@ export default function EquipmentPage({
variant="outline"
onClick={() =>
asset.setData({
geography_reference:
e.geography_reference ??
null,
id: String(e.id),
version: String(e.version),
code: e.code,
@@ -332,12 +371,36 @@ export default function EquipmentPage({
simulate();
return;
}
asset.transform((data) => {
const { geography_reference, ...rest } =
data;
return geographyEnabled
? { ...rest, geography_reference }
: rest;
});
asset.post('/equipamentos/activos', {
onSuccess: () => asset.reset(),
});
}}
>
<FormErrors errors={asset.errors} />
{geographyEnabled && !demo && (
<AdministrativeLocation
key={asset.data.id || 'new'}
value={asset.data.geography_reference}
initial={
equipmentGeography[
Number(asset.data.id)
] ?? null
}
onChange={(value) =>
asset.setData(
'geography_reference',
value,
)
}
/>
)}
{(
[
'code',
+286
View File
@@ -0,0 +1,286 @@
import type { GeographyDescription } from '@/components/administrative-location';
import { Head, Link } from '@inertiajs/react';
import { PageTitle, Panel } from '@/components/procurement';
import { quantity, warehouseStateLabels } from '@/types/inventory';
import { statusLabels } from '@/types/procurement';
type Page<T> = {
data: T[];
total: number;
current_page: number;
last_page: number;
prev_page_url: string | null;
next_page_url: string | null;
};
type Purchase = {
id: number;
number: string;
status: string;
needed_by: string;
items: {
id: number;
description: string;
quantity: string;
unit: string;
}[];
};
type Movement = {
id: number;
kind: string;
reference: string;
recorded_at: string;
quantity_milli: number;
item: { code: string; name: string; unit: string } | null;
warehouse: { code: string; name: string } | null;
};
function Pages({ page, label }: { page: Page<unknown>; label: string }) {
return (
<nav aria-label={label} className="mt-4 flex gap-4 text-sm">
<span>
Página {page.current_page} de {page.last_page}
</span>
{page.prev_page_url && (
<Link href={page.prev_page_url} preserveScroll>
Anterior
</Link>
)}
{page.next_page_url && (
<Link href={page.next_page_url} preserveScroll>
Seguinte
</Link>
)}
</nav>
);
}
export default function EquipmentShow({
equipment,
geography = null,
purchases,
movements,
warehouseRequests = null,
}: {
geography?: GeographyDescription;
equipment: {
id: number;
code: string;
description: string;
area: string;
status: string;
};
purchases: Page<Purchase>;
movements: Page<Movement>;
warehouseRequests?: Page<{
id: number;
state: string;
version: number;
reservation_ready: boolean;
lines: {
line: number;
item: { code: string; name: string; unit: string };
destination: string;
requested_milli: number;
reserved_milli: number;
delivered_milli: number;
remaining_milli: number;
cancelled_milli: number;
}[];
}> | null;
}) {
return (
<>
<Head title={equipment.code} />
<div className="mx-auto flex w-full max-w-6xl flex-col gap-6 p-5 lg:p-8">
<PageTitle
eyebrow="Equipamentos"
title={`${equipment.code} · ${equipment.description}`}
description={equipment.area}
/>
<Link className="text-sm underline" href="/equipamentos">
Voltar a Equipamentos e peças
</Link>
{geography && (
<Panel title="Localização actual">
<p>
{geography.path
.map((node) => node.name)
.join(' / ')}
</p>
<p className="mt-2 text-sm text-muted-foreground">
Referência actual do cadastro. Os documentos e
movimentos anteriores conservam os seus dados de
origem.
</p>
</Panel>
)}
<Panel
title={`Requisições de compra associadas · ${purchases.total}`}
>
<p className="mb-4 text-sm">
Estas quantidades representam pedidos de compra. Não
comprovam recepção, entrega ao equipamento ou consumo.
Cada processo conserva as suas aprovações.
</p>
{purchases.data.map((purchase) => (
<article
key={purchase.id}
className="mb-3 rounded border p-3 text-sm"
>
<Link
className="font-medium underline"
href={`/requisicoes/${purchase.id}/processo`}
>
{purchase.number}
</Link>
<p>
Estado do processo:{' '}
{statusLabels[purchase.status] ??
purchase.status}{' '}
· Necessário até {purchase.needed_by}
</p>
{purchase.items.map((item) => (
<p key={item.id}>
{item.description} · Pedido: {item.quantity}{' '}
{item.unit}
</p>
))}
</article>
))}
{!purchases.data.length && (
<p>Sem requisições associadas que possa consultar.</p>
)}
<Pages
page={purchases}
label="Páginas de compras do equipamento"
/>
</Panel>
<Panel
title={`Requisições internas ao armazém${warehouseRequests ? ' · ' + warehouseRequests.total : ''}`}
>
<p className="mb-4 text-sm">
Pedidos e reservas para este equipamento, conforme os
seus acessos ao armazém. As entregas acumuladas não
descontam devoluções ou correcções posteriores.
</p>
{warehouseRequests === null ? (
<p>
Consulta indisponível para o seu acesso ou nesta
instalação.
</p>
) : (
<>
{warehouseRequests.data.map((record) => (
<article
key={record.id}
className="mb-3 rounded border p-3 text-sm"
>
<Link
className="font-medium underline"
href={`/stock/requisicoes/${record.id}`}
>
RA-{record.id}
</Link>
<p>
{warehouseStateLabels[record.state] ??
record.state}{' '}
· Versão {record.version}
</p>
{record.lines.map((line) => (
<div key={line.line} className="mt-3">
<p>
{line.item.code} ·{' '}
{line.item.name} ·{' '}
{line.destination}
</p>
<p>
Pedida:{' '}
{quantity(line.requested_milli)}{' '}
{line.item.unit} · Reservada
agora:{' '}
{record.reservation_ready
? quantity(
line.reserved_milli,
)
: 'Indisponível'}{' '}
· Entregue acumulada:{' '}
{quantity(line.delivered_milli)}{' '}
· Por entregar:{' '}
{quantity(line.remaining_milli)}{' '}
· Cancelada:{' '}
{quantity(line.cancelled_milli)}
</p>
</div>
))}
</article>
))}
{!warehouseRequests.data.length && (
<p>
Sem requisições internas visíveis para este
equipamento.
</p>
)}
<Pages
page={warehouseRequests}
label="Páginas de requisições internas do equipamento"
/>
</>
)}
</Panel>
<Panel
title={`Movimentos físicos associados · ${movements.total}`}
>
<p className="mb-4 text-sm">
Documentos originais ligados ao equipamento, pela ordem
de registo. Um estorno tem documento próprio; estas
quantidades não são um saldo nem comprovam consumo
técnico.
</p>
{movements.data.map((movement) => (
<article
key={movement.id}
className="mb-3 rounded border p-3 text-sm"
>
<p className="font-medium">
{movement.reference} ·{' '}
{movement.kind === 'issue'
? 'Saída'
: movement.kind === 'reversal'
? 'Estorno'
: movement.kind}
</p>
<p>
{movement.recorded_at} ·{' '}
{movement.warehouse?.code}{' '}
{movement.warehouse?.name}
</p>
<p>
{movement.item?.code} · {movement.item?.name} ·
Quantidade do documento:{' '}
{quantity(movement.quantity_milli)}{' '}
{movement.item?.unit}
</p>
</article>
))}
{!movements.data.length && (
<p>
Sem movimentos físicos registados para este
equipamento.
</p>
)}
<Pages
page={movements}
label="Páginas de movimentos do equipamento"
/>
</Panel>
</div>
</>
);
}
EquipmentShow.layout = {
breadcrumbs: [
{ title: 'Equipamentos', href: '/equipamentos' },
{ title: 'Acompanhamento', href: '#' },
],
};
+32
View File
@@ -1,3 +1,5 @@
import { CandidateAvailability } from '@/components/candidate-availability';
import type { AvailabilityLocation } from '@/components/candidate-availability';
import { Head, Link, useForm, usePage } from '@inertiajs/react';
import {
PageTitle,
@@ -62,6 +64,13 @@ type Process = {
};
};
type Candidate = {
received_availability?: {
submission_id: number;
reference: string;
profile_version: number;
availability: AvailabilityLocation;
additional_availability: AvailabilityLocation[];
};
electronic_source?: {
submission_id: number;
reference: string;
@@ -587,6 +596,13 @@ export default function PeopleShow({
<Link className="underline" href="/pessoas">
Voltar a Pessoas e contratações
</Link>
<a
className="block underline print:hidden"
href={`/pessoas/${p.id}/dossier.json`}
>
Descarregar dossiê de preparação — dados conforme o seu
acesso
</a>
{(canPrepare || canViewElectronicSources) && (
<Link
className="block underline"
@@ -739,6 +755,22 @@ export default function PeopleShow({
<strong>
{c.name} · {c.reference}
</strong>
{c.received_availability && (
<section className="my-3 rounded-lg border p-3 text-sm">
<CandidateAvailability
data={c.received_availability}
/>
<p className="mt-2 text-muted-foreground">
Dados recebidos no perfil v
{
c.received_availability
.profile_version
}
. A edição posterior do perfil
conserva esta versão.
</p>
</section>
)}
<p>
Recebida em {c.received_on} ·{' '}
{c.evaluation_count} avaliação(ões) ·{' '}
+39
View File
@@ -1,3 +1,5 @@
import { TerritorialFilter } from '@/components/territorial-filter';
import type { GeographyDescription } from '@/components/administrative-location';
import { Head, Link, useForm } from '@inertiajs/react';
import {
CandidateDocumentList,
@@ -108,10 +110,16 @@ export default function Submissions({
publicUrl,
canPrepare = false,
canTriage = false,
geographyEnabled = false,
geographyFilter = null,
filters = {},
}: {
process: { id: number; title: string; version: number };
canPrepare?: boolean;
canTriage?: boolean;
geographyEnabled?: boolean;
geographyFilter?: GeographyDescription;
filters?: { submission?: number; location?: string };
publication: null | {
version: number;
active: boolean;
@@ -172,6 +180,37 @@ export default function Submissions({
<Link className="underline" href={`/pessoas/${process.id}`}>
Processo interno
</Link>
{geographyEnabled && (
<section className="space-y-3 rounded-lg border p-4">
<h2 className="font-semibold">
Disponibilidade territorial na candidatura
</h2>
<p className="text-sm">
Consulta os locais principal e adicionais registados
na versão submetida. Para consultar também os locais
manuais ou de outras edições, retire o filtro.
</p>
<TerritorialFilter
target={`/pessoas/${process.id}/recebidas`}
endpoint={`/pessoas/${process.id}/divisao-administrativa`}
maxLevel={4}
initial={geographyFilter}
extra={
filters.submission
? { submission: String(filters.submission) }
: {}
}
/>
{filters.location && (
<Link
className="inline-block text-sm underline"
href={`/pessoas/${process.id}/recebidas${filters.submission ? `?submission=${filters.submission}` : ''}`}
>
Retirar filtro territorial
</Link>
)}
</section>
)}
{canPrepare && (
<form
className="space-y-3"
@@ -0,0 +1,333 @@
import { Head, Link, useForm } from '@inertiajs/react';
import {
Panel,
PageTitle,
FormErrors,
controlClass,
} from '@/components/procurement';
import { Button } from '@/components/ui/button';
type Record = {
id: number;
order_number: string;
purchase_order_id: number;
source_href: string;
status: string;
reason: string;
evidence: string;
review_reason: string | null;
revised_requisition_id: number | null;
canDecide: boolean;
canRevise: boolean;
};
type Policy = {
id: number;
revision: number;
status: string;
enabled: boolean;
valid_from: string;
valid_until: string;
canReview: boolean;
};
function Decision({ url }: { url: string }) {
const form = useForm({ decision: 'rejected', reason: '' });
return (
<form
className="mt-3 space-y-3"
onSubmit={(event) => {
event.preventDefault();
if (window.confirm('Confirmar esta decisão definitiva?'))
form.post(url);
}}
>
<FormErrors errors={form.errors} />
<label className="block">
Decisão
<select
className={controlClass}
value={form.data.decision}
onChange={(event) =>
form.setData('decision', event.target.value)
}
>
<option value="rejected">Rejeitar</option>
<option value="approved">Aprovar</option>
</select>
</label>
<label className="block">
Fundamento
<textarea
className={controlClass}
minLength={10}
maxLength={4000}
required
value={form.data.reason}
onChange={(event) =>
form.setData('reason', event.target.value)
}
/>
</label>
<Button disabled={form.processing}>Registar decisão</Button>
</form>
);
}
function Revision({ record }: { record: Record }) {
const form = useForm({ needed_by: '', reason: '' });
return (
<form
className="mt-3 space-y-3"
onSubmit={(event) => {
event.preventDefault();
form.post(`/ordens/cancelamentos/${record.id}/rever`);
}}
>
<FormErrors errors={form.errors} />
<p>
Nova requisição em rascunho, com os artigos reutilizados. Não
copia propostas, decisões, validações ou reserva.
</p>
<label className="block">
Nova data necessária
<input
className={controlClass}
type="date"
required
value={form.data.needed_by}
onChange={(event) =>
form.setData('needed_by', event.target.value)
}
/>
</label>
<label className="block">
Nova justificação
<textarea
className={controlClass}
minLength={10}
maxLength={4000}
required
value={form.data.reason}
onChange={(event) =>
form.setData('reason', event.target.value)
}
/>
</label>
<Button disabled={form.processing}>Preparar rascunho ligado</Button>
</form>
);
}
export default function OrderCancellations({
records,
policies,
canAdminister,
}: {
records: {
data: Record[];
prev_page_url: string | null;
next_page_url: string | null;
};
policies: Policy[];
canAdminister: boolean;
}) {
const policy = useForm({
previous_id: policies[0]?.id ?? 0,
mode: 'issued_order',
enabled: false,
valid_from: '',
valid_until: '',
reason: '',
});
const labels: { [key: string]: string } = {
pending: 'Pendente',
approved: 'Aprovado',
rejected: 'Rejeitado',
};
return (
<>
<Head title="Cancelamento de ordens" />
<div className="mx-auto flex w-full max-w-5xl flex-col gap-6 p-5 lg:p-8">
<PageTitle
eyebrow="Compras e Finanças"
title="Cancelamento de ordens emitidas"
description="Circuito integral sem recepção, factura ou pagamento. Os documentos e as aprovações originais são preservados."
/>
<Link className="underline" href="/ordens">
Voltar às ordens
</Link>
<Link className="underline" href="/ordens/cancelamentos">
Ver todos os pedidos de cancelamento
</Link>
{records.data.map((record) => (
<Panel
key={record.id}
title={`${record.order_number} · ${labels[record.status]}`}
>
<div id={`cancellation-${record.id}`}>
<p className="whitespace-pre-wrap">
{record.reason}
</p>
<p className="whitespace-pre-wrap">
Suporte: {record.evidence}
</p>
<Link
className="underline"
href={record.source_href}
>
Consultar origem autorizada
</Link>
{record.review_reason && (
<p className="mt-3 whitespace-pre-wrap">
Decisão: {record.review_reason}
</p>
)}
{record.canDecide && (
<Decision
url={`/ordens/cancelamentos/${record.id}/decidir`}
/>
)}
{record.revised_requisition_id ? (
<Link
className="mt-3 block underline"
href={`/requisicoes/${record.revised_requisition_id}`}
>
Consultar rascunho ligado
</Link>
) : (
record.canRevise && <Revision record={record} />
)}
</div>
</Panel>
))}
{!records.data.length && (
<p>Sem pedidos de cancelamento visíveis.</p>
)}
<nav className="flex gap-4">
{records.prev_page_url && (
<Link href={records.prev_page_url}>Anterior</Link>
)}
{records.next_page_url && (
<Link href={records.next_page_url}>Seguinte</Link>
)}
</nav>
{canAdminister && (
<Panel title="Política própria da empresa">
<p>
Uma proposta e duas aprovações administrativas de
pessoas distintas são necessárias. Publicar uma
política não cancela ordens.
</p>
{policies.map((item) => (
<article
className="mt-3 rounded border p-3"
key={item.id}
id={`policy-${item.id}`}
>
<p>
Versão {item.revision} ·{' '}
{labels[item.status]} ·{' '}
{item.enabled
? 'Permite cancelamento'
: 'Não permite cancelamento'}{' '}
· {item.valid_from} a {item.valid_until}
</p>
{item.canReview && (
<Decision
url={`/ordens/cancelamentos/politicas/${item.id}/decidir`}
/>
)}
</article>
))}
<details className="mt-4">
<summary>Propor nova versão</summary>
<form
className="mt-3 space-y-3"
onSubmit={(event) => {
event.preventDefault();
policy.transform((data) => ({
...data,
previous_id: policies[0]?.id ?? 0,
}));
policy.post(
'/ordens/cancelamentos/politicas',
);
}}
>
<FormErrors errors={policy.errors} />
<label className="block">
<input
type="checkbox"
checked={policy.data.enabled}
onChange={(event) =>
policy.setData(
'enabled',
event.target.checked,
)
}
/>{' '}
Permitir cancelamento de ordens neste âmbito
</label>
<label className="block">
Vigência inicial
<input
className={controlClass}
type="date"
required
value={policy.data.valid_from}
onChange={(event) =>
policy.setData(
'valid_from',
event.target.value,
)
}
/>
</label>
<label className="block">
Vigência final
<input
className={controlClass}
type="date"
required
value={policy.data.valid_until}
onChange={(event) =>
policy.setData(
'valid_until',
event.target.value,
)
}
/>
</label>
<label className="block">
Fundamento
<textarea
className={controlClass}
minLength={10}
maxLength={4000}
required
value={policy.data.reason}
onChange={(event) =>
policy.setData(
'reason',
event.target.value,
)
}
/>
</label>
<Button disabled={policy.processing}>
Propor política
</Button>
</form>
</details>
</Panel>
)}
</div>
</>
);
}
OrderCancellations.layout = {
breadcrumbs: [
{ title: 'Ordens', href: '/ordens' },
{ title: 'Cancelamentos', href: '/ordens/cancelamentos' },
],
};
+21 -6
View File
@@ -6,6 +6,9 @@ import { PageTitle, Panel } from '@/components/procurement';
import { Button } from '@/components/ui/button';
import { date, money, roleLabels } from '@/types/procurement';
import type { PurchaseOrder } from '@/types/purchase';
import OrderCancellationRequest, {
type OrderCancellationState,
} from '@/components/order-cancellation-request';
type History = {
id: number;
@@ -22,20 +25,32 @@ const actions: Record<string, string> = {
export default function OrderShow({
order,
history,
orderCancellation,
}: {
order: PurchaseOrder;
history: History[];
orderCancellation?: OrderCancellationState;
}) {
const snapshot = order.snapshot;
return (
<>
<Head title={order.number} />
<Link
href={`/ordens/${order.id}/recepcoes`}
className="mx-auto mt-4 w-full max-w-6xl px-5 text-sm font-medium text-teal-700 dark:text-teal-400"
>
Recepções, qualidade e quantidades pendentes
</Link>
{orderCancellation && (
<div className="mx-auto mt-4 w-full max-w-6xl px-5">
<OrderCancellationRequest
orderId={order.id}
state={orderCancellation}
/>
</div>
)}
{(!orderCancellation || orderCancellation.state === 'issued') && (
<Link
href={`/ordens/${order.id}/recepcoes`}
className="mx-auto mt-4 w-full max-w-6xl px-5 text-sm font-medium text-teal-700 dark:text-teal-400"
>
Recepções, qualidade e quantidades pendentes
</Link>
)}
<div className="mx-auto flex w-full max-w-6xl flex-col gap-7 p-5 lg:p-8">
<PageTitle
eyebrow={snapshot.company.name}
@@ -1,9 +1,12 @@
import { TerritorialFilter } from '@/components/territorial-filter';
import type { GeographyDescription } from '@/components/administrative-location';
import { Head, Link, useForm } from '@inertiajs/react';
import { Printer } from 'lucide-react';
import { PageTitle, Panel, controlClass } from '@/components/procurement';
import { Button } from '@/components/ui/button';
type Filters = {
location?: string;
supplier_id?: string;
responsible_id?: string;
status?: string;
@@ -50,6 +53,8 @@ export default function SupplierImprovementReport({
responsibles,
today,
generatedAt,
geographyEnabled = false,
geographyFilter = null,
}: {
records: {
data: Row[];
@@ -62,6 +67,8 @@ export default function SupplierImprovementReport({
next_page_url: string | null;
};
filters: Filters;
geographyEnabled?: boolean;
geographyFilter?: GeographyDescription;
counts: Record<string, number>;
overdue: number;
suppliers: { id: number; name: string }[];
@@ -70,6 +77,7 @@ export default function SupplierImprovementReport({
generatedAt: string;
}) {
const form = useForm({
location: filters.location ?? '',
supplier_id: filters.supplier_id ?? '',
responsible_id: filters.responsible_id ?? '',
status: filters.status ?? '',
@@ -109,6 +117,49 @@ export default function SupplierImprovementReport({
</div>
}
/>
{geographyEnabled && (
<Panel title="Território actual dos fornecedores">
<div className="print:hidden">
<TerritorialFilter
target={base}
initial={geographyFilter}
extra={Object.fromEntries(
Object.entries(filters)
.filter(
([key, value]) =>
key !== 'location' &&
value !== undefined &&
value !== null,
)
.map(([key, value]) => [
key,
String(value),
]),
)}
/>
</div>
<p className="mt-3 text-sm">
{geographyFilter?.path
.map((node) => node.name)
.join(' / ') || 'Todos os territórios'}
. O filtro usa a localização actual da ficha; os
dados preservados nas avaliações mantêm a sua
origem. Para incluir fichas sem referência ou de
outra edição, retire o filtro.
</p>
{filters.location && (
<Link
className="mt-2 inline-block text-sm underline"
href={
base +
query({ ...filters, location: undefined })
}
>
Retirar filtro territorial
</Link>
)}
</Panel>
)}
<Panel title="Filtros do acompanhamento">
<form
className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4 print:hidden"
+112 -2
View File
@@ -1,3 +1,9 @@
import { AdministrativeLocation } from '@/components/administrative-location';
import type {
GeographyDescription,
GeographyReference,
} from '@/components/administrative-location';
import { TerritorialFilter } from '@/components/territorial-filter';
import { Head, Link, useForm } from '@inertiajs/react';
import { InventoryNotice, InventoryPagination } from '@/components/inventory';
import {
@@ -18,7 +24,50 @@ import type {
Warehouse,
} from '@/types/inventory';
function WarehouseLocation({
warehouse,
geography,
}: {
warehouse: Warehouse;
geography: GeographyDescription;
}) {
const form = useForm({
geography_reference:
geography?.reference ?? (null as GeographyReference | null),
expected_reference: geography?.reference ?? null,
});
return (
<details className="mb-4 rounded-lg border p-3">
<summary className="cursor-pointer text-sm font-medium">
Localização de {warehouse.code} · {warehouse.name}
</summary>
<form
className="mt-4 space-y-3"
onSubmit={(event) => {
event.preventDefault();
form.post(`/stock/armazens/${warehouse.id}/localizacao`, {
preserveScroll: true,
});
}}
>
<FormErrors errors={form.errors} />
<AdministrativeLocation
value={form.data.geography_reference}
initial={geography}
onChange={(value) =>
form.setData('geography_reference', value)
}
/>
<Button disabled={form.processing}>Guardar localização</Button>
</form>
</details>
);
}
type Props = {
geographyEnabled?: boolean;
warehouseGeography?: Record<number, GeographyDescription>;
geographyFilter?: GeographyDescription;
items: StockItem[];
warehouses: Warehouse[];
balances: {
@@ -32,7 +81,7 @@ type Props = {
} | null;
}[];
movements: Page<StockMovement>;
filters: { search?: string; warehouse_id?: number };
filters: { search?: string; warehouse_id?: number; location?: string };
canManage: boolean;
};
export default function Stock({
@@ -42,13 +91,21 @@ export default function Stock({
movements,
filters,
canManage,
geographyEnabled = false,
warehouseGeography = {},
geographyFilter = null,
}: Props) {
const search = useForm({
location: filters.location ?? '',
search: filters.search ?? '',
warehouse_id: filters.warehouse_id ? String(filters.warehouse_id) : '',
});
const item = useForm({ code: '', name: '', unit: '' });
const warehouse = useForm({ code: '', name: '' });
const warehouse = useForm({
code: '',
name: '',
geography_reference: null as GeographyReference | null,
});
return (
<>
<Head title="Stock e movimentos" />
@@ -59,6 +116,20 @@ export default function Stock({
description="Saldo por artigo e armazém, calculado a partir de entradas, saídas, transferências e ajustes confirmados. O histórico permanece preservado."
/>
<InventoryNotice />
{geographyEnabled && (
<Panel title="Localização dos armazéns">
<TerritorialFilter
target="/stock"
initial={geographyFilter}
extra={{
search: filters.search ?? '',
warehouse_id: filters.warehouse_id
? String(filters.warehouse_id)
: '',
}}
/>
</Panel>
)}
{canManage && (
<Link
className="font-semibold text-teal-700"
@@ -282,14 +353,40 @@ export default function Stock({
{warehouses.map((w) => (
<p key={w.id}>
<strong>{w.code}</strong> · {w.name}
{warehouseGeography[w.id]?.path
.map((node) => node.name)
.join(' / ') && (
<span className="block text-muted-foreground">
Localização actual:{' '}
{warehouseGeography[w.id]?.path
.map((node) => node.name)
.join(' / ')}
</span>
)}
</p>
))}
</div>
{geographyEnabled &&
canManage &&
warehouses.map((w) => (
<WarehouseLocation
key={`${w.id}:${JSON.stringify(warehouseGeography[w.id]?.reference ?? null)}`}
warehouse={w}
geography={warehouseGeography[w.id] ?? null}
/>
))}
{canManage && (
<form
className="space-y-4 border-t pt-4"
onSubmit={(e) => {
e.preventDefault();
warehouse.transform((data) => {
const { geography_reference, ...rest } =
data;
return geographyEnabled
? { ...rest, geography_reference }
: rest;
});
warehouse.post('/stock/armazens', {
preserveScroll: true,
onSuccess: () => warehouse.reset(),
@@ -297,6 +394,19 @@ export default function Stock({
}}
>
<FormErrors errors={warehouse.errors} />
{geographyEnabled && (
<AdministrativeLocation
value={
warehouse.data.geography_reference
}
onChange={(value) =>
warehouse.setData(
'geography_reference',
value,
)
}
/>
)}
{(['code', 'name'] as const).map((key) => (
<div className="space-y-2" key={key}>
<Label htmlFor={`warehouse-${key}`}>
+19 -3
View File
@@ -265,12 +265,20 @@ export default function WarehouseRequest(props: Props) {
description={`Estado: ${labels[p.state] ?? p.state}`}
/>
<div className="flex gap-4 print:hidden">
{props.canViewReturns && <Link href={`/stock/devolucoes-internas?request_id=${r.id}`}>Conferir devolução de excedentes</Link>}
{props.canViewReturns && (
<Link
href={`/stock/devolucoes-internas?request_id=${r.id}`}
>
Conferir devolução de excedentes
</Link>
)}
<Link href="/stock/requisicoes">
Requisições ao armazém
</Link>
<Button variant="outline" onClick={() => window.print()}>
Imprimir requisição e entregas
<Button variant="outline" asChild>
<a href={`/stock/requisicoes/${r.id}/imprimir`}>
Imprimir requisição e entregas
</a>
</Button>
</div>
<Panel title="Utilização e origem">
@@ -672,6 +680,14 @@ export default function WarehouseRequest(props: Props) {
Documento de saída: RA-{r.id} ·
Entrega #{event.id}
</p>
<a
href={`/stock/requisicoes/${r.id}/entregas/${event.id}/imprimir`}
target="_blank"
rel="noopener noreferrer"
className="text-sm underline print:hidden"
>
Imprimir apenas esta entrega
</a>
{event.data.lines?.map((line) => (
<p key={line.index}>
{
+26
View File
@@ -110,6 +110,32 @@ export default function Requests(props: Props) {
eyebrow="Armazém e activos"
title="Requisições ao armazém"
description="Acompanhar autorizações, reservas, entregas e recepções conforme as suas tarefas."
action={
props.ready ? (
<Button variant="outline" asChild>
<a
href={
'/stock/requisicoes.csv?' +
new URLSearchParams({
view: props.filters.view,
state: props.filters.state,
search: props.filters.search,
...(props.filters.warehouse_id
? {
warehouse_id: String(
props.filters
.warehouse_id,
),
}
: {}),
}).toString()
}
>
Exportar todos os resultados (CSV)
</a>
</Button>
) : undefined
}
/>
<p className="text-sm">
Uso interno sem factura: a requisição autorizada acompanha a
+31 -1
View File
@@ -1,3 +1,8 @@
import { AdministrativeLocation } from '@/components/administrative-location';
import type {
GeographyDescription,
GeographyReference,
} from '@/components/administrative-location';
import { Head, Link, useForm } from '@inertiajs/react';
import {
FormErrors,
@@ -11,8 +16,18 @@ import { Label } from '@/components/ui/label';
import { supplierFields } from '@/types/supplier';
import type { Supplier } from '@/types/supplier';
export default function EditSupplier({ supplier }: { supplier: Supplier }) {
export default function EditSupplier({
supplier,
geographyEnabled = false,
geography = null,
}: {
supplier: Supplier;
geographyEnabled?: boolean;
geography?: GeographyDescription;
}) {
const form = useForm({
geography_reference:
supplier.geography_reference ?? (null as GeographyReference | null),
name: supplier.name,
nuit: supplier.nuit,
contact: supplier.contact,
@@ -46,10 +61,25 @@ export default function EditSupplier({ supplier }: { supplier: Supplier }) {
className="space-y-5"
onSubmit={(e) => {
e.preventDefault();
form.transform((data) => {
const { geography_reference, ...rest } = data;
return geographyEnabled
? { ...rest, geography_reference }
: rest;
});
form.put(`/fornecedores/${supplier.id}`);
}}
>
<FormErrors errors={form.errors} />
{geographyEnabled && (
<AdministrativeLocation
value={form.data.geography_reference}
initial={geography}
onChange={(value) =>
form.setData('geography_reference', value)
}
/>
)}
<div className="grid gap-4 md:grid-cols-2">
{Object.entries(supplierFields).map(
([key, label]) => {
+42 -2
View File
@@ -1,3 +1,8 @@
import { AdministrativeLocation } from '@/components/administrative-location';
import type {
GeographyReference,
GeographyDescription,
} from '@/components/administrative-location';
import { Head, Link, router, useForm } from '@inertiajs/react';
import { useState } from 'react';
import {
@@ -50,6 +55,8 @@ export default function Suppliers({
suppliers,
filters,
canCreate,
geographyEnabled = false,
geographyFilter = null,
canReview,
}: {
suppliers: {
@@ -57,11 +64,14 @@ export default function Suppliers({
prev_page_url: string | null;
next_page_url: string | null;
};
filters: { search?: string };
filters: { search?: string; location?: string };
canCreate: boolean;
geographyEnabled?: boolean;
geographyFilter?: GeographyDescription;
canReview: boolean;
}) {
const form = useForm({
geography_reference: null as GeographyReference | null,
name: '',
nuit: '',
contact: '',
@@ -78,6 +88,9 @@ export default function Suppliers({
const review = useForm({ status: 'active', comment: '', version: 0 });
const [creating, setCreating] = useState(false);
const [selected, setSelected] = useState<Supplier | null>(null);
const [location, setLocation] = useState<GeographyReference | null>(
geographyFilter?.reference ?? null,
);
const [search, setSearch] = useState(filters.search ?? '');
return (
<>
@@ -103,6 +116,13 @@ export default function Suppliers({
className="space-y-5"
onSubmit={(e) => {
e.preventDefault();
form.transform((data) => {
const { geography_reference, ...rest } =
data;
return geographyEnabled
? { ...rest, geography_reference }
: rest;
});
form.post('/fornecedores', {
onSuccess: () => {
form.reset();
@@ -112,6 +132,17 @@ export default function Suppliers({
}}
>
<FormErrors errors={form.errors} />
{geographyEnabled && (
<AdministrativeLocation
value={form.data.geography_reference}
onChange={(value) =>
form.setData(
'geography_reference',
value,
)
}
/>
)}
<div className="grid gap-4 md:grid-cols-2">
{Object.entries(fields).map(([key, label]) => {
const name = key as keyof typeof fields;
@@ -167,13 +198,22 @@ export default function Suppliers({
</Panel>
)}
<Panel title="Directório de fornecedores">
{geographyEnabled && (
<div className="mb-5">
<AdministrativeLocation
value={location}
initial={geographyFilter}
onChange={setLocation}
/>
</div>
)}
<form
className="mb-5 flex gap-3"
onSubmit={(e) => {
e.preventDefault();
router.get(
'/fornecedores',
{ search },
{ search, location: location?.record_id ?? '' },
{ preserveState: true },
);
}}
+14
View File
@@ -1,3 +1,4 @@
import type { GeographyDescription } from '@/components/administrative-location';
import { Head, Link, useForm } from '@inertiajs/react';
import { Download, FileLock2, Pencil, Upload } from 'lucide-react';
import { useRef } from 'react';
@@ -27,6 +28,7 @@ type Document = {
sha256: string;
};
type Props = {
geography?: GeographyDescription;
supplier: Supplier;
documents: Document[];
canEdit: boolean;
@@ -36,6 +38,7 @@ type Props = {
export default function SupplierShow({
supplier,
geography = null,
documents,
canEdit,
canDocuments,
@@ -69,6 +72,17 @@ export default function SupplierShow({
}
/>
<Panel title="Dados do fornecedor">
{geography && (
<p className="mb-4 text-sm">
Localização administrativa:{' '}
{geography.path
.map((node) => node.name)
.join(' / ')}
{geography.requires_review
? ' (requer revisão)'
: ''}
</p>
)}
{canDocuments && (
<Link
className="mb-4 inline-block font-semibold text-teal-700"
+2
View File
@@ -1,4 +1,6 @@
import type { GeographyReference } from '@/components/administrative-location';
export type Supplier = {
geography_reference?: GeographyReference | null;
id: number;
name: string;
nuit: string;
@@ -23,6 +23,9 @@
@php($money = fn ($minor) => number_format($minor / 100, 2, ',', '.') . ' MZN')
<button type="button" class="no-print" onclick="window.print()">Imprimir ou guardar como PDF</button>
<h1>Ordem de compra {{ $order->number }}</h1>
@if(($operationalState ?? 'issued') !== 'issued')
<p class="notice"><strong>{{ $operationalState === 'cancelled' ? 'Ordem cancelada' : 'Cancelamento pendente — execução suspensa' }}.</strong> Reprodução do documento original, preservado no histórico.</p>
@endif
<p>{{ $snapshot['company']['name'] }} · {{ $snapshot['requisition']['number'] }}</p>
<div class="notice"><strong>Documento de desenvolvimento. Não autoriza compras reais.</strong><br>Orçamento não verificado. @if($snapshot['approval_rules']['rules_provisional']) Regras de aprovação provisórias. @endif</div>
<div class="columns">
+1 -1
View File
@@ -19,7 +19,7 @@
</head>
<body>
@php($quantity = fn ($milli) => number_format($milli / 1000, 3, ',', '.'))
@php($quality = ['accepted' => 'Aceite', 'rejected' => 'Rejeitado', 'partial' => 'Parcial', 'pending' => 'Pendente'])
@php($quality = ['compliant' => 'Conforme', 'reservations' => 'Conforme com reservas', 'nonconforming' => 'Não conforme'])
@php($types = ['delivery_note' => 'Guia de remessa', 'quality' => 'Qualidade', 'other' => 'Outro'])
<button type="button" class="no-print" onclick="window.print()">Imprimir ou guardar como PDF</button>
<h1>Recepção {{ $receipt->number }}</h1>
@@ -0,0 +1,64 @@
<!DOCTYPE html>
<html lang="pt">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>RA-{{ $record->id }} · Entrega #{{ $delivery->id }} · SGC</title>
<style>
@page { size: A4; margin: 17mm; }
* { box-sizing: border-box; }
body { color: #111; font: 12px/1.5 Arial, sans-serif; max-width: 950px; margin: 24px auto; }
h1 { font-size: 24px; } h2 { font-size: 16px; }
table { width: 100%; border-collapse: collapse; margin: 18px 0; }
th, td { border: 1px solid #ccc; padding: 8px; text-align: left; vertical-align: top; overflow-wrap: anywhere; }
thead { display: table-header-group; } tr { break-inside: avoid; }
.pre { white-space: pre-wrap; overflow-wrap: anywhere; } .notice { border: 1px solid #aaa; padding: 12px; }
button { padding: 10px; } @media print { .no-print { display: none; } body { margin: 0; max-width: none; } }
</style>
</head>
<body>
<button type="button" class="no-print" onclick="window.print()">Imprimir ou guardar como PDF</button>
<h1>Documento de saída interna</h1>
<p><strong>Requisição RA-{{ $record->id }} · Entrega #{{ $delivery->id }}</strong> · Sem factura</p>
<p class="notice">Esta reprodução identifica exclusivamente a entrega registada abaixo. Quantidades pedidas, reservadas ou entregues noutros momentos não integram esta saída. Não constitui factura nem assinatura digital.</p>
<h2>Utilização e responsáveis</h2>
<p>Armazém: {{ $record->snapshot['warehouse']['code'] }} · {{ $record->snapshot['warehouse']['name'] }}<br>
Requisitante: {{ $record->snapshot['requester']['name'] }}<br>
Centro de custo: {{ $record->snapshot['cost_center']['code'] }} · {{ $record->snapshot['cost_center']['name'] }}<br>
Destino: {{ $record->snapshot['destination'] }}<br>
Entregue por: {{ $delivery->data['actor']['name'] ?? 'Utilizador #'.$delivery->actor_id }} · {{ $delivery->created_at }}</p>
<p class="pre">Finalidade: {{ $record->snapshot['reason'] }}</p>
@if($authorization)
<p>Autorização por {{ $authorization->data['actor']['name'] ?? 'Utilizador #'.$authorization->actor_id }} · {{ $authorization->created_at }} · Registo #{{ $authorization->id }}</p>
@endif
<table>
<thead><tr><th>Artigo</th><th>Quantidade desta entrega</th><th>Utilização / equipamento</th><th>Movimento de origem</th></tr></thead>
<tbody>
@foreach($delivery->data['lines'] as $line)
@php($source = $record->snapshot['lines'][$line['index']])
<tr>
<td>{{ $source['item']['code'] }} · {{ $source['item']['name'] }}</td>
<td>{{ number_format($line['quantity_milli'] / 1000, 3, ',', '.') }} {{ $source['item']['unit'] }}</td>
<td>{{ $source['destination'] }}
@if($source['equipment'] ?? null)
<br>{{ $source['equipment']['code'] }} · {{ $source['equipment']['description'] }}
@else
<br>Uso interno
@endif
</td>
<td>Operação #{{ $line['stock_operation_id'] }}</td>
</tr>
@endforeach
</tbody>
</table>
<p class="pre">Motivo da entrega: {{ $delivery->reason }}</p>
<h2>Confirmação de recepção</h2>
@if($confirmation)
<p>Recepção confirmada por {{ $confirmation->data['actor']['name'] ?? 'Utilizador #'.$confirmation->actor_id }} · {{ $confirmation->created_at }} · Registo #{{ $confirmation->id }}</p>
<p class="pre">{{ $confirmation->reason }}</p>
@else
<p>Recepção por confirmar à data desta consulta.</p>
@endif
<p>A entrega é preservada como registo original. Devoluções ou correcções posteriores devem ser consultadas nos respectivos processos; esta reprodução não calcula o saldo actual.</p>
</body>
</html>
@@ -0,0 +1,74 @@
<!DOCTYPE html>
<html lang="pt">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Requisição RA-{{ $record->id }} · SGC</title>
<style>
@page { size: A4 landscape; margin: 15mm; }
body { font: 12px/1.5 Arial, sans-serif; color: #111; max-width: 1100px; margin: 24px auto; }
table { width: 100%; border-collapse: collapse; margin: 18px 0; }
th, td { border: 1px solid #bbb; padding: 8px; text-align: left; vertical-align: top; overflow-wrap: anywhere; }
thead { display: table-header-group; } tr { break-inside: avoid; }
.pre { white-space: pre-wrap; overflow-wrap: anywhere; }
@media print { .no-print { display: none; } body { margin: 0; max-width: none; } }
</style>
</head>
<body>
@php
$states = ['draft'=>'Rascunho', 'submitted'=>'Por autorizar', 'authorized'=>'Autorizada', 'partial'=>'Entrega parcial', 'delivered'=>'Entregue', 'closed'=>'Recepção confirmada', 'rejected'=>'Rejeitada', 'cancelled'=>'Cancelada'];
$actions = ['submit'=>'Submissão', 'authorize'=>'Autorização', 'reject'=>'Rejeição', 'cancel'=>'Cancelamento', 'reserve'=>'Reserva', 'deliver'=>'Entrega', 'receive'=>'Recepção'];
@endphp
<button class="no-print" type="button" onclick="window.print()">Imprimir ou guardar como PDF</button>
<h1>Requisição RA-{{ $record->id }}</h1>
<p><strong>Uso interno · Sem factura</strong> · {{ $states[$progress['state']] ?? $progress['state'] }} · Versão {{ $progress['version'] }}<br>Consulta em {{ $generatedAt }}</p>
<p>Resumo de acompanhamento da requisição. As quantidades pedidas ou reservadas não representam uma saída. Cada entrega tem o seu documento individual, ligado abaixo. Esta consulta não regista autorizações, movimentos ou assinaturas.</p>
<h2>Utilização e origem</h2>
<p>Requisitante: {{ $record->snapshot['requester']['name'] }}<br>
Armazém: {{ $record->snapshot['warehouse']['code'] }} · {{ $record->snapshot['warehouse']['name'] }}<br>
Centro de custo: {{ $record->snapshot['cost_center']['code'] }} · {{ $record->snapshot['cost_center']['name'] }}<br>
Destino: {{ $record->snapshot['destination'] }}</p>
<p class="pre">Finalidade: {{ $record->snapshot['reason'] }}</p>
<table>
<thead><tr><th>Artigo / unidade</th><th>Utilização</th><th>Pedida</th><th>Reservada agora</th><th>Entregue acumulada</th><th>Por entregar</th><th>Cancelada</th></tr></thead>
<tbody>
@foreach($record->snapshot['lines'] as $index => $line)
<tr>
<td>{{ $line['item']['code'] }} · {{ $line['item']['name'] }}<br>{{ $line['item']['unit'] }}</td>
<td>{{ $line['destination'] }}
@if($line['equipment'] ?? null)<br>{{ $line['equipment']['code'] }} · {{ $line['equipment']['description'] }}@endif
</td>
@foreach([$line['quantity_milli'], $progress['reserved'][$index], $progress['delivered'][$index], $progress['remaining'][$index], $progress['cancelled'][$index]] as $quantity)
<td>{{ number_format($quantity / 1000, 3, ',', '.') }}</td>
@endforeach
</tr>
@endforeach
</tbody>
</table>
@unless($progress['reservation_ready'])<p>Consulta de reservas indisponível nesta instalação; os zeros não certificam ausência de compromissos.</p>@endunless
<p>Entregas acumuladas reproduzem as saídas registadas. Não descontam devoluções ou correcções posteriores; consulte esses processos para o saldo físico.</p>
<h2>Autorizações, entregas e confirmações</h2>
<table>
<thead><tr><th>Registo / versão</th><th>Intervenção</th><th>Responsável / data</th><th>Motivo e documento</th></tr></thead>
<tbody>
@forelse($progress['events'] as $event)
<tr>
<td>#{{ $event['id'] }} / {{ $event['version'] }}</td>
<td>{{ $actions[$event['action']] ?? $event['action'] }}</td>
<td>{{ $event['data']['actor']['name'] ?? 'Utilizador #'.$event['actor_id'] }}<br>{{ $event['created_at'] }}</td>
<td><span class="pre">{{ $event['reason'] }}</span>
@if($event['action'] === 'deliver')
<br><a href="{{ url('/stock/requisicoes/'.$record->id.'/entregas/'.$event['id'].'/imprimir') }}">Documento da entrega #{{ $event['id'] }}</a>
<br>{{ in_array($event['id'], $progress['received_deliveries'], true) ? 'Recepção confirmada' : 'Recepção por confirmar' }}
@elseif($event['action'] === 'receive')
<br>Entrega #{{ $event['data']['delivery_event_id'] ?? '' }}
@endif
</td>
</tr>
@empty
<tr><td colspan="4">Sem intervenções registadas. O rascunho não constitui autorização nem saída.</td></tr>
@endforelse
</tbody>
</table>
</body>
</html>