From a78f0e9632542cca8dc2789213753725548b2ca0 Mon Sep 17 00:00:00 2001 From: vladtechno Date: Thu, 24 Sep 2026 12:03:53 +1000 Subject: [PATCH] =?UTF-8?q?feat(warehouse):=20=D1=8D=D0=BA=D1=80=D0=B0?= =?UTF-8?q?=D0=BD=20=C2=AB=D0=92=D1=8B=D0=B4=D0=B0=D1=87=D0=B0=20=D0=B7?= =?UTF-8?q?=D0=B0=D0=BF=D1=87=D0=B0=D1=81=D1=82=D0=B5=D0=B9=C2=BB=20=D0=BD?= =?UTF-8?q?=D0=B0=20=D0=BC=D0=B0=D1=88=D0=B8=D0=BD=D1=83=20=D0=B8=20=D0=B6?= =?UTF-8?q?=D1=83=D1=80=D0=BD=D0=B0=D0=BB=20=D0=B2=D1=8B=D0=B4=D0=B0=D1=87?= =?UTF-8?q?=20(=D0=B7=D0=B0=D0=B4=D0=B0=D1=87=D0=B0=205763)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Механик выбирает машину по госномеру, набирает детали из складского каталога (тот же PartsPickerModal, что в ремонте), пишет комментарий — детали списываются сразу, без карточки ремонта. Ключ идемпотентности живёт пока открыта форма. Журнал показывает выдачи и списания в ремонт рядом. Плитка в меню видна всем, кто вошёл в приложение (гейт require_mechanic на сервере). Заодно плитки меню переведены с эмодзи на иконки lucide по правилу проекта, а выбор машины вынесен в общий CarPicker (используется и резиной). Co-Authored-By: Claude Fable 5.1 --- mechanic-pwa/frontend/src/App.tsx | 5 + mechanic-pwa/frontend/src/api/warehouse.ts | 64 +++++ .../src/components/warehouse/CarPicker.tsx | 74 ++++++ .../frontend/src/pages/ActionMenu.tsx | 34 ++- .../pages/warehouse/PartsIssueJournalPage.tsx | 117 +++++++++ .../src/pages/warehouse/PartsIssuePage.tsx | 242 ++++++++++++++++++ .../src/pages/warehouse/TyresPage.tsx | 66 +---- 7 files changed, 531 insertions(+), 71 deletions(-) create mode 100644 mechanic-pwa/frontend/src/components/warehouse/CarPicker.tsx create mode 100644 mechanic-pwa/frontend/src/pages/warehouse/PartsIssueJournalPage.tsx create mode 100644 mechanic-pwa/frontend/src/pages/warehouse/PartsIssuePage.tsx diff --git a/mechanic-pwa/frontend/src/App.tsx b/mechanic-pwa/frontend/src/App.tsx index 50eb33b..8542737 100644 --- a/mechanic-pwa/frontend/src/App.tsx +++ b/mechanic-pwa/frontend/src/App.tsx @@ -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() { } /> } /> } /> + {/* Выдача запчастей (5763) — всем, кто вошёл в PWA: гейт на сервере require_mechanic. */} + } /> + } /> } /> ); diff --git a/mechanic-pwa/frontend/src/api/warehouse.ts b/mechanic-pwa/frontend/src/api/warehouse.ts index c5d8197..d1cdb5f 100644 --- a/mechanic-pwa/frontend/src/api/warehouse.ts +++ b/mechanic-pwa/frontend/src/api/warehouse.ts @@ -500,3 +500,67 @@ export async function setTyreSize(body: { export async function getTyreStock(): Promise { return api.get("wh/tyres/stock").json(); } + +// ── Выдача запчастей на машину (задача 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 { + return api + .post("wh/issues", { json: body, headers: { "Idempotency-Key": idempotencyKey } }) + .json(); +} + +export async function getPartsIssues(params?: { + car_id?: number; + without_repair?: boolean; + limit?: number; +}): Promise { + 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(); +} diff --git a/mechanic-pwa/frontend/src/components/warehouse/CarPicker.tsx b/mechanic-pwa/frontend/src/components/warehouse/CarPicker.tsx new file mode 100644 index 0000000..7e9cb3f --- /dev/null +++ b/mechanic-pwa/frontend/src/components/warehouse/CarPicker.tsx @@ -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(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 ( + <> +
+
+ + setQ(e.target.value)} + className="pl-8" + /> +
+
+
+ {loading &&

Загрузка…

} + {!loading && cars.length === 0 && ( +

+ {carsQuery.isError ? "Не удалось загрузить список машин" : "Ничего не нашлось"} +

+ )} + {cars.map((c) => ( + + ))} +
+ + ); +} diff --git a/mechanic-pwa/frontend/src/pages/ActionMenu.tsx b/mechanic-pwa/frontend/src/pages/ActionMenu.tsx index 788b63f..435548d 100644 --- a/mechanic-pwa/frontend/src/pages/ActionMenu.tsx +++ b/mechanic-pwa/frontend/src/pages/ActionMenu.tsx @@ -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() { } >
-
{t.emoji}
+

