wip(local): repairs Edit+Detail snapshot 2026-05-25

Untracked: EditRepairPage, RepairDetailPage
Modified: App.tsx, repairsFeed.ts, InspectionEditor.tsx, CreateRepairPage.tsx
+ public/icons docx files (oferta, 1032_*)

Snapshot to prevent loss; main untouched at a5bd730.
This commit is contained in:
2026-05-25 00:18:41 +10:00
parent a5bd7308b5
commit 85f3a5c682
9 changed files with 1045 additions and 26 deletions
+4
View File
@@ -9,6 +9,8 @@ import InspectionEditor from "@/pages/InspectionEditor";
import InspectionReview from "@/pages/InspectionReview";
import TtStateDetail from "@/pages/TtStateDetail";
import RepairsFeedPage from "@/pages/repairs/RepairsFeedPage";
import RepairDetailPage from "@/pages/repairs/RepairDetailPage";
import EditRepairPage from "@/pages/repairs/EditRepairPage";
import CarSelectPage from "@/pages/repairs/CarSelectPage";
import CreateRepairPage from "@/pages/repairs/CreateRepairPage";
@@ -37,6 +39,8 @@ export default function App() {
<Route path="/repairs" element={<RequireAuth><RepairsFeedPage /></RequireAuth>} />
<Route path="/repairs/new" element={<RequireAuth><CarSelectPage /></RequireAuth>} />
<Route path="/repairs/new/:carId" element={<RequireAuth><CreateRepairPage /></RequireAuth>} />
<Route path="/repairs/:id" element={<RequireAuth><RepairDetailPage /></RequireAuth>} />
<Route path="/repairs/:id/edit" element={<RequireAuth><EditRepairPage /></RequireAuth>} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
);
@@ -36,3 +36,88 @@ export async function getRepairsFeed(params: FeedParams = {}): Promise<FeedRespo
.get(`repairs${qs ? `?${qs}` : ""}`)
.json<FeedResponse>();
}
// ── Детальная карточка ремонта ─────────────────────────────────────────────
export interface RepairDetailWork {
id: number;
work_catalog_id: number;
name: string;
price_applied: number;
manual_override: boolean;
override_comment: string | null;
}
export interface RepairDetailPart {
id: number;
name: string;
qty: number;
}
export interface RepairDetailPhoto {
photo_uuid: string;
thumb_url: string | null;
orig_url: string | null;
}
export interface RepairDetailOil {
mileage_at_change: number | null;
next_in_km: number | null;
has_sticker: boolean;
sticker_thumb_url: string | null;
sticker_orig_url: string | null;
}
export interface RepairDetailResponse {
id: number;
created_at: string;
car_plate: string | null;
car_make: string | null;
car_model: string | null;
driver_name: string | null;
mechanic_name: string | null;
mileage: number | null;
works: RepairDetailWork[];
parts: RepairDetailPart[];
photos: RepairDetailPhoto[];
oil_change: RepairDetailOil | null;
total_sum: number;
edited_in_crm: boolean;
can_edit: boolean;
edit_until: string | null;
}
export async function getRepairDetail(id: number): Promise<RepairDetailResponse> {
return api.get(`repairs/${id}`).json<RepairDetailResponse>();
}
// ── PATCH (правка в 1-часовом окне У49) ────────────────────────────────────
export interface PatchWork {
work_catalog_id: number;
price_applied: number;
manual_override: boolean;
override_comment: string | null;
}
export interface PatchPart {
name: string;
qty: number;
}
export interface PatchOilChange {
enabled: boolean;
mileage_at_change: number | null;
next_in_km: number | null;
}
export interface PatchRepairPayload {
mileage: number | null;
works: PatchWork[];
parts: PatchPart[];
oil_change: PatchOilChange | null;
}
export async function patchRepair(id: number, body: PatchRepairPayload): Promise<RepairDetailResponse> {
return api.patch(`repairs/${id}`, { json: body }).json<RepairDetailResponse>();
}
@@ -37,13 +37,17 @@ const SLOTS_GENERAL: { side: string; label: string }[] = [
];
const SLOT_JACK = { side: "jack", label: "Домкрат" };
// Шильдик замены масла — отдельный слот при выдаче/приёмке.
// Фото нужно как для сверки текущего пробега со следующим ТО, так и для
// контроля что водитель не клеит свой стикер.
const SLOT_OIL_STICKER = { side: "oil-sticker", label: "Шильдик замены масла" };
/** Все типы осмотров (выдача/приёмка/плановый/...) показывают одинаковый
* набор слотов общих ракурсов + домкрат. Раньше «return» исключал общие
* фото в пользу скорости приёмки, но фидбек: при приёмке всё равно надо
* фиксировать общее состояние машины, как и при выдаче/осмотре. */
function slotsForType(_type: string): typeof SLOTS_GENERAL {
return [...SLOTS_GENERAL, SLOT_JACK];
return [...SLOTS_GENERAL, SLOT_JACK, SLOT_OIL_STICKER];
}
const SEVERITY_LABELS: Record<string, string> = {
@@ -41,6 +41,10 @@ interface PhotoState {
tag: "auto" | "part" | "other";
status: "uploading" | "uploaded" | "error";
errorMessage?: string;
// Превью локального файла через URL.createObjectURL — отдаётся в <img>
// вместо плейсхолдера «Загружено». Освобождается через revokeObjectURL
// при удалении и при размонтировании страницы.
previewUrl?: string;
}
interface WorkRow {
@@ -70,6 +74,14 @@ interface OilChangeState {
}
// Цены ремонта — целые рубли без копеек. API отдаёт Numeric(10,2)
// строкой типа "500.00" — пропускаем через округление при отображении.
function fmtPrice(p: number | string): string {
const n = Number(p);
if (Number.isNaN(n)) return String(p);
return new Intl.NumberFormat("ru-RU", { maximumFractionDigits: 0 }).format(Math.round(n));
}
function uuid4(): string {
// crypto.randomUUID требует secure context; mechanic.pptaxi.ru — https.
return (crypto as any).randomUUID
@@ -132,6 +144,7 @@ export default function CreateRepairPage() {
if (!files || files.length === 0) return;
for (const file of Array.from(files)) {
const ext = (file.name.split(".").pop() || "jpg").toLowerCase();
const previewUrl = URL.createObjectURL(file);
const placeholder: PhotoState = {
presign: {
photo_uuid: uuid4(),
@@ -143,6 +156,7 @@ export default function CreateRepairPage() {
},
tag: "auto",
status: "uploading",
previewUrl,
};
if (target === "gallery") setPhotos((arr) => [...arr, placeholder]);
else setOilChange((oc) => ({ ...oc, sticker: { ...placeholder, tag: "auto" } }));
@@ -150,7 +164,7 @@ export default function CreateRepairPage() {
try {
const presign = await presignPhoto(ext, placeholder.presign.photo_uuid);
await uploadPhotoToTmp(file, presign);
const updated: PhotoState = { presign, tag: "auto", status: "uploaded" };
const updated: PhotoState = { presign, tag: "auto", status: "uploaded", previewUrl };
if (target === "gallery") {
setPhotos((arr) =>
arr.map((p) => (p.presign.photo_uuid === presign.photo_uuid ? updated : p)),
@@ -179,7 +193,11 @@ export default function CreateRepairPage() {
};
const removePhoto = (photoUuid: string) =>
setPhotos((arr) => arr.filter((p) => p.presign.photo_uuid !== photoUuid));
setPhotos((arr) => {
const target = arr.find((p) => p.presign.photo_uuid === photoUuid);
if (target?.previewUrl) URL.revokeObjectURL(target.previewUrl);
return arr.filter((p) => p.presign.photo_uuid !== photoUuid);
});
// ── Works picker ─────────────────────────────────────────────────────────
@@ -196,7 +214,7 @@ export default function CreateRepairPage() {
};
const addWorkFromCatalog = (w: MechWork) => {
const price = Number(w.price);
const price = Math.round(Number(w.price));
setWorks((arr) => [
...arr,
{
@@ -395,17 +413,28 @@ export default function CreateRepairPage() {
<div className="grid grid-cols-3 gap-2 mt-2">
{photos.map((p) => (
<div key={p.presign.photo_uuid} className="relative aspect-square border rounded-md bg-muted overflow-hidden">
{p.previewUrl && (
<img
src={p.previewUrl}
alt=""
className="absolute inset-0 w-full h-full object-cover"
/>
)}
{p.status === "uploading" && (
<div className="absolute inset-0 flex items-center justify-center text-xs">Загрузка</div>
<div className="absolute inset-0 flex items-center justify-center text-xs bg-black/40 text-white">
Загрузка
</div>
)}
{p.status === "error" && (
<div className="absolute inset-0 flex items-center justify-center text-xs text-destructive p-1 text-center">
<div className="absolute inset-0 flex items-center justify-center text-xs text-destructive p-1 text-center bg-background/85">
{p.errorMessage || "Ошибка"}
</div>
)}
{p.status === "uploaded" && (
<div className="absolute inset-0 flex items-center justify-center text-xs text-muted-foreground">
Загружено
<div className="absolute bottom-1 right-1 rounded-full bg-green-600 text-white p-1 shadow">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
<path d="M5 12l5 5L20 7" />
</svg>
</div>
)}
<button
@@ -449,11 +478,21 @@ export default function CreateRepairPage() {
key={w.rowKey}
className={`rounded-md border p-2 ${w.unlocked ? "bg-amber-50 border-amber-300" : ""}`}
>
<div className="flex items-center justify-between gap-2">
<div className="flex items-start justify-between gap-2">
<div className="flex-1 min-w-0">
<div className="text-sm font-medium truncate">{w.name}</div>
<div className="text-xs text-muted-foreground">
Прайс: {w.price_catalog}
<div
className="text-sm font-medium leading-snug break-words"
style={{
display: '-webkit-box',
WebkitLineClamp: 2,
WebkitBoxOrient: 'vertical',
overflow: 'hidden',
}}
>
{w.name}
</div>
<div className="text-xs text-muted-foreground mt-0.5">
Прайс: {fmtPrice(w.price_catalog)}
</div>
</div>
<div className="flex items-center gap-1">
@@ -505,7 +544,7 @@ export default function CreateRepairPage() {
</ul>
)}
{works.length > 0 && (
<div className="mt-3 text-right text-sm font-medium">Итого: {totalSum} </div>
<div className="mt-3 text-right text-sm font-medium">Итого: {fmtPrice(totalSum)} </div>
)}
</section>
@@ -607,17 +646,34 @@ export default function CreateRepairPage() {
</div>
<div>
<Label className="text-sm">Фото стикера (одно)</Label>
<label className="mt-1 block border-2 border-dashed rounded-md p-4 text-center cursor-pointer hover:bg-accent/40">
{oilChange.sticker == null ? (
<span className="text-sm text-muted-foreground">Тап чтобы загрузить</span>
) : oilChange.sticker.status === "uploading" ? (
"Загрузка…"
) : oilChange.sticker.status === "error" ? (
<span className="text-sm text-destructive">
Ошибка: {oilChange.sticker.errorMessage}
</span>
<label className="mt-1 block border-2 border-dashed rounded-md text-center cursor-pointer hover:bg-accent/40 overflow-hidden relative aspect-video">
{oilChange.sticker?.previewUrl ? (
<img
src={oilChange.sticker.previewUrl}
alt=""
className="absolute inset-0 w-full h-full object-contain bg-muted"
/>
) : (
<span className="text-sm"> Загружено</span>
<div className="absolute inset-0 flex items-center justify-center">
<span className="text-sm text-muted-foreground">Тап чтобы загрузить</span>
</div>
)}
{oilChange.sticker?.status === "uploading" && (
<div className="absolute inset-0 flex items-center justify-center text-xs bg-black/40 text-white">
Загрузка
</div>
)}
{oilChange.sticker?.status === "error" && (
<div className="absolute inset-0 flex items-center justify-center text-xs text-destructive p-2 bg-background/85 text-center">
Ошибка: {oilChange.sticker.errorMessage}
</div>
)}
{oilChange.sticker?.status === "uploaded" && (
<div className="absolute bottom-1 right-1 rounded-full bg-green-600 text-white p-1 shadow">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
<path d="M5 12l5 5L20 7" />
</svg>
</div>
)}
<input
type="file"
@@ -654,10 +710,22 @@ export default function CreateRepairPage() {
<button
type="button"
onClick={() => addWorkFromCatalog(w)}
className="w-full text-left p-3 hover:bg-accent/40 flex items-baseline justify-between gap-3"
className="w-full text-left p-3 hover:bg-accent/40 flex items-start justify-between gap-3"
>
<span className="flex-1 min-w-0 truncate">{w.name}</span>
<span className="text-sm text-muted-foreground">{w.price} </span>
<span
className="flex-1 min-w-0 text-sm leading-snug break-words"
style={{
display: '-webkit-box',
WebkitLineClamp: 2,
WebkitBoxOrient: 'vertical',
overflow: 'hidden',
}}
>
{w.name}
</span>
<span className="text-sm text-muted-foreground font-mono whitespace-nowrap shrink-0 mt-0.5">
{fmtPrice(w.price)}
</span>
</button>
</li>
))}
@@ -0,0 +1,564 @@
/**
* Правка ремонта в 1-часовом окне (У49).
*
* Минимальная версия: редактируются работы (имя из каталога + цена +
* ручная правка + комментарий), запчасти, замена масла, пробег. Фото
* НЕ редактируются — для смены фото нужно дождаться PR-9.
*/
import { useEffect, useMemo, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { ChevronLeft, Plus, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
getRepairDetail,
patchRepair,
type RepairDetailResponse,
} from "@/api/repairsFeed";
import { searchWorks, suggestParts, type MechWork } from "@/api/repairsCreate";
interface WorkRow {
rowKey: string;
work_catalog_id: number;
name: string;
price_catalog: number;
price_applied: number;
manual_override: boolean;
override_comment: string | null;
}
interface PartRow {
rowKey: string;
name: string;
qty: number;
}
interface OilState {
enabled: boolean;
mileage_at_change: number | null;
next_in_km: number | null;
}
function uid(): string {
return Math.random().toString(36).slice(2, 10);
}
function fmt(n: number): string {
return new Intl.NumberFormat("ru-RU", { maximumFractionDigits: 0 }).format(Math.round(n));
}
export default function EditRepairPage() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [detail, setDetail] = useState<RepairDetailResponse | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
// Form state.
const [mileage, setMileage] = useState<number | null>(null);
const [works, setWorks] = useState<WorkRow[]>([]);
const [parts, setParts] = useState<PartRow[]>([]);
const [oil, setOil] = useState<OilState>({ enabled: false, mileage_at_change: null, next_in_km: null });
const [worksPicker, setWorksPicker] = useState<{ open: boolean; q: string; results: MechWork[] }>(
{ open: false, q: "", results: [] }
);
const [overrideModal, setOverrideModal] = useState<{ rowKey: string; comment: string } | null>(null);
useEffect(() => {
if (!id) return;
setLoading(true);
getRepairDetail(Number(id))
.then((d) => {
setDetail(d);
setMileage(d.mileage);
setWorks(d.works.map((w) => ({
rowKey: uid(),
work_catalog_id: w.work_catalog_id,
name: w.name,
price_catalog: w.price_applied, // в payload мы не знаем catalog price отдельно — фронт хранит applied; PATCH перечитает из БД каталога
price_applied: w.price_applied,
manual_override: w.manual_override,
override_comment: w.override_comment,
})));
setParts(d.parts.map((p) => ({
rowKey: uid(), name: p.name, qty: p.qty,
})));
if (d.oil_change) {
setOil({
enabled: true,
mileage_at_change: d.oil_change.mileage_at_change,
next_in_km: d.oil_change.next_in_km,
});
}
if (!d.can_edit) {
setError("Окно правки закрыто. Изменения отправить нельзя.");
}
})
.catch((e: Error) => setError(e.message || "Не удалось загрузить ремонт"))
.finally(() => setLoading(false));
}, [id]);
const totalSum = useMemo(() => works.reduce((s, w) => s + (w.price_applied || 0), 0), [works]);
// Works picker — поиск по каталогу.
const openWorksPicker = async () => {
setWorksPicker({ open: true, q: "", results: [] });
const list = await searchWorks("");
setWorksPicker((s) => ({ ...s, results: list }));
};
const queryWorks = async (q: string) => {
setWorksPicker((s) => ({ ...s, q }));
const list = await searchWorks(q);
setWorksPicker((s) => ({ ...s, results: list }));
};
const pickWork = (mw: MechWork) => {
const p = Math.round(Number(mw.price));
setWorks((arr) => [...arr, {
rowKey: uid(),
work_catalog_id: mw.id,
name: mw.name,
price_catalog: p,
price_applied: p,
manual_override: false,
override_comment: null,
}]);
setWorksPicker({ open: false, q: "", results: [] });
};
// Override-цена: открываем модалку для комментария.
const startOverride = (rowKey: string) => {
const cur = works.find((w) => w.rowKey === rowKey);
setOverrideModal({ rowKey, comment: cur?.override_comment ?? "" });
};
const confirmOverride = (newPrice: number) => {
if (!overrideModal) return;
setWorks((arr) => arr.map((w) =>
w.rowKey === overrideModal.rowKey
? { ...w, price_applied: newPrice, manual_override: true, override_comment: overrideModal.comment }
: w
));
setOverrideModal(null);
};
const submit = async () => {
if (!detail) return;
setError(null);
// Валидация: каждый manual_override → комментарий.
for (const w of works) {
if (w.manual_override && !(w.override_comment || "").trim()) {
setError(`У работы «${w.name}» включена ручная правка цены, но не указан комментарий`);
return;
}
}
if (works.length === 0) {
setError("Минимум одна работа в ремонте");
return;
}
setSaving(true);
try {
await patchRepair(detail.id, {
mileage,
works: works.map((w) => ({
work_catalog_id: w.work_catalog_id,
price_applied: Math.round(w.price_applied),
manual_override: w.manual_override,
override_comment: w.manual_override ? (w.override_comment ?? "").trim() : null,
})),
parts: parts.filter((p) => p.name.trim().length > 0).map((p) => ({
name: p.name.trim(),
qty: p.qty,
})),
oil_change: oil.enabled
? { enabled: true, mileage_at_change: oil.mileage_at_change, next_in_km: oil.next_in_km }
: { enabled: false, mileage_at_change: null, next_in_km: null },
});
navigate(`/repairs/${detail.id}`, { replace: true });
} catch (e) {
setError((e as Error).message || "Не удалось сохранить");
setSaving(false);
}
};
return (
<div className="min-h-screen bg-background">
<header className="sticky top-0 z-10 border-b bg-background/95 backdrop-blur">
<div className="flex items-center gap-3 p-3">
<button
onClick={() => navigate(-1)}
className="rounded-full p-2 hover:bg-accent"
aria-label="Назад"
>
<ChevronLeft className="h-5 w-5" />
</button>
<h1 className="flex-1 text-base font-semibold truncate">
Правка ремонта {detail ? `#${detail.id}` : ""}
</h1>
</div>
</header>
<main className="p-4 space-y-5 pb-32">
{loading && (
<div className="text-sm text-muted-foreground text-center py-12">
Загрузка
</div>
)}
{error && (
<div className="text-sm text-destructive bg-destructive/10 rounded-md p-3">
{error}
</div>
)}
{detail && (
<>
{/* Шапка машины — read-only */}
<section className="rounded-lg border bg-muted/40 p-4">
<div className="text-lg font-bold font-mono">{detail.car_plate ?? "—"}</div>
{(detail.car_make || detail.car_model) && (
<div className="text-sm text-muted-foreground">{detail.car_make} {detail.car_model}</div>
)}
{detail.driver_name && (
<div className="text-sm mt-1">
<span className="text-muted-foreground">Водитель: </span>
{detail.driver_name}
</div>
)}
</section>
{/* Пробег */}
<section>
<Label className="text-sm">Пробег, км</Label>
<Input
type="number"
inputMode="numeric"
value={mileage ?? ""}
onChange={(e) => setMileage(e.target.value === "" ? null : Number(e.target.value))}
className="mt-1"
/>
</section>
{/* Работы */}
<section>
<div className="flex items-baseline justify-between">
<Label className="text-sm">Работы</Label>
<span className="text-xs text-muted-foreground">
{works.length} {works.length === 1 ? "шт" : "шт"}
</span>
</div>
<div className="mt-2 space-y-2">
{works.map((w) => (
<div key={w.rowKey} className="border rounded-md p-3 bg-card">
<div className="flex items-start gap-2">
<div className="flex-1 min-w-0">
<div className="text-sm font-medium">{w.name}</div>
<div className="flex items-baseline gap-2 mt-1">
<span className="text-sm font-mono">
{fmt(w.price_applied)}
</span>
{w.manual_override && (
<span className="text-xs text-amber-700">
ручная правка
</span>
)}
{w.manual_override && w.price_applied !== w.price_catalog && (
<span className="text-xs text-muted-foreground line-through">
{fmt(w.price_catalog)}
</span>
)}
</div>
{w.manual_override && w.override_comment && (
<div className="text-xs text-muted-foreground mt-1">
{w.override_comment}
</div>
)}
</div>
<button
onClick={() => startOverride(w.rowKey)}
className="rounded-full p-2 hover:bg-accent text-amber-700"
title="Изменить цену"
>
</button>
<button
onClick={() => setWorks((arr) => arr.filter((x) => x.rowKey !== w.rowKey))}
className="rounded-full p-2 hover:bg-accent text-destructive"
title="Удалить"
>
<Trash2 className="h-4 w-4" />
</button>
</div>
</div>
))}
<button
onClick={openWorksPicker}
className="w-full border-2 border-dashed rounded-md py-2.5 text-sm hover:bg-accent/40 flex items-center justify-center gap-1.5"
>
<Plus className="h-4 w-4" /> Добавить работу
</button>
<div className="flex items-baseline justify-between pt-2 border-t mt-2">
<span className="text-sm font-semibold">Итого</span>
<span className="text-base font-mono font-bold">{fmt(totalSum)} </span>
</div>
</div>
</section>
{/* Запчасти */}
<section>
<div className="flex items-baseline justify-between">
<Label className="text-sm">Запчасти (опционально)</Label>
<span className="text-xs text-muted-foreground">{parts.length} шт</span>
</div>
<div className="mt-2 space-y-2">
{parts.map((p) => (
<PartEditRow
key={p.rowKey}
name={p.name}
qty={p.qty}
onChange={(name, qty) =>
setParts((arr) => arr.map((x) => x.rowKey === p.rowKey ? { ...x, name, qty } : x))
}
onRemove={() => setParts((arr) => arr.filter((x) => x.rowKey !== p.rowKey))}
/>
))}
<button
onClick={() => setParts((arr) => [...arr, { rowKey: uid(), name: "", qty: 1 }])}
className="w-full border-2 border-dashed rounded-md py-2.5 text-sm hover:bg-accent/40 flex items-center justify-center gap-1.5"
>
<Plus className="h-4 w-4" /> Добавить запчасть
</button>
</div>
</section>
{/* Замена масла */}
<section className="border rounded-md p-3">
<label className="flex items-center gap-2 text-sm font-medium">
<input
type="checkbox"
checked={oil.enabled}
onChange={(e) => setOil((o) => ({ ...o, enabled: e.target.checked }))}
/>
Замена масла
</label>
{oil.enabled && (
<div className="mt-3 grid grid-cols-2 gap-2">
<div>
<Label className="text-xs">Пробег</Label>
<Input
type="number"
inputMode="numeric"
value={oil.mileage_at_change ?? ""}
onChange={(e) => setOil((o) => ({
...o, mileage_at_change: e.target.value === "" ? null : Number(e.target.value),
}))}
/>
</div>
<div>
<Label className="text-xs">Через, км</Label>
<Input
type="number"
inputMode="numeric"
value={oil.next_in_km ?? 10000}
onChange={(e) => setOil((o) => ({
...o, next_in_km: e.target.value === "" ? null : Number(e.target.value),
}))}
/>
</div>
</div>
)}
</section>
<div className="text-xs text-muted-foreground">
Фото и стикер замены масла редактировать пока нельзя для смены
нужно создать новый ремонт.
</div>
</>
)}
</main>
{/* Sticky footer */}
{detail && (
<footer className="fixed bottom-0 left-0 right-0 border-t bg-background p-3 flex gap-2 z-10">
<Button variant="outline" onClick={() => navigate(`/repairs/${detail.id}`)} disabled={saving} className="flex-1">
Отмена
</Button>
<Button onClick={submit} disabled={saving || !detail.can_edit} className="flex-1">
{saving ? "Сохранение…" : "Сохранить"}
</Button>
</footer>
)}
{/* Works picker modal */}
{worksPicker.open && (
<div className="fixed inset-0 z-50 bg-background/95 flex flex-col">
<header className="border-b p-3 flex items-center gap-2">
<button onClick={() => setWorksPicker({ open: false, q: "", results: [] })}
className="rounded-full p-2 hover:bg-accent">
<ChevronLeft className="h-5 w-5" />
</button>
<Input
autoFocus
placeholder="Поиск работы…"
value={worksPicker.q}
onChange={(e) => queryWorks(e.target.value)}
/>
</header>
<div className="flex-1 overflow-auto">
{worksPicker.results.map((mw) => (
<button
key={mw.id}
onClick={() => pickWork(mw)}
className="w-full text-left p-3 border-b hover:bg-accent/40"
>
<div className="text-sm font-medium">{mw.name}</div>
<div className="text-xs text-muted-foreground font-mono">
{fmt(Number(mw.price))}
</div>
</button>
))}
{worksPicker.results.length === 0 && (
<div className="text-center text-muted-foreground p-8 text-sm">
Ничего не найдено
</div>
)}
</div>
</div>
)}
{/* Override modal */}
{overrideModal && (() => {
const cur = works.find((w) => w.rowKey === overrideModal.rowKey);
if (!cur) return null;
return (
<OverridePriceModal
workName={cur.name}
catalogPrice={cur.price_catalog}
appliedPrice={cur.price_applied}
initialComment={overrideModal.comment}
onCancel={() => setOverrideModal(null)}
onSubmit={(newPrice, comment) => {
setOverrideModal((m) => m ? { ...m, comment } : m);
confirmOverride(newPrice);
}}
/>
);
})()}
</div>
);
}
function PartEditRow({ name, qty, onChange, onRemove }: {
name: string;
qty: number;
onChange: (name: string, qty: number) => void;
onRemove: () => void;
}) {
const [suggestions, setSuggestions] = useState<string[]>([]);
const [showSugg, setShowSugg] = useState(false);
const fetchSuggestions = async (q: string) => {
if (!q.trim()) { setSuggestions([]); return; }
try {
const r = await suggestParts(q);
setSuggestions(r.map((x) => x.name));
} catch { /* noop */ }
};
return (
<div className="flex gap-2 items-start">
<div className="flex-1 relative">
<Input
placeholder="Название запчасти"
value={name}
onChange={(e) => { onChange(e.target.value, qty); fetchSuggestions(e.target.value); setShowSugg(true); }}
onFocus={() => name && fetchSuggestions(name)}
onBlur={() => setTimeout(() => setShowSugg(false), 150)}
/>
{showSugg && suggestions.length > 0 && (
<div className="absolute top-full left-0 right-0 z-10 mt-1 bg-popover border rounded-md shadow-md max-h-48 overflow-auto">
{suggestions.map((s) => (
<button
key={s}
onClick={() => { onChange(s, qty); setShowSugg(false); }}
className="w-full text-left px-3 py-2 text-sm hover:bg-accent"
>
{s}
</button>
))}
</div>
)}
</div>
<Input
type="number"
inputMode="numeric"
min={1}
value={qty}
onChange={(e) => onChange(name, Math.max(1, Number(e.target.value) || 1))}
className="w-20"
/>
<button onClick={onRemove} className="rounded-full p-2 hover:bg-accent text-destructive">
<Trash2 className="h-4 w-4" />
</button>
</div>
);
}
function OverridePriceModal({ workName, catalogPrice, appliedPrice, initialComment, onCancel, onSubmit }: {
workName: string;
catalogPrice: number;
appliedPrice: number;
initialComment: string;
onCancel: () => void;
onSubmit: (newPrice: number, comment: string) => void;
}) {
const [price, setPrice] = useState(String(Math.round(appliedPrice)));
const [comment, setComment] = useState(initialComment);
return (
<div className="fixed inset-0 z-50 bg-black/50 flex items-end justify-center" onClick={onCancel}>
<div className="bg-background w-full max-w-md rounded-t-xl p-4 space-y-3" onClick={(e) => e.stopPropagation()}>
<h3 className="text-base font-semibold">Изменить цену</h3>
<div className="text-sm">
<div className="font-medium">{workName}</div>
<div className="text-xs text-muted-foreground mt-0.5">
По каталогу: <span className="font-mono">{fmt(catalogPrice)} </span>
</div>
</div>
<div>
<Label className="text-xs">Применённая цена, </Label>
<Input
type="number"
inputMode="numeric"
value={price}
onChange={(e) => setPrice(e.target.value)}
autoFocus
/>
</div>
<div>
<Label className="text-xs">Причина (обязательно)</Label>
<textarea
className="w-full mt-1 border rounded-md px-3 py-2 text-sm"
rows={2}
value={comment}
onChange={(e) => setComment(e.target.value)}
placeholder="Например: договорились с клиентом"
/>
</div>
<div className="flex gap-2 pt-2">
<Button variant="outline" onClick={onCancel} className="flex-1">Отмена</Button>
<Button
disabled={!comment.trim() || !price}
onClick={() => onSubmit(Number(price), comment.trim())}
className="flex-1"
>
Применить
</Button>
</div>
</div>
</div>
);
}
@@ -0,0 +1,294 @@
/**
* Карточка ремонта (PWA): read-only просмотр после клика по строке ленты.
*
* Минимальная версия для возможности «открыть и посмотреть». Полноценный
* вариант с lightbox, копированием госномера, обратным счётчиком и
* редактированием в 24h-окне — в PR-9 по плану.
*
* Endpoint: GET /api/v1/mechanic/repairs/{id}
*/
import { useEffect, useMemo, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { ChevronLeft, Pencil } from "lucide-react";
import { getRepairDetail, type RepairDetailResponse } from "@/api/repairsFeed";
function fmt(n: number): string {
return new Intl.NumberFormat("ru-RU", { maximumFractionDigits: 0 }).format(Math.round(n));
}
function fmtDateTime(iso: string): string {
const d = new Date(iso);
return new Intl.DateTimeFormat("ru-RU", {
day: "2-digit", month: "long", year: "numeric",
hour: "2-digit", minute: "2-digit",
}).format(d);
}
export default function RepairDetailPage() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [data, setData] = useState<RepairDetailResponse | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [now, setNow] = useState(() => Date.now());
// Тикер для обратного счётчика «Осталось X мин». Раз в 30 секунд хватит —
// окно правки 1 час, точность до минуты допустима.
useEffect(() => {
const t = setInterval(() => setNow(Date.now()), 30_000);
return () => clearInterval(t);
}, []);
const editRemaining = useMemo(() => {
if (!data?.can_edit || !data.edit_until) return null;
const until = new Date(data.edit_until).getTime();
const ms = until - now;
if (ms <= 0) return null;
const minutes = Math.floor(ms / 60_000);
if (minutes < 1) return "меньше минуты";
if (minutes < 60) return `${minutes} мин`;
const h = Math.floor(minutes / 60);
const m = minutes - h * 60;
return `${h} ч ${m} мин`;
}, [data, now]);
useEffect(() => {
if (!id) return;
setLoading(true);
getRepairDetail(Number(id))
.then((r) => { setData(r); setError(null); })
.catch((e: Error) => setError(e.message || "Не удалось загрузить ремонт"))
.finally(() => setLoading(false));
}, [id]);
return (
<div className="min-h-screen bg-background">
<header className="sticky top-0 z-10 border-b bg-background/95 backdrop-blur">
<div className="flex items-center gap-3 p-3">
<button
onClick={() => navigate("/repairs")}
className="rounded-full p-2 hover:bg-accent"
aria-label="Назад"
>
<ChevronLeft className="h-5 w-5" />
</button>
<div className="flex-1 min-w-0">
<h1 className="text-base font-semibold truncate">
{data ? `Ремонт #${data.id}` : "Ремонт"}
</h1>
{data && (
<div className="text-xs text-muted-foreground truncate">
{fmtDateTime(data.created_at)}
</div>
)}
</div>
</div>
</header>
<main className="p-4 space-y-5 pb-12">
{loading && (
<div className="text-sm text-muted-foreground text-center py-12">
Загрузка
</div>
)}
{error && (
<div className="text-sm text-destructive bg-destructive/10 rounded-md p-3">
{error}
</div>
)}
{data && (
<>
{/* Кнопка правки в 1-часовом окне (У49). */}
{data.can_edit && editRemaining && (
<button
onClick={() => navigate(`/repairs/${data.id}/edit`)}
className="w-full flex items-center justify-between gap-2 rounded-lg border-2 border-amber-300 bg-amber-50 px-4 py-3 hover:bg-amber-100 transition-colors"
>
<span className="flex items-center gap-2 text-sm font-semibold text-amber-900">
<Pencil className="h-4 w-4" />
Изменить ремонт
</span>
<span className="text-xs font-mono text-amber-800">
осталось {editRemaining}
</span>
</button>
)}
{/* Шапка: машина + водитель + механик */}
<section className="rounded-lg border bg-card p-4 space-y-2">
<div className="text-xl font-bold font-mono">
{data.car_plate || "—"}
</div>
{(data.car_make || data.car_model) && (
<div className="text-sm text-muted-foreground">
{data.car_make} {data.car_model}
</div>
)}
<div className="pt-2 border-t text-sm space-y-1">
{data.driver_name && (
<div>
<span className="text-muted-foreground">Водитель: </span>
{data.driver_name}
</div>
)}
<div>
<span className="text-muted-foreground">Механик: </span>
{data.mechanic_name || "—"}
</div>
{data.mileage != null && (
<div>
<span className="text-muted-foreground">Пробег: </span>
<span className="font-mono">{fmt(data.mileage)} км</span>
</div>
)}
</div>
</section>
{/* Фото */}
{data.photos.length > 0 && (
<section>
<div className="text-sm font-semibold mb-2">
Фото · {data.photos.length}
</div>
<div className="grid grid-cols-3 gap-2">
{data.photos.map((p) => (
<a
key={p.photo_uuid}
href={p.orig_url ?? "#"}
target="_blank"
rel="noreferrer"
className="block aspect-square overflow-hidden rounded-md border bg-muted"
>
{p.thumb_url && (
<img
src={p.thumb_url}
alt=""
loading="lazy"
className="w-full h-full object-cover"
/>
)}
</a>
))}
</div>
</section>
)}
{/* Работы */}
<section className="rounded-lg border bg-card overflow-hidden">
<div className="px-4 py-3 border-b bg-muted/40">
<div className="text-sm font-semibold">
Работы · {data.works.length}
</div>
</div>
<div className="divide-y">
{data.works.map((w, i) => (
<div key={i} className="px-4 py-3 flex items-start justify-between gap-3">
<div className="text-sm flex-1 min-w-0">
<div>
{w.name}
{w.manual_override && (
<span title="Цена изменена вручную" className="ml-2 text-amber-700">
</span>
)}
</div>
{w.manual_override && w.override_comment && (
<div className="mt-1 text-xs text-amber-800 bg-amber-50 border-l-2 border-amber-300 pl-2 py-0.5 leading-snug">
{w.override_comment}
</div>
)}
</div>
<div className="text-sm font-mono whitespace-nowrap text-muted-foreground shrink-0 mt-0.5">
{fmt(w.price_applied)}
</div>
</div>
))}
<div className="px-4 py-3 flex items-baseline justify-between bg-muted/30">
<div className="text-sm font-semibold">Итого</div>
<div className="text-base font-mono font-bold">
{fmt(data.total_sum)}
</div>
</div>
</div>
</section>
{/* Запчасти */}
{data.parts.length > 0 && (
<section className="rounded-lg border bg-card overflow-hidden">
<div className="px-4 py-3 border-b bg-muted/40">
<div className="text-sm font-semibold">
Запчасти · {data.parts.length}
</div>
</div>
<div className="divide-y">
{data.parts.map((p, i) => (
<div key={i} className="px-4 py-3 flex items-baseline justify-between gap-3">
<div className="text-sm">{p.name}</div>
<div className="text-sm font-mono whitespace-nowrap text-muted-foreground">
{p.qty} шт
</div>
</div>
))}
</div>
</section>
)}
{/* Замена масла */}
{data.oil_change && (
<section className="rounded-lg border bg-card overflow-hidden">
<div className="px-4 py-3 border-b bg-muted/40">
<div className="text-sm font-semibold">Замена масла</div>
</div>
<div className="p-4">
<div className="flex gap-3 items-start">
{data.oil_change.sticker_thumb_url && (
<a
href={data.oil_change.sticker_orig_url ?? "#"}
target="_blank"
rel="noreferrer"
className="flex-shrink-0"
>
<img
src={data.oil_change.sticker_thumb_url}
alt="Стикер замены масла"
loading="lazy"
className="w-24 h-24 object-cover rounded-md border bg-muted"
/>
</a>
)}
<div className="flex-1 text-sm space-y-1">
{data.oil_change.mileage_at_change != null && (
<div>
<span className="text-muted-foreground">Пробег при замене: </span>
<span className="font-mono">{fmt(data.oil_change.mileage_at_change)} км</span>
</div>
)}
{data.oil_change.next_in_km != null && (
<div>
<span className="text-muted-foreground">Следующая через: </span>
<span className="font-mono">{fmt(data.oil_change.next_in_km)} км</span>
</div>
)}
{data.oil_change.has_sticker && !data.oil_change.sticker_thumb_url && (
<div className="text-xs text-muted-foreground pt-1">
фото стикера загружено
</div>
)}
</div>
</div>
</div>
</section>
)}
{data.edited_in_crm && (
<div className="text-xs text-amber-700 bg-amber-50 border border-amber-200 rounded-md p-3">
Этот ремонт был отредактирован в CRM. Кнопка «Редактировать»
в PWA для него недоступна.
</div>
)}
</>
)}
</main>
</div>
);
}