feat(warehouse): экран «Выдача запчастей» на машину и журнал выдач (задача 5763)

Механик выбирает машину по госномеру, набирает детали из складского каталога
(тот же PartsPickerModal, что в ремонте), пишет комментарий — детали
списываются сразу, без карточки ремонта. Ключ идемпотентности живёт пока
открыта форма. Журнал показывает выдачи и списания в ремонт рядом.

Плитка в меню видна всем, кто вошёл в приложение (гейт require_mechanic на
сервере). Заодно плитки меню переведены с эмодзи на иконки lucide по правилу
проекта, а выбор машины вынесен в общий CarPicker (используется и резиной).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
tremble7681andClaude Fable 5.1 committed 2026-09-24 12:03:53 +10:00
1 parent b3e5d05849
commit a78f0e9632
7 files changed
+531 -71

No files matched your search

+5
View File
@@ -22,6 +22,8 @@ import StocktakePage from "@/pages/warehouse/StocktakePage";
import TyresPage from "@/pages/warehouse/TyresPage";
import TyreSizesPage from "@/pages/warehouse/TyreSizesPage";
import TyreJournalPage from "@/pages/warehouse/TyreJournalPage";
import PartsIssuePage from "@/pages/warehouse/PartsIssuePage";
import PartsIssueJournalPage from "@/pages/warehouse/PartsIssueJournalPage";
import StocktakeSessionPage from "@/pages/warehouse/StocktakeSessionPage";
function RequireAuth({ children }: { children: React.ReactNode }) {
@@ -92,6 +94,9 @@ export default function App() {
<Route path="/wh/tyres" element={<RequireTyres><TyresPage /></RequireTyres>} />
<Route path="/wh/tyres/sizes" element={<RequireTyres><TyreSizesPage /></RequireTyres>} />
<Route path="/wh/tyres/journal" element={<RequireTyres><TyreJournalPage /></RequireTyres>} />
{/* Выдача запчастей (5763) — всем, кто вошёл в PWA: гейт на сервере require_mechanic. */}
<Route path="/wh/issues" element={<RequireAuth><PartsIssuePage /></RequireAuth>} />
<Route path="/wh/issues/journal" element={<RequireAuth><PartsIssueJournalPage /></RequireAuth>} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
);
@@ -500,3 +500,67 @@ export async function setTyreSize(body: {
export async function getTyreStock(): Promise<TyreStockRow[]> {
return api.get("wh/tyres/stock").json<TyreStockRow[]>();
}
// ── Выдача запчастей на машину (задача 5763) ──────────────────────────────
//
// Отдельно от списания в ремонт: механик ставит деталь на машину, а карточки
// ремонта под это может и не быть. Строки — по номенклатуре, партию выбирает
// склад; недостача уходит в минус, как у ремонта и резины.
export interface PartsIssueLineIn {
part_id: number;
qty: number;
}
export interface PartsIssueLine {
batch_id: number;
part_id: number;
part_name: string;
qty: number;
unit_price: number | string;
amount: number | string;
}
export interface PartsIssue {
id: number;
repair_id: number | null;
car_id: number | null;
car_number: string | null;
car_brand: string | null;
car_model: string | null;
comment: string | null;
user_id: number | null;
user_name: string | null;
total_amount: number | string;
lines: PartsIssueLine[];
created_at: string;
}
export interface PartsIssueListResponse {
items: PartsIssue[];
total: number;
}
/** Выдать детали на машину. Ключ идемпотентности живёт, пока открыта форма:
* ретрай после обрыва связи попадает в ту же выдачу, а не создаёт вторую. */
export async function issueParts(
body: { car_id: number; lines: PartsIssueLineIn[]; comment?: string | null },
idempotencyKey: string,
): Promise<PartsIssue> {
return api
.post("wh/issues", { json: body, headers: { "Idempotency-Key": idempotencyKey } })
.json<PartsIssue>();
}
export async function getPartsIssues(params?: {
car_id?: number;
without_repair?: boolean;
limit?: number;
}): Promise<PartsIssueListResponse> {
const qs = new URLSearchParams();
if (params?.car_id) qs.set("car_id", String(params.car_id));
if (params?.without_repair) qs.set("without_repair", "true");
if (params?.limit) qs.set("limit", String(params.limit));
const s = qs.toString();
return api.get(`wh/issues${s ? `?${s}` : ""}`).json<PartsIssueListResponse>();
}
@@ -0,0 +1,74 @@
/**
* Выбор машины парка по госномеру — общий для складских экранов PWA
* (выдача резины, выдача запчастей).
*
* Поиск с задержкой 200 мс: у подъёмника номер набирают по буквам, и запрос
* на каждую букву по слабой связи только замедлит список. Пока новый ответ не
* пришёл, на экране остаётся прошлый список — без мигания «Загрузка…» на
* каждую букву.
*/
import { useEffect, useState } from "react";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { Search } from "lucide-react";
import { Input } from "@/components/ui/input";
import { searchCars } from "@/api/repairsCreate";
function useDebounced<T>(value: T, ms: number): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const t = setTimeout(() => setDebounced(value), ms);
return () => clearTimeout(t);
}, [value, ms]);
return debounced;
}
export default function CarPicker({ onPick }: { onPick: (carId: number) => void }) {
const [q, setQ] = useState("");
const debouncedQ = useDebounced(q, 200);
const carsQuery = useQuery({
queryKey: ["cars-search", debouncedQ],
queryFn: () => searchCars(debouncedQ),
placeholderData: keepPreviousData,
staleTime: 30_000,
});
const cars = carsQuery.data ?? [];
const loading = carsQuery.isLoading;
return (
<>
<div className="px-3 py-3 border-b">
<div className="relative">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
autoFocus
placeholder="Госномер…"
value={q}
onChange={(e) => setQ(e.target.value)}
className="pl-8"
/>
</div>
</div>
<main className="flex-1 divide-y">
{loading && <p className="p-4 text-sm text-muted-foreground">Загрузка…</p>}
{!loading && cars.length === 0 && (
<p className="p-4 text-sm text-muted-foreground">
{carsQuery.isError ? "Не удалось загрузить список машин" : "Ничего не нашлось"}
</p>
)}
{cars.map((c) => (
<button
key={c.id}
onClick={() => onPick(c.id)}
className="w-full text-left p-3 active:bg-muted flex items-baseline gap-3"
>
<span className="font-mono font-semibold">{c.plate ?? "—"}</span>
<span className="text-sm text-muted-foreground">
{[c.brand, c.model].filter(Boolean).join(" ")}
</span>
</button>
))}
</main>
</>
);
}
+27 -7
View File
@@ -1,5 +1,14 @@
import { useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import {
CircleDot,
ClipboardList,
PackageMinus,
PackagePlus,
Search,
Wrench,
type LucideIcon,
} from "lucide-react";
import { getMe } from "@/api/me";
import { logout } from "@/api/auth";
import { Card } from "@/components/ui/card";
@@ -9,7 +18,9 @@ interface ActionTile {
key: string;
title: string;
description: string;
emoji: string;
// Иконка из пака, не эмодзи: эмодзи рисуется системным шрифтом и на каждом
// телефоне выглядит по-своему (правило проекта — иконки только из паков).
icon: LucideIcon;
onClick: () => void;
disabled?: boolean;
comingSoon?: boolean;
@@ -24,16 +35,25 @@ export default function ActionMenu() {
key: "inspect",
title: "Осмотр",
description: "Создать или продолжить осмотр машины",
emoji: "🔍",
icon: Search,
onClick: () => navigate("/vehicles?action=inspect"),
},
{
key: "repair",
title: "Ремонт",
description: "Лента ремонтов парка + создать новый",
emoji: "🔧",
icon: Wrench,
onClick: () => navigate("/repairs"),
},
// Выдача запчастей на машину без ремонта (задача 5763) — всему отделу
// авторемонта, то есть каждому, кто вошёл в приложение.
{
key: "issues",
title: "Выдача запчастей",
description: "Списать детали со склада на машину — без карточки ремонта",
icon: PackageMinus,
onClick: () => navigate("/wh/issues"),
},
// Приёмка и инвентаризация правят остатки и деньги — пока только админам
// (тот же гейт стоит на сервере, здесь просто не показываем лишнего).
...(meQuery.data?.is_admin
@@ -42,14 +62,14 @@ export default function ActionMenu() {
key: "receiving",
title: "Приёмка",
description: "Снять накладную камерой и оприходовать товар",
emoji: "📦",
icon: PackagePlus,
onClick: () => navigate("/wh/receiving"),
},
{
key: "stocktake",
title: "Инвентаризация",
description: "Пересчитать зону склада и провести расхождения",
emoji: "📋",
icon: ClipboardList,
onClick: () => navigate("/wh/stocktake"),
},
]
@@ -62,7 +82,7 @@ export default function ActionMenu() {
key: "tyres",
title: "Выдача резины",
description: "Сезонная переобувка: выдать комплект и закрыть старый",
emoji: "🛞",
icon: CircleDot,
onClick: () => navigate("/wh/tyres"),
},
]
@@ -107,7 +127,7 @@ export default function ActionMenu() {
}
>
<div className="flex items-start gap-3">
<div className="text-3xl leading-none">{t.emoji}</div>
<t.icon className="h-7 w-7 shrink-0 text-primary" strokeWidth={1.5} />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<h3 className="font-semibold text-base">{t.title}</h3>
@@ -0,0 +1,117 @@
/**
* Журнал выдач запчастей.
*
* Отвечает на вопрос «эту деталь на эту машину уже брали?» — поэтому по
* умолчанию показывает и выдачи на машину, и списания в ремонт: физически это
* одно и то же событие «деталь ушла со склада», а различаются они только тем,
* есть ли карточка ремонта. Переключатель оставляет только выдачи без ремонта.
*/
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { ChevronLeft } from "lucide-react";
import { Button } from "@/components/ui/button";
import { getPartsIssues, type PartsIssue } from "@/api/warehouse";
const FILTERS: { key: boolean; label: string }[] = [
{ key: false, label: "Все" },
{ key: true, label: "Без ремонта" },
];
function fmtDateTime(iso: string): string {
const d = new Date(iso);
return Number.isNaN(d.getTime())
? iso
: new Intl.DateTimeFormat("ru-RU", {
day: "2-digit",
month: "2-digit",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
}).format(d);
}
export default function PartsIssueJournalPage() {
const navigate = useNavigate();
const [withoutRepair, setWithoutRepair] = useState(false);
const q = useQuery({
queryKey: ["parts-issues", withoutRepair],
queryFn: () => getPartsIssues({ without_repair: withoutRepair, limit: 100 }),
staleTime: 15_000,
});
const items = q.data?.items ?? [];
return (
<div className="min-h-screen bg-background flex flex-col">
<header className="sticky top-0 z-10 bg-background/95 backdrop-blur border-b">
<div className="flex items-center gap-2 p-3">
<Button variant="ghost" size="sm" className="-ml-2" onClick={() => navigate("/wh/issues")}>
<ChevronLeft className="h-5 w-5" />
</Button>
<div>
<h1 className="text-base font-semibold">Журнал выдач</h1>
<p className="text-xs text-muted-foreground">всего записей: {q.data?.total ?? 0}</p>
</div>
</div>
<div className="flex gap-2 px-3 pb-3">
{FILTERS.map((f) => (
<Button
key={String(f.key)}
variant={withoutRepair === f.key ? "default" : "outline"}
size="sm"
onClick={() => setWithoutRepair(f.key)}
>
{f.label}
</Button>
))}
</div>
</header>
<main className="flex-1 divide-y">
{q.isLoading && <p className="p-4 text-sm text-muted-foreground">Загрузка…</p>}
{!q.isLoading && items.length === 0 && (
<p className="p-4 text-sm text-muted-foreground">Выдач пока не было.</p>
)}
{items.map((it) => (
<IssueRow key={it.id} issue={it} />
))}
</main>
</div>
);
}
function IssueRow({ issue }: { issue: PartsIssue }) {
return (
<div className="p-3">
<div className="flex items-baseline justify-between gap-2">
<span className="flex items-baseline gap-2 min-w-0">
<span className="font-mono font-semibold">{issue.car_number ?? "—"}</span>
<span className="text-sm text-muted-foreground truncate">
{[issue.car_brand, issue.car_model].filter(Boolean).join(" ")}
</span>
</span>
<span className="text-xs text-muted-foreground whitespace-nowrap">
{fmtDateTime(issue.created_at)}
</span>
</div>
<ul className="mt-1 text-sm">
{issue.lines.map((ln, i) => (
<li key={`${ln.batch_id}-${i}`} className="flex justify-between gap-2">
<span className="truncate">{ln.part_name}</span>
<span className="text-muted-foreground whitespace-nowrap">{ln.qty} шт</span>
</li>
))}
</ul>
<p className="text-xs text-muted-foreground mt-1">
{[
issue.repair_id ? `ремонт #${issue.repair_id}` : "без ремонта",
issue.user_name,
issue.comment,
]
.filter(Boolean)
.join(" · ")}
</p>
</div>
);
}
@@ -0,0 +1,242 @@
/**
* Выдача запчастей на машину — экран механика (задача 5763).
*
* Сценарий: деталь ставится на машину, а карточки ремонта под это нет
* (расходник, мелочь, донор). Выбрал машину → набрал детали со склада →
* комментарий → выдал. Со склада списывается сразу; партию выбирает склад,
* недостача уходит в минус — как в ремонте и резине: механика у подъёмника
* из-за неоприходованного прихода не останавливаем.
*
* Доступ — у всех, кто входит в приложение (весь отдел авторемонта): так
* решил постановщик задачи.
*/
import { useMemo, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { ChevronLeft, History, Plus, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import CarPicker from "@/components/warehouse/CarPicker";
import PartsPickerModal from "@/components/repairs/PartsPickerModal";
import QtyStepper from "@/components/repairs/QtyStepper";
import { getCarContext, type PartCatalogItem } from "@/api/repairsCreate";
import { apiErrorText, issueParts } from "@/api/warehouse";
interface Line {
part_id: number;
name: string;
article: string | null;
in_stock: number;
qty: number | "";
}
/** «Выдать 3 позиции» — по числу строк, а не штук: механик считает позициями. */
function issueLabel(n: number): string {
if (n === 0) return "Добавьте хотя бы одну деталь";
const mod10 = n % 10;
const mod100 = n % 100;
const noun =
mod10 === 1 && mod100 !== 11
? "позицию"
: mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)
? "позиции"
: "позиций";
return `Выдать ${n} ${noun}`;
}
export default function PartsIssuePage() {
const navigate = useNavigate();
const [sp, setSp] = useSearchParams();
const carId = sp.get("car") ? Number(sp.get("car")) : null;
return (
<div className="min-h-screen bg-background flex flex-col">
<header className="sticky top-0 z-10 bg-background/95 backdrop-blur border-b">
<div className="flex items-center justify-between p-3">
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="sm"
className="-ml-2"
onClick={() => (carId ? setSp({}, { replace: true }) : navigate("/"))}
>
<ChevronLeft className="h-5 w-5" />
</Button>
<h1 className="text-base font-semibold">Выдача запчастей</h1>
</div>
<Button variant="ghost" size="sm" onClick={() => navigate("/wh/issues/journal")}>
<History className="h-4 w-4 mr-1" />
Журнал
</Button>
</div>
</header>
{carId ? (
// key — чтобы смена машины давала чистую форму и новый ключ идемпотентности.
<IssueForm key={carId} carId={carId} onDone={() => setSp({}, { replace: true })} />
) : (
<CarPicker onPick={(id) => setSp({ car: String(id) }, { replace: true })} />
)}
</div>
);
}
function IssueForm({ carId, onDone }: { carId: number; onDone: () => void }) {
const ctxQuery = useQuery({
queryKey: ["car-ctx", carId],
queryFn: () => getCarContext(carId),
staleTime: 60_000,
});
const ctx = ctxQuery.data;
const [lines, setLines] = useState<Line[]>([]);
const [pickerOpen, setPickerOpen] = useState(false);
const [comment, setComment] = useState("");
const [saving, setSaving] = useState(false);
// Ключ идемпотентности живёт, пока форма открыта: ретрай после обрыва связи
// должен попасть в ТУ ЖЕ выдачу, а не создать вторую.
const [idemKey] = useState(() => crypto.randomUUID());
const addPart = (p: PartCatalogItem) => {
setLines((arr) => {
const existing = arr.find((l) => l.part_id === p.id);
// Та же деталь второй раз — плюс одна штука, а не вторая строка.
if (existing) {
return arr.map((l) =>
l.part_id === p.id ? { ...l, qty: (l.qty === "" ? 0 : l.qty) + 1 } : l,
);
}
return [...arr, { part_id: p.id, name: p.name, article: p.article, in_stock: p.in_stock, qty: 1 }];
});
setPickerOpen(false);
};
const setQty = (partId: number, qty: number | "") =>
setLines((arr) => arr.map((l) => (l.part_id === partId ? { ...l, qty } : l)));
const removeLine = (partId: number) =>
setLines((arr) => arr.filter((l) => l.part_id !== partId));
// Пустое поле количества — легальное состояние во время набора (см. QtyStepper);
// на отправке приводим к единице.
const normalized = useMemo(
() => lines.map((l) => ({ part_id: l.part_id, qty: l.qty === "" || l.qty < 1 ? 1 : l.qty })),
[lines],
);
const shortages = lines.filter((l) => {
const q = l.qty === "" ? 1 : l.qty;
return q > l.in_stock;
});
const submit = async () => {
if (normalized.length === 0) {
toast.error("Добавьте хотя бы одну деталь");
return;
}
setSaving(true);
try {
const issued = await issueParts(
{ car_id: carId, lines: normalized, comment: comment.trim() || null },
idemKey,
);
const total = issued.lines.reduce((s, ln) => s + ln.qty, 0);
toast.success(`Выдано ${total} шт · ${issued.car_number ?? ""}`.trim());
onDone();
} catch (e) {
toast.error(await apiErrorText(e, "Не удалось выдать запчасти"));
setSaving(false);
}
};
if (ctxQuery.isLoading) {
return <main className="p-4 text-sm text-muted-foreground">Загрузка…</main>;
}
if (!ctx) {
return <main className="p-4 text-sm text-destructive">Не удалось загрузить машину</main>;
}
return (
<main className="flex-1 pb-28">
{/* Машина и арендатор */}
<section className="p-3 border-b">
<div className="flex items-baseline gap-3">
<span className="font-mono text-lg font-semibold">{ctx.plate ?? "—"}</span>
<span className="text-sm text-muted-foreground">
{[ctx.brand, ctx.model].filter(Boolean).join(" ")}
</span>
</div>
<p className="text-sm text-muted-foreground mt-0.5">
{ctx.driver_name ? `Водитель: ${ctx.driver_name}` : "Водитель не определён"}
</p>
</section>
{/* Что выдаём */}
<section className="p-3 border-b">
<div className="flex items-center justify-between mb-2">
<h2 className="text-sm font-semibold">Что выдаём</h2>
<Button variant="outline" size="sm" onClick={() => setPickerOpen(true)}>
<Plus className="h-3 w-3 mr-1" />
Добавить деталь
</Button>
</div>
{lines.length === 0 ? (
<p className="text-sm text-muted-foreground">
Детали выбираются со склада и списываются сразу при выдаче.
</p>
) : (
<ul className="space-y-2">
{lines.map((l) => (
<li key={l.part_id} className="flex items-center gap-2 text-sm">
<div className="flex-1 min-w-0">
<div className="truncate">{l.name}</div>
<div className="text-xs text-muted-foreground">
{l.article ? `арт. ${l.article} · ` : ""}
{l.in_stock > 0
? `на складе: ${l.in_stock}`
: l.in_stock < 0
? `на складе: ${l.in_stock}`
: "нет в наличии"}
</div>
</div>
<QtyStepper value={l.qty} onChange={(next) => setQty(l.part_id, next)} />
<Button variant="ghost" size="sm" onClick={() => removeLine(l.part_id)} aria-label="Убрать">
<Trash2 className="h-3 w-3" />
</Button>
</li>
))}
</ul>
)}
{shortages.length > 0 && (
<p className="text-sm text-amber-700 dark:text-amber-500 mt-2">
{shortages.length === 1
? `«${shortages[0].name}» — на складе меньше, чем выдаём. Склад уйдёт в минус, выдать можно.`
: `По ${shortages.length} позициям на складе меньше, чем выдаём. Склад уйдёт в минус, выдать можно.`}
</p>
)}
</section>
{/* Комментарий */}
<section className="p-3 border-b">
<Input
placeholder="Комментарий (необязательно) — что и зачем поставили"
value={comment}
onChange={(e) => setComment(e.target.value)}
/>
</section>
{/* Кнопка выдачи */}
<div className="fixed bottom-0 left-0 right-0 border-t bg-background p-3">
<Button className="w-full" disabled={saving || lines.length === 0} onClick={submit}>
{saving ? "Выдаём…" : issueLabel(lines.length)}
</Button>
</div>
<PartsPickerModal
open={pickerOpen}
carId={carId}
onPick={addPart}
onClose={() => setPickerOpen(false)}
/>
</main>
);
}
@@ -13,11 +13,11 @@
import { useEffect, useMemo, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { ChevronLeft, Circle, History, Ruler, Search } from "lucide-react";
import { ChevronLeft, Circle, History, Ruler } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { searchCars, type CarBrief } from "@/api/repairsCreate";
import CarPicker from "@/components/warehouse/CarPicker";
import {
apiErrorText,
getTyreContext,
@@ -101,68 +101,6 @@ export default function TyresPage() {
);
}
// ── Выбор машины ───────────────────────────────────────────────────────────
function CarPicker({ onPick }: { onPick: (carId: number) => void }) {
const [q, setQ] = useState("");
const [cars, setCars] = useState<CarBrief[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
let cancelled = false;
setLoading(true);
const t = setTimeout(async () => {
try {
const list = await searchCars(q);
if (!cancelled) setCars(list);
} catch {
if (!cancelled) setCars([]);
} finally {
if (!cancelled) setLoading(false);
}
}, 200);
return () => {
cancelled = true;
clearTimeout(t);
};
}, [q]);
return (
<>
<div className="px-3 py-3 border-b">
<div className="relative">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
autoFocus
placeholder="Госномер…"
value={q}
onChange={(e) => setQ(e.target.value)}
className="pl-8"
/>
</div>
</div>
<main className="flex-1 divide-y">
{loading && <p className="p-4 text-sm text-muted-foreground">Загрузка…</p>}
{!loading && cars.length === 0 && (
<p className="p-4 text-sm text-muted-foreground">Ничего не нашлось</p>
)}
{cars.map((c) => (
<button
key={c.id}
onClick={() => onPick(c.id)}
className="w-full text-left p-3 active:bg-muted flex items-baseline gap-3"
>
<span className="font-mono font-semibold">{c.plate ?? "—"}</span>
<span className="text-sm text-muted-foreground">
{[c.brand, c.model].filter(Boolean).join(" ")}
</span>
</button>
))}
</main>
</>
);
}
// ── Выдача ─────────────────────────────────────────────────────────────────
function IssueForm({ carId, onDone }: { carId: number; onDone: () => void }) {