commit14
This commit is contained in:
@@ -183,14 +183,19 @@ export default function Availability(props: Props) {
|
||||
<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'}
|
||||
: row.free_milli !==
|
||||
null &&
|
||||
row.free_milli < 0
|
||||
? 'Reserva com défice de material utilizável — rever qualidade, validade e atendimento'
|
||||
: 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>
|
||||
))}
|
||||
|
||||
@@ -62,6 +62,9 @@ function EntryForm({ entry }: { entry: Entry }) {
|
||||
>
|
||||
<option value="consumable">Insumos / matéria-prima</option>
|
||||
<option value="other">Outro bem</option>
|
||||
<option value="spare_part">
|
||||
Peça registada para equipamento
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Head, useForm } from '@inertiajs/react';
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { InventoryNotice, InventoryPagination } from '@/components/inventory';
|
||||
import { LotCountFields, countTotal } from '@/components/inventory-lot-count';
|
||||
@@ -92,6 +92,7 @@ type Props = {
|
||||
operations: Page<Operation>;
|
||||
counts: Operation[];
|
||||
canOperate: boolean;
|
||||
canViewReturns?: boolean;
|
||||
correctedOperations?: Record<number, string>;
|
||||
canAdjust?: boolean;
|
||||
lotCounts?: LotCountSource[];
|
||||
@@ -112,6 +113,7 @@ export default function Operations({
|
||||
operations,
|
||||
counts,
|
||||
canOperate,
|
||||
canViewReturns = false,
|
||||
correctedOperations = {},
|
||||
canAdjust = false,
|
||||
lotCounts = [],
|
||||
@@ -171,6 +173,7 @@ export default function Operations({
|
||||
description="Movimentos com fundamento, contagens físicas e histórico preservado."
|
||||
/>
|
||||
<InventoryNotice />
|
||||
{canViewReturns && <Link href="/stock/devolucoes-internas">Conferir devoluções de excedentes</Link>}
|
||||
{canOperate && form.data.kind === 'issue' && (
|
||||
<label className="grid gap-2 text-sm">
|
||||
Equipamento de destino (obrigatório para peças
|
||||
@@ -534,6 +537,7 @@ export default function Operations({
|
||||
'Devolução ao fornecedor',
|
||||
write_off: 'Abate físico',
|
||||
reversal: 'Estorno integral',
|
||||
workshop_return: 'Devolução de excedente',
|
||||
}[o.kind] ??
|
||||
o.kind}
|
||||
</strong>
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
import { Head, Link } from '@inertiajs/react';
|
||||
import { PageTitle, Panel } from '@/components/procurement';
|
||||
|
||||
type Person = {
|
||||
id: number;
|
||||
name: string;
|
||||
department_id: number | null;
|
||||
has_cost_center?: boolean;
|
||||
};
|
||||
type Props = {
|
||||
syntheticEvaluation: boolean;
|
||||
report: {
|
||||
checked_at: string;
|
||||
warehouse_scenario_ready: boolean;
|
||||
replenishment_scenario_ready: boolean;
|
||||
client_configuration_complete: boolean;
|
||||
checks: {
|
||||
key: string;
|
||||
label: string;
|
||||
ok: boolean;
|
||||
detail: string;
|
||||
path: string | null;
|
||||
}[];
|
||||
participants: Record<string, Person[]>;
|
||||
registered: Person[];
|
||||
runtime: {
|
||||
scanMinutes: number;
|
||||
schedulerRecent: boolean;
|
||||
schedulerStatus: { finished_at: string; result: string } | null;
|
||||
};
|
||||
};
|
||||
};
|
||||
const tasks: Record<string, string> = {
|
||||
prepare: 'Preparar e confirmar requisições ao armazém',
|
||||
review: 'Autorizar e acompanhar reservas',
|
||||
deliver: 'Entregar pelo armazém (com independência)',
|
||||
purchase_requester: 'Requisitante de compra',
|
||||
supply_prepare: 'Preparar políticas e reposição',
|
||||
supply_review: 'Conferir políticas e activar reposição',
|
||||
};
|
||||
|
||||
export default function Pilot({ report: r, syntheticEvaluation }: Props) {
|
||||
return (
|
||||
<>
|
||||
<Head title="Preparação do piloto" />
|
||||
<div className="space-y-6 p-6">
|
||||
<PageTitle
|
||||
eyebrow="Administração · Armazém e reposição"
|
||||
title="Preparação do piloto"
|
||||
description="Conferir o que está instalado e parametrizado, antes de experimentar o percurso completo. Esta consulta não altera contas, permissões, regras ou stock."
|
||||
/>
|
||||
<p className="rounded border bg-slate-50 p-4 text-sm">
|
||||
{syntheticEvaluation
|
||||
? 'Avaliação de desenvolvimento: usar contas e dados sintéticos.'
|
||||
: 'Diagnóstico da configuração desta empresa.'}{' '}
|
||||
O resultado indica condições observadas, sem certificar
|
||||
aceitação comercial, revisão visual completa ou cobertura
|
||||
transferida para o SGF.
|
||||
</p>
|
||||
<nav className="flex flex-wrap gap-4 print:hidden">
|
||||
<a href="/stock/piloto.csv">Exportar conferências (CSV)</a>
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() => window.print()}
|
||||
>
|
||||
Imprimir diagnóstico
|
||||
</button>
|
||||
<Link href="/stock/requisicoes">
|
||||
Acompanhamento de requisições
|
||||
</Link>
|
||||
<Link href="/stock/reposicao">Reposição automática</Link>
|
||||
<Link href="/administracao/parametrizacao">
|
||||
Parametrização da aplicação
|
||||
</Link>
|
||||
</nav>
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
{[
|
||||
['Percurso de armazém', r.warehouse_scenario_ready],
|
||||
['Reposição periódica', r.replenishment_scenario_ready],
|
||||
[
|
||||
'Configuração de cliente',
|
||||
r.client_configuration_complete,
|
||||
],
|
||||
].map(([label, ok]) => (
|
||||
<div key={String(label)} className="rounded border p-4">
|
||||
<p className="font-semibold">{label}</p>
|
||||
<p>
|
||||
{ok
|
||||
? 'Condições básicas observadas'
|
||||
: 'Há preparação por concluir'}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<Panel title="Conferências e próximos passos">
|
||||
<p className="mb-4 text-sm">
|
||||
A exportação regista a situação observada na data
|
||||
indicada. Não activa configurações nem substitui o
|
||||
ensaio dos percursos. Os dados podem mudar entre a
|
||||
consulta e uma nova exportação.
|
||||
</p>
|
||||
<p className="mb-4 text-sm">
|
||||
Conferido em{' '}
|
||||
{new Date(r.checked_at).toLocaleString('pt-PT')}. Não
|
||||
são presumidos valores, intervenientes ou aprovações em
|
||||
falta.
|
||||
</p>
|
||||
{r.checks.map((c) => (
|
||||
<div key={c.key} className="mb-3 rounded border p-4">
|
||||
<p className="font-medium">
|
||||
{c.ok ? '✓ Conferido' : 'A preparar'} ·{' '}
|
||||
{c.label}
|
||||
</p>
|
||||
<p className="mt-1 text-sm">{c.detail}</p>
|
||||
{c.path && (
|
||||
<Link
|
||||
className="mt-2 inline-block underline"
|
||||
href={c.path}
|
||||
>
|
||||
Consultar / configurar
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</Panel>
|
||||
<Panel title="Pessoas com tarefas actualmente elegíveis">
|
||||
<p className="mb-4 text-sm">
|
||||
Elegibilidade conforme as competências existentes,
|
||||
contexto e departamento. Ter uma conta ou título de
|
||||
função não concede as tarefas específicas deste
|
||||
percurso. É necessário requisitante e autorizador do
|
||||
mesmo departamento, centro de custo compatível e
|
||||
entregador distinto de ambos.
|
||||
</p>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{Object.entries(tasks).map(([key, label]) => (
|
||||
<div key={key} className="rounded border p-3">
|
||||
<p className="font-medium">{label}</p>
|
||||
{r.participants[key]?.length ? (
|
||||
<ul className="mt-2 list-inside list-disc text-sm">
|
||||
{r.participants[key].map((p) => (
|
||||
<li key={p.id}>
|
||||
{p.name}
|
||||
{p.department_id !== null
|
||||
? ` · departamento #${p.department_id}`
|
||||
: ''}
|
||||
{(key === 'prepare' ||
|
||||
key ===
|
||||
'purchase_requester') &&
|
||||
!p.has_cost_center
|
||||
? ' · falta centro de custo no departamento'
|
||||
: ''}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="mt-2 text-sm">
|
||||
Nenhuma conta elegível nesta tarefa.
|
||||
Definir o perfil e a associação na
|
||||
parametrização.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Panel>
|
||||
<Panel title="Contas já cadastradas">
|
||||
<details>
|
||||
<summary className="cursor-pointer">
|
||||
Consultar {r.registered.length} conta(s), sem criar
|
||||
novas identidades
|
||||
</summary>
|
||||
<ul className="mt-3 list-inside list-disc text-sm">
|
||||
{r.registered.map((p) => (
|
||||
<li key={p.id}>
|
||||
{p.name} · #{p.id}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
</Panel>
|
||||
<Panel title="Roteiro do ensaio">
|
||||
<ol className="list-inside list-decimal space-y-2 text-sm">
|
||||
<li>
|
||||
Conferir tarefas, centro de custo, artigo publicado
|
||||
e armazém usando contas existentes.
|
||||
</li>
|
||||
<li>
|
||||
Preparar e submeter uma requisição com local de
|
||||
utilização e equipamento quando aplicável.
|
||||
</li>
|
||||
<li>
|
||||
Autorizar com outra conta elegível, conferir reserva
|
||||
e entregar com uma terceira conta independente.
|
||||
</li>
|
||||
<li>
|
||||
Confirmar a recepção pelo requisitante; conferir
|
||||
saldo e ausência de segunda saída.
|
||||
</li>
|
||||
<li>
|
||||
Ensaiar entrega parcial, cancelamento apenas do
|
||||
restante e material indisponível por
|
||||
qualidade/validade.
|
||||
</li>
|
||||
<li>
|
||||
Na reposição configurada, conferir um único rascunho
|
||||
e manutenção das aprovações; testar recuperação em
|
||||
base descartável.
|
||||
</li>
|
||||
</ol>
|
||||
<p className="mt-4 text-sm">
|
||||
Preparar ou diagnosticar não executa estes passos. A
|
||||
preparação e a activação de reposição exigem
|
||||
competências e independência próprias. O SGF real e a
|
||||
proposta de identidade adicional mantêm o seu âmbito
|
||||
separado.
|
||||
</p>
|
||||
</Panel>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -20,6 +20,7 @@ type RecordRow = {
|
||||
unit_price?: string;
|
||||
tax_rate?: string;
|
||||
needed_days?: number;
|
||||
equipment_id?: number;
|
||||
valid_until?: string;
|
||||
message?: string;
|
||||
purchases?: { id: number; number: string; quantity_milli: number }[];
|
||||
@@ -37,13 +38,66 @@ type RecordRow = {
|
||||
}[];
|
||||
};
|
||||
};
|
||||
type Page<T> = {
|
||||
data: T[];
|
||||
total: number;
|
||||
from: number | null;
|
||||
to: number | null;
|
||||
prev_page_url: string | null;
|
||||
next_page_url: string | null;
|
||||
};
|
||||
function Pagination<T>({
|
||||
page,
|
||||
label,
|
||||
}: {
|
||||
page: Page<T> | null;
|
||||
label: string;
|
||||
}) {
|
||||
return page ? (
|
||||
<nav aria-label={label} className="mt-4 flex flex-wrap gap-4 text-sm">
|
||||
<span>
|
||||
{page.from ?? 0}–{page.to ?? 0} de {page.total}
|
||||
</span>
|
||||
{page.prev_page_url && (
|
||||
<Link preserveScroll href={page.prev_page_url}>
|
||||
Anterior
|
||||
</Link>
|
||||
)}
|
||||
{page.next_page_url && (
|
||||
<Link preserveScroll href={page.next_page_url}>
|
||||
Seguinte
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
) : null;
|
||||
}
|
||||
type Props = {
|
||||
ready: boolean;
|
||||
canPrepare: boolean;
|
||||
canReview: boolean;
|
||||
rules: RecordRow[];
|
||||
needs: RecordRow[];
|
||||
history: RecordRow[];
|
||||
rules: Page<RecordRow> | null;
|
||||
needs: Page<RecordRow> | null;
|
||||
history: Page<RecordRow> | null;
|
||||
filters: { need_state: string };
|
||||
recoveryReady: boolean;
|
||||
workItems: Page<{
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
warehouse: string;
|
||||
last_error: string | null;
|
||||
due_at: string;
|
||||
failures: number;
|
||||
}> | null;
|
||||
scanMinutes: number;
|
||||
schedulerStatus: { finished_at: string; result: string } | null;
|
||||
schedulerRecent: boolean;
|
||||
work: {
|
||||
total: number;
|
||||
pending: number | null;
|
||||
failed: number | null;
|
||||
last_run_at: string | null;
|
||||
} | null;
|
||||
policies: RecordRow[];
|
||||
requesters: { id: number; name: string; department_id: number }[];
|
||||
centers: {
|
||||
@@ -52,6 +106,13 @@ type Props = {
|
||||
name: string;
|
||||
department_id: number;
|
||||
}[];
|
||||
equipment: {
|
||||
id: number;
|
||||
code: string;
|
||||
description: string;
|
||||
department_id: number;
|
||||
}[];
|
||||
catalogueTypes: Record<number, string>;
|
||||
};
|
||||
const states: Record<string, string> = {
|
||||
draft: 'Por activar',
|
||||
@@ -76,6 +137,7 @@ function RuleForm({ props, rule }: { props: Props; rule?: RecordRow }) {
|
||||
unit_price: rule?.data.unit_price ?? '',
|
||||
tax_rate: rule?.data.tax_rate ?? '',
|
||||
needed_days: rule?.data.needed_days?.toString() ?? '',
|
||||
equipment_id: rule?.data.equipment_id?.toString() ?? '',
|
||||
valid_until: rule?.data.valid_until ?? '',
|
||||
},
|
||||
});
|
||||
@@ -86,7 +148,10 @@ function RuleForm({ props, rule }: { props: Props; rule?: RecordRow }) {
|
||||
form.setData('data', {
|
||||
...form.data.data,
|
||||
[key]: value,
|
||||
...(key === 'requester_id' ? { cost_center_id: '' } : {}),
|
||||
...(key === 'requester_id'
|
||||
? { cost_center_id: '', equipment_id: '' }
|
||||
: {}),
|
||||
...(key === 'policy_key' ? { equipment_id: '' } : {}),
|
||||
});
|
||||
return (
|
||||
<form
|
||||
@@ -150,6 +215,36 @@ function RuleForm({ props, rule }: { props: Props; rule?: RecordRow }) {
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{props.catalogueTypes[
|
||||
props.policies.find(
|
||||
(p) => p.record_key === form.data.data.policy_key,
|
||||
)?.snapshot.item.id ?? 0
|
||||
] === 'spare_part' && (
|
||||
<label>
|
||||
Equipamento de destino da peça
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={form.data.data.equipment_id}
|
||||
onChange={(e) => set('equipment_id', e.target.value)}
|
||||
>
|
||||
<option value="">
|
||||
Seleccione um equipamento compatível
|
||||
</option>
|
||||
{props.equipment
|
||||
.filter(
|
||||
(e) =>
|
||||
e.department_id ===
|
||||
requester?.department_id,
|
||||
)
|
||||
.map((e) => (
|
||||
<option key={e.id} value={e.id}>
|
||||
{e.code} · {e.description}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<label>
|
||||
Preço estimado (MZN), se não existir no acordo
|
||||
<input
|
||||
@@ -286,14 +381,82 @@ export default function Replenishment(props: Props) {
|
||||
<RuleForm props={props} />
|
||||
</Panel>
|
||||
)}
|
||||
<Panel title="Verificação e recuperação da reposição">
|
||||
<p>
|
||||
{props.recoveryReady
|
||||
? 'Recuperação durável instalada. A verificação periódica depende do serviço de agendamento em execução.'
|
||||
: 'Instalação da recuperação durável pendente.'}
|
||||
</p>
|
||||
{props.recoveryReady && (
|
||||
<p>
|
||||
Intervalo de verificação por artigo/armazém:{' '}
|
||||
{props.scanMinutes} minutos. Serviço:{' '}
|
||||
{props.schedulerStatus
|
||||
? `${!props.schedulerRecent ? 'sem passagem recente confirmada; último registo' : props.schedulerStatus.result === 'passed' ? 'última passagem concluída' : 'recuperação pendente'} em ${props.schedulerStatus.finished_at}`
|
||||
: 'sem confirmação recente nesta interface'}
|
||||
.
|
||||
</p>
|
||||
)}
|
||||
{props.work && (
|
||||
<p>
|
||||
Trabalhos acompanhados: {props.work.total} ·
|
||||
Sinais pendentes: {props.work.pending ?? 0}{' '}
|
||||
· A recuperar: {props.work.failed ?? 0} ·
|
||||
Última verificação:{' '}
|
||||
{props.work.last_run_at ??
|
||||
'Ainda sem execução registada'}
|
||||
</p>
|
||||
)}
|
||||
</Panel>
|
||||
{props.workItems && props.workItems.total > 0 && (
|
||||
<Panel title="Verificações pendentes e interrompidas">
|
||||
{props.workItems.data.map((w) => (
|
||||
<div
|
||||
key={w.id}
|
||||
className="mb-3 rounded border p-3"
|
||||
>
|
||||
<p>
|
||||
{w.code} · {w.name} · {w.warehouse}
|
||||
</p>
|
||||
<p>
|
||||
{w.last_error ??
|
||||
'Alteração registada; avaliação pendente.'}{' '}
|
||||
Próxima tentativa: {w.due_at}
|
||||
</p>
|
||||
{(props.canPrepare ||
|
||||
props.canReview) && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
router.post(
|
||||
`/stock/reposicao/trabalhos/${w.id}/avaliar`,
|
||||
{},
|
||||
{
|
||||
preserveState:
|
||||
'errors',
|
||||
},
|
||||
)
|
||||
}
|
||||
>
|
||||
Reavaliar agora
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<Pagination
|
||||
page={props.workItems}
|
||||
label="Páginas dos trabalhos pendentes"
|
||||
/>
|
||||
</Panel>
|
||||
)}
|
||||
<Panel title="Parametrizações">
|
||||
{props.rules.length === 0 ? (
|
||||
{(props.rules?.data.length ?? 0) === 0 ? (
|
||||
<p>
|
||||
Sem parametrizações. Não são assumidos
|
||||
requisitantes ou centros de custo.
|
||||
</p>
|
||||
) : (
|
||||
props.rules.map((r) => (
|
||||
props.rules?.data.map((r) => (
|
||||
<div
|
||||
className="mb-4 rounded border p-4"
|
||||
key={r.id}
|
||||
@@ -345,22 +508,55 @@ export default function Replenishment(props: Props) {
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
<Pagination
|
||||
page={props.rules}
|
||||
label="Páginas das parametrizações"
|
||||
/>
|
||||
</Panel>
|
||||
<Panel title="Necessidades e compras associadas">
|
||||
{props.needs.length === 0 ? (
|
||||
<label>
|
||||
Estado
|
||||
<select
|
||||
className={controlClass}
|
||||
value={props.filters.need_state}
|
||||
onChange={(e) =>
|
||||
router.get(
|
||||
'/stock/reposicao',
|
||||
{ need_state: e.target.value },
|
||||
{ preserveScroll: true },
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="all">
|
||||
Todos · pendências primeiro
|
||||
</option>
|
||||
{[
|
||||
'pending',
|
||||
'created',
|
||||
'covered',
|
||||
'satisfied',
|
||||
].map((s) => (
|
||||
<option key={s} value={s}>
|
||||
{states[s]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{(props.needs?.data.length ?? 0) === 0 ? (
|
||||
<p>
|
||||
Sem necessidades registadas após alterações
|
||||
de stock ou activação de regras.
|
||||
</p>
|
||||
) : (
|
||||
props.needs.map((n) => (
|
||||
props.needs?.data.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} ·{' '}
|
||||
{n.snapshot.item.code} ·{' '}
|
||||
{n.snapshot.item.name} ·
|
||||
{n.snapshot.warehouse.name} ·{' '}
|
||||
{states[n.state]}
|
||||
</p>
|
||||
<p>{n.data.message}</p>
|
||||
@@ -412,19 +608,27 @@ export default function Replenishment(props: Props) {
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
<Pagination
|
||||
page={props.needs}
|
||||
label="Páginas das necessidades"
|
||||
/>
|
||||
</Panel>
|
||||
<Panel title="Histórico">
|
||||
<details>
|
||||
<summary>
|
||||
Consultar versões e fundamentos
|
||||
</summary>
|
||||
{props.history.map((h) => (
|
||||
{props.history?.data.map((h) => (
|
||||
<p key={h.id} className="mt-2">
|
||||
#{h.id} · {h.created_at} · Versão{' '}
|
||||
{h.version} · {states[h.state]} ·{' '}
|
||||
{h.reason}
|
||||
</p>
|
||||
))}
|
||||
<Pagination
|
||||
page={props.history}
|
||||
label="Páginas do histórico"
|
||||
/>
|
||||
</details>
|
||||
</Panel>
|
||||
</>
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
controlClass,
|
||||
} from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import type { WarehouseHealth } from '@/types/inventory';
|
||||
type Line = {
|
||||
item: { code: string; name: string; unit: string };
|
||||
quantity_milli: number;
|
||||
@@ -30,6 +31,45 @@ type Event = {
|
||||
};
|
||||
};
|
||||
type Props = {
|
||||
canViewReturns?: boolean;
|
||||
supplyTrace: {
|
||||
ready: boolean;
|
||||
groups: {
|
||||
item: { id: number; code: string; name: string; unit: string };
|
||||
line_indexes: number[];
|
||||
origin_need_id: number;
|
||||
current_need_id: number;
|
||||
need_state: string;
|
||||
message: string;
|
||||
unreserved_milli: number;
|
||||
restricted: boolean;
|
||||
purchases: {
|
||||
id: number;
|
||||
number: string;
|
||||
status: string;
|
||||
href: string;
|
||||
next_task: string | null;
|
||||
orders: {
|
||||
id: number;
|
||||
number: string;
|
||||
href: string | null;
|
||||
effective_received_milli: number;
|
||||
receipts: {
|
||||
id: number;
|
||||
item_id: number;
|
||||
received_on: string;
|
||||
accepted_milli: number;
|
||||
reversed: boolean;
|
||||
}[];
|
||||
}[];
|
||||
}[];
|
||||
}[];
|
||||
};
|
||||
health: WarehouseHealth;
|
||||
people: Record<
|
||||
'requester' | 'review' | 'delivery',
|
||||
{ id: number; name: string }[]
|
||||
>;
|
||||
record: {
|
||||
id: number;
|
||||
snapshot: {
|
||||
@@ -99,7 +139,10 @@ function Command({
|
||||
.filter((line) => line.remaining > 0),
|
||||
});
|
||||
return (
|
||||
<details className="rounded border p-3 print:hidden">
|
||||
<details
|
||||
id={`warehouse-command-${action}${delivery === undefined ? '' : `-${delivery}`}`}
|
||||
className="rounded border p-3 print:hidden"
|
||||
>
|
||||
<summary className="cursor-pointer font-medium">
|
||||
{labels[action]}
|
||||
</summary>
|
||||
@@ -163,6 +206,8 @@ function Command({
|
||||
.code
|
||||
}{' '}
|
||||
· Pendente {line.remaining / 1000}{' '}
|
||||
{props.progress.reservation_ready &&
|
||||
`· Reservado ${props.progress.reserved[line.index] / 1000} `}
|
||||
{
|
||||
props.record.snapshot.lines[line.index].item
|
||||
.unit
|
||||
@@ -220,6 +265,7 @@ export default function WarehouseRequest(props: Props) {
|
||||
description={`Estado: ${labels[p.state] ?? p.state}`}
|
||||
/>
|
||||
<div className="flex gap-4 print:hidden">
|
||||
{props.canViewReturns && <Link href={`/stock/devolucoes-internas?request_id=${r.id}`}>Conferir devolução de excedentes</Link>}
|
||||
<Link href="/stock/requisicoes">
|
||||
Requisições ao armazém
|
||||
</Link>
|
||||
@@ -237,6 +283,204 @@ export default function WarehouseRequest(props: Props) {
|
||||
<p>Local de utilização: {r.snapshot.destination}</p>
|
||||
<p>Finalidade: {r.snapshot.reason}</p>
|
||||
</Panel>
|
||||
{props.supplyTrace.ready &&
|
||||
(props.supplyTrace.groups.length > 0 ||
|
||||
props.health.needs_reservation) && (
|
||||
<div className="print:hidden">
|
||||
<Panel title="Reposição e compras associadas">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
A reposição serve o artigo neste armazém.
|
||||
Após uma entrada, o autorizador confere o
|
||||
stock utilizável e actualiza a reserva do
|
||||
pedido; a saída acontece na entrega.
|
||||
</p>
|
||||
{props.canManageReservation &&
|
||||
props.supplyTrace.groups.some(
|
||||
(group) => group.unreserved_milli > 0,
|
||||
) && (
|
||||
<Button
|
||||
className="mt-3"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
const command =
|
||||
document.getElementById(
|
||||
'warehouse-command-reserve',
|
||||
);
|
||||
if (
|
||||
command instanceof
|
||||
HTMLDetailsElement
|
||||
) {
|
||||
command.open = true;
|
||||
command.scrollIntoView({
|
||||
block: 'center',
|
||||
behavior: 'smooth',
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
Conferir e actualizar reserva
|
||||
</Button>
|
||||
)}
|
||||
{props.supplyTrace.groups.length === 0 && (
|
||||
<p className="mt-3">
|
||||
Ainda não existe ligação de reposição
|
||||
registada para este pedido. A avaliação
|
||||
depende da parametrização e das
|
||||
necessidades detectadas.
|
||||
</p>
|
||||
)}
|
||||
{props.supplyTrace.groups.map((group) => (
|
||||
<section
|
||||
key={group.origin_need_id}
|
||||
className="mt-4 rounded-lg border p-4"
|
||||
>
|
||||
<h3 className="font-medium">
|
||||
{group.item.code} ·{' '}
|
||||
{group.item.name}
|
||||
</h3>
|
||||
<p className="text-sm">
|
||||
Saldo deste pedido sem reserva:{' '}
|
||||
{group.unreserved_milli / 1000}{' '}
|
||||
{group.item.unit}. Necessidade de
|
||||
origem #{group.origin_need_id};
|
||||
avaliação actual #
|
||||
{group.current_need_id}.
|
||||
</p>
|
||||
<p className="mt-2 text-sm">
|
||||
{group.message}
|
||||
</p>
|
||||
{group.restricted && (
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
O detalhe de algumas compras
|
||||
exige acesso ao respectivo
|
||||
processo.
|
||||
</p>
|
||||
)}
|
||||
{group.purchases.map((purchase) => (
|
||||
<div
|
||||
key={purchase.id}
|
||||
className="mt-3 border-t pt-3"
|
||||
>
|
||||
<p>
|
||||
<Link
|
||||
href={purchase.href}
|
||||
className="underline"
|
||||
>
|
||||
Compra {purchase.number}
|
||||
</Link>{' '}
|
||||
·{' '}
|
||||
{(
|
||||
{
|
||||
draft: 'Rascunho a conferir e submeter',
|
||||
pending:
|
||||
'Em aprovação',
|
||||
approved:
|
||||
'Aprovada',
|
||||
rejected:
|
||||
'Rejeitada',
|
||||
} as Record<
|
||||
string,
|
||||
string
|
||||
>
|
||||
)[purchase.status] ??
|
||||
purchase.status}
|
||||
</p>
|
||||
{purchase.next_task && (
|
||||
<p className="text-sm">
|
||||
Etapa pendente:{' '}
|
||||
{purchase.next_task}
|
||||
</p>
|
||||
)}
|
||||
{purchase.orders.length ===
|
||||
0 && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Sem encomenda emitida
|
||||
neste processo.
|
||||
</p>
|
||||
)}
|
||||
{purchase.orders.map(
|
||||
(order) => (
|
||||
<div
|
||||
key={order.id}
|
||||
className="mt-2 text-sm"
|
||||
>
|
||||
<p>
|
||||
Encomenda{' '}
|
||||
{order.href ? (
|
||||
<Link
|
||||
href={
|
||||
order.href
|
||||
}
|
||||
className="underline"
|
||||
>
|
||||
{
|
||||
order.number
|
||||
}
|
||||
</Link>
|
||||
) : (
|
||||
order.number
|
||||
)}{' '}
|
||||
· Entradas
|
||||
aceites
|
||||
efectivas neste
|
||||
armazém:{' '}
|
||||
{order.effective_received_milli /
|
||||
1000}{' '}
|
||||
{
|
||||
group.item
|
||||
.unit
|
||||
}
|
||||
</p>
|
||||
{order.receipts
|
||||
.length ===
|
||||
0 && (
|
||||
<p className="text-muted-foreground">
|
||||
Sem entrada
|
||||
deste artigo
|
||||
registada no
|
||||
destino.
|
||||
</p>
|
||||
)}
|
||||
{order.receipts.map(
|
||||
(receipt) => (
|
||||
<p
|
||||
key={
|
||||
receipt.item_id
|
||||
}
|
||||
>
|
||||
Recebimento
|
||||
#
|
||||
{
|
||||
receipt.id
|
||||
}{' '}
|
||||
·{' '}
|
||||
{
|
||||
receipt.received_on
|
||||
}{' '}
|
||||
·{' '}
|
||||
{receipt.accepted_milli /
|
||||
1000}{' '}
|
||||
{
|
||||
group
|
||||
.item
|
||||
.unit
|
||||
}
|
||||
{receipt.reversed
|
||||
? ' · Estornado'
|
||||
: ' · Aceite'}
|
||||
</p>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
</Panel>
|
||||
</div>
|
||||
)}
|
||||
<Panel title="Artigos e atendimento">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
@@ -299,7 +543,60 @@ export default function WarehouseRequest(props: Props) {
|
||||
? '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>
|
||||
{props.health.lines.some((l) => l.attention) && (
|
||||
<div className="mt-3 space-y-2 rounded border border-amber-400 bg-amber-50 p-3 text-sm text-amber-950">
|
||||
{props.health.lines
|
||||
.filter((l) => l.attention)
|
||||
.map((l) => (
|
||||
<p key={l.index}>
|
||||
{r.snapshot.lines[l.index].item.code} ·{' '}
|
||||
{l.attention}
|
||||
{l.unreserved_milli > 0
|
||||
? ` Saldo sem reserva: ${l.unreserved_milli / 1000} ${r.snapshot.lines[l.index].item.unit}.`
|
||||
: ''}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{props.health.unconfirmed_deliveries > 0 && (
|
||||
<p className="mt-3 text-sm">
|
||||
{props.health.unconfirmed_deliveries} entrega(s)
|
||||
aguardam confirmação de recepção pelo requisitante.
|
||||
Confirmar não gera nova saída.
|
||||
</p>
|
||||
)}
|
||||
</Panel>
|
||||
<div className="print:hidden">
|
||||
<Panel title="Pessoas actualmente elegíveis para as tarefas">
|
||||
<p className="mb-3 text-sm">
|
||||
Conforme perfis, contexto, departamento e
|
||||
independência actuais. Esta consulta não atribui
|
||||
tarefas nem altera decisões anteriores.
|
||||
</p>
|
||||
{(
|
||||
[
|
||||
[
|
||||
'requester',
|
||||
'Requisição e confirmação de recepção',
|
||||
],
|
||||
[
|
||||
'review',
|
||||
'Autorização e acompanhamento da reserva',
|
||||
],
|
||||
['delivery', 'Entrega pelo armazém'],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<p key={key} className="mb-2">
|
||||
<strong>{label}:</strong>{' '}
|
||||
{props.people[key].length
|
||||
? props.people[key]
|
||||
.map((u) => u.name)
|
||||
.join(', ')
|
||||
: 'Sem pessoa elegível nas competências actualmente atribuídas; requer parametrização.'}
|
||||
</p>
|
||||
))}
|
||||
</Panel>
|
||||
</div>
|
||||
{!props.ready ? (
|
||||
<Panel title="Instalação pendente">
|
||||
<p>Autorização e entrega ainda não instaladas.</p>
|
||||
@@ -327,7 +624,7 @@ export default function WarehouseRequest(props: Props) {
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{props.canDeliver && (
|
||||
{props.canDeliver && props.health.delivery_ready && (
|
||||
<Command
|
||||
key={`deliver:${p.version}`}
|
||||
props={props}
|
||||
|
||||
@@ -6,6 +6,11 @@ import {
|
||||
controlClass,
|
||||
} from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
warehouseStateLabels,
|
||||
type WarehouseHealth,
|
||||
type WarehouseActions,
|
||||
} from '@/types/inventory';
|
||||
type Item = { id: number; code: string; name: string; unit: string };
|
||||
type Line = {
|
||||
stock_item_id: string;
|
||||
@@ -29,6 +34,15 @@ type Snapshot = {
|
||||
}[];
|
||||
};
|
||||
type Props = {
|
||||
filters: {
|
||||
view: string;
|
||||
state: string;
|
||||
search: string;
|
||||
warehouse_id: number | null;
|
||||
};
|
||||
views: { key: string; label: string; total: number }[];
|
||||
states: Record<string, number>;
|
||||
checkedAt: string;
|
||||
ready: boolean;
|
||||
canPrepare: boolean;
|
||||
items: Item[];
|
||||
@@ -40,10 +54,13 @@ type Props = {
|
||||
id: number;
|
||||
status: string;
|
||||
snapshot: Snapshot;
|
||||
progress?: { state: string };
|
||||
progress?: { state: string; reserved: number[] };
|
||||
health: WarehouseHealth;
|
||||
actions: WarehouseActions;
|
||||
}[];
|
||||
prev_page_url: string | null;
|
||||
next_page_url: string | null;
|
||||
total: number;
|
||||
};
|
||||
};
|
||||
const blank = (): Line => ({
|
||||
@@ -53,6 +70,22 @@ const blank = (): Line => ({
|
||||
equipment_id: '',
|
||||
});
|
||||
export default function Requests(props: Props) {
|
||||
const filters = useForm({
|
||||
search: props.filters.search,
|
||||
state: props.filters.state,
|
||||
warehouse_id: props.filters.warehouse_id?.toString() ?? '',
|
||||
view: props.filters.view,
|
||||
});
|
||||
const viewUrl = (view: string) => {
|
||||
const query = new URLSearchParams({
|
||||
view,
|
||||
state: 'all',
|
||||
search: props.filters.search,
|
||||
});
|
||||
if (props.filters.warehouse_id)
|
||||
query.set('warehouse_id', props.filters.warehouse_id.toString());
|
||||
return '/stock/requisicoes?' + query.toString();
|
||||
};
|
||||
const form = useForm({
|
||||
operation_key: crypto.randomUUID(),
|
||||
warehouse_id: '',
|
||||
@@ -76,17 +109,108 @@ export default function Requests(props: Props) {
|
||||
<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."
|
||||
description="Acompanhar autorizações, reservas, entregas e recepções conforme as suas tarefas."
|
||||
/>
|
||||
<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.
|
||||
saída e as entregas. A autorização reserva o material
|
||||
disponível. A compra automática por falta depende da
|
||||
parametrização do artigo e armazém. Consulte a reposição
|
||||
para acompanhar as necessidades e os rascunhos associados. A
|
||||
venda a terceiros pertence à composição SGF.
|
||||
</p>
|
||||
<Link href="/stock/disponibilidade">
|
||||
Consultar disponibilidade (conforme o seu acesso)
|
||||
</Link>
|
||||
<nav
|
||||
aria-label="Tarefas do armazém"
|
||||
className="flex flex-wrap gap-3"
|
||||
>
|
||||
{props.views.map((v) => (
|
||||
<Link
|
||||
key={v.key}
|
||||
href={viewUrl(v.key)}
|
||||
className={`rounded border px-4 py-3 ${props.filters.view === v.key ? 'bg-teal-50 font-semibold text-teal-950' : ''}`}
|
||||
>
|
||||
{v.label} · {v.total}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
<Panel title="Pesquisar e filtrar acompanhamento">
|
||||
<form
|
||||
className="grid gap-3 md:grid-cols-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
filters.get('/stock/requisicoes', {
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
Referência, requisitante ou local
|
||||
<input
|
||||
className={controlClass}
|
||||
value={filters.data.search}
|
||||
onChange={(e) =>
|
||||
filters.setData('search', e.target.value)
|
||||
}
|
||||
placeholder="RA-123 ou local de utilização"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Armazém
|
||||
<select
|
||||
className={controlClass}
|
||||
value={filters.data.warehouse_id}
|
||||
onChange={(e) =>
|
||||
filters.setData(
|
||||
'warehouse_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Todos no meu âmbito</option>
|
||||
{props.warehouses.map((w) => (
|
||||
<option key={w.id} value={w.id}>
|
||||
{w.code} · {w.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Estado
|
||||
<select
|
||||
className={controlClass}
|
||||
value={filters.data.state}
|
||||
onChange={(e) =>
|
||||
filters.setData('state', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="all">Todos</option>
|
||||
{Object.entries(warehouseStateLabels).map(
|
||||
([key, label]) => (
|
||||
<option key={key} value={key}>
|
||||
{label} · {props.states[key] ?? 0}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
<Button
|
||||
className="self-end"
|
||||
disabled={filters.processing}
|
||||
>
|
||||
Aplicar filtros
|
||||
</Button>
|
||||
</form>
|
||||
<FormErrors errors={filters.errors} />
|
||||
<p className="mt-3 text-sm">
|
||||
{props.records?.total ?? 0} requisições nos filtros ·
|
||||
Ordem de registo, mais antigas primeiro. Conferência:{' '}
|
||||
{new Date(props.checkedAt).toLocaleString('pt-PT')}.
|
||||
</p>
|
||||
</Panel>
|
||||
{!props.ready ? (
|
||||
<Panel title="Instalação pendente">
|
||||
<p>
|
||||
@@ -95,265 +219,292 @@ export default function Requests(props: Props) {
|
||||
</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>
|
||||
<details
|
||||
open={
|
||||
Object.keys(form.errors).length > 0
|
||||
? true
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<summary className="cursor-pointer font-medium">
|
||||
Preparar nova requisição
|
||||
</summary>
|
||||
<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>
|
||||
Artigo do cadastro
|
||||
Armazém
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={row.stock_item_id}
|
||||
value={form.data.warehouse_id}
|
||||
onChange={(e) =>
|
||||
line(index, {
|
||||
stock_item_id:
|
||||
e.target.value,
|
||||
})
|
||||
form.setData(
|
||||
'warehouse_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Seleccione
|
||||
</option>
|
||||
{props.items.map((item) => (
|
||||
{props.warehouses.map((w) => (
|
||||
<option
|
||||
key={item.id}
|
||||
value={item.id}
|
||||
key={w.id}
|
||||
value={w.id}
|
||||
>
|
||||
{item.code} ·{' '}
|
||||
{item.name} ({item.unit}
|
||||
)
|
||||
{w.code} · {w.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Quantidade
|
||||
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}
|
||||
inputMode="decimal"
|
||||
placeholder="Ex.: 2.500"
|
||||
value={row.quantity}
|
||||
value={form.data.destination}
|
||||
onChange={(e) =>
|
||||
line(index, {
|
||||
quantity:
|
||||
e.target.value,
|
||||
})
|
||||
form.setData(
|
||||
'destination',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Utilização
|
||||
Prioridade
|
||||
<select
|
||||
className={controlClass}
|
||||
value={row.use}
|
||||
value={form.data.priority}
|
||||
onChange={(e) =>
|
||||
line(index, {
|
||||
use: e.target.value,
|
||||
equipment_id: '',
|
||||
})
|
||||
form.setData(
|
||||
'priority',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="internal">
|
||||
Uso interno no local
|
||||
indicado
|
||||
<option value="normal">
|
||||
Normal
|
||||
</option>
|
||||
<option value="equipment">
|
||||
Em equipamento
|
||||
<option value="urgent">
|
||||
Urgente
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
{row.use === 'equipment' && (
|
||||
</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>
|
||||
Equipamento de destino
|
||||
Artigo do cadastro
|
||||
<select
|
||||
required
|
||||
className={controlClass}
|
||||
value={row.equipment_id}
|
||||
value={row.stock_item_id}
|
||||
onChange={(e) =>
|
||||
line(index, {
|
||||
equipment_id:
|
||||
stock_item_id:
|
||||
e.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Seleccione do seu
|
||||
departamento
|
||||
Seleccione
|
||||
</option>
|
||||
{props.equipment.map(
|
||||
(eq) => (
|
||||
<option
|
||||
key={eq.id}
|
||||
value={eq.id}
|
||||
>
|
||||
{eq.code} ·{' '}
|
||||
{eq.description}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
{props.items.map((item) => (
|
||||
<option
|
||||
key={item.id}
|
||||
value={item.id}
|
||||
>
|
||||
{item.code} ·{' '}
|
||||
{item.name} (
|
||||
{item.unit})
|
||||
</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>
|
||||
<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>
|
||||
</details>
|
||||
)
|
||||
)}
|
||||
<Panel title="Requisições registadas">
|
||||
@@ -368,18 +519,9 @@ export default function Requests(props: Props) {
|
||||
<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']
|
||||
warehouseStateLabels[
|
||||
record.progress?.state ?? 'draft'
|
||||
]
|
||||
}{' '}
|
||||
· {record.snapshot.requester.name} ·{' '}
|
||||
{record.snapshot.warehouse.name}
|
||||
@@ -389,8 +531,8 @@ export default function Requests(props: Props) {
|
||||
className="underline"
|
||||
href={`/stock/requisicoes/${record.id}`}
|
||||
>
|
||||
Abrir requisição, autorizar ou registar
|
||||
entrega
|
||||
Consultar requisição e tarefas
|
||||
disponíveis
|
||||
</Link>
|
||||
<p>
|
||||
Destino: {record.snapshot.destination}
|
||||
@@ -401,6 +543,44 @@ export default function Requests(props: Props) {
|
||||
{record.snapshot.cost_center.name}
|
||||
</p>
|
||||
<p>Finalidade: {record.snapshot.reason}</p>
|
||||
{record.actions.canReview && (
|
||||
<p>
|
||||
Para si: autorizar ou rejeitar o
|
||||
pedido.
|
||||
</p>
|
||||
)}
|
||||
{record.actions.canManageReservation && (
|
||||
<p>
|
||||
Para si: acompanhar/actualizar a
|
||||
reserva ou cancelar
|
||||
fundamentadamente o saldo.
|
||||
</p>
|
||||
)}
|
||||
{record.actions.canDeliver && (
|
||||
<p>
|
||||
{record.health.delivery_ready
|
||||
? 'Para si: há material reservado para registar a entrega efectiva.'
|
||||
: 'Entrega pendente: conferir reserva, disponibilidade e destino antes de retirar material.'}
|
||||
</p>
|
||||
)}
|
||||
{record.actions.canReceive &&
|
||||
record.health.unconfirmed_deliveries >
|
||||
0 && (
|
||||
<p>
|
||||
Para si: confirmar{' '}
|
||||
{
|
||||
record.health
|
||||
.unconfirmed_deliveries
|
||||
}{' '}
|
||||
entrega(s) recebida(s).
|
||||
</p>
|
||||
)}
|
||||
{record.actions.canSubmit && (
|
||||
<p>
|
||||
Para si: conferir e submeter o
|
||||
rascunho.
|
||||
</p>
|
||||
)}
|
||||
{record.snapshot.lines.map(
|
||||
(item, index) => (
|
||||
<p key={index}>
|
||||
@@ -411,6 +591,36 @@ export default function Requests(props: Props) {
|
||||
{item.equipment
|
||||
? `Equipamento ${item.equipment.code} · ${item.equipment.description}`
|
||||
: item.destination}
|
||||
{record.progress && (
|
||||
<span>
|
||||
{' '}
|
||||
· Reservado{' '}
|
||||
{record.progress
|
||||
.reserved[index] /
|
||||
1000}
|
||||
</span>
|
||||
)}
|
||||
{record.health.lines[index]
|
||||
?.unreserved_milli > 0 && (
|
||||
<span>
|
||||
{' '}
|
||||
· Sem reserva{' '}
|
||||
{record.health.lines[
|
||||
index
|
||||
].unreserved_milli /
|
||||
1000}
|
||||
</span>
|
||||
)}
|
||||
{record.health.lines[index]
|
||||
?.attention && (
|
||||
<span className="block text-amber-800">
|
||||
{
|
||||
record.health.lines[
|
||||
index
|
||||
].attention
|
||||
}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
),
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Head, Link } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState, type FormEvent } from 'react';
|
||||
import { PageTitle, Panel, controlClass } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
type Impact = { physical_before: string; physical_after: string; return_quantity_milli: string; not_returned_before: string; not_returned_after: string; original_movement_id: number; item: { code: string; name: string; unit: string }; warehouse: { code: string; name: string } };
|
||||
type Page = { page: number; last_page: number; total: number };
|
||||
type Row = { id: number; prepared_id: number; version: number; state: string; reason: string; evidence: string; preparer_id: number; author_id: number; created_at: string; impact: Impact };
|
||||
type Option = { delivery_event_id: number; line_index: number; delivered_milli: string; item: Impact['item'] };
|
||||
const milli = (value: string) => { const q = BigInt(value); return `${q / 1000n},${(q % 1000n).toString().padStart(3, '0')}`; };
|
||||
const states: Record<string,string> = {prepared:'Por confirmar',confirmed:'Confirmada',withdrawn:'Retirada',rejected:'Recusada'};
|
||||
export function WarehouseReturnImpact({ impact: p }: { impact: Impact }) {
|
||||
return <p>Stock físico: {milli(p.physical_before)} → {milli(p.physical_after)}. Devolução: {milli(p.return_quantity_milli)} {p.item.unit}. Entrega ainda não devolvida: {milli(p.not_returned_before)} → {milli(p.not_returned_after)}. {p.item.code} · {p.warehouse.code} · Saída original #{p.original_movement_id}.</p>;
|
||||
}
|
||||
async function api<T>(url: string, body?: object, signal?: AbortSignal): Promise<T> {
|
||||
const token = document.cookie.split('; ').find((c) => c.startsWith('XSRF-TOKEN='))?.slice(11);
|
||||
const response = await fetch(url, { method: body ? 'POST' : 'GET', credentials: 'same-origin', signal, headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', ...(token ? { 'X-XSRF-TOKEN': decodeURIComponent(token) } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) });
|
||||
const result = await response.json(); if (!response.ok) throw new Error(result.errors ? Object.values(result.errors).flat().join(' ') : result.message || `Pedido recusado (${response.status})`); return result;
|
||||
}
|
||||
export default function WarehouseReturns({ requestId, actorId, canPrepare, canConfirm, canWithdraw=false }: { requestId: number | null; actorId: number; canPrepare: boolean; canConfirm: boolean; canWithdraw?:boolean }) {
|
||||
const [history, setHistory] = useState<{ rows: Row[]; pagination: Page } | null>(null), [sources, setSources] = useState<{ options: Option[]; pagination: Page } | null>(null);
|
||||
const [page, setPage] = useState(1), [sourcePage, setSourcePage] = useState(1), [state, setState] = useState('all'), [reload, setReload] = useState(0), [error, setError] = useState(''), [busy, setBusy] = useState(false), [preview, setPreview] = useState<{ id: number; impact: Impact; state?:string } | null>(null);
|
||||
const generation = useRef(0), command = useRef<{ data: string; key: string } | null>(null);
|
||||
useEffect(() => { const n = ++generation.current, abort = new AbortController(); setHistory(null); setSources(null); setError('');
|
||||
Promise.all([api<{ rows: Row[]; pagination: Page }>(`/api/stock-returns?page=${page}&state=${state}`, undefined, abort.signal), requestId ? api<{ options: Option[]; pagination: Page }>(`/api/stock-returns/sources?request_id=${requestId}&source_page=${sourcePage}`, undefined, abort.signal) : Promise.resolve(null)])
|
||||
.then(([h, s]) => { if (n === generation.current) { setHistory(h); setSources(s); } }).catch((e: Error) => { if (!abort.signal.aborted && n === generation.current) setError(e.message); });
|
||||
return () => { generation.current++; abort.abort(); };
|
||||
}, [requestId, actorId, page, sourcePage, state, reload]);
|
||||
useEffect(() => { setPreview(null); command.current = null; setPage(1); setSourcePage(1); }, [requestId, actorId]);
|
||||
async function prepare(e: FormEvent<HTMLFormElement>) { e.preventDefault(); const n = generation.current; setBusy(true); setError(''); const fields = Object.fromEntries(new FormData(e.currentTarget)), choice = sources?.options.find((o) => `${o.delivery_event_id}:${o.line_index}` === fields.source);
|
||||
if (!choice) { setError('Seleccione uma entrega recebida.'); setBusy(false); return; }
|
||||
const body = { delivery_event_id: choice.delivery_event_id, line_index: choice.line_index, quantity: fields.quantity, declared_unused: fields.declared_unused === 'on', reason: fields.reason, evidence: fields.evidence }, data = JSON.stringify(body);
|
||||
if (command.current?.data !== data) command.current = { data, key: crypto.randomUUID() };
|
||||
try { const p = await api<{ id: number; impact: Impact }>('/api/stock-returns/prepare', { ...body, operation_key: command.current.key }); if (n === generation.current) { setPreview(p); setReload((x) => x + 1); } } catch (err) { if (n === generation.current) setError((err as Error).message); } finally { setBusy(false); }
|
||||
}
|
||||
async function confirm(e: FormEvent<HTMLFormElement>, row: Row) { e.preventDefault(); const n = generation.current; setBusy(true); setError(''); const fields = Object.fromEntries(new FormData(e.currentTarget));
|
||||
try { await api(`/api/stock-returns/${row.prepared_id}/confirm`, { version: 1, received_in_warehouse: fields.received_in_warehouse === 'on', reason: fields.reason }); if (n === generation.current) { setPreview(null); setReload((x) => x + 1); } } catch (err) { if (n === generation.current) setError((err as Error).message); } finally { setBusy(false); }
|
||||
}
|
||||
async function close(e:FormEvent<HTMLFormElement>,row:Row,action:'withdraw'|'reject'){e.preventDefault();const n=generation.current;setBusy(true);setError('');const fields=Object.fromEntries(new FormData(e.currentTarget));try{await api(`/api/stock-returns/${row.prepared_id}/${action}`,{version:1,reason:fields.reason});if(n===generation.current){setPreview(null);setReload(x=>x+1);}}catch(err){if(n===generation.current)setError((err as Error).message);}finally{setBusy(false);}}
|
||||
return <><Head title="Devoluções de excedentes" /><div className="space-y-6 p-6"><PageTitle eyebrow="Armazém · Material não consumido" title="Devoluções de excedentes" description="Declaração do destinatário e recepção física independente. O original permanece intacto." />
|
||||
<Link href={requestId ? `/stock/requisicoes/${requestId}` : '/dashboard'}>{requestId ? 'Consultar a requisição de origem' : 'Voltar ao Painel Inicial'}</Link>
|
||||
{error && <p role="alert">{error}</p>}<Button disabled={busy} onClick={() => setReload((x) => x + 1)}>Actualizar</Button>
|
||||
{canPrepare && requestId && sources && <Panel title={`Entregas recebidas · RA-${requestId}`}><form onSubmit={prepare} className="space-y-4"><label>Entrega e linha de origem<select name="source" className={controlClass} defaultValue="" required><option value="" disabled>Seleccione a origem</option>{sources.options.map((o) => <option key={`${o.delivery_event_id}:${o.line_index}`} value={`${o.delivery_event_id}:${o.line_index}`}>Entrega #{o.delivery_event_id} · {o.item.code} · {o.item.name} · entregue {milli(o.delivered_milli)} {o.item.unit}</option>)}</select></label>
|
||||
<label>Quantidade efectivamente devolvida<input name="quantity" className={controlClass} pattern="[0-9]{1,6}(\.[0-9]{1,3})?" required /></label><label>Evidência de excedente e entrega física<textarea name="evidence" className={controlClass} minLength={10} maxLength={1000} required /></label><label>Fundamento<textarea name="reason" className={controlClass} minLength={10} maxLength={1000} required /></label><label><input type="checkbox" name="declared_unused" required />Declaro que esta quantidade não foi consumida</label><Button disabled={busy}>Conferir impacto</Button></form>
|
||||
<Button disabled={sourcePage <= 1 || busy} onClick={() => setSourcePage((x) => x - 1)}>Entregas anteriores</Button><Button disabled={sourcePage >= sources.pagination.last_page || busy} onClick={() => setSourcePage((x) => x + 1)}>Entregas seguintes</Button></Panel>}
|
||||
{preview && <Panel title={`Prévia da proposta #${preview.id}`}><WarehouseReturnImpact impact={preview.impact} /><p>{preview.state&&preview.state!=='prepared'?`Decisão já registada: ${states[preview.state]??'Arquivada'}. Sem novo efeito.`:'A preparação não altera stock. Aguarda outra identidade autorizada.'}</p></Panel>}
|
||||
<Panel title="Histórico e decisões"><label>Estado<select className={controlClass} value={state} onChange={(e) => { setState(e.target.value); setPage(1); }}><option value="all">Todos</option><option value="prepared">Por confirmar</option><option value="confirmed">Confirmados</option><option value="withdrawn">Retirados</option><option value="rejected">Recusados</option></select></label>
|
||||
{!history ? <p role="status">A consultar decisões…</p> : <>{history.rows.map((r) => <article key={r.id} className="space-y-3 border-b py-4"><h3>Proposta #{r.prepared_id} · v{r.version} · {states[r.state]??'Estado arquivado'}</h3><p>{r.state==="confirmed"?"Entrada efectuada":r.state==="prepared"?"Impacto proposto":"Prévia arquivada, não executada"}</p><WarehouseReturnImpact impact={r.impact} /><p>{r.reason} · Evidência: {r.evidence}</p><p>Preparação #{r.preparer_id} · Autor desta versão #{r.author_id} · {r.created_at}</p>
|
||||
{r.state === 'prepared' && canConfirm && r.preparer_id !== actorId && <form onSubmit={(e) => confirm(e, r)}><label>Fundamento da recepção<textarea name="reason" className={controlClass} minLength={10} maxLength={1000} required /></label><label><input type="checkbox" name="received_in_warehouse" required />Recebi fisicamente esta quantidade no armazém indicado</label><Button disabled={busy}>Confirmar entrada conferida</Button></form>}<>{r.state==="prepared"&&canWithdraw&&r.preparer_id===actorId&&<details><summary>Retirar proposta sem movimento</summary><form onSubmit={e=>close(e,r,"withdraw")}><label>Fundamento da retirada<textarea name="reason" className={controlClass} minLength={10} maxLength={1000} required/></label><Button disabled={busy}>Retirar proposta</Button></form></details>}{r.state==="prepared"&&canConfirm&&r.preparer_id!==actorId&&<details><summary>Recusar recepção sem movimento</summary><form onSubmit={e=>close(e,r,"reject")}><label>Fundamento da recusa<textarea name="reason" className={controlClass} minLength={10} maxLength={1000} required/></label><Button disabled={busy}>Recusar conferência</Button></form></details>}</></article>)}{!history.rows.length && <p>Sem decisões neste filtro.</p>}<Button disabled={page <= 1 || busy} onClick={() => setPage((x) => x - 1)}>Anterior</Button><Button disabled={page >= history.pagination.last_page || busy} onClick={() => setPage((x) => x + 1)}>Seguinte</Button></>}
|
||||
</Panel></div></>;
|
||||
}
|
||||
Reference in New Issue
Block a user