{t.title}

diff --git a/mechanic-pwa/frontend/src/pages/warehouse/PartsIssueJournalPage.tsx b/mechanic-pwa/frontend/src/pages/warehouse/PartsIssueJournalPage.tsx new file mode 100644 index 0000000..1817d1b --- /dev/null +++ b/mechanic-pwa/frontend/src/pages/warehouse/PartsIssueJournalPage.tsx @@ -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 ( +
+
+
+ +
+

Журнал выдач

+

всего записей: {q.data?.total ?? 0}

+
+
+
+ {FILTERS.map((f) => ( + + ))} +
+
+ +
+ {q.isLoading &&

Загрузка…

} + {!q.isLoading && items.length === 0 && ( +

Выдач пока не было.

+ )} + {items.map((it) => ( + + ))} +
+
+ ); +} + +function IssueRow({ issue }: { issue: PartsIssue }) { + return ( +
+
+ + {issue.car_number ?? "—"} + + {[issue.car_brand, issue.car_model].filter(Boolean).join(" ")} + + + + {fmtDateTime(issue.created_at)} + +
+
    + {issue.lines.map((ln, i) => ( +
  • + {ln.part_name} + {ln.qty} шт +
  • + ))} +
+

+ {[ + issue.repair_id ? `ремонт #${issue.repair_id}` : "без ремонта", + issue.user_name, + issue.comment, + ] + .filter(Boolean) + .join(" · ")} +

+
+ ); +} diff --git a/mechanic-pwa/frontend/src/pages/warehouse/PartsIssuePage.tsx b/mechanic-pwa/frontend/src/pages/warehouse/PartsIssuePage.tsx new file mode 100644 index 0000000..7584ef5 --- /dev/null +++ b/mechanic-pwa/frontend/src/pages/warehouse/PartsIssuePage.tsx @@ -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 ( +
+
+
+
+ +

Выдача запчастей

+
+ +
+
+ + {carId ? ( + // key — чтобы смена машины давала чистую форму и новый ключ идемпотентности. + setSp({}, { replace: true })} /> + ) : ( + setSp({ car: String(id) }, { replace: true })} /> + )} +
+ ); +} + +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([]); + 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
Загрузка…
; + } + if (!ctx) { + return
Не удалось загрузить машину
; + } + + return ( +
+ {/* Машина и арендатор */} +
+
+ {ctx.plate ?? "—"} + + {[ctx.brand, ctx.model].filter(Boolean).join(" ")} + +
+

+ {ctx.driver_name ? `Водитель: ${ctx.driver_name}` : "Водитель не определён"} +

+
+ + {/* Что выдаём */} +
+
+

Что выдаём

+ +
+ {lines.length === 0 ? ( +

+ Детали выбираются со склада и списываются сразу при выдаче. +

+ ) : ( +
    + {lines.map((l) => ( +
  • +
    +
    {l.name}
    +
    + {l.article ? `арт. ${l.article} · ` : ""} + {l.in_stock > 0 + ? `на складе: ${l.in_stock}` + : l.in_stock < 0 + ? `на складе: ${l.in_stock}` + : "нет в наличии"} +
    +
    + setQty(l.part_id, next)} /> + +
  • + ))} +
+ )} + {shortages.length > 0 && ( +

+ {shortages.length === 1 + ? `«${shortages[0].name}» — на складе меньше, чем выдаём. Склад уйдёт в минус, выдать можно.` + : `По ${shortages.length} позициям на складе меньше, чем выдаём. Склад уйдёт в минус, выдать можно.`} +

+ )} +
+ + {/* Комментарий */} +
+ setComment(e.target.value)} + /> +
+ + {/* Кнопка выдачи */} +
+ +
+ + setPickerOpen(false)} + /> +
+ ); +} diff --git a/mechanic-pwa/frontend/src/pages/warehouse/TyresPage.tsx b/mechanic-pwa/frontend/src/pages/warehouse/TyresPage.tsx index b05dc92..65a7651 100644 --- a/mechanic-pwa/frontend/src/pages/warehouse/TyresPage.tsx +++ b/mechanic-pwa/frontend/src/pages/warehouse/TyresPage.tsx @@ -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([]); - 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 ( - <> -
-
- - setQ(e.target.value)} - className="pl-8" - /> -
-
-
- {loading &&

Загрузка…

} - {!loading && cars.length === 0 && ( -

Ничего не нашлось

- )} - {cars.map((c) => ( - - ))} -
- - ); -} - // ── Выдача ───────────────────────────────────────────────────────────────── function IssueForm({ carId, onDone }: { carId: number; onDone: () => void }) {