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
@@ -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>
);
}