609 lines
24 KiB
TypeScript
609 lines
24 KiB
TypeScript
import { Head, Link, useForm } from '@inertiajs/react';
|
|
import {
|
|
FormErrors,
|
|
PageTitle,
|
|
Panel,
|
|
controlClass,
|
|
} from '@/components/procurement';
|
|
import { Button } from '@/components/ui/button';
|
|
import SupplyPagination, {
|
|
type SupplyPageInfo,
|
|
} from '@/components/supply-pagination';
|
|
|
|
type Analysis = {
|
|
days: number;
|
|
total_milli: number;
|
|
daily_mean_milli: string;
|
|
active_days: number;
|
|
zero_balance_days: number;
|
|
negative_balance_days: number;
|
|
invalid_issue: boolean;
|
|
opening_milli: number;
|
|
movement_count: number;
|
|
movement_types: Record<string, number>;
|
|
convention: string;
|
|
series: {
|
|
date: string;
|
|
consumption_milli: number;
|
|
balance_milli: number;
|
|
}[];
|
|
};
|
|
type HistoryRecord = {
|
|
canApprove?: boolean;
|
|
canReturn?: boolean;
|
|
canSuspend?: boolean;
|
|
id: number;
|
|
record_key: string;
|
|
version: number;
|
|
state: string;
|
|
reason: string;
|
|
created_at: string;
|
|
data: {
|
|
stock_item_id: number;
|
|
warehouse_id: number;
|
|
purpose: string;
|
|
period_from: string;
|
|
period_until: string;
|
|
quality: string;
|
|
pattern: string;
|
|
};
|
|
snapshot: {
|
|
item: { code: string; name: string; unit: string };
|
|
warehouse: { name: string };
|
|
analysis: Analysis;
|
|
contributors: number[];
|
|
actor: { name: string };
|
|
};
|
|
};
|
|
type Props = {
|
|
recordPagination?: SupplyPageInfo | null;
|
|
focusRecordId?: number | null;
|
|
focusChanged?: boolean;
|
|
ready: boolean;
|
|
actorId: number;
|
|
canPrepare: boolean;
|
|
canReview: boolean;
|
|
records: HistoryRecord[];
|
|
history: Record<string, HistoryRecord[]>;
|
|
items: { id: number; code: string; name: string; unit: string }[];
|
|
warehouses: { id: number; code: string; name: string }[];
|
|
defaultPeriod: { from: string; until: string };
|
|
};
|
|
const states: Record<string, string> = {
|
|
draft: 'Para conferência',
|
|
returned: 'Devolvida para actualização',
|
|
approved: 'Análise conferida',
|
|
suspended: 'Análise suspensa',
|
|
};
|
|
const quality: Record<string, string> = {
|
|
unknown: 'Cobertura por confirmar',
|
|
complete: 'Cobertura completa sem procura oculta conhecida',
|
|
incomplete: 'Período incompleto ou âmbito misto não separado',
|
|
stockout: 'Ruptura ou procura não satisfeita conhecida',
|
|
};
|
|
const patterns: Record<string, string> = {
|
|
unknown: 'Padrão por confirmar',
|
|
regular: 'Regular — média simples aplicável',
|
|
seasonal: 'Sazonal — exige método próprio',
|
|
intermittent: 'Intermitente — exige método próprio',
|
|
};
|
|
const movementNames: Record<string, string> = {
|
|
issue: 'Saídas de consumo',
|
|
receipt_in: 'Recepções',
|
|
transfer_in: 'Transferências de entrada',
|
|
transfer_out: 'Transferências de saída',
|
|
adjustment: 'Ajustes',
|
|
adjustment_in: 'Ajustes de entrada por lote',
|
|
adjustment_out: 'Ajustes de saída por lote',
|
|
supplier_return: 'Devoluções ao fornecedor',
|
|
write_off: 'Abates físicos',
|
|
reversal_in: 'Estornos de entrada',
|
|
reversal_out: 'Estornos de saída',
|
|
count: 'Contagens',
|
|
};
|
|
const qty = (milli: number | string, mean = false) =>
|
|
(Number(milli) / 1000).toLocaleString('pt-MZ', {
|
|
maximumFractionDigits: mean ? 9 : 3,
|
|
});
|
|
|
|
function Prepare({ props, old }: { props: Props; old?: HistoryRecord }) {
|
|
const form = useForm({
|
|
operation_key: crypto.randomUUID(),
|
|
record_key: old?.record_key,
|
|
version: old?.version ?? 0,
|
|
action: 'save',
|
|
reason: '',
|
|
data: {
|
|
stock_item_id: old ? String(old.data.stock_item_id) : '',
|
|
warehouse_id: old ? String(old.data.warehouse_id) : '',
|
|
purpose: old?.data.purpose ?? 'internal',
|
|
period_from: old?.data.period_from ?? props.defaultPeriod.from,
|
|
period_until: old?.data.period_until ?? props.defaultPeriod.until,
|
|
quality: old?.data.quality ?? 'unknown',
|
|
pattern: old?.data.pattern ?? 'unknown',
|
|
},
|
|
});
|
|
const select = (
|
|
key: keyof typeof form.data.data,
|
|
label: string,
|
|
options: [string, string][],
|
|
disabled = false,
|
|
) => (
|
|
<label className="grid gap-1 text-sm">
|
|
{label}
|
|
<select
|
|
className={controlClass}
|
|
required
|
|
disabled={disabled}
|
|
value={form.data.data[key]}
|
|
onChange={(e) =>
|
|
form.setData('data', {
|
|
...form.data.data,
|
|
[key]: e.target.value,
|
|
})
|
|
}
|
|
>
|
|
{options.map(([value, text]) => (
|
|
<option key={value} value={value}>
|
|
{text}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
);
|
|
return (
|
|
<form
|
|
className="mt-4 space-y-4"
|
|
onSubmit={(e) => {
|
|
e.preventDefault();
|
|
form.post('/compras/fornecimento/history', {
|
|
preserveScroll: true,
|
|
});
|
|
}}
|
|
>
|
|
<FormErrors errors={form.errors} />
|
|
<div className="grid gap-4 md:grid-cols-2">
|
|
{select(
|
|
'stock_item_id',
|
|
'Artigo existente',
|
|
[
|
|
['', 'Seleccionar artigo'],
|
|
...props.items.map(
|
|
(i) =>
|
|
[
|
|
String(i.id),
|
|
`${i.code} · ${i.name} (${i.unit})`,
|
|
] as [string, string],
|
|
),
|
|
],
|
|
Boolean(old),
|
|
)}
|
|
{select(
|
|
'warehouse_id',
|
|
'Local de armazenamento',
|
|
[
|
|
['', 'Seleccionar armazém'],
|
|
...props.warehouses.map(
|
|
(w) =>
|
|
[String(w.id), `${w.code} · ${w.name}`] as [
|
|
string,
|
|
string,
|
|
],
|
|
),
|
|
],
|
|
Boolean(old),
|
|
)}
|
|
{select(
|
|
'purpose',
|
|
'Finalidade dos consumos analisados',
|
|
[
|
|
['internal', 'Uso interno e reposição'],
|
|
['resale', 'Revenda'],
|
|
],
|
|
Boolean(old),
|
|
)}
|
|
<div className="grid gap-3 sm:grid-cols-2">
|
|
<label className="grid gap-1 text-sm">
|
|
Desde
|
|
<input
|
|
type="date"
|
|
className={controlClass}
|
|
required
|
|
value={form.data.data.period_from}
|
|
onChange={(e) =>
|
|
form.setData('data', {
|
|
...form.data.data,
|
|
period_from: e.target.value,
|
|
})
|
|
}
|
|
/>
|
|
</label>
|
|
<label className="grid gap-1 text-sm">
|
|
Até (dia completo)
|
|
<input
|
|
type="date"
|
|
className={controlClass}
|
|
required
|
|
value={form.data.data.period_until}
|
|
onChange={(e) =>
|
|
form.setData('data', {
|
|
...form.data.data,
|
|
period_until: e.target.value,
|
|
})
|
|
}
|
|
/>
|
|
</label>
|
|
</div>
|
|
{select(
|
|
'quality',
|
|
'Cobertura do histórico',
|
|
Object.entries(quality),
|
|
)}
|
|
{select(
|
|
'pattern',
|
|
'Padrão observado',
|
|
Object.entries(patterns),
|
|
)}
|
|
</div>
|
|
<p className="text-sm text-muted-foreground">
|
|
O sistema calcula os valores a partir dos movimentos. Confirme a
|
|
finalidade e a cobertura do período; quando as saídas misturam
|
|
finalidades sem separação, assinale cobertura incompleta.
|
|
</p>
|
|
<label className="grid gap-1 text-sm">
|
|
Evidências e fundamento da cobertura/padrão
|
|
<textarea
|
|
className="rounded-lg border p-3"
|
|
required
|
|
minLength={10}
|
|
maxLength={4000}
|
|
value={form.data.reason}
|
|
onChange={(e) => form.setData('reason', e.target.value)}
|
|
/>
|
|
</label>
|
|
<Button disabled={form.processing || !props.ready}>
|
|
Calcular e guardar análise para conferência
|
|
</Button>
|
|
</form>
|
|
);
|
|
}
|
|
|
|
function Facts({
|
|
record: r,
|
|
series = false,
|
|
}: {
|
|
record: HistoryRecord;
|
|
series?: boolean;
|
|
}) {
|
|
const a = r.snapshot.analysis;
|
|
return (
|
|
<div className="space-y-3 text-sm">
|
|
<p>
|
|
{r.data.period_from} a {r.data.period_until} · {a.days} dias
|
|
corridos ·{' '}
|
|
{r.data.purpose === 'resale' ? 'Revenda' : 'Uso interno'}
|
|
</p>
|
|
<div className="grid gap-3 md:grid-cols-4">
|
|
<p>
|
|
Consumo registado
|
|
<br />
|
|
<strong>
|
|
{qty(a.total_milli)} {r.snapshot.item.unit}
|
|
</strong>
|
|
</p>
|
|
<p>
|
|
Média observada por dia
|
|
<br />
|
|
<strong>
|
|
{qty(a.daily_mean_milli, true)} {r.snapshot.item.unit}
|
|
</strong>
|
|
</p>
|
|
<p>
|
|
Dias com consumo
|
|
<br />
|
|
<strong>
|
|
{a.active_days} de {a.days}
|
|
</strong>
|
|
</p>
|
|
<p>
|
|
Saldo final nulo
|
|
<br />
|
|
<strong>{a.zero_balance_days} dias</strong>
|
|
</p>
|
|
</div>
|
|
<p>
|
|
{quality[r.data.quality]} · {patterns[r.data.pattern]}
|
|
</p>
|
|
{(a.invalid_issue ||
|
|
a.negative_balance_days > 0 ||
|
|
a.opening_milli < 0) && (
|
|
<p className="font-medium">
|
|
Foram detectadas inconsistências de movimentos ou saldos
|
|
negativos. Reconcilie o razão antes de reutilizar a média.
|
|
</p>
|
|
)}
|
|
{a.total_milli === 0 && (
|
|
<p className="font-medium">
|
|
Não há consumo registado neste período. Só é considerado
|
|
consumo zero confirmado após conferência da cobertura
|
|
completa; ausência de saídas não prova ausência de procura.
|
|
</p>
|
|
)}
|
|
{r.state === 'approved' &&
|
|
(r.data.quality !== 'complete' ||
|
|
r.data.pattern !== 'regular') && (
|
|
<p className="font-medium">
|
|
A análise está conferida, mas não pode alimentar
|
|
automaticamente uma média simples. Mantém-se o
|
|
planeamento manual ou por necessidades conhecidas.
|
|
</p>
|
|
)}
|
|
{series && (
|
|
<details>
|
|
<summary className="cursor-pointer font-medium">
|
|
Consultar dias e movimentos considerados
|
|
</summary>
|
|
<div className="mt-3 space-y-3">
|
|
<p>{a.convention}</p>
|
|
<p>
|
|
{a.movement_count} movimentos no período ·{' '}
|
|
{Object.entries(a.movement_types)
|
|
.map(
|
|
([type, count]) =>
|
|
`${movementNames[type] ?? 'Outro movimento'}: ${count}`,
|
|
)
|
|
.join(' · ') || 'Sem movimentos no período'}
|
|
</p>
|
|
<p className="text-muted-foreground">
|
|
Dias sem saída entram no denominador. Saldo final
|
|
positivo não prova ausência de rupturas durante o
|
|
dia; a conferência humana verifica lacunas e procura
|
|
não satisfeita.
|
|
</p>
|
|
<div className="max-h-72 overflow-auto">
|
|
<table className="w-full">
|
|
<thead>
|
|
<tr>
|
|
<th className="text-left">Data</th>
|
|
<th className="text-right">Consumo</th>
|
|
<th className="text-right">
|
|
Saldo final
|
|
</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{a.series.map((day) => (
|
|
<tr key={day.date}>
|
|
<td>{day.date}</td>
|
|
<td className="text-right">
|
|
{qty(day.consumption_milli)}
|
|
</td>
|
|
<td className="text-right">
|
|
{qty(day.balance_milli)}
|
|
</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
</details>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function Decision({
|
|
props,
|
|
record: r,
|
|
}: {
|
|
props: Props;
|
|
record: HistoryRecord;
|
|
}) {
|
|
const form = useForm({
|
|
operation_key: crypto.randomUUID(),
|
|
record_key: r.record_key,
|
|
version: r.version,
|
|
action: '',
|
|
reason: '',
|
|
data: { confirm_scope: false },
|
|
});
|
|
return (
|
|
<div className="mt-4 space-y-4">
|
|
{props.canPrepare && ['draft', 'returned'].includes(r.state) && (
|
|
<details>
|
|
<summary className="cursor-pointer text-sm font-medium">
|
|
Actualizar análise e evidências
|
|
</summary>
|
|
<Prepare props={props} old={r} />
|
|
</details>
|
|
)}
|
|
{(r.canApprove || r.canReturn || r.canSuspend) && (
|
|
<>
|
|
<label className="grid gap-1 text-sm">
|
|
Decisão da minha responsabilidade
|
|
<select
|
|
className={controlClass}
|
|
value={form.data.action}
|
|
onChange={(e) =>
|
|
form.setData('action', e.target.value)
|
|
}
|
|
>
|
|
<option value="">Seleccionar acção</option>
|
|
{r.canSuspend && (
|
|
<option value="suspend">
|
|
Suspender reutilização
|
|
</option>
|
|
)}
|
|
{r.canApprove && (
|
|
<option value="approve">
|
|
Conferir e aprovar análise
|
|
</option>
|
|
)}
|
|
{r.canReturn && (
|
|
<option value="return">
|
|
Devolver para correcção
|
|
</option>
|
|
)}
|
|
</select>
|
|
</label>
|
|
{form.data.action && (
|
|
<form
|
|
className="space-y-3"
|
|
onSubmit={(e) => {
|
|
e.preventDefault();
|
|
form.post('/compras/fornecimento/history', {
|
|
preserveScroll: true,
|
|
});
|
|
}}
|
|
>
|
|
<FormErrors errors={form.errors} />
|
|
{form.data.action === 'approve' && (
|
|
<label className="flex items-start gap-2 text-sm">
|
|
<input
|
|
type="checkbox"
|
|
required
|
|
checked={form.data.data.confirm_scope}
|
|
onChange={(e) =>
|
|
form.setData('data', {
|
|
confirm_scope: e.target.checked,
|
|
})
|
|
}
|
|
/>
|
|
Conferi os movimentos, a finalidade, a
|
|
cobertura declarada, o padrão e a existência
|
|
de rupturas ou procura oculta. A ausência de
|
|
movimentos não foi tomada automaticamente
|
|
como consumo zero.
|
|
</label>
|
|
)}
|
|
<label className="grid gap-1 text-sm">
|
|
Fundamento da decisão
|
|
<textarea
|
|
className="rounded-lg border p-3"
|
|
required
|
|
minLength={10}
|
|
maxLength={4000}
|
|
value={form.data.reason}
|
|
onChange={(e) =>
|
|
form.setData('reason', e.target.value)
|
|
}
|
|
/>
|
|
</label>
|
|
<Button disabled={form.processing}>
|
|
Confirmar decisão
|
|
</Button>
|
|
</form>
|
|
)}
|
|
</>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export default function History(props: Props) {
|
|
return (
|
|
<>
|
|
<Head title="Histórico de consumo" />
|
|
<div className="space-y-6 p-5 lg:p-8">
|
|
<PageTitle
|
|
eyebrow="Armazém · Reposição"
|
|
title="Histórico de consumo"
|
|
description="Reutilizar as saídas reais do razão, analisar um período fechado e conferir a qualidade antes de o aplicar numa política."
|
|
/>
|
|
<Panel title="Responsabilidades">
|
|
<p className="text-sm text-muted-foreground">
|
|
O preparador selecciona artigo, local e período. Os
|
|
valores são calculados pelo sistema. Outra pessoa
|
|
confere cobertura e padrão. A política escolhe a análise
|
|
aprovada e define o mínimo de dias e a idade máxima
|
|
admissível; sazonalidade, intermitência e dados
|
|
incompletos mantêm percurso manual.
|
|
</p>
|
|
</Panel>
|
|
{!props.ready && (
|
|
<p role="status">Instalação do fornecimento pendente.</p>
|
|
)}
|
|
{props.focusRecordId && (
|
|
<div className="space-y-2 text-sm">
|
|
<Link
|
|
href="/compras/fornecimento?view=history"
|
|
className="underline"
|
|
>
|
|
Ver todas as análises
|
|
</Link>
|
|
{props.focusChanged && (
|
|
<p role="status">
|
|
Esta análise foi actualizada. Está a consultar a
|
|
versão actual; as versões anteriores permanecem
|
|
no histórico.
|
|
</p>
|
|
)}
|
|
</div>
|
|
)}
|
|
{props.canPrepare && !props.focusRecordId && (
|
|
<Panel title="Analisar período existente">
|
|
<details>
|
|
<summary className="cursor-pointer font-medium">
|
|
Seleccionar artigo e período
|
|
</summary>
|
|
<Prepare props={props} />
|
|
</details>
|
|
</Panel>
|
|
)}
|
|
{props.records.length === 0 && (
|
|
<Panel title="Sem análises">
|
|
<p className="text-sm text-muted-foreground">
|
|
Ainda não foi conferido um período. O sistema mantém
|
|
a previsão histórica indisponível; não atribui
|
|
consumo zero por falta de dados.
|
|
</p>
|
|
</Panel>
|
|
)}
|
|
{props.records.map((r) => (
|
|
<Panel
|
|
key={r.id}
|
|
title={`${r.snapshot.item.code} · ${r.snapshot.item.name}`}
|
|
description={`${r.snapshot.warehouse.name} · ${states[r.state]} · Versão ${r.version}`}
|
|
>
|
|
<div id={`supply-record-${r.id}`} />
|
|
<Facts record={r} series />
|
|
<p className="mt-3 text-sm">{r.reason}</p>
|
|
<Decision props={props} record={r} />
|
|
<details className="mt-4">
|
|
<summary className="cursor-pointer text-sm">
|
|
Histórico de análises e decisões
|
|
</summary>
|
|
<ol className="mt-3 space-y-4">
|
|
{props.history[r.record_key]?.map((h) => (
|
|
<li
|
|
key={h.id}
|
|
className="border-l-2 pl-4 text-sm"
|
|
>
|
|
<p className="font-medium">
|
|
Versão {h.version} ·{' '}
|
|
{states[h.state]} ·{' '}
|
|
{h.snapshot.actor.name} ·{' '}
|
|
{new Date(
|
|
h.created_at,
|
|
).toLocaleString('pt-MZ')}
|
|
</p>
|
|
<p className="my-2">{h.reason}</p>
|
|
<Facts record={h} />
|
|
</li>
|
|
))}
|
|
</ol>
|
|
</details>
|
|
</Panel>
|
|
))}
|
|
<SupplyPagination page={props.recordPagination} />
|
|
<p className="text-sm text-muted-foreground">
|
|
Uma análise conferida pode ser seleccionada pelo responsável
|
|
pelas políticas. A consulta do razão e a configuração de
|
|
políticas seguem as permissões próprias desses menus.
|
|
</p>
|
|
</div>
|
|
</>
|
|
);
|
|
}
|