commit13
This commit is contained in:
@@ -0,0 +1,215 @@
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import {
|
||||
PageTitle,
|
||||
Panel,
|
||||
FormErrors,
|
||||
controlClass,
|
||||
} from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
type Row = {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
unit: string;
|
||||
physical_milli: number;
|
||||
usable_milli: number | null;
|
||||
blocked_milli: number | null;
|
||||
lot_control: boolean;
|
||||
reconciled: boolean;
|
||||
planned_milli: number | null;
|
||||
minimum_milli: number | null;
|
||||
at_minimum: boolean;
|
||||
physical_commitment_milli: number | null;
|
||||
free_milli: number | null;
|
||||
};
|
||||
type Props = {
|
||||
filters: { warehouse_id?: number; search?: string };
|
||||
warehouses: { id: number; code: string; name: string }[];
|
||||
warehouse: { name: string } | null;
|
||||
checkedAt: string;
|
||||
planningVisible: boolean;
|
||||
rows: null | {
|
||||
data: Row[];
|
||||
total: number;
|
||||
prev_page_url: string | null;
|
||||
next_page_url: string | null;
|
||||
};
|
||||
};
|
||||
const quantity = (n: number | null) =>
|
||||
n === null
|
||||
? 'Por determinar'
|
||||
: (n / 1000).toLocaleString('pt-PT', { maximumFractionDigits: 3 });
|
||||
export default function Availability(props: Props) {
|
||||
const form = useForm({
|
||||
warehouse_id: props.filters.warehouse_id?.toString() ?? '',
|
||||
search: props.filters.search ?? '',
|
||||
});
|
||||
return (
|
||||
<>
|
||||
<Head title="Disponibilidade para requisições" />
|
||||
<div className="space-y-6 p-6">
|
||||
<PageTitle
|
||||
eyebrow="Armazém e activos"
|
||||
title="Disponibilidade para requisições"
|
||||
description="Consulta dos registos existentes. Consultar não reserva nem autoriza uma saída."
|
||||
/>
|
||||
<Panel title="Escolher armazém">
|
||||
<form
|
||||
className="grid gap-4 md:grid-cols-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.get('/stock/disponibilidade');
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
Armazém
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={form.data.warehouse_id}
|
||||
onChange={(e) =>
|
||||
form.setData('warehouse_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{props.warehouses.map((warehouse) => (
|
||||
<option
|
||||
key={warehouse.id}
|
||||
value={warehouse.id}
|
||||
>
|
||||
{warehouse.code} · {warehouse.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Artigo ou código
|
||||
<input
|
||||
className={controlClass}
|
||||
value={form.data.search}
|
||||
onChange={(e) =>
|
||||
form.setData('search', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<Button disabled={form.processing}>Consultar</Button>
|
||||
<FormErrors errors={form.errors} />
|
||||
</form>
|
||||
</Panel>
|
||||
<Panel
|
||||
title={props.warehouse?.name ?? 'Disponibilidade'}
|
||||
description={`Consulta em ${props.checkedAt}. Cada quantidade mantém a unidade do artigo.`}
|
||||
>
|
||||
<p className="mb-4 text-sm">
|
||||
As necessidades planeadas são apresentadas
|
||||
separadamente. O compromisso físico e a reserva
|
||||
autorizada de requisições ao armazém ainda não estão
|
||||
implementados; não são considerados zero nem deduzidos
|
||||
como se já existissem.
|
||||
</p>
|
||||
{!props.rows ? (
|
||||
<p>Seleccione o armazém para consultar.</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
{[
|
||||
'Artigo',
|
||||
'Físico',
|
||||
'Utilizável pelos controlos activos',
|
||||
'Retido/indisponível',
|
||||
'Necessidades planeadas',
|
||||
'Reservado / livre',
|
||||
'Mínimo aprovado',
|
||||
'Situação',
|
||||
].map((label) => (
|
||||
<th
|
||||
className="border-b p-3"
|
||||
key={label}
|
||||
>
|
||||
{label}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{props.rows.data.map((row) => (
|
||||
<tr key={row.id}>
|
||||
<td className="border-b p-3">
|
||||
{row.code} · {row.name}
|
||||
<p>{row.unit}</p>
|
||||
</td>
|
||||
<td className="border-b p-3">
|
||||
{quantity(
|
||||
row.physical_milli,
|
||||
)}
|
||||
</td>
|
||||
<td className="border-b p-3">
|
||||
{quantity(row.usable_milli)}
|
||||
{!row.lot_control && (
|
||||
<p className="text-xs">
|
||||
Sem controlo por
|
||||
lote neste âmbito
|
||||
</p>
|
||||
)}
|
||||
</td>
|
||||
<td className="border-b p-3">
|
||||
{row.lot_control
|
||||
? quantity(
|
||||
row.blocked_milli,
|
||||
)
|
||||
: 'Sem controlo por lote'}
|
||||
</td>
|
||||
<td className="border-b p-3">
|
||||
{props.planningVisible
|
||||
? quantity(
|
||||
row.planned_milli,
|
||||
)
|
||||
: 'Sem acesso ao planeamento'}
|
||||
</td>
|
||||
<td className="border-b p-3">{quantity(row.physical_commitment_milli)} / {quantity(row.free_milli)}</td>
|
||||
<td className="border-b p-3">{quantity(row.minimum_milli)}</td>
|
||||
<td className="border-b p-3">
|
||||
{!row.reconciled
|
||||
? 'Reconciliar repartição dos lotes'
|
||||
: row.usable_milli === 0
|
||||
? 'Sem material utilizável — necessidade de compra'
|
||||
: row.at_minimum
|
||||
? 'No mínimo ou abaixo — necessidade de compra'
|
||||
: row.minimum_milli ===
|
||||
null
|
||||
? 'Mínimo por determinar'
|
||||
: 'Acima do mínimo'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{props.rows.data.length === 0 && (
|
||||
<p>Sem artigos nos filtros seleccionados.</p>
|
||||
)}
|
||||
<p className="mt-4 text-sm">
|
||||
A compra automática usa a parametrização do artigo e armazém. Esta consulta não cria documentos. <Link href="/stock/reposicao">Consultar reposição e necessidades pendentes</Link>.
|
||||
</p>
|
||||
<div className="mt-4 flex gap-4">
|
||||
{props.rows.prev_page_url && (
|
||||
<Link href={props.rows.prev_page_url}>
|
||||
Anterior
|
||||
</Link>
|
||||
)}
|
||||
{props.rows.next_page_url && (
|
||||
<Link href={props.rows.next_page_url}>
|
||||
Seguinte
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Panel>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
import { InventoryEventActions } from '@/components/inventory-event-actions';
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import {
|
||||
FormErrors,
|
||||
PageTitle,
|
||||
Panel,
|
||||
controlClass,
|
||||
} from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
type Source = {
|
||||
item: { code: string; name: string; unit: string };
|
||||
warehouse: { name: string };
|
||||
lot: { code: string | null } | null;
|
||||
receipt: {
|
||||
number: string;
|
||||
supplier_name: string;
|
||||
order_number: string;
|
||||
} | null;
|
||||
};
|
||||
type RecordEntry = {
|
||||
id: number;
|
||||
record_key: string;
|
||||
version: number;
|
||||
state: string;
|
||||
reason: string;
|
||||
created_at: string;
|
||||
data: {
|
||||
kind: string;
|
||||
stock_item_id: number;
|
||||
warehouse_id: number;
|
||||
lot_id: number | null;
|
||||
receipt_item_id: number | null;
|
||||
quantity_milli: number;
|
||||
reference: string;
|
||||
stock_operation_id?: number;
|
||||
event?: { event_on: string; evidence: string };
|
||||
};
|
||||
snapshot: {
|
||||
source: Source;
|
||||
contributors: number[];
|
||||
reviewed_by?: number;
|
||||
actor: { name: string };
|
||||
};
|
||||
};
|
||||
type Props = {
|
||||
canViewReversals: boolean;
|
||||
correctedOperations?: Record<number, string>;
|
||||
canViewOperations: boolean;
|
||||
ready: boolean;
|
||||
today: string;
|
||||
actorId: number;
|
||||
capabilities: Record<string, boolean>;
|
||||
records: RecordEntry[];
|
||||
history: Record<string, RecordEntry[]>;
|
||||
items: { id: number; code: string; name: string; unit: string }[];
|
||||
warehouses: { id: number; code: string; name: string }[];
|
||||
receipts: {
|
||||
id: number;
|
||||
stock_item_id: number;
|
||||
warehouse_id: number;
|
||||
accepted_milli: number;
|
||||
returned_milli: number;
|
||||
label: string;
|
||||
}[];
|
||||
lots: {
|
||||
id: number;
|
||||
stock_item_id: number;
|
||||
warehouse_id: number;
|
||||
code: string | null;
|
||||
quantity_milli: number;
|
||||
receipt_item_id: number | null;
|
||||
reconciled: boolean;
|
||||
}[];
|
||||
};
|
||||
const quantity = (n: number) =>
|
||||
(n / 1000).toLocaleString('pt-MZ', { maximumFractionDigits: 3 });
|
||||
const states: Record<string, string> = {
|
||||
draft: 'Em preparação',
|
||||
returned: 'Devolvido para actualização',
|
||||
approved: 'Aprovado para saída física',
|
||||
executed: 'Saída física registada',
|
||||
};
|
||||
|
||||
function Prepare({ props, old }: { props: Props; old?: RecordEntry }) {
|
||||
const form = useForm({
|
||||
operation_key: crypto.randomUUID(),
|
||||
record_key: old?.record_key,
|
||||
version: old?.version ?? 0,
|
||||
action: 'save',
|
||||
reason: '',
|
||||
data: {
|
||||
kind: old?.data.kind ?? 'supplier_return',
|
||||
stock_item_id: old ? String(old.data.stock_item_id) : '',
|
||||
warehouse_id: old ? String(old.data.warehouse_id) : '',
|
||||
lot_id: old?.data.lot_id ? String(old.data.lot_id) : '',
|
||||
receipt_item_id: old?.data.receipt_item_id
|
||||
? String(old.data.receipt_item_id)
|
||||
: '',
|
||||
quantity: old ? String(old.data.quantity_milli / 1000) : '',
|
||||
reference: old?.data.reference ?? '',
|
||||
},
|
||||
});
|
||||
const change = (update: Partial<typeof form.data.data>) =>
|
||||
form.setData('data', { ...form.data.data, ...update });
|
||||
const lots = props.lots.filter(
|
||||
(l) =>
|
||||
String(l.stock_item_id) === form.data.data.stock_item_id &&
|
||||
String(l.warehouse_id) === form.data.data.warehouse_id &&
|
||||
(form.data.data.kind !== 'supplier_return' ||
|
||||
String(l.receipt_item_id) === form.data.data.receipt_item_id),
|
||||
);
|
||||
return (
|
||||
<form
|
||||
className="grid gap-4 md:grid-cols-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post('/stock/ocorrencias');
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
<label className="grid gap-1 text-sm">
|
||||
Operação
|
||||
<select
|
||||
className={controlClass}
|
||||
value={form.data.data.kind}
|
||||
onChange={(e) =>
|
||||
change({
|
||||
kind: e.target.value,
|
||||
lot_id: '',
|
||||
receipt_item_id: '',
|
||||
stock_item_id: '',
|
||||
warehouse_id: '',
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="supplier_return">
|
||||
Devolução ao fornecedor
|
||||
</option>
|
||||
<option value="write_off">Abate físico</option>
|
||||
</select>
|
||||
</label>
|
||||
{form.data.data.kind === 'supplier_return' && (
|
||||
<label className="grid gap-1 text-sm">
|
||||
Recepção de origem
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={form.data.data.receipt_item_id}
|
||||
onChange={(e) => {
|
||||
const source = props.receipts.find(
|
||||
(r) => String(r.id) === e.target.value,
|
||||
);
|
||||
change({
|
||||
receipt_item_id: e.target.value,
|
||||
stock_item_id: source
|
||||
? String(source.stock_item_id)
|
||||
: '',
|
||||
warehouse_id: source
|
||||
? String(source.warehouse_id)
|
||||
: '',
|
||||
lot_id: '',
|
||||
});
|
||||
}}
|
||||
>
|
||||
<option value="">Seleccione a recepção aceite</option>
|
||||
{props.receipts.map((r) => (
|
||||
<option key={r.id} value={r.id}>
|
||||
{r.label} · Devolvível da origem:{' '}
|
||||
{quantity(r.accepted_milli - r.returned_milli)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<label className="grid gap-1 text-sm">
|
||||
Artigo
|
||||
<select
|
||||
required
|
||||
disabled={form.data.data.kind === 'supplier_return'}
|
||||
className={controlClass}
|
||||
value={form.data.data.stock_item_id}
|
||||
onChange={(e) =>
|
||||
change({ stock_item_id: e.target.value, lot_id: '' })
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{props.items.map((i) => (
|
||||
<option key={i.id} value={i.id}>
|
||||
{i.code} · {i.name} ({i.unit})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid gap-1 text-sm">
|
||||
Local da saída
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={form.data.data.warehouse_id}
|
||||
onChange={(e) =>
|
||||
change({ warehouse_id: e.target.value, lot_id: '' })
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{props.warehouses.map((w) => (
|
||||
<option key={w.id} value={w.id}>
|
||||
{w.code} · {w.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid gap-1 text-sm">
|
||||
Lote exacto, quando controlado
|
||||
<select
|
||||
className={controlClass}
|
||||
value={form.data.data.lot_id}
|
||||
onChange={(e) => change({ lot_id: e.target.value })}
|
||||
>
|
||||
<option value="">Sem lote seleccionado</option>
|
||||
{lots.map((l) => (
|
||||
<option
|
||||
key={l.id}
|
||||
disabled={!l.reconciled}
|
||||
value={l.id}
|
||||
>
|
||||
{l.code ?? `Por identificar #${l.id}`} · Quantidade
|
||||
física: {quantity(l.quantity_milli)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid gap-1 text-sm">
|
||||
Quantidade a retirar
|
||||
<input
|
||||
required
|
||||
className={controlClass}
|
||||
inputMode="decimal"
|
||||
pattern="\d{1,9}(\.\d{1,3})?"
|
||||
value={form.data.data.quantity}
|
||||
onChange={(e) => change({ quantity: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label className="grid gap-1 text-sm">
|
||||
Referência única do documento de saída
|
||||
<input
|
||||
required
|
||||
maxLength={100}
|
||||
className={controlClass}
|
||||
value={form.data.data.reference}
|
||||
onChange={(e) => change({ reference: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label className="grid gap-1 text-sm md:col-span-2">
|
||||
Motivo e evidência da proposta
|
||||
<textarea
|
||||
required
|
||||
minLength={10}
|
||||
className={controlClass}
|
||||
value={form.data.reason}
|
||||
onChange={(e) => form.setData('reason', e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<Button disabled={form.processing}>Guardar preparação</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function RecordActions({
|
||||
props,
|
||||
record,
|
||||
}: {
|
||||
props: Props;
|
||||
record: RecordEntry;
|
||||
}) {
|
||||
const choices: { value: string; label: string }[] = [];
|
||||
if (
|
||||
props.capabilities.review &&
|
||||
!record.snapshot.contributors.includes(props.actorId)
|
||||
) {
|
||||
if (['draft', 'returned'].includes(record.state))
|
||||
choices.push({ value: 'approve', label: 'Conferir e aprovar' });
|
||||
if (['draft', 'returned', 'approved'].includes(record.state))
|
||||
choices.push({
|
||||
value: 'return',
|
||||
label: 'Devolver para actualização',
|
||||
});
|
||||
}
|
||||
if (
|
||||
props.capabilities.execute &&
|
||||
record.state === 'approved' &&
|
||||
record.snapshot.reviewed_by !== props.actorId
|
||||
)
|
||||
choices.push({ value: 'execute', label: 'Confirmar saída física' });
|
||||
return (
|
||||
<InventoryEventActions
|
||||
route="/stock/ocorrencias"
|
||||
record={record}
|
||||
choices={choices}
|
||||
today={props.today}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Dispositions(props: Props) {
|
||||
return (
|
||||
<>
|
||||
<Head title="Devoluções e abates" />
|
||||
<div className="mx-auto flex w-full max-w-6xl flex-col gap-6 p-5 lg:p-8">
|
||||
<PageTitle
|
||||
eyebrow="Armazém"
|
||||
title="Devoluções e abates"
|
||||
description="Preparar, conferir e comprovar a saída de material, preservando as suas origens."
|
||||
/>
|
||||
{props.canViewReversals && (
|
||||
<Link href="/stock/estornos" className="text-sm underline">
|
||||
Estornos de stock ligados ao original
|
||||
</Link>
|
||||
)}
|
||||
<Panel title="Responsabilidades separadas">
|
||||
<p className="text-sm">
|
||||
A preparação reutiliza a recepção ou o lote existente.
|
||||
Outra pessoa aprova; Armazém comprova a saída, por
|
||||
pessoa diferente de quem aprovou. Material em quarentena
|
||||
ou vencido pode sair por estes percursos sem ser
|
||||
considerado consumo.
|
||||
</p>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
A devolução ou abate físico não cria crédito,
|
||||
restituição, despesa ou pagamento. Facturas e obrigações
|
||||
já validadas conservam o histórico e precisam da
|
||||
regularização financeira correspondente. Novas facturas
|
||||
consideram as quantidades já devolvidas.
|
||||
</p>
|
||||
</Panel>
|
||||
{!props.ready ? (
|
||||
<Panel title="Instalação pendente">
|
||||
<p>
|
||||
O diário de stock ainda não está instalado neste
|
||||
ambiente.
|
||||
</p>
|
||||
</Panel>
|
||||
) : (
|
||||
<>
|
||||
{props.capabilities.prepare && (
|
||||
<Panel title="Preparar saída">
|
||||
<Prepare props={props} />
|
||||
</Panel>
|
||||
)}
|
||||
{props.records.map((record) => (
|
||||
<Panel
|
||||
key={record.id}
|
||||
title={`${record.data.reference} · ${record.data.kind === 'supplier_return' ? 'Devolução ao fornecedor' : 'Abate físico'}`}
|
||||
description={
|
||||
record.data.stock_operation_id &&
|
||||
props.correctedOperations?.[
|
||||
record.data.stock_operation_id
|
||||
]
|
||||
? `Saída estornada por ${props.correctedOperations[record.data.stock_operation_id]}`
|
||||
: states[record.state]
|
||||
}
|
||||
>
|
||||
<p className="text-sm">
|
||||
{record.snapshot.source.item.code} ·{' '}
|
||||
{record.snapshot.source.item.name} ·{' '}
|
||||
{quantity(record.data.quantity_milli)}{' '}
|
||||
{record.snapshot.source.item.unit} ·{' '}
|
||||
{record.snapshot.source.warehouse.name}
|
||||
</p>
|
||||
{record.snapshot.source.receipt && (
|
||||
<p className="mt-2 text-sm">
|
||||
Origem:{' '}
|
||||
{record.snapshot.source.receipt.number}{' '}
|
||||
·{' '}
|
||||
{
|
||||
record.snapshot.source.receipt
|
||||
.order_number
|
||||
}{' '}
|
||||
·{' '}
|
||||
{
|
||||
record.snapshot.source.receipt
|
||||
.supplier_name
|
||||
}
|
||||
</p>
|
||||
)}
|
||||
{record.snapshot.source.lot && (
|
||||
<p className="mt-2 text-sm">
|
||||
Lote:{' '}
|
||||
{record.snapshot.source.lot.code ??
|
||||
`Por identificar #${record.data.lot_id}`}
|
||||
</p>
|
||||
)}
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
{record.reason}
|
||||
</p>
|
||||
{props.capabilities.prepare &&
|
||||
['draft', 'returned'].includes(
|
||||
record.state,
|
||||
) && (
|
||||
<details className="mt-4">
|
||||
<summary className="cursor-pointer text-sm">
|
||||
Actualizar preparação
|
||||
</summary>
|
||||
<Prepare
|
||||
props={props}
|
||||
old={record}
|
||||
/>
|
||||
</details>
|
||||
)}
|
||||
<RecordActions props={props} record={record} />
|
||||
{record.state === 'executed' && (
|
||||
<p className="mt-3 text-sm font-medium">
|
||||
Saída em {record.data.event?.event_on} ·{' '}
|
||||
{record.data.event?.evidence}.
|
||||
Regularização financeira/contabilística
|
||||
não concluída por este registo.{' '}
|
||||
{props.canViewOperations && (
|
||||
<Link
|
||||
href="/stock/operacoes"
|
||||
className="underline"
|
||||
>
|
||||
Consultar movimentos
|
||||
</Link>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
<details className="mt-4 text-sm">
|
||||
<summary className="cursor-pointer">
|
||||
Histórico preservado
|
||||
</summary>
|
||||
<ul className="mt-2 space-y-2">
|
||||
{props.history[record.record_key]?.map(
|
||||
(version) => (
|
||||
<li key={version.id}>
|
||||
Versão {version.version} ·{' '}
|
||||
{states[version.state]} ·{' '}
|
||||
{
|
||||
version.snapshot.actor
|
||||
.name
|
||||
}{' '}
|
||||
· {version.created_at} ·{' '}
|
||||
{version.reason}
|
||||
</li>
|
||||
),
|
||||
)}
|
||||
</ul>
|
||||
</details>
|
||||
</Panel>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -25,6 +25,11 @@ type Props = {
|
||||
stock_item_id: number;
|
||||
warehouse_id: number;
|
||||
quantity_milli: number;
|
||||
lot_control?: {
|
||||
usable_milli: number;
|
||||
blocked_milli: number;
|
||||
reconciled: boolean;
|
||||
} | null;
|
||||
}[];
|
||||
movements: Page<StockMovement>;
|
||||
filters: { search?: string; warehouse_id?: number };
|
||||
@@ -139,6 +144,14 @@ export default function Stock({
|
||||
balance.quantity_milli,
|
||||
)}{' '}
|
||||
{article?.unit}
|
||||
{balance.lot_control && (
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{balance.lot_control
|
||||
.reconciled
|
||||
? `Utilizável: ${quantity(balance.lot_control.usable_milli)} · Indisponível: ${quantity(balance.lot_control.blocked_milli)}`
|
||||
: 'Repartição por lotes por conferir'}
|
||||
</p>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,805 @@
|
||||
import { InventoryEventActions } from '@/components/inventory-event-actions';
|
||||
import { Head, useForm } from '@inertiajs/react';
|
||||
import {
|
||||
FormErrors,
|
||||
PageTitle,
|
||||
Panel,
|
||||
controlClass,
|
||||
} from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
type Metadata = {
|
||||
code: string | null;
|
||||
expires_on: string | null;
|
||||
no_expiry: boolean;
|
||||
quantity_milli: number;
|
||||
};
|
||||
type RecordEntry = {
|
||||
id: number;
|
||||
record_key: string;
|
||||
version: number;
|
||||
kind: string;
|
||||
state: string;
|
||||
reason: string;
|
||||
created_at: string;
|
||||
data: {
|
||||
stock_item_id: number;
|
||||
warehouse_id: number;
|
||||
requires_expiry: boolean;
|
||||
minimum_remaining_days: number;
|
||||
quarantine_on_receipt?: boolean;
|
||||
lots: Metadata[];
|
||||
};
|
||||
snapshot: {
|
||||
contributors: number[];
|
||||
actor: { name: string };
|
||||
item: { code: string; name: string; unit: string };
|
||||
warehouse: { name: string };
|
||||
balance: { quantity: number; version: number };
|
||||
previous_setup_id?: number | null;
|
||||
impact?: { before_milli: number; after_milli: number } | null;
|
||||
};
|
||||
};
|
||||
type Lot = {
|
||||
id: number;
|
||||
record_key: string;
|
||||
version: number;
|
||||
metadata_id: number;
|
||||
data: Metadata;
|
||||
quantity_milli: number;
|
||||
usable_milli: number;
|
||||
eligible: boolean;
|
||||
state: string;
|
||||
state_version: number;
|
||||
contributors: number[];
|
||||
last_usable_on: string | null;
|
||||
release_mode?: string;
|
||||
release_setup_id?: number | null;
|
||||
};
|
||||
type Props = {
|
||||
ready: boolean;
|
||||
actorId: number;
|
||||
capabilities: Record<string, boolean>;
|
||||
records: RecordEntry[];
|
||||
contexts: Record<
|
||||
string,
|
||||
{
|
||||
reconciled: boolean;
|
||||
physical: { quantity: number };
|
||||
usable_milli: number;
|
||||
blocked_milli: number;
|
||||
lots: Lot[];
|
||||
}
|
||||
>;
|
||||
items: { id: number; code: string; name: string; unit: string }[];
|
||||
warehouses: { id: number; code: string; name: string }[];
|
||||
history: RecordEntry[];
|
||||
};
|
||||
const qty = (n: number) =>
|
||||
(n / 1000).toLocaleString('pt-MZ', { maximumFractionDigits: 3 });
|
||||
const states: Record<string, string> = {
|
||||
held: 'Em quarentena',
|
||||
released: 'Libertado',
|
||||
expired: 'Validade insuficiente',
|
||||
unidentified: 'Identificação incompleta',
|
||||
active: 'Activo',
|
||||
draft: 'Para conferência',
|
||||
registered: 'Identificação registada',
|
||||
};
|
||||
|
||||
function Prepare({ props, old }: { props: Props; old?: RecordEntry }) {
|
||||
const revision =
|
||||
old?.state === 'active' || !!old?.snapshot.previous_setup_id;
|
||||
const form = useForm({
|
||||
operation_key: crypto.randomUUID(),
|
||||
record_key: old?.record_key,
|
||||
version: old?.version ?? 0,
|
||||
action: 'prepare',
|
||||
reason: '',
|
||||
data: {
|
||||
stock_item_id: old ? String(old.data.stock_item_id) : '',
|
||||
warehouse_id: old ? String(old.data.warehouse_id) : '',
|
||||
requires_expiry: old?.data.requires_expiry ?? true,
|
||||
quarantine_on_receipt: old?.data.quarantine_on_receipt ?? true,
|
||||
minimum_remaining_days: String(
|
||||
old?.data.minimum_remaining_days ?? 0,
|
||||
),
|
||||
lots: revision
|
||||
? []
|
||||
: (old?.data.lots.map((l) => ({
|
||||
code: l.code ?? '',
|
||||
expires_on: l.expires_on ?? '',
|
||||
no_expiry: l.no_expiry,
|
||||
quantity: String(l.quantity_milli / 1000),
|
||||
})) ?? []),
|
||||
},
|
||||
});
|
||||
return (
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post('/stock/lotes');
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<label className="grid gap-1 text-sm">
|
||||
Artigo
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={form.data.data.stock_item_id}
|
||||
disabled={revision}
|
||||
onChange={(e) =>
|
||||
form.setData('data', {
|
||||
...form.data.data,
|
||||
stock_item_id: e.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{props.items.map((i) => (
|
||||
<option key={i.id} value={i.id}>
|
||||
{i.code} · {i.name} ({i.unit})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid gap-1 text-sm">
|
||||
Armazém
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={form.data.data.warehouse_id}
|
||||
disabled={revision}
|
||||
onChange={(e) =>
|
||||
form.setData('data', {
|
||||
...form.data.data,
|
||||
warehouse_id: e.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{props.warehouses.map((w) => (
|
||||
<option key={w.id} value={w.id}>
|
||||
{w.code} · {w.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid gap-1 text-sm">
|
||||
Dias mínimos de validade restante
|
||||
<input
|
||||
type="number"
|
||||
required
|
||||
min={0}
|
||||
max={3650}
|
||||
className={controlClass}
|
||||
value={form.data.data.minimum_remaining_days}
|
||||
onChange={(e) =>
|
||||
form.setData('data', {
|
||||
...form.data.data,
|
||||
minimum_remaining_days: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.data.requires_expiry}
|
||||
onChange={(e) =>
|
||||
form.setData('data', {
|
||||
...form.data.data,
|
||||
requires_expiry: e.target.checked,
|
||||
})
|
||||
}
|
||||
/>
|
||||
Este artigo exige prazo de validade
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.data.quarantine_on_receipt}
|
||||
onChange={(e) =>
|
||||
form.setData('data', {
|
||||
...form.data.data,
|
||||
quarantine_on_receipt: e.target.checked,
|
||||
})
|
||||
}
|
||||
/>
|
||||
Exigir quarentena nas novas recepções
|
||||
</label>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Dispensar quarentena exige aprovação independente desta
|
||||
configuração. Aplica-se apenas a futuras recepções conformes,
|
||||
identificadas e com validade suficiente. Reservas de qualidade,
|
||||
transferências, saldo inicial e quantidades encontradas em
|
||||
contagem continuam em quarentena.
|
||||
</p>
|
||||
{revision ? (
|
||||
<p className="text-sm">
|
||||
A revisão reutiliza a configuração activa e não cria saldo
|
||||
nem altera movimentos. Validade exigida e dias mínimos
|
||||
passam a determinar a disponibilidade actual; a regra de
|
||||
quarentena aplica-se às novas recepções.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
O saldo actual é reutilizado. Sem repartição, será
|
||||
criado um lote por identificar com a totalidade do
|
||||
saldo. Um só lote dispensa repetir a quantidade; vários
|
||||
lotes exigem repartição exacta.
|
||||
</p>
|
||||
{form.data.data.lots.map((lot, i) => (
|
||||
<fieldset
|
||||
key={i}
|
||||
className="grid gap-3 rounded border p-3 md:grid-cols-4"
|
||||
>
|
||||
<legend>Lote {i + 1}</legend>
|
||||
{(['code', 'expires_on', 'quantity'] as const).map(
|
||||
(key) => (
|
||||
<label
|
||||
key={key}
|
||||
className="grid gap-1 text-sm"
|
||||
>
|
||||
{
|
||||
{
|
||||
code: 'Código',
|
||||
expires_on: 'Validade',
|
||||
quantity: 'Quantidade',
|
||||
}[key]
|
||||
}
|
||||
<input
|
||||
className={controlClass}
|
||||
type={
|
||||
key === 'expires_on'
|
||||
? 'date'
|
||||
: 'text'
|
||||
}
|
||||
value={lot[key]}
|
||||
onChange={(e) =>
|
||||
form.setData('data', {
|
||||
...form.data.data,
|
||||
lots: form.data.data.lots.map(
|
||||
(l, index) =>
|
||||
index === i
|
||||
? {
|
||||
...l,
|
||||
[key]: e
|
||||
.target
|
||||
.value,
|
||||
}
|
||||
: l,
|
||||
),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
),
|
||||
)}
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={lot.no_expiry}
|
||||
onChange={(e) =>
|
||||
form.setData('data', {
|
||||
...form.data.data,
|
||||
lots: form.data.data.lots.map(
|
||||
(l, index) =>
|
||||
index === i
|
||||
? {
|
||||
...l,
|
||||
no_expiry:
|
||||
e.target
|
||||
.checked,
|
||||
}
|
||||
: l,
|
||||
),
|
||||
})
|
||||
}
|
||||
/>
|
||||
Sem prazo
|
||||
</label>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
form.setData('data', {
|
||||
...form.data.data,
|
||||
lots: form.data.data.lots.filter(
|
||||
(_, index) => index !== i,
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Remover repartição
|
||||
</Button>
|
||||
</fieldset>
|
||||
))}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
form.setData('data', {
|
||||
...form.data.data,
|
||||
lots: [
|
||||
...form.data.data.lots,
|
||||
{
|
||||
code: '',
|
||||
expires_on: '',
|
||||
no_expiry: false,
|
||||
quantity: '',
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
>
|
||||
Acrescentar lote ao saldo existente
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<label className="grid gap-1 text-sm">
|
||||
Evidência da conferência
|
||||
<textarea
|
||||
required
|
||||
minLength={10}
|
||||
className={controlClass}
|
||||
value={form.data.reason}
|
||||
onChange={(e) => form.setData('reason', e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<Button disabled={form.processing}>Guardar preparação</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function Decision({
|
||||
record,
|
||||
lot,
|
||||
action,
|
||||
}: {
|
||||
record: { record_key: string; version: number };
|
||||
lot?: Lot & { warehouse_id: number };
|
||||
action: 'activate' | 'hold' | 'release';
|
||||
}) {
|
||||
return (
|
||||
<InventoryEventActions
|
||||
route="/stock/lotes"
|
||||
record={record}
|
||||
choices={[
|
||||
{
|
||||
value: action,
|
||||
label:
|
||||
action === 'activate'
|
||||
? 'Conferir e activar'
|
||||
: action === 'hold'
|
||||
? 'Colocar em quarentena'
|
||||
: 'Conferir e libertar',
|
||||
},
|
||||
]}
|
||||
data={
|
||||
lot
|
||||
? {
|
||||
lot_id: lot.id,
|
||||
warehouse_id: lot.warehouse_id,
|
||||
state_version: lot.state_version,
|
||||
}
|
||||
: {}
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
function Identify({ lot }: { lot: Lot }) {
|
||||
const form = useForm({
|
||||
operation_key: crypto.randomUUID(),
|
||||
record_key: lot.record_key,
|
||||
version: lot.version,
|
||||
action: 'identify',
|
||||
reason: '',
|
||||
data: {
|
||||
code: lot.data.code ?? '',
|
||||
expires_on: lot.data.expires_on ?? '',
|
||||
no_expiry: lot.data.no_expiry,
|
||||
},
|
||||
});
|
||||
return (
|
||||
<details className="mt-3">
|
||||
<summary className="cursor-pointer text-sm">
|
||||
Identificar ou corrigir dados do lote
|
||||
</summary>
|
||||
<form
|
||||
className="mt-3 grid gap-3 md:grid-cols-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post('/stock/lotes');
|
||||
}}
|
||||
>
|
||||
<p className="text-sm text-muted-foreground md:col-span-2">
|
||||
A correcção preserva o histórico e exige nova libertação
|
||||
independente em todos os locais.
|
||||
</p>
|
||||
<FormErrors errors={form.errors} />
|
||||
<label className="grid gap-1 text-sm">
|
||||
Código do lote
|
||||
<input
|
||||
className={controlClass}
|
||||
value={form.data.data.code}
|
||||
onChange={(e) =>
|
||||
form.setData('data', {
|
||||
...form.data.data,
|
||||
code: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="grid gap-1 text-sm">
|
||||
Validade
|
||||
<input
|
||||
type="date"
|
||||
className={controlClass}
|
||||
value={form.data.data.expires_on}
|
||||
onChange={(e) =>
|
||||
form.setData('data', {
|
||||
...form.data.data,
|
||||
expires_on: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.data.no_expiry}
|
||||
onChange={(e) =>
|
||||
form.setData('data', {
|
||||
...form.data.data,
|
||||
no_expiry: e.target.checked,
|
||||
})
|
||||
}
|
||||
/>
|
||||
Confirmo que o artigo não tem prazo de validade
|
||||
</label>
|
||||
<label className="grid gap-1 text-sm">
|
||||
Motivo / evidência
|
||||
<input
|
||||
required
|
||||
minLength={10}
|
||||
className={controlClass}
|
||||
value={form.data.reason}
|
||||
onChange={(e) => form.setData('reason', e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<Button disabled={form.processing}>
|
||||
Registar identificação
|
||||
</Button>
|
||||
</form>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Lots(props: Props) {
|
||||
return (
|
||||
<>
|
||||
<Head title="Lotes, validade e quarentena" />
|
||||
<div className="mx-auto flex w-full max-w-6xl flex-col gap-6 p-5 lg:p-8">
|
||||
<PageTitle
|
||||
eyebrow="Armazém"
|
||||
title="Lotes, validade e quarentena"
|
||||
description="O saldo físico mantém a sua origem. A qualidade determina a quantidade utilizável."
|
||||
/>
|
||||
<Panel title="Antes de activar">
|
||||
<p className="text-sm">
|
||||
A activação é por artigo e armazém e exige conferência
|
||||
por outra pessoa. O saldo inicial entra sempre em
|
||||
quarentena. Novas recepções seguem a regra de quarentena
|
||||
aprovada. As saídas escolhem automaticamente os lotes
|
||||
libertados com validade mais próxima.
|
||||
</p>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
Transferências exigem controlo activo nos dois armazéns.
|
||||
A chegada coloca o lote inteiro no destino em
|
||||
quarentena, incluindo quantidades desse lote já
|
||||
existentes no local. Ajustes por lote reutilizam uma
|
||||
contagem com conferência independente. Os parâmetros
|
||||
podem ser revistos com impacto conferido. A previsão
|
||||
exclui entradas futuras sem qualificação do lote.
|
||||
</p>
|
||||
</Panel>
|
||||
{!props.ready ? (
|
||||
<Panel title="Instalação pendente">
|
||||
<p>
|
||||
O controlo por lotes ainda não está instalado neste
|
||||
ambiente.
|
||||
</p>
|
||||
</Panel>
|
||||
) : (
|
||||
<>
|
||||
{props.capabilities.prepare && (
|
||||
<Panel title="Preparar novo controlo">
|
||||
<Prepare props={props} />
|
||||
</Panel>
|
||||
)}
|
||||
{props.records.map((record) => {
|
||||
const context = props.contexts[record.record_key];
|
||||
return (
|
||||
<Panel
|
||||
key={record.id}
|
||||
title={`${record.snapshot.item.code} · ${record.snapshot.item.name} · ${record.snapshot.warehouse.name}`}
|
||||
description={
|
||||
states[record.state] ?? record.state
|
||||
}
|
||||
>
|
||||
<p className="mb-3 text-sm text-muted-foreground">
|
||||
Validade{' '}
|
||||
{record.data.requires_expiry
|
||||
? 'obrigatória'
|
||||
: 'ou confirmação explícita de artigo sem prazo'}{' '}
|
||||
· Mínimo restante:{' '}
|
||||
{record.data.minimum_remaining_days}{' '}
|
||||
dias · Novas recepções:{' '}
|
||||
{(record.data.quarantine_on_receipt ??
|
||||
true)
|
||||
? 'quarentena obrigatória'
|
||||
: 'dispensa apenas quando conformes e completamente identificadas'}
|
||||
.
|
||||
</p>
|
||||
{record.snapshot.impact &&
|
||||
record.state === 'draft' && (
|
||||
<p className="mb-3 text-sm font-medium">
|
||||
Impacto conferido da revisão:
|
||||
utilizável actual{' '}
|
||||
{qty(
|
||||
record.snapshot.impact
|
||||
.before_milli,
|
||||
)}{' '}
|
||||
→{' '}
|
||||
{qty(
|
||||
record.snapshot.impact
|
||||
.after_milli,
|
||||
)}{' '}
|
||||
{record.snapshot.item.unit}.
|
||||
Mudanças no saldo ou qualidade
|
||||
exigem actualizar esta
|
||||
preparação.
|
||||
</p>
|
||||
)}
|
||||
{record.state === 'draft' ? (
|
||||
<>
|
||||
<p className="text-sm">
|
||||
Saldo conferido:{' '}
|
||||
{qty(
|
||||
record.snapshot.balance
|
||||
.quantity,
|
||||
)}{' '}
|
||||
{record.snapshot.item.unit}.
|
||||
{record.snapshot
|
||||
.previous_setup_id
|
||||
? 'A revisão não volta a repartir o saldo; activa apenas os parâmetros conferidos.'
|
||||
: 'Todo o saldo ficará em quarentena após activação.'}
|
||||
</p>
|
||||
{record.data.lots.map((lot, i) => (
|
||||
<p
|
||||
key={i}
|
||||
className="mt-2 text-sm"
|
||||
>
|
||||
{lot.code ??
|
||||
'Por identificar'}{' '}
|
||||
·{' '}
|
||||
{lot.expires_on ??
|
||||
(lot.no_expiry
|
||||
? 'Sem prazo confirmado'
|
||||
: 'Validade por confirmar')}{' '}
|
||||
· {qty(lot.quantity_milli)}
|
||||
</p>
|
||||
))}
|
||||
{props.capabilities.prepare && (
|
||||
<details className="mt-3">
|
||||
<summary>
|
||||
Actualizar preparação
|
||||
após nova conferência
|
||||
</summary>
|
||||
<Prepare
|
||||
props={props}
|
||||
old={record}
|
||||
/>
|
||||
</details>
|
||||
)}
|
||||
{props.capabilities.review &&
|
||||
!record.snapshot.contributors.includes(
|
||||
props.actorId,
|
||||
) && (
|
||||
<Decision
|
||||
record={record}
|
||||
action="activate"
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
context && (
|
||||
<>
|
||||
<p className="text-sm">
|
||||
Físico:{' '}
|
||||
{qty(
|
||||
context.physical
|
||||
.quantity,
|
||||
)}{' '}
|
||||
· Utilizável:{' '}
|
||||
{qty(context.usable_milli)}{' '}
|
||||
· Indisponível:{' '}
|
||||
{qty(context.blocked_milli)}{' '}
|
||||
{record.snapshot.item.unit}
|
||||
</p>
|
||||
{!context.reconciled && (
|
||||
<p
|
||||
role="alert"
|
||||
className="mt-2 text-destructive"
|
||||
>
|
||||
Repartição divergente.
|
||||
Confira as origens antes
|
||||
de operar.
|
||||
</p>
|
||||
)}
|
||||
{props.capabilities.prepare &&
|
||||
!props.records.some(
|
||||
(r) =>
|
||||
r.record_key ===
|
||||
record.record_key &&
|
||||
r.state === 'draft',
|
||||
) && (
|
||||
<details className="mt-4">
|
||||
<summary className="cursor-pointer text-sm">
|
||||
Rever parâmetros
|
||||
por referência a
|
||||
esta
|
||||
configuração
|
||||
</summary>
|
||||
<Prepare
|
||||
props={props}
|
||||
old={record}
|
||||
/>
|
||||
</details>
|
||||
)}
|
||||
{context.lots.map((lot) => (
|
||||
<article
|
||||
key={lot.id}
|
||||
className="mt-4 rounded-lg border p-4"
|
||||
>
|
||||
<p className="font-medium">
|
||||
{lot.data.code ??
|
||||
`Lote por identificar #${lot.id}`}{' '}
|
||||
·{' '}
|
||||
{states[lot.state]}
|
||||
</p>
|
||||
{lot.state ===
|
||||
'released' &&
|
||||
lot.release_mode ===
|
||||
'receipt_policy' && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Dispensa de
|
||||
quarentena
|
||||
pela
|
||||
configuração
|
||||
aprovada #
|
||||
{
|
||||
lot.release_setup_id
|
||||
}
|
||||
. Não
|
||||
corresponde
|
||||
a uma
|
||||
conferência
|
||||
manual deste
|
||||
lote.
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{qty(
|
||||
lot.quantity_milli,
|
||||
)}{' '}
|
||||
{
|
||||
record.snapshot
|
||||
.item.unit
|
||||
}{' '}
|
||||
· Validade:{' '}
|
||||
{lot.data
|
||||
.expires_on ??
|
||||
(lot.data
|
||||
.no_expiry
|
||||
? 'Sem prazo confirmado'
|
||||
: 'Por confirmar')}
|
||||
{lot.last_usable_on &&
|
||||
` · Último dia utilizável: ${lot.last_usable_on}`}
|
||||
</p>
|
||||
{props.capabilities
|
||||
.prepare && (
|
||||
<Identify
|
||||
key={`identify-${lot.version}`}
|
||||
lot={lot}
|
||||
/>
|
||||
)}
|
||||
{context.reconciled &&
|
||||
lot.quantity_milli >
|
||||
0 && (
|
||||
<>
|
||||
{props
|
||||
.capabilities
|
||||
.release &&
|
||||
lot.eligible &&
|
||||
lot.state !==
|
||||
'released' &&
|
||||
!lot.contributors.includes(
|
||||
props.actorId,
|
||||
) && (
|
||||
<Decision
|
||||
key={`release-${lot.version}-${lot.state_version}`}
|
||||
record={
|
||||
lot
|
||||
}
|
||||
lot={{
|
||||
...lot,
|
||||
warehouse_id:
|
||||
record
|
||||
.data
|
||||
.warehouse_id,
|
||||
}}
|
||||
action="release"
|
||||
/>
|
||||
)}
|
||||
{props
|
||||
.capabilities
|
||||
.hold &&
|
||||
lot.state ===
|
||||
'released' && (
|
||||
<Decision
|
||||
key={`hold-${lot.version}-${lot.state_version}`}
|
||||
record={
|
||||
lot
|
||||
}
|
||||
lot={{
|
||||
...lot,
|
||||
warehouse_id:
|
||||
record
|
||||
.data
|
||||
.warehouse_id,
|
||||
}}
|
||||
action="hold"
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
)}
|
||||
</Panel>
|
||||
);
|
||||
})}
|
||||
<Panel title="Histórico de conferências">
|
||||
<details>
|
||||
<summary className="cursor-pointer text-sm">
|
||||
Consultar os últimos 200 registos
|
||||
</summary>
|
||||
<div className="mt-3 space-y-3">
|
||||
{props.history.map((record) => (
|
||||
<p key={record.id} className="text-sm">
|
||||
#{record.id} ·{' '}
|
||||
{states[record.state] ??
|
||||
record.state}{' '}
|
||||
· {record.snapshot.actor.name} ·{' '}
|
||||
{record.created_at} ·{' '}
|
||||
{record.reason}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
</Panel>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
import { Head, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { InventoryNotice, InventoryPagination } from '@/components/inventory';
|
||||
import { LotCountFields, countTotal } from '@/components/inventory-lot-count';
|
||||
import type {
|
||||
CountInput,
|
||||
LotCountSource,
|
||||
} from '@/components/inventory-lot-count';
|
||||
import {
|
||||
PageTitle,
|
||||
Panel,
|
||||
@@ -30,6 +35,43 @@ type Operation = {
|
||||
warehouse: { name: string };
|
||||
destination_warehouse?: { name: string } | null;
|
||||
equipment?: { code: string; description: string } | null;
|
||||
reversal?: {
|
||||
source: {
|
||||
document: { reference: string };
|
||||
rows: {
|
||||
source_movement_id: number;
|
||||
warehouse_name: string;
|
||||
quantity_milli: number;
|
||||
}[];
|
||||
};
|
||||
};
|
||||
lot_count?: {
|
||||
rows: {
|
||||
lot_id: number | null;
|
||||
code: string | null;
|
||||
previous_milli: number;
|
||||
counted_milli: number;
|
||||
delta_milli: number;
|
||||
}[];
|
||||
};
|
||||
lot_adjustment?: {
|
||||
rows: {
|
||||
lot_id: number | null;
|
||||
code: string | null;
|
||||
previous_milli: number;
|
||||
counted_milli: number;
|
||||
delta_milli: number;
|
||||
}[];
|
||||
};
|
||||
lot_partition?: {
|
||||
plan: {
|
||||
lot_id: number;
|
||||
quantity: number;
|
||||
code: string | null;
|
||||
expires_on: string | null;
|
||||
metadata_id: number;
|
||||
}[];
|
||||
};
|
||||
};
|
||||
};
|
||||
type Props = {
|
||||
@@ -41,10 +83,18 @@ type Props = {
|
||||
warehouse_id: number;
|
||||
quantity: number;
|
||||
version: number;
|
||||
lot_control?: {
|
||||
usable_milli: number;
|
||||
blocked_milli: number;
|
||||
reconciled: boolean;
|
||||
} | null;
|
||||
}[];
|
||||
operations: Page<Operation>;
|
||||
counts: Operation[];
|
||||
canOperate: boolean;
|
||||
correctedOperations?: Record<number, string>;
|
||||
canAdjust?: boolean;
|
||||
lotCounts?: LotCountSource[];
|
||||
demo?: boolean;
|
||||
equipment?: { id: number; code: string; description: string }[];
|
||||
};
|
||||
@@ -62,12 +112,15 @@ export default function Operations({
|
||||
operations,
|
||||
counts,
|
||||
canOperate,
|
||||
correctedOperations = {},
|
||||
canAdjust = false,
|
||||
lotCounts = [],
|
||||
demo = false,
|
||||
equipment = [],
|
||||
}: Props) {
|
||||
const [message, setMessage] = useState('');
|
||||
const form = useForm({
|
||||
kind: 'issue',
|
||||
kind: canOperate ? 'issue' : 'adjustment',
|
||||
reference: '',
|
||||
idempotency_key: crypto.randomUUID(),
|
||||
stock_item_id: String(items[0]?.id ?? ''),
|
||||
@@ -86,6 +139,28 @@ export default function Operations({
|
||||
String(b.stock_item_id) === form.data.stock_item_id &&
|
||||
String(b.warehouse_id) === form.data.warehouse_id,
|
||||
);
|
||||
const countSource = lotCounts.find(
|
||||
(s) =>
|
||||
String(s.stock_item_id) === form.data.stock_item_id &&
|
||||
String(s.warehouse_id) === form.data.warehouse_id,
|
||||
);
|
||||
const [countInputs, setCountInputs] = useState<
|
||||
Record<string, CountInput[]>
|
||||
>({});
|
||||
const countKey = countSource?.hash ?? '';
|
||||
const countRows =
|
||||
countInputs[countKey] ??
|
||||
countSource?.lots
|
||||
.filter((lot) => lot.quantity_milli > 0)
|
||||
.map((lot) => ({
|
||||
lot_id: lot.lot_id,
|
||||
new_key: null,
|
||||
quantity: '',
|
||||
code: lot.code ?? '',
|
||||
expires_on: lot.expires_on ?? '',
|
||||
no_expiry: lot.no_expiry,
|
||||
})) ??
|
||||
[];
|
||||
return (
|
||||
<>
|
||||
<Head title="Operações de stock" />
|
||||
@@ -124,9 +199,9 @@ export default function Operations({
|
||||
)}
|
||||
<Panel
|
||||
title="Registar operação"
|
||||
description="Só Recepção / Armazém executa movimentos. Administração, Procurement e Finanças consultam. Periodicidade, tolerâncias e investigação de divergências aguardam decisão da empresa."
|
||||
description="Armazém regista as contagens. Ajustes por lote exigem pessoa independente com competência própria de conferência."
|
||||
>
|
||||
{canOperate ? (
|
||||
{canOperate || canAdjust ? (
|
||||
<form
|
||||
className="grid gap-4 sm:grid-cols-2"
|
||||
onSubmit={(e) => {
|
||||
@@ -140,6 +215,15 @@ export default function Operations({
|
||||
form.transform((d) => ({
|
||||
...d,
|
||||
ledger_version: balance?.version ?? 0,
|
||||
...(d.kind === 'count' && countSource
|
||||
? {
|
||||
lot_version: countSource.hash,
|
||||
lot_counts: countRows,
|
||||
quantity:
|
||||
countTotal(countRows) ??
|
||||
'0.000',
|
||||
}
|
||||
: {}),
|
||||
}));
|
||||
form.post('/stock/operacoes', {
|
||||
onSuccess: () => {
|
||||
@@ -164,11 +248,17 @@ export default function Operations({
|
||||
form.setData('kind', e.target.value)
|
||||
}
|
||||
>
|
||||
{Object.entries(kinds).map(([k, v]) => (
|
||||
<option key={k} value={k}>
|
||||
{v}
|
||||
</option>
|
||||
))}
|
||||
{Object.entries(kinds)
|
||||
.filter(
|
||||
([k]) =>
|
||||
canOperate ||
|
||||
k === 'adjustment',
|
||||
)
|
||||
.map(([k, v]) => (
|
||||
<option key={k} value={k}>
|
||||
{v}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid gap-2 text-sm">
|
||||
@@ -229,6 +319,19 @@ export default function Operations({
|
||||
física sobre este saldo; movimentos posteriores
|
||||
exigem nova contagem.
|
||||
</p>
|
||||
{balance?.lot_control && (
|
||||
<p className="text-sm sm:col-span-2">
|
||||
{balance.lot_control.reconciled
|
||||
? `Controlo por lotes · Utilizável: ${quantity(balance.lot_control.usable_milli)} · Indisponível: ${quantity(balance.lot_control.blocked_milli)}. As saídas usam primeiro a validade mais próxima.`
|
||||
: 'Repartição de lotes divergente. Confira as origens antes de operar.'}{' '}
|
||||
Transferências exigem controlo nos dois
|
||||
armazéns e colocam o lote inteiro no destino
|
||||
em quarentena, incluindo o saldo desse lote
|
||||
já existente no local. Ajustes por lote
|
||||
reutilizam uma contagem e exigem conferência
|
||||
independente.
|
||||
</p>
|
||||
)}
|
||||
{form.data.kind === 'transfer' && (
|
||||
<label className="grid gap-2 text-sm">
|
||||
Armazém de destino
|
||||
@@ -294,6 +397,11 @@ export default function Operations({
|
||||
Seleccionar contagem
|
||||
</option>
|
||||
{counts
|
||||
.filter(
|
||||
(c) =>
|
||||
canOperate ||
|
||||
!!c.snapshot.lot_count,
|
||||
)
|
||||
.filter(
|
||||
(c) =>
|
||||
String(c.warehouse_id) ===
|
||||
@@ -314,6 +422,17 @@ export default function Operations({
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
) : form.data.kind === 'count' && countSource ? (
|
||||
<LotCountFields
|
||||
source={countSource}
|
||||
rows={countRows}
|
||||
setRows={(rows) =>
|
||||
setCountInputs({
|
||||
...countInputs,
|
||||
[countKey]: rows,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<label className="grid gap-2 text-sm">
|
||||
{form.data.kind === 'count'
|
||||
@@ -372,7 +491,14 @@ export default function Operations({
|
||||
</label>
|
||||
<div className="sm:col-span-2">
|
||||
<FormErrors errors={form.errors} />
|
||||
<Button disabled={form.processing}>
|
||||
<Button
|
||||
disabled={
|
||||
form.processing ||
|
||||
(form.data.kind === 'adjustment' &&
|
||||
!!balance?.lot_control &&
|
||||
!canAdjust)
|
||||
}
|
||||
>
|
||||
{demo
|
||||
? 'Rever simulação'
|
||||
: 'Confirmar operação'}
|
||||
@@ -401,7 +527,15 @@ export default function Operations({
|
||||
>
|
||||
<div className="flex flex-wrap justify-between gap-2">
|
||||
<strong>
|
||||
{o.reference} · {kinds[o.kind]}
|
||||
{o.reference} ·{' '}
|
||||
{kinds[o.kind] ??
|
||||
{
|
||||
supplier_return:
|
||||
'Devolução ao fornecedor',
|
||||
write_off: 'Abate físico',
|
||||
reversal: 'Estorno integral',
|
||||
}[o.kind] ??
|
||||
o.kind}
|
||||
</strong>
|
||||
<time>
|
||||
{new Date(o.recorded_at).toLocaleString(
|
||||
@@ -411,9 +545,10 @@ export default function Operations({
|
||||
</div>
|
||||
<p className="mt-2">
|
||||
{o.snapshot.stock_item.name} ·{' '}
|
||||
{quantity(o.quantity_milli)}{' '}
|
||||
{o.snapshot.stock_item.unit} ·{' '}
|
||||
{o.snapshot.warehouse.name}
|
||||
{o.kind === 'reversal'
|
||||
? `${o.snapshot.reversal?.source.rows.length ?? 0} movimentos corrigidos`
|
||||
: `${quantity(o.quantity_milli)} ${o.snapshot.stock_item.unit}`}{' '}
|
||||
· {o.snapshot.warehouse.name}
|
||||
{o.snapshot.destination_warehouse &&
|
||||
` → ${o.snapshot.destination_warehouse.name}`}
|
||||
{o.destination && ` → ${o.destination}`}
|
||||
@@ -431,6 +566,115 @@ export default function Operations({
|
||||
</p>
|
||||
)}
|
||||
<p className="mt-2">{o.reason}</p>
|
||||
{correctedOperations[o.id] && (
|
||||
<p className="mt-2 text-sm font-medium">
|
||||
Operação estornada integralmente por{' '}
|
||||
{correctedOperations[o.id]}. O original
|
||||
permanece no histórico.
|
||||
</p>
|
||||
)}
|
||||
{o.snapshot.reversal && (
|
||||
<div className="mt-3 text-sm">
|
||||
<p>
|
||||
Origem:{' '}
|
||||
{
|
||||
o.snapshot.reversal.source
|
||||
.document.reference
|
||||
}
|
||||
</p>
|
||||
<ul className="mt-1 space-y-1">
|
||||
{o.snapshot.reversal.source.rows.map(
|
||||
(row) => (
|
||||
<li
|
||||
key={
|
||||
row.source_movement_id
|
||||
}
|
||||
>
|
||||
{row.warehouse_name} ·{' '}
|
||||
{row.quantity_milli > 0
|
||||
? '+'
|
||||
: ''}
|
||||
{quantity(
|
||||
row.quantity_milli,
|
||||
)}{' '}
|
||||
{
|
||||
o.snapshot
|
||||
.stock_item.unit
|
||||
}{' '}
|
||||
· Corrige movimento #
|
||||
{row.source_movement_id}
|
||||
</li>
|
||||
),
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
{(o.snapshot.lot_count ??
|
||||
o.snapshot.lot_adjustment) && (
|
||||
<details className="mt-3 text-sm">
|
||||
<summary className="cursor-pointer">
|
||||
Conferência por lote
|
||||
</summary>
|
||||
<ul className="mt-2 space-y-1">
|
||||
{(
|
||||
o.snapshot.lot_count ??
|
||||
o.snapshot.lot_adjustment
|
||||
)?.rows.map((row, index) => (
|
||||
<li key={row.lot_id ?? index}>
|
||||
{row.code ??
|
||||
'Por identificar'}{' '}
|
||||
· Referência:{' '}
|
||||
{quantity(
|
||||
row.previous_milli,
|
||||
)}{' '}
|
||||
· Contado:{' '}
|
||||
{quantity(
|
||||
row.counted_milli,
|
||||
)}{' '}
|
||||
· Diferença:{' '}
|
||||
{quantity(row.delta_milli)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
)}
|
||||
{o.snapshot.lot_partition && (
|
||||
<details className="mt-3 text-sm">
|
||||
<summary className="cursor-pointer">
|
||||
Lotes usados nesta operação
|
||||
</summary>
|
||||
<ul className="mt-2 space-y-1">
|
||||
{o.snapshot.lot_partition.plan.map(
|
||||
(lot) => (
|
||||
<li key={lot.lot_id}>
|
||||
{lot.code ??
|
||||
`Lote #${lot.lot_id}`}{' '}
|
||||
·{' '}
|
||||
{quantity(lot.quantity)}{' '}
|
||||
{
|
||||
o.snapshot
|
||||
.stock_item.unit
|
||||
}{' '}
|
||||
· Validade:{' '}
|
||||
{lot.expires_on ??
|
||||
'Sem prazo confirmado'}{' '}
|
||||
· Identificação #
|
||||
{lot.metadata_id}
|
||||
</li>
|
||||
),
|
||||
)}
|
||||
</ul>
|
||||
{o.kind === 'transfer' && (
|
||||
<p className="mt-2 text-muted-foreground">
|
||||
A entrada colocou o lote inteiro
|
||||
no destino em quarentena.
|
||||
Consulte a conferência actual de
|
||||
lotes para conhecer a
|
||||
disponibilidade.
|
||||
</p>
|
||||
)}
|
||||
</details>
|
||||
)}
|
||||
{o.snapshot.equipment && (
|
||||
<p className="mt-2">
|
||||
Equipamento no momento da saída:{' '}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Head, Link, useForm, router } from '@inertiajs/react';
|
||||
import { PageTitle, Panel, FormErrors, controlClass } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
type RecordRow = { id:number; record_key:string; version:number; state:string; reason:string; created_at:string; data:{ policy_key?:string; requester_id?:number; cost_center_id?:number; unit_price?:string; tax_rate?:string; needed_days?:number; valid_until?:string; message?:string; purchases?:{id:number;number:string;quantity_milli:number}[] }; snapshot:{item:{id:number;code?:string;name?:string};warehouse:{id:number;name?:string};requester?:{name:string};cost_center?:{code:string;name:string};origins?:{warehouse_request_id:number;destination:string;equipment:{code:string;description:string}|null;remaining_milli:number}[]} };
|
||||
type Props={ready:boolean;canPrepare:boolean;canReview:boolean;rules:RecordRow[];needs:RecordRow[];history:RecordRow[];policies:RecordRow[];requesters:{id:number;name:string;department_id:number}[];centers:{id:number;code:string;name:string;department_id:number}[]};
|
||||
const states:Record<string,string>={draft:'Por activar',approved:'Activa',suspended:'Suspensa',pending:'Necessidade pendente',created:'Rascunho criado',covered:'Reposição em curso',satisfied:'Disponibilidade suficiente'};
|
||||
function RuleForm({props,rule}:{props:Props;rule?:RecordRow}) {
|
||||
const form=useForm({operation_key:crypto.randomUUID(),record_key:rule?.record_key??null,version:rule?.version??0,action:'save',reason:'',data:{policy_key:rule?.data.policy_key??'',requester_id:rule?.data.requester_id?.toString()??'',cost_center_id:rule?.data.cost_center_id?.toString()??'',unit_price:rule?.data.unit_price??'',tax_rate:rule?.data.tax_rate??'',needed_days:rule?.data.needed_days?.toString()??'',valid_until:rule?.data.valid_until??''}});
|
||||
const requester=props.requesters.find(u=>u.id.toString()===form.data.data.requester_id);
|
||||
const set=(key:keyof typeof form.data.data,value:string)=>form.setData('data',{...form.data.data,[key]:value,...(key==='requester_id'?{cost_center_id:''}:{})});
|
||||
return <form className="grid gap-3 md:grid-cols-2" onSubmit={e=>{e.preventDefault();form.post('/stock/reposicao',{preserveState:'errors'});}}><FormErrors errors={form.errors}/>
|
||||
<label>Política aprovada · artigo/armazém<select required className={controlClass} value={form.data.data.policy_key} onChange={e=>set('policy_key',e.target.value)}><option value="">Seleccione</option>{props.policies.map(p=><option key={p.record_key} value={p.record_key}>{p.snapshot.item.code} · {p.snapshot.item.name} · {p.snapshot.warehouse.name}</option>)}</select></label>
|
||||
<label>Requisitante responsável<select required className={controlClass} value={form.data.data.requester_id} onChange={e=>set('requester_id',e.target.value)}><option value="">Seleccione</option>{props.requesters.map(u=><option key={u.id} value={u.id}>{u.name}</option>)}</select></label>
|
||||
<label>Centro de custo<select required className={controlClass} value={form.data.data.cost_center_id} onChange={e=>set('cost_center_id',e.target.value)}><option value="">Seleccione</option>{props.centers.filter(c=>c.department_id===requester?.department_id).map(c=><option key={c.id} value={c.id}>{c.code} · {c.name}</option>)}</select></label>
|
||||
<label>Preço estimado (MZN), se não existir no acordo<input inputMode="decimal" placeholder="Vazio: reutilizar acordo em MZN" className={controlClass} value={form.data.data.unit_price} onChange={e=>set('unit_price',e.target.value)}/></label>
|
||||
<label>Imposto estimado (%), se diferente do parâmetro da empresa<input inputMode="decimal" placeholder="Vazio: reutilizar parâmetro da empresa" className={controlClass} value={form.data.data.tax_rate} onChange={e=>set('tax_rate',e.target.value)}/></label>
|
||||
<label>Prazo pretendido após geração (dias)<input required type="number" min="0" max="366" className={controlClass} value={form.data.data.needed_days} onChange={e=>set('needed_days',e.target.value)}/></label>
|
||||
<label>Validade desta parametrização e estimativa<input required type="date" className={controlClass} value={form.data.data.valid_until} onChange={e=>set('valid_until',e.target.value)}/></label>
|
||||
<label>Fundamento<textarea required minLength={10} className={controlClass} value={form.data.reason} onChange={e=>form.setData('reason',e.target.value)}/></label>
|
||||
<p className="text-sm md:col-span-2">Mínimo, alvo, máximo e embalagem são reutilizados da política aprovada. A activação exige outro responsável. Alterar uma regra exige nova activação e afecta apenas novas gerações; documentos existentes conservam a sua origem.</p><Button disabled={form.processing}>Guardar para activação</Button></form>;
|
||||
}
|
||||
function Decision({rule,action}:{rule:RecordRow;action:'approve'|'suspend'}) {
|
||||
const form=useForm({operation_key:crypto.randomUUID(),record_key:rule.record_key,version:rule.version,action,reason:'',data:{}});
|
||||
return <form className="mt-3 flex flex-wrap gap-3" onSubmit={e=>{e.preventDefault();form.post('/stock/reposicao',{preserveState:'errors'});}}><FormErrors errors={form.errors}/><input aria-label="Fundamento da decisão" required minLength={10} placeholder="Fundamento da decisão" className={controlClass} value={form.data.reason} onChange={e=>form.setData('reason',e.target.value)}/><Button disabled={form.processing}>{action==='approve'?'Activar parametrização':'Suspender parametrização'}</Button></form>;
|
||||
}
|
||||
export default function Replenishment(props:Props){return <><Head title="Reposição automática"/><div className="space-y-6 p-6"><PageTitle eyebrow="Armazém e compras" title="Reposição automática" description="Reutilizar a política aprovada e preparar a compra quando houver falta ou atingir o mínimo. As aprovações de compra mantêm-se."/><div className="flex gap-4"><Link href="/stock/disponibilidade">Disponibilidade</Link><Link href="/stock/requisicoes">Requisições ao armazém</Link><Link href="/compras/fornecimento?view=calendar">Políticas de reposição</Link></div>
|
||||
{!props.ready?<Panel title="Instalação pendente"><p>Instale a reserva e reposição para activar estas regras.</p></Panel>:<>
|
||||
{props.canPrepare&&<Panel title="Parametrizar artigo e armazém"><RuleForm props={props}/></Panel>}
|
||||
<Panel title="Parametrizações">{props.rules.length===0?<p>Sem parametrizações. Não são assumidos requisitantes ou centros de custo.</p>:props.rules.map(r=><div className="mb-4 rounded border p-4" key={r.id}><p className="font-medium">{r.snapshot.item.code} · {r.snapshot.item.name} · {r.snapshot.warehouse.name}</p><p>{states[r.state]} · Versão {r.version} · {r.snapshot.requester?.name} · {r.snapshot.cost_center?.code}</p><p>Preço estimado {r.data.unit_price} MZN · Imposto {r.data.tax_rate}% · Validade {r.data.valid_until}</p>{props.canReview&&r.state==='draft'&&<Decision key={`approve:${r.id}`} rule={r} action="approve"/>}{props.canReview&&r.state==='approved'&&<Decision key={`suspend:${r.id}`} rule={r} action="suspend"/>}{props.canPrepare&&<details className="mt-3"><summary>Rever parametrização</summary><RuleForm key={r.id} props={props} rule={r}/></details>}</div>)}</Panel>
|
||||
<Panel title="Necessidades e compras associadas">{props.needs.length===0?<p>Sem necessidades registadas após alterações de stock ou activação de regras.</p>:props.needs.map(n=><div key={n.id} className="mb-4 rounded border p-4"><p className="font-medium">Artigo #{n.snapshot.item.id} · Armazém #{n.snapshot.warehouse.id} · {states[n.state]}</p><p>{n.data.message}</p>{n.snapshot.origins?.map((o,i)=><p key={i}><Link href={`/stock/requisicoes/${o.warehouse_request_id}`}>RA-{o.warehouse_request_id}</Link> · {o.destination}{o.equipment?` · ${o.equipment.code} · ${o.equipment.description}`:''} · Pendente {o.remaining_milli/1000}</p>)}{n.data.purchases?.map(p=><p key={p.id}><Link href={`/requisicoes/${p.id}`}>{p.number}</Link> · Quantidade original {p.quantity_milli/1000}</p>)}{(props.canPrepare||props.canReview)&&<Button variant="outline" className="mt-3" onClick={()=>router.post(`/stock/reposicao/${n.id}/avaliar`,{}, {preserveState:'errors'})}>Reavaliar necessidade</Button>}</div>)}</Panel>
|
||||
<Panel title="Histórico"><details><summary>Consultar versões e fundamentos</summary>{props.history.map(h=><p key={h.id} className="mt-2">#{h.id} · {h.created_at} · Versão {h.version} · {states[h.state]} · {h.reason}</p>)}</details></Panel></>}
|
||||
</div></>}
|
||||
@@ -0,0 +1,408 @@
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import {
|
||||
PageTitle,
|
||||
Panel,
|
||||
FormErrors,
|
||||
controlClass,
|
||||
} from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
type Line = {
|
||||
item: { code: string; name: string; unit: string };
|
||||
quantity_milli: number;
|
||||
destination: string;
|
||||
equipment: { code: string; description: string } | null;
|
||||
};
|
||||
type Event = {
|
||||
id: number;
|
||||
version: number;
|
||||
action: string;
|
||||
actor_id: number;
|
||||
reason: string;
|
||||
created_at: string;
|
||||
data: {
|
||||
actor?: { id: number; name: string };
|
||||
lines?: {
|
||||
index: number;
|
||||
quantity_milli: number;
|
||||
stock_operation_id: number;
|
||||
}[];
|
||||
delivery_event_id?: number;
|
||||
};
|
||||
};
|
||||
type Props = {
|
||||
record: {
|
||||
id: number;
|
||||
snapshot: {
|
||||
requester: { name: string };
|
||||
warehouse: { name: string };
|
||||
cost_center: { code: string; name: string };
|
||||
destination: string;
|
||||
reason: string;
|
||||
lines: Line[];
|
||||
};
|
||||
};
|
||||
progress: {
|
||||
state: string;
|
||||
version: number;
|
||||
remaining: number[];
|
||||
reserved: number[];
|
||||
cancelled: number[];
|
||||
reservation_ready: boolean;
|
||||
delivered: number[];
|
||||
partial_requested: boolean;
|
||||
partial_allowed: boolean;
|
||||
events: Event[];
|
||||
received_deliveries: number[];
|
||||
};
|
||||
ready: boolean;
|
||||
canSubmit: boolean;
|
||||
canReview: boolean;
|
||||
canDeliver: boolean;
|
||||
canReceive: boolean;
|
||||
canManageReservation: boolean;
|
||||
};
|
||||
const labels: Record<string, string> = {
|
||||
draft: 'Rascunho',
|
||||
submitted: 'Submetida',
|
||||
authorized: 'Autorizada',
|
||||
partial: 'Parcialmente entregue',
|
||||
delivered: 'Entregue',
|
||||
closed: 'Encerrada — recepção confirmada',
|
||||
rejected: 'Rejeitada',
|
||||
submit: 'Submissão',
|
||||
authorize: 'Autorização',
|
||||
reject: 'Rejeição',
|
||||
deliver: 'Entrega física',
|
||||
receive: 'Confirmação de recepção',
|
||||
reserve: 'Actualizar reserva de stock',
|
||||
cancel: 'Cancelar saldo e libertar reserva',
|
||||
cancelled: 'Saldo cancelado',
|
||||
};
|
||||
function Command({
|
||||
props,
|
||||
action,
|
||||
delivery,
|
||||
}: {
|
||||
props: Props;
|
||||
action: string;
|
||||
delivery?: number;
|
||||
}) {
|
||||
const form = useForm({
|
||||
operation_key: crypto.randomUUID(),
|
||||
version: props.progress.version,
|
||||
action,
|
||||
reason: '',
|
||||
partial_allowed: false,
|
||||
delivery_event_id: delivery,
|
||||
lines: props.progress.remaining
|
||||
.map((qty, index) => ({ index, quantity: '', remaining: qty }))
|
||||
.filter((line) => line.remaining > 0),
|
||||
});
|
||||
return (
|
||||
<details className="rounded border p-3 print:hidden">
|
||||
<summary className="cursor-pointer font-medium">
|
||||
{labels[action]}
|
||||
</summary>
|
||||
<form
|
||||
className="mt-3 space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.transform((values) => ({
|
||||
...values,
|
||||
lines:
|
||||
action === 'deliver'
|
||||
? values.lines
|
||||
.filter((line) => line.quantity !== '')
|
||||
.map(({ index, quantity }) => ({
|
||||
index,
|
||||
quantity,
|
||||
}))
|
||||
: undefined,
|
||||
}));
|
||||
form.post(`/stock/requisicoes/${props.record.id}/eventos`, {
|
||||
preserveState: 'errors',
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
{(action === 'submit' || action === 'authorize') && (
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.partial_allowed}
|
||||
disabled={
|
||||
action === 'authorize' &&
|
||||
!props.progress.partial_requested
|
||||
}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'partial_allowed',
|
||||
e.target.checked,
|
||||
)
|
||||
}
|
||||
/>
|
||||
{action === 'submit'
|
||||
? 'Aceito entregas parciais'
|
||||
: 'Permitir entregas parciais aceites pelo requisitante'}
|
||||
</label>
|
||||
)}
|
||||
{action === 'deliver' && (
|
||||
<>
|
||||
<p className="text-sm">
|
||||
Preencha só as quantidades entregues agora. A
|
||||
requisição é o documento de saída, sem factura. A
|
||||
data de registo é a data efectiva da entrega.{' '}
|
||||
{props.progress.partial_allowed
|
||||
? 'As quantidades não entregues mantêm-se pendentes.'
|
||||
: 'Esta autorização exige uma entrega integral.'}
|
||||
</p>
|
||||
{form.data.lines.map((line, i) => (
|
||||
<label className="block" key={line.index}>
|
||||
{
|
||||
props.record.snapshot.lines[line.index].item
|
||||
.code
|
||||
}{' '}
|
||||
· Pendente {line.remaining / 1000}{' '}
|
||||
{
|
||||
props.record.snapshot.lines[line.index].item
|
||||
.unit
|
||||
}
|
||||
<input
|
||||
inputMode="decimal"
|
||||
placeholder="Quantidade efectivamente entregue"
|
||||
className={controlClass}
|
||||
value={line.quantity}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'lines',
|
||||
form.data.lines.map((row, j) =>
|
||||
j === i
|
||||
? {
|
||||
...row,
|
||||
quantity:
|
||||
e.target.value,
|
||||
}
|
||||
: row,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
<label className="block">
|
||||
Fundamento / registo da intervenção
|
||||
<textarea
|
||||
required
|
||||
minLength={10}
|
||||
maxLength={4000}
|
||||
className={controlClass}
|
||||
value={form.data.reason}
|
||||
onChange={(e) => form.setData('reason', e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<Button disabled={form.processing}>{labels[action]}</Button>
|
||||
</form>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
export default function WarehouseRequest(props: Props) {
|
||||
const r = props.record;
|
||||
const p = props.progress;
|
||||
return (
|
||||
<>
|
||||
<Head title={`Requisição RA-${r.id}`} />
|
||||
<div className="space-y-6 p-6">
|
||||
<PageTitle
|
||||
eyebrow="Documento de saída interna · Sem factura"
|
||||
title={`Requisição RA-${r.id}`}
|
||||
description={`Estado: ${labels[p.state] ?? p.state}`}
|
||||
/>
|
||||
<div className="flex gap-4 print:hidden">
|
||||
<Link href="/stock/requisicoes">
|
||||
Requisições ao armazém
|
||||
</Link>
|
||||
<Button variant="outline" onClick={() => window.print()}>
|
||||
Imprimir requisição e entregas
|
||||
</Button>
|
||||
</div>
|
||||
<Panel title="Utilização e origem">
|
||||
<p>Requisitante: {r.snapshot.requester.name}</p>
|
||||
<p>Armazém: {r.snapshot.warehouse.name}</p>
|
||||
<p>
|
||||
Centro de custo: {r.snapshot.cost_center.code} ·{' '}
|
||||
{r.snapshot.cost_center.name}
|
||||
</p>
|
||||
<p>Local de utilização: {r.snapshot.destination}</p>
|
||||
<p>Finalidade: {r.snapshot.reason}</p>
|
||||
</Panel>
|
||||
<Panel title="Artigos e atendimento">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
{[
|
||||
'Artigo / unidade',
|
||||
'Destino',
|
||||
'Pedido',
|
||||
'Entregue',
|
||||
'Reservado',
|
||||
'Cancelado',
|
||||
'Pendente',
|
||||
].map((label) => (
|
||||
<th
|
||||
className="border-b p-3"
|
||||
key={label}
|
||||
>
|
||||
{label}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{r.snapshot.lines.map((line, index) => (
|
||||
<tr key={index}>
|
||||
<td className="border-b p-3">
|
||||
{line.item.code} · {line.item.name}{' '}
|
||||
({line.item.unit})
|
||||
</td>
|
||||
<td className="border-b p-3">
|
||||
{line.equipment
|
||||
? `${line.equipment.code} · ${line.equipment.description}`
|
||||
: line.destination}
|
||||
</td>
|
||||
<td className="border-b p-3">
|
||||
{line.quantity_milli / 1000}
|
||||
</td>
|
||||
<td className="border-b p-3">
|
||||
{p.delivered[index] / 1000}
|
||||
</td>
|
||||
<td className="border-b p-3">{p.reservation_ready ? p.reserved[index] / 1000 : 'Por instalar'}</td>
|
||||
<td className="border-b p-3">{p.cancelled[index] / 1000}</td>
|
||||
<td className="border-b p-3">
|
||||
{p.remaining[index] / 1000}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p className="mt-4 text-sm">
|
||||
{p.reservation_ready ? 'A autorização reserva o material utilizável disponível. Só a entrega confirmada reduz o stock. Retenções de qualidade e validade são revalidadas na entrega.' : 'Reserva de stock por instalar. A disponibilidade é revalidada na entrega.'}
|
||||
</p>
|
||||
</Panel>
|
||||
{!props.ready ? (
|
||||
<Panel title="Instalação pendente">
|
||||
<p>Autorização e entrega ainda não instaladas.</p>
|
||||
</Panel>
|
||||
) : (
|
||||
<div className="space-y-3 print:hidden">
|
||||
{props.canSubmit && (
|
||||
<Command
|
||||
key={`submit:${p.version}`}
|
||||
props={props}
|
||||
action="submit"
|
||||
/>
|
||||
)}
|
||||
{props.canReview && (
|
||||
<>
|
||||
<Command
|
||||
key={`authorize:${p.version}`}
|
||||
props={props}
|
||||
action="authorize"
|
||||
/>
|
||||
<Command
|
||||
key={`reject:${p.version}`}
|
||||
props={props}
|
||||
action="reject"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{props.canDeliver && (
|
||||
<Command
|
||||
key={`deliver:${p.version}`}
|
||||
props={props}
|
||||
action="deliver"
|
||||
/>
|
||||
)}
|
||||
{props.canManageReservation && p.reservation_ready && <>
|
||||
<Command key={`reserve:${p.version}`} props={props} action="reserve" />
|
||||
<Command key={`cancel:${p.version}`} props={props} action="cancel" />
|
||||
</>}
|
||||
</div>
|
||||
)}
|
||||
<Panel title="Decisões, entregas e recepção">
|
||||
{p.events.length === 0 ? (
|
||||
<p>Sem intervenções.</p>
|
||||
) : (
|
||||
p.events.map((event) => (
|
||||
<div
|
||||
key={event.id}
|
||||
className="mb-4 rounded border p-3"
|
||||
>
|
||||
<p className="font-medium">
|
||||
{labels[event.action]} · Registo #{event.id}{' '}
|
||||
·{' '}
|
||||
{event.data.actor?.name ??
|
||||
`Utilizador #${event.actor_id}`}
|
||||
</p>
|
||||
<p>{event.created_at}</p>
|
||||
<p className="whitespace-pre-wrap">
|
||||
{event.reason}
|
||||
</p>
|
||||
{event.action === 'deliver' && (
|
||||
<>
|
||||
<p>
|
||||
Documento de saída: RA-{r.id} ·
|
||||
Entrega #{event.id}
|
||||
</p>
|
||||
{event.data.lines?.map((line) => (
|
||||
<p key={line.index}>
|
||||
{
|
||||
r.snapshot.lines[line.index]
|
||||
.item.code
|
||||
}{' '}
|
||||
· {line.quantity_milli / 1000}{' '}
|
||||
{
|
||||
r.snapshot.lines[line.index]
|
||||
.item.unit
|
||||
}{' '}
|
||||
· Operação de stock #
|
||||
{line.stock_operation_id}
|
||||
</p>
|
||||
))}
|
||||
<p>
|
||||
{p.received_deliveries.includes(
|
||||
event.id,
|
||||
)
|
||||
? 'Recepção confirmada pelo requisitante'
|
||||
: 'Recepção por confirmar'}
|
||||
</p>
|
||||
{props.canReceive &&
|
||||
!p.received_deliveries.includes(
|
||||
event.id,
|
||||
) && (
|
||||
<Command
|
||||
key={`receive:${event.id}:${p.version}`}
|
||||
props={props}
|
||||
action="receive"
|
||||
delivery={event.id}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{event.action === 'receive' && (
|
||||
<p>
|
||||
Relativa à entrega #
|
||||
{event.data.delivery_event_id}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</Panel>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import {
|
||||
PageTitle,
|
||||
Panel,
|
||||
FormErrors,
|
||||
controlClass,
|
||||
} from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
type Item = { id: number; code: string; name: string; unit: string };
|
||||
type Line = {
|
||||
stock_item_id: string;
|
||||
quantity: string;
|
||||
use: string;
|
||||
equipment_id: string;
|
||||
};
|
||||
type Snapshot = {
|
||||
requester: { name: string };
|
||||
warehouse: { name: string };
|
||||
cost_center: { code: string; name: string };
|
||||
destination: string;
|
||||
reason: string;
|
||||
priority: string;
|
||||
lines: {
|
||||
item: Item;
|
||||
quantity_milli: number;
|
||||
use: string;
|
||||
destination: string;
|
||||
equipment: { code: string; description: string } | null;
|
||||
}[];
|
||||
};
|
||||
type Props = {
|
||||
ready: boolean;
|
||||
canPrepare: boolean;
|
||||
items: Item[];
|
||||
warehouses: { id: number; code: string; name: string }[];
|
||||
costCenters: { id: number; code: string; name: string }[];
|
||||
equipment: { id: number; code: string; description: string }[];
|
||||
records: null | {
|
||||
data: {
|
||||
id: number;
|
||||
status: string;
|
||||
snapshot: Snapshot;
|
||||
progress?: { state: string };
|
||||
}[];
|
||||
prev_page_url: string | null;
|
||||
next_page_url: string | null;
|
||||
};
|
||||
};
|
||||
const blank = (): Line => ({
|
||||
stock_item_id: '',
|
||||
quantity: '',
|
||||
use: 'internal',
|
||||
equipment_id: '',
|
||||
});
|
||||
export default function Requests(props: Props) {
|
||||
const form = useForm({
|
||||
operation_key: crypto.randomUUID(),
|
||||
warehouse_id: '',
|
||||
cost_center_id: '',
|
||||
destination: '',
|
||||
reason: '',
|
||||
priority: 'normal',
|
||||
lines: [blank()],
|
||||
});
|
||||
const line = (index: number, values: Partial<Line>) =>
|
||||
form.setData(
|
||||
'lines',
|
||||
form.data.lines.map((row, i) =>
|
||||
i === index ? { ...row, ...values } : row,
|
||||
),
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Head title="Requisições ao armazém" />
|
||||
<div className="space-y-6 p-6">
|
||||
<PageTitle
|
||||
eyebrow="Armazém e activos"
|
||||
title="Requisições ao armazém"
|
||||
description="Registo inicial com destino de utilização. Um rascunho não autoriza, reserva ou retira material."
|
||||
/>
|
||||
<p className="text-sm">
|
||||
Uso interno sem factura: a requisição autorizada acompanha a
|
||||
saída e as entregas. Reserva física exclusiva e geração
|
||||
automática de compra por falta ainda estão em implementação.
|
||||
A venda a terceiros pertence à composição SGF.
|
||||
</p>
|
||||
<Link href="/stock/disponibilidade">
|
||||
Consultar disponibilidade (conforme o seu acesso)
|
||||
</Link>
|
||||
{!props.ready ? (
|
||||
<Panel title="Instalação pendente">
|
||||
<p>
|
||||
O registo de requisições ainda não está instalado.
|
||||
</p>
|
||||
</Panel>
|
||||
) : (
|
||||
props.canPrepare && (
|
||||
<Panel title="Preparar rascunho">
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post('/stock/requisicoes', {
|
||||
preserveState: 'errors',
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<label>
|
||||
Armazém
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={form.data.warehouse_id}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'warehouse_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{props.warehouses.map((w) => (
|
||||
<option key={w.id} value={w.id}>
|
||||
{w.code} · {w.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Centro de custo
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={form.data.cost_center_id}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'cost_center_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Seleccione do seu departamento
|
||||
</option>
|
||||
{props.costCenters.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.code} · {c.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Onde será utilizado
|
||||
<input
|
||||
required
|
||||
className={controlClass}
|
||||
value={form.data.destination}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'destination',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Prioridade
|
||||
<select
|
||||
className={controlClass}
|
||||
value={form.data.priority}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'priority',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="normal">
|
||||
Normal
|
||||
</option>
|
||||
<option value="urgent">
|
||||
Urgente
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<label className="block">
|
||||
Finalidade/justificação
|
||||
<textarea
|
||||
required
|
||||
minLength={10}
|
||||
className={controlClass}
|
||||
value={form.data.reason}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'reason',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
{form.data.lines.map((row, index) => (
|
||||
<fieldset
|
||||
key={index}
|
||||
className="grid gap-3 rounded border p-3 md:grid-cols-2"
|
||||
>
|
||||
<legend>Artigo {index + 1}</legend>
|
||||
<label>
|
||||
Artigo do cadastro
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={row.stock_item_id}
|
||||
onChange={(e) =>
|
||||
line(index, {
|
||||
stock_item_id:
|
||||
e.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Seleccione
|
||||
</option>
|
||||
{props.items.map((item) => (
|
||||
<option
|
||||
key={item.id}
|
||||
value={item.id}
|
||||
>
|
||||
{item.code} ·{' '}
|
||||
{item.name} ({item.unit}
|
||||
)
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Quantidade
|
||||
<input
|
||||
required
|
||||
className={controlClass}
|
||||
inputMode="decimal"
|
||||
placeholder="Ex.: 2.500"
|
||||
value={row.quantity}
|
||||
onChange={(e) =>
|
||||
line(index, {
|
||||
quantity:
|
||||
e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Utilização
|
||||
<select
|
||||
className={controlClass}
|
||||
value={row.use}
|
||||
onChange={(e) =>
|
||||
line(index, {
|
||||
use: e.target.value,
|
||||
equipment_id: '',
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="internal">
|
||||
Uso interno no local
|
||||
indicado
|
||||
</option>
|
||||
<option value="equipment">
|
||||
Em equipamento
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
{row.use === 'equipment' && (
|
||||
<label>
|
||||
Equipamento de destino
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={row.equipment_id}
|
||||
onChange={(e) =>
|
||||
line(index, {
|
||||
equipment_id:
|
||||
e.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Seleccione do seu
|
||||
departamento
|
||||
</option>
|
||||
{props.equipment.map(
|
||||
(eq) => (
|
||||
<option
|
||||
key={eq.id}
|
||||
value={eq.id}
|
||||
>
|
||||
{eq.code} ·{' '}
|
||||
{eq.description}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{form.data.lines.length > 1 && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
form.setData(
|
||||
'lines',
|
||||
form.data.lines.filter(
|
||||
(_, i) =>
|
||||
i !== index,
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
Retirar linha
|
||||
</Button>
|
||||
)}
|
||||
</fieldset>
|
||||
))}
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={form.data.lines.length >= 50}
|
||||
onClick={() =>
|
||||
form.setData('lines', [
|
||||
...form.data.lines,
|
||||
blank(),
|
||||
])
|
||||
}
|
||||
>
|
||||
Acrescentar artigo
|
||||
</Button>
|
||||
<Button
|
||||
disabled={
|
||||
form.processing ||
|
||||
props.costCenters.length === 0
|
||||
}
|
||||
>
|
||||
Guardar rascunho
|
||||
</Button>
|
||||
</div>
|
||||
{props.costCenters.length === 0 && (
|
||||
<p>
|
||||
É necessário um centro de custo
|
||||
associado ao seu departamento.
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
</Panel>
|
||||
)
|
||||
)}
|
||||
<Panel title="Requisições registadas">
|
||||
{!props.records?.data.length ? (
|
||||
<p>Sem registos no seu âmbito.</p>
|
||||
) : (
|
||||
props.records.data.map((record) => (
|
||||
<details
|
||||
key={record.id}
|
||||
className="mb-3 rounded border p-4"
|
||||
>
|
||||
<summary className="cursor-pointer font-medium">
|
||||
RA-{record.id} ·{' '}
|
||||
{
|
||||
(
|
||||
{
|
||||
draft: 'Rascunho',
|
||||
submitted: 'Submetida',
|
||||
authorized: 'Autorizada',
|
||||
partial:
|
||||
'Parcialmente entregue',
|
||||
delivered: 'Entregue',
|
||||
closed: 'Encerrada',
|
||||
rejected: 'Rejeitada',
|
||||
} as Record<string, string>
|
||||
)[record.progress?.state ?? 'draft']
|
||||
}{' '}
|
||||
· {record.snapshot.requester.name} ·{' '}
|
||||
{record.snapshot.warehouse.name}
|
||||
</summary>
|
||||
<div className="mt-3 space-y-2 text-sm">
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/stock/requisicoes/${record.id}`}
|
||||
>
|
||||
Abrir requisição, autorizar ou registar
|
||||
entrega
|
||||
</Link>
|
||||
<p>
|
||||
Destino: {record.snapshot.destination}
|
||||
</p>
|
||||
<p>
|
||||
Centro:{' '}
|
||||
{record.snapshot.cost_center.code} ·{' '}
|
||||
{record.snapshot.cost_center.name}
|
||||
</p>
|
||||
<p>Finalidade: {record.snapshot.reason}</p>
|
||||
{record.snapshot.lines.map(
|
||||
(item, index) => (
|
||||
<p key={index}>
|
||||
{item.item.code} ·{' '}
|
||||
{item.item.name} ·{' '}
|
||||
{item.quantity_milli / 1000}{' '}
|
||||
{item.item.unit} ·{' '}
|
||||
{item.equipment
|
||||
? `Equipamento ${item.equipment.code} · ${item.equipment.description}`
|
||||
: item.destination}
|
||||
</p>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
</details>
|
||||
))
|
||||
)}
|
||||
<div className="mt-4 flex gap-4">
|
||||
{props.records?.prev_page_url && (
|
||||
<Link href={props.records.prev_page_url}>
|
||||
Anterior
|
||||
</Link>
|
||||
)}
|
||||
{props.records?.next_page_url && (
|
||||
<Link href={props.records.next_page_url}>
|
||||
Seguinte
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</Panel>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
import { InventoryEventActions } from '@/components/inventory-event-actions';
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import {
|
||||
FormErrors,
|
||||
PageTitle,
|
||||
Panel,
|
||||
controlClass,
|
||||
} from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
type Row = {
|
||||
source_movement_id: number;
|
||||
warehouse_id: number;
|
||||
warehouse_name: string;
|
||||
original_quantity_milli: number;
|
||||
quantity_milli: number;
|
||||
original_type: string;
|
||||
lots: { lot_id: number | null; code: string | null; quantity: number }[];
|
||||
};
|
||||
type Entry = {
|
||||
id: number;
|
||||
record_key: string;
|
||||
version: number;
|
||||
state: string;
|
||||
reason: string;
|
||||
created_at: string;
|
||||
data: {
|
||||
reference: string;
|
||||
source_kind: string;
|
||||
source_operation_id: number | null;
|
||||
receipt_item_id: number | null;
|
||||
event?: { event_on: string; evidence: string };
|
||||
};
|
||||
snapshot: {
|
||||
execution_lots?: {
|
||||
lot_id: number;
|
||||
movement_id: number;
|
||||
quantity: number;
|
||||
}[];
|
||||
contributors: number[];
|
||||
reviewed_by?: number;
|
||||
actor: { name: string };
|
||||
source: {
|
||||
document: { reference: string };
|
||||
item: { code: string; name: string; unit: string };
|
||||
rows: Row[];
|
||||
};
|
||||
};
|
||||
};
|
||||
type Props = {
|
||||
ready: boolean;
|
||||
actorId: number;
|
||||
today: string;
|
||||
canViewDispositions: boolean;
|
||||
capabilities: Record<string, boolean>;
|
||||
records: Entry[];
|
||||
operations: { id: number; label: string }[];
|
||||
receipts: { id: number; label: string }[];
|
||||
history: Record<string, Entry[]>;
|
||||
};
|
||||
const qty = (milli: number) =>
|
||||
(milli / 1000).toLocaleString('pt-MZ', { maximumFractionDigits: 3 });
|
||||
const states: Record<string, string> = {
|
||||
draft: 'Em preparação',
|
||||
returned: 'Para actualização',
|
||||
approved: 'Aprovado para estorno',
|
||||
executed: 'Estorno integral registado',
|
||||
};
|
||||
|
||||
function Prepare({ props, old }: { props: Props; old?: Entry }) {
|
||||
const form = useForm({
|
||||
operation_key: crypto.randomUUID(),
|
||||
record_key: old?.record_key,
|
||||
version: old?.version ?? 0,
|
||||
action: 'save',
|
||||
reason: '',
|
||||
data: {
|
||||
reference: old?.data.reference ?? '',
|
||||
source_kind: old?.data.source_kind ?? 'operation',
|
||||
source_operation_id: old?.data.source_operation_id
|
||||
? String(old.data.source_operation_id)
|
||||
: '',
|
||||
receipt_item_id: old?.data.receipt_item_id
|
||||
? String(old.data.receipt_item_id)
|
||||
: '',
|
||||
},
|
||||
});
|
||||
return (
|
||||
<form
|
||||
className="grid gap-4 md:grid-cols-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post('/stock/estornos');
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
<label className="grid gap-1 text-sm">
|
||||
Origem
|
||||
<select
|
||||
className={controlClass}
|
||||
value={form.data.data.source_kind}
|
||||
onChange={(e) =>
|
||||
form.setData('data', {
|
||||
...form.data.data,
|
||||
source_kind: e.target.value,
|
||||
source_operation_id: '',
|
||||
receipt_item_id: '',
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="operation">
|
||||
Saída, transferência, ajuste, devolução ou abate
|
||||
</option>
|
||||
<option value="receipt">Linha física de recepção</option>
|
||||
</select>
|
||||
</label>
|
||||
{form.data.data.source_kind === 'operation' ? (
|
||||
<label className="grid gap-1 text-sm">
|
||||
Operação original
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={form.data.data.source_operation_id}
|
||||
onChange={(e) =>
|
||||
form.setData('data', {
|
||||
...form.data.data,
|
||||
source_operation_id: e.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Seleccione a operação a corrigir
|
||||
</option>
|
||||
{props.operations.map((op) => (
|
||||
<option key={op.id} value={op.id}>
|
||||
{op.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
) : (
|
||||
<label className="grid gap-1 text-sm">
|
||||
Linha de recepção original
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={form.data.data.receipt_item_id}
|
||||
onChange={(e) =>
|
||||
form.setData('data', {
|
||||
...form.data.data,
|
||||
receipt_item_id: e.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione a linha a anular</option>
|
||||
{props.receipts.map((receipt) => (
|
||||
<option key={receipt.id} value={receipt.id}>
|
||||
{receipt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<label className="grid gap-1 text-sm">
|
||||
Referência única do documento de correcção
|
||||
<input
|
||||
required
|
||||
maxLength={100}
|
||||
className={controlClass}
|
||||
value={form.data.data.reference}
|
||||
onChange={(e) =>
|
||||
form.setData('data', {
|
||||
...form.data.data,
|
||||
reference: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="grid gap-1 text-sm md:col-span-2">
|
||||
Erro identificado e evidência da correcção
|
||||
<textarea
|
||||
required
|
||||
minLength={10}
|
||||
className={controlClass}
|
||||
value={form.data.reason}
|
||||
onChange={(e) => form.setData('reason', e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<Button disabled={form.processing}>
|
||||
Preparar estorno integral
|
||||
</Button>
|
||||
<p className="text-sm text-muted-foreground md:col-span-2">
|
||||
Artigo, locais, lotes e quantidades são reutilizados
|
||||
integralmente da origem. O registo original permanece no
|
||||
histórico. Não use estorno para simular consumo, devolução
|
||||
parcial ou uma operação nova.
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
function RecordActions({ props, record }: { props: Props; record: Entry }) {
|
||||
const choices: { value: string; label: string }[] = [];
|
||||
if (
|
||||
props.capabilities.review &&
|
||||
!record.snapshot.contributors.includes(props.actorId)
|
||||
) {
|
||||
if (['draft', 'returned'].includes(record.state))
|
||||
choices.push({ value: 'approve', label: 'Conferir e aprovar' });
|
||||
if (['draft', 'returned', 'approved'].includes(record.state))
|
||||
choices.push({
|
||||
value: 'return',
|
||||
label: 'Devolver para actualização',
|
||||
});
|
||||
}
|
||||
if (
|
||||
props.capabilities.execute &&
|
||||
record.state === 'approved' &&
|
||||
record.snapshot.reviewed_by !== props.actorId
|
||||
)
|
||||
choices.push({ value: 'execute', label: 'Confirmar estorno integral' });
|
||||
return (
|
||||
<InventoryEventActions
|
||||
route="/stock/estornos"
|
||||
record={record}
|
||||
choices={choices}
|
||||
today={props.today}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Reversals(props: Props) {
|
||||
return (
|
||||
<>
|
||||
<Head title="Estornos de stock" />
|
||||
<div className="mx-auto flex w-full max-w-6xl flex-col gap-6 p-5 lg:p-8">
|
||||
<PageTitle
|
||||
eyebrow="Armazém"
|
||||
title="Estornos de stock"
|
||||
description="Corrigir por referência ao original, sem apagar documentos nem repetir quantidades."
|
||||
/>
|
||||
{props.canViewDispositions && (
|
||||
<Link
|
||||
href="/stock/ocorrencias"
|
||||
className="text-sm underline"
|
||||
>
|
||||
Devoluções e abates
|
||||
</Link>
|
||||
)}
|
||||
<Panel title="Antes de corrigir">
|
||||
<p className="text-sm">
|
||||
O estorno é integral e só pode ocorrer uma vez por
|
||||
origem. A preparação, aprovação e comprovação da
|
||||
execução têm responsabilidades separadas. Quantidades
|
||||
repostas em locais com controlo por lote ficam em
|
||||
quarentena, incluindo saldo anterior da mesma
|
||||
identidade. As retiradas exigem a quantidade física dos
|
||||
lotes originais.
|
||||
</p>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
A correcção actualiza o stock, a satisfação de reservas
|
||||
e as quantidades efectivas de recepção. Não cria
|
||||
crédito, restituição ou estorno financeiro. Documentos e
|
||||
obrigações já validados precisam de conferência própria
|
||||
em Finanças. Não há estorno parcial, estorno de outro
|
||||
estorno ou de aceitação de serviços neste percurso.
|
||||
</p>
|
||||
</Panel>
|
||||
{!props.ready ? (
|
||||
<Panel title="Instalação pendente">
|
||||
<p>
|
||||
O diário de stock ainda não está instalado neste
|
||||
ambiente.
|
||||
</p>
|
||||
</Panel>
|
||||
) : (
|
||||
<>
|
||||
{props.capabilities.prepare && (
|
||||
<Panel title="Preparar correcção">
|
||||
<Prepare props={props} />
|
||||
</Panel>
|
||||
)}
|
||||
{props.records.map((record) => (
|
||||
<Panel
|
||||
key={record.id}
|
||||
title={`${record.data.reference} · ${states[record.state]}`}
|
||||
description={`Origem: ${record.snapshot.source.document.reference}`}
|
||||
>
|
||||
<p className="text-sm">
|
||||
{record.snapshot.source.item.code} ·{' '}
|
||||
{record.snapshot.source.item.name}
|
||||
</p>
|
||||
<ul className="mt-3 space-y-2 text-sm">
|
||||
{record.snapshot.source.rows.map((row) => (
|
||||
<li key={row.source_movement_id}>
|
||||
{row.warehouse_name} · Movimento
|
||||
original #{row.source_movement_id}:{' '}
|
||||
{qty(row.original_quantity_milli)} →
|
||||
correcção{' '}
|
||||
{row.quantity_milli > 0 ? '+' : ''}
|
||||
{qty(row.quantity_milli)}{' '}
|
||||
{record.snapshot.source.item.unit}
|
||||
{row.lots.length > 0 && (
|
||||
<ul className="mt-1 ml-4 list-disc">
|
||||
{row.lots.map((lot, i) => (
|
||||
<li
|
||||
key={
|
||||
lot.lot_id ?? i
|
||||
}
|
||||
>
|
||||
{lot.code ??
|
||||
(lot.lot_id
|
||||
? `Lote #${lot.lot_id}`
|
||||
: 'Identidade desconhecida a conferir')}{' '}
|
||||
·{' '}
|
||||
{qty(lot.quantity)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="mt-3 text-sm text-muted-foreground">
|
||||
{record.reason}
|
||||
</p>
|
||||
{props.capabilities.prepare &&
|
||||
['draft', 'returned'].includes(
|
||||
record.state,
|
||||
) && (
|
||||
<details className="mt-3">
|
||||
<summary className="cursor-pointer text-sm">
|
||||
Actualizar preparação
|
||||
</summary>
|
||||
<Prepare
|
||||
props={props}
|
||||
old={record}
|
||||
/>
|
||||
</details>
|
||||
)}
|
||||
<RecordActions props={props} record={record} />
|
||||
{record.state === 'executed' && (
|
||||
<p className="mt-3 text-sm font-medium">
|
||||
Correcção em{' '}
|
||||
{record.data.event?.event_on} ·{' '}
|
||||
{record.data.event?.evidence}. O
|
||||
original foi preservado e não pode ser
|
||||
estornado novamente.
|
||||
</p>
|
||||
)}
|
||||
{record.snapshot.execution_lots &&
|
||||
record.snapshot.execution_lots.length >
|
||||
0 && (
|
||||
<details className="mt-3 text-sm">
|
||||
<summary className="cursor-pointer">
|
||||
Repartição efectiva do estorno
|
||||
por lote
|
||||
</summary>
|
||||
<ul className="mt-2 space-y-1">
|
||||
{record.snapshot.execution_lots.map(
|
||||
(lot) => (
|
||||
<li
|
||||
key={`${lot.movement_id}-${lot.lot_id}`}
|
||||
>
|
||||
Lote #{lot.lot_id} ·{' '}
|
||||
{lot.quantity > 0
|
||||
? '+'
|
||||
: ''}
|
||||
{qty(lot.quantity)}{' '}
|
||||
{
|
||||
record.snapshot
|
||||
.source.item
|
||||
.unit
|
||||
}{' '}
|
||||
· Movimento #
|
||||
{lot.movement_id}
|
||||
</li>
|
||||
),
|
||||
)}
|
||||
</ul>
|
||||
</details>
|
||||
)}
|
||||
<details className="mt-4 text-sm">
|
||||
<summary className="cursor-pointer">
|
||||
Histórico preservado
|
||||
</summary>
|
||||
<ul className="mt-2 space-y-2">
|
||||
{props.history[record.record_key]?.map(
|
||||
(version) => (
|
||||
<li key={version.id}>
|
||||
Versão {version.version} ·{' '}
|
||||
{states[version.state]} ·{' '}
|
||||
{
|
||||
version.snapshot.actor
|
||||
.name
|
||||
}{' '}
|
||||
· {version.created_at} ·{' '}
|
||||
{version.reason}
|
||||
</li>
|
||||
),
|
||||
)}
|
||||
</ul>
|
||||
</details>
|
||||
</Panel>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user