Compare commits
14
Commits
main
..
b2969f36c3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b2969f36c3 | ||
|
|
fab8b4496b | ||
|
|
8c9caedb03 | ||
|
|
d0ebd9ddf5 | ||
|
|
7e6817b3ff | ||
|
|
3d875642f8 | ||
|
|
10492e52a4 | ||
|
|
fd0ec64da9 | ||
|
|
3b7b2ae56d | ||
|
|
205078c5ce | ||
|
|
8eac0b74fc | ||
|
|
9642eb6e45 | ||
|
|
087693877d | ||
|
|
85f3a5c682 |
Generated
+1345
-1
File diff suppressed because it is too large
Load Diff
@@ -7,7 +7,9 @@
|
|||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "tsc -b && vite build",
|
"build": "tsc -b && vite build",
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview",
|
||||||
|
"test": "vitest run",
|
||||||
|
"test:watch": "vitest"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@radix-ui/react-label": "^2.1.8",
|
"@radix-ui/react-label": "^2.1.8",
|
||||||
@@ -29,19 +31,25 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^10.0.1",
|
"@eslint/js": "^10.0.1",
|
||||||
|
"@testing-library/jest-dom": "^6.9.1",
|
||||||
|
"@testing-library/react": "^16.3.2",
|
||||||
|
"@testing-library/user-event": "^14.6.1",
|
||||||
"@types/node": "^24.12.4",
|
"@types/node": "^24.12.4",
|
||||||
"@types/react": "^19.2.14",
|
"@types/react": "^19.2.14",
|
||||||
"@types/react-dom": "^19.2.3",
|
"@types/react-dom": "^19.2.3",
|
||||||
"@vitejs/plugin-react": "^6.0.1",
|
"@vitejs/plugin-react": "^6.0.1",
|
||||||
|
"@vitest/coverage-v8": "^4.1.8",
|
||||||
"autoprefixer": "^10.5.0",
|
"autoprefixer": "^10.5.0",
|
||||||
"eslint": "^10.3.0",
|
"eslint": "^10.3.0",
|
||||||
"eslint-plugin-react-hooks": "^7.1.1",
|
"eslint-plugin-react-hooks": "^7.1.1",
|
||||||
"eslint-plugin-react-refresh": "^0.5.2",
|
"eslint-plugin-react-refresh": "^0.5.2",
|
||||||
"globals": "^17.6.0",
|
"globals": "^17.6.0",
|
||||||
|
"jsdom": "^29.1.1",
|
||||||
"postcss": "^8.5.14",
|
"postcss": "^8.5.14",
|
||||||
"tailwindcss": "^3.4.19",
|
"tailwindcss": "^3.4.19",
|
||||||
"typescript": "~6.0.2",
|
"typescript": "~6.0.2",
|
||||||
"typescript-eslint": "^8.59.2",
|
"typescript-eslint": "^8.59.2",
|
||||||
"vite": "^8.0.12"
|
"vite": "^8.0.12",
|
||||||
|
"vitest": "^4.1.8"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -9,6 +9,8 @@ import InspectionEditor from "@/pages/InspectionEditor";
|
|||||||
import InspectionReview from "@/pages/InspectionReview";
|
import InspectionReview from "@/pages/InspectionReview";
|
||||||
import TtStateDetail from "@/pages/TtStateDetail";
|
import TtStateDetail from "@/pages/TtStateDetail";
|
||||||
import RepairsFeedPage from "@/pages/repairs/RepairsFeedPage";
|
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 CarSelectPage from "@/pages/repairs/CarSelectPage";
|
||||||
import CreateRepairPage from "@/pages/repairs/CreateRepairPage";
|
import CreateRepairPage from "@/pages/repairs/CreateRepairPage";
|
||||||
|
|
||||||
@@ -37,6 +39,9 @@ export default function App() {
|
|||||||
<Route path="/repairs" element={<RequireAuth><RepairsFeedPage /></RequireAuth>} />
|
<Route path="/repairs" element={<RequireAuth><RepairsFeedPage /></RequireAuth>} />
|
||||||
<Route path="/repairs/new" element={<RequireAuth><CarSelectPage /></RequireAuth>} />
|
<Route path="/repairs/new" element={<RequireAuth><CarSelectPage /></RequireAuth>} />
|
||||||
<Route path="/repairs/new/:carId" element={<RequireAuth><CreateRepairPage /></RequireAuth>} />
|
<Route path="/repairs/new/:carId" element={<RequireAuth><CreateRepairPage /></RequireAuth>} />
|
||||||
|
<Route path="/repairs/new-external" 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 />} />
|
<Route path="*" element={<Navigate to="/" replace />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -65,8 +65,14 @@ export interface CreateOilChangePayload {
|
|||||||
sticker_extension: string | null;
|
sticker_extension: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ExternalCarPayload {
|
||||||
|
plate: string;
|
||||||
|
make: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
export interface CreateRepairPayload {
|
export interface CreateRepairPayload {
|
||||||
car_id: number;
|
car_id?: number;
|
||||||
|
external_car?: ExternalCarPayload;
|
||||||
mileage: number | null;
|
mileage: number | null;
|
||||||
works: CreateWorkPayload[];
|
works: CreateWorkPayload[];
|
||||||
parts: CreatePartPayload[];
|
parts: CreatePartPayload[];
|
||||||
|
|||||||
@@ -12,8 +12,10 @@ export interface FeedItem {
|
|||||||
car_model: string | null;
|
car_model: string | null;
|
||||||
driver_name: string | null;
|
driver_name: string | null;
|
||||||
mechanic_name: string;
|
mechanic_name: string;
|
||||||
|
is_external: boolean;
|
||||||
works_preview: FeedWorkBrief[];
|
works_preview: FeedWorkBrief[];
|
||||||
works_extra: number;
|
works_extra: number;
|
||||||
|
works_total: number; // сумма работ без запчастей
|
||||||
photo_url: string | null;
|
photo_url: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,3 +38,97 @@ export async function getRepairsFeed(params: FeedParams = {}): Promise<FeedRespo
|
|||||||
.get(`repairs${qs ? `?${qs}` : ""}`)
|
.get(`repairs${qs ? `?${qs}` : ""}`)
|
||||||
.json<FeedResponse>();
|
.json<FeedResponse>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface RepairsMonthStats {
|
||||||
|
total: number;
|
||||||
|
count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getRepairsMonthStats(): Promise<RepairsMonthStats> {
|
||||||
|
return api.get("repairs/stats/month").json<RepairsMonthStats>();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Детальная карточка ремонта ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
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>();
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
import { vi } from "vitest";
|
||||||
|
import WorksPickerModal from "@/components/repairs/WorksPickerModal";
|
||||||
|
import type { MechWork } from "@/api/repairsCreate";
|
||||||
|
|
||||||
|
const works: MechWork[] = [
|
||||||
|
{ id: 1, name: "Замена масла", category_id: 1, price: 1500, norma_hours: null },
|
||||||
|
{ id: 2, name: "Развал-схождение", category_id: 1, price: "2000", norma_hours: null },
|
||||||
|
];
|
||||||
|
|
||||||
|
test("рендерит работы с ценой и зовёт onPick по клику", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
const onPick = vi.fn();
|
||||||
|
render(
|
||||||
|
<WorksPickerModal query="" results={works} onQuery={() => {}} onPick={onPick} onClose={() => {}} />,
|
||||||
|
);
|
||||||
|
expect(screen.getByText("Замена масла")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("1 500 ₽")).toBeInTheDocument(); // число из 1500
|
||||||
|
expect(screen.getByText("2 000 ₽")).toBeInTheDocument(); // строка "2000" → число
|
||||||
|
await user.click(screen.getByText("Развал-схождение"));
|
||||||
|
expect(onPick).toHaveBeenCalledWith(works[1]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("пустой список → «Ничего не найдено»", () => {
|
||||||
|
render(
|
||||||
|
<WorksPickerModal query="x" results={[]} onQuery={() => {}} onPick={() => {}} onClose={() => {}} />,
|
||||||
|
);
|
||||||
|
expect(screen.getByText("Ничего не найдено")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("ввод в поиск зовёт onQuery; кнопка назад — onClose", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
const onQuery = vi.fn();
|
||||||
|
const onClose = vi.fn();
|
||||||
|
render(
|
||||||
|
<WorksPickerModal query="" results={[]} onQuery={onQuery} onPick={() => {}} onClose={onClose} />,
|
||||||
|
);
|
||||||
|
await user.type(screen.getByPlaceholderText("Поиск работы…"), "масло");
|
||||||
|
expect(onQuery).toHaveBeenCalled();
|
||||||
|
await user.click(screen.getByLabelText("Закрыть"));
|
||||||
|
expect(onClose).toHaveBeenCalled();
|
||||||
|
});
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
/**
|
||||||
|
* Модалка выбора работы из каталога. Раньше была продублирована почти один-в-один
|
||||||
|
* в CreateRepairPage и EditRepairPage — вынесена в общий презентационный компонент.
|
||||||
|
*
|
||||||
|
* Состояние (открыта/запрос/результаты) живёт в родителе; здесь только UI +
|
||||||
|
* колбэки. Это сознательно: формы создания и правки ремонта разошлись по UX
|
||||||
|
* (inline-разблокировка цены против модалки-override, фото против их отсутствия),
|
||||||
|
* поэтому единая «форма ремонта» была бы хуже — общим является именно этот пикер.
|
||||||
|
*/
|
||||||
|
import { ChevronLeft } from "lucide-react";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { fmtMoney } from "@/lib/repairsFeed";
|
||||||
|
import type { MechWork } from "@/api/repairsCreate";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
query: string;
|
||||||
|
results: MechWork[];
|
||||||
|
onQuery: (q: string) => void;
|
||||||
|
onPick: (work: MechWork) => void;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function WorksPickerModal({ query, results, onQuery, onPick, onClose }: Props) {
|
||||||
|
return (
|
||||||
|
<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
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
className="rounded-full p-2 hover:bg-accent"
|
||||||
|
aria-label="Закрыть"
|
||||||
|
>
|
||||||
|
<ChevronLeft className="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
<Input
|
||||||
|
autoFocus
|
||||||
|
placeholder="Поиск работы…"
|
||||||
|
value={query}
|
||||||
|
onChange={(e) => onQuery(e.target.value)}
|
||||||
|
/>
|
||||||
|
</header>
|
||||||
|
<div className="flex-1 overflow-auto">
|
||||||
|
{results.map((mw) => (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
key={mw.id}
|
||||||
|
onClick={() => onPick(mw)}
|
||||||
|
className="w-full text-left p-3 border-b hover:bg-accent/40 flex items-start justify-between gap-3"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className="flex-1 min-w-0 text-sm leading-snug break-words"
|
||||||
|
style={{
|
||||||
|
display: "-webkit-box",
|
||||||
|
WebkitLineClamp: 2,
|
||||||
|
WebkitBoxOrient: "vertical",
|
||||||
|
overflow: "hidden",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{mw.name}
|
||||||
|
</span>
|
||||||
|
<span className="text-sm text-muted-foreground font-mono whitespace-nowrap shrink-0 mt-0.5">
|
||||||
|
{fmtMoney(Number(mw.price))} ₽
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
{results.length === 0 && (
|
||||||
|
<div className="text-center text-muted-foreground p-8 text-sm">
|
||||||
|
Ничего не найдено
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -31,5 +31,29 @@
|
|||||||
* { @apply border-border; }
|
* { @apply border-border; }
|
||||||
body {
|
body {
|
||||||
@apply bg-background text-foreground font-sans;
|
@apply bg-background text-foreground font-sans;
|
||||||
|
/* iOS PWA: status bar (status-bar-style=black-translucent) и home-indicator
|
||||||
|
перекрывают контент при viewport-fit=cover. Сдвигаем body content вниз
|
||||||
|
на высоту safe-area, чтобы шапки/кнопки не уезжали под системные зоны. */
|
||||||
|
padding-top: env(safe-area-inset-top);
|
||||||
|
padding-bottom: env(safe-area-inset-bottom);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer utilities {
|
||||||
|
/* iOS PWA: position:sticky + top:0 прилипает к самому верху viewport,
|
||||||
|
т.е. под статус-бар (containing-block тут не помогает). Переопределяем
|
||||||
|
top у всех Tailwind .top-0, чтобы шапки залипали ниже notch. */
|
||||||
|
.sticky.top-0,
|
||||||
|
.fixed.top-0 {
|
||||||
|
top: env(safe-area-inset-top);
|
||||||
|
}
|
||||||
|
/* Full-screen page-replacement модалки (fixed inset-0 с app background) —
|
||||||
|
поиск работ, аннотация фото, zone-detail, inspection-editor. Шапка внутри
|
||||||
|
должна сидеть ниже status-bar, нижние кнопки выше home-indicator.
|
||||||
|
bg-black/40·50·90 диалоги/просмотрщики не задеваем — у них inset-0 full-bleed. */
|
||||||
|
.fixed.inset-0.bg-background,
|
||||||
|
.fixed.inset-0.bg-background\/95 {
|
||||||
|
padding-top: env(safe-area-inset-top);
|
||||||
|
padding-bottom: env(safe-area-inset-bottom);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { repairCanSubmit, repairSubmitWhyDisabled } from "@/lib/repairForm";
|
||||||
|
|
||||||
|
const okPhoto = { status: "uploaded" as const };
|
||||||
|
const okWork = { unlocked: false, override_comment: "" };
|
||||||
|
|
||||||
|
describe("repairSubmitWhyDisabled", () => {
|
||||||
|
it("нет фото → причина про фото", () => {
|
||||||
|
expect(repairSubmitWhyDisabled([], [okWork])).toBe("Добавьте хотя бы одно фото");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("фото ещё грузится → причина про загрузку", () => {
|
||||||
|
expect(
|
||||||
|
repairSubmitWhyDisabled([{ status: "uploading" }], [okWork]),
|
||||||
|
).toBe("Дождитесь окончания загрузки фото");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("фото с ошибкой загрузки тоже блокирует", () => {
|
||||||
|
expect(
|
||||||
|
repairSubmitWhyDisabled([{ status: "error" }], [okWork]),
|
||||||
|
).toBe("Дождитесь окончания загрузки фото");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("нет работ → причина про работы", () => {
|
||||||
|
expect(repairSubmitWhyDisabled([okPhoto], [])).toBe("Добавьте хотя бы одну работу");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("разблокированная цена без комментария → требует комментарий", () => {
|
||||||
|
expect(
|
||||||
|
repairSubmitWhyDisabled([okPhoto], [{ unlocked: true, override_comment: " " }]),
|
||||||
|
).toBe("Укажите комментарий к ручной правке цены");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("разблокированная цена с комментарием → ок", () => {
|
||||||
|
expect(
|
||||||
|
repairSubmitWhyDisabled([okPhoto], [{ unlocked: true, override_comment: "скидка" }]),
|
||||||
|
).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("валидная форма → пустая причина", () => {
|
||||||
|
expect(repairSubmitWhyDisabled([okPhoto], [okWork])).toBe("");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("repairCanSubmit", () => {
|
||||||
|
it("= (нет причины блокировки)", () => {
|
||||||
|
expect(repairCanSubmit([okPhoto], [okWork])).toBe(true);
|
||||||
|
expect(repairCanSubmit([], [okWork])).toBe(false);
|
||||||
|
expect(repairCanSubmit([{ status: "uploading" }], [okWork])).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
/**
|
||||||
|
* Логика гейтинга сохранения формы ремонта (Create/Edit). Вынесена из
|
||||||
|
* CreateRepairPage, чтобы быть единым источником правды и покрытой тестами:
|
||||||
|
* `canSubmit` теперь буквально «нет причины блокировки», без расхождения
|
||||||
|
* между двумя проверками.
|
||||||
|
*
|
||||||
|
* Принимает структурные срезы стейта (только нужные поля), поэтому не зависит
|
||||||
|
* от конкретных типов страниц.
|
||||||
|
*/
|
||||||
|
export interface RepairFormPhotoLike {
|
||||||
|
status: "uploading" | "uploaded" | "error" | string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RepairFormWorkLike {
|
||||||
|
unlocked: boolean;
|
||||||
|
override_comment: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Возвращает причину, по которой сохранение заблокировано, или "" если можно. */
|
||||||
|
export function repairSubmitWhyDisabled(
|
||||||
|
photos: RepairFormPhotoLike[],
|
||||||
|
works: RepairFormWorkLike[],
|
||||||
|
): string {
|
||||||
|
if (photos.length === 0) return "Добавьте хотя бы одно фото";
|
||||||
|
if (photos.some((p) => p.status !== "uploaded")) return "Дождитесь окончания загрузки фото";
|
||||||
|
if (works.length === 0) return "Добавьте хотя бы одну работу";
|
||||||
|
const unlockedNoComment = works.find((w) => w.unlocked && !w.override_comment.trim());
|
||||||
|
if (unlockedNoComment) return "Укажите комментарий к ручной правке цены";
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function repairCanSubmit(
|
||||||
|
photos: RepairFormPhotoLike[],
|
||||||
|
works: RepairFormWorkLike[],
|
||||||
|
): boolean {
|
||||||
|
return repairSubmitWhyDisabled(photos, works) === "";
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import type { FeedItem } from "@/api/repairsFeed";
|
||||||
|
import {
|
||||||
|
toLocalDateKey,
|
||||||
|
formatDayLabel,
|
||||||
|
groupByLocalDay,
|
||||||
|
fmtMoney,
|
||||||
|
pluralRepairs,
|
||||||
|
pluralWorks,
|
||||||
|
} from "@/lib/repairsFeed";
|
||||||
|
|
||||||
|
function item(id: number, created_at: string, works_total = 0): FeedItem {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
created_at,
|
||||||
|
car_plate: "А001АА125",
|
||||||
|
car_make: null,
|
||||||
|
car_model: null,
|
||||||
|
driver_name: null,
|
||||||
|
mechanic_name: "M",
|
||||||
|
works_preview: [],
|
||||||
|
works_extra: 0,
|
||||||
|
works_total,
|
||||||
|
photo_url: null,
|
||||||
|
is_external: false,
|
||||||
|
} as FeedItem;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("toLocalDateKey (Asia/Vladivostok)", () => {
|
||||||
|
it("маппит UTC-инстант на VLA-сутки (+10)", () => {
|
||||||
|
// 2026-05-25 20:00Z == 2026-05-26 06:00 VLA → день 26-го
|
||||||
|
expect(toLocalDateKey("2026-05-25T20:00:00Z")).toBe("2026-05-26");
|
||||||
|
// 2026-05-25 13:00Z == 2026-05-25 23:00 VLA → ещё 25-е
|
||||||
|
expect(toLocalDateKey("2026-05-25T13:00:00Z")).toBe("2026-05-25");
|
||||||
|
// 2026-05-25 14:00Z == 2026-05-26 00:00 VLA → уже 26-е (граница суток)
|
||||||
|
expect(toLocalDateKey("2026-05-25T14:00:00Z")).toBe("2026-05-26");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("formatDayLabel", () => {
|
||||||
|
const now = new Date("2026-05-26T05:00:00Z"); // 15:00 VLA, день 26-го
|
||||||
|
it("Сегодня / Вчера относительно VLA-now", () => {
|
||||||
|
expect(formatDayLabel("2026-05-26", now)).toBe("Сегодня");
|
||||||
|
expect(formatDayLabel("2026-05-25", now)).toBe("Вчера");
|
||||||
|
});
|
||||||
|
it("прочие даты — «D месяц»", () => {
|
||||||
|
expect(formatDayLabel("2026-05-20", now)).toBe("20 мая");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("groupByLocalDay", () => {
|
||||||
|
it("группирует по VLA-дню, суммирует works_total, сохраняет порядок", () => {
|
||||||
|
const items = [
|
||||||
|
item(3, "2026-05-26T01:00:00Z", 100), // 26-е VLA
|
||||||
|
item(2, "2026-05-25T20:00:00Z", 50), // тоже 26-е VLA (06:00)
|
||||||
|
item(1, "2026-05-25T01:00:00Z", 200), // 25-е VLA
|
||||||
|
];
|
||||||
|
const groups = groupByLocalDay(items);
|
||||||
|
expect(groups.map((g) => g.key)).toEqual(["2026-05-26", "2026-05-25"]);
|
||||||
|
expect(groups[0].total).toBe(150);
|
||||||
|
expect(groups[0].items).toHaveLength(2);
|
||||||
|
expect(groups[1].total).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("пустой вход → пустой массив", () => {
|
||||||
|
expect(groupByLocalDay([])).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("fmtMoney", () => {
|
||||||
|
it("округляет и форматирует тысячи (NBSP-разделитель)", () => {
|
||||||
|
expect(fmtMoney(91000).replace(/ /g, " ")).toBe("91 000");
|
||||||
|
expect(fmtMoney(1499.6).replace(/ /g, " ")).toBe("1 500");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("склонения", () => {
|
||||||
|
it.each([
|
||||||
|
[1, "ремонт"],
|
||||||
|
[2, "ремонта"],
|
||||||
|
[4, "ремонта"],
|
||||||
|
[5, "ремонтов"],
|
||||||
|
[11, "ремонтов"],
|
||||||
|
[21, "ремонт"],
|
||||||
|
[22, "ремонта"],
|
||||||
|
])("pluralRepairs(%i) = %s", (n, exp) => {
|
||||||
|
expect(pluralRepairs(n)).toBe(exp);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
[1, "работа"],
|
||||||
|
[3, "работы"],
|
||||||
|
[5, "работ"],
|
||||||
|
[12, "работ"],
|
||||||
|
])("pluralWorks(%i) = %s", (n, exp) => {
|
||||||
|
expect(pluralWorks(n)).toBe(exp);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
/**
|
||||||
|
* Чистые помощники ленты ремонтов: группировка по локальной дате (VLA),
|
||||||
|
* форматирование сумм и склонения. Вынесены из RepairsFeedPage, чтобы быть
|
||||||
|
* переиспользуемыми и покрытыми юнит-тестами (TZ-логика группировки —
|
||||||
|
* частый источник off-by-one багов).
|
||||||
|
*/
|
||||||
|
import type { FeedItem } from "@/api/repairsFeed";
|
||||||
|
|
||||||
|
export interface DayGroup {
|
||||||
|
key: string; // YYYY-MM-DD (VLAT)
|
||||||
|
items: FeedItem[];
|
||||||
|
total: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** ISO → дата в Asia/Vladivostok (+10) как YYYY-MM-DD. */
|
||||||
|
export function toLocalDateKey(iso: string): string {
|
||||||
|
const d = new Date(iso);
|
||||||
|
const fmt = new Intl.DateTimeFormat("en-CA", {
|
||||||
|
timeZone: "Asia/Vladivostok",
|
||||||
|
year: "numeric",
|
||||||
|
month: "2-digit",
|
||||||
|
day: "2-digit",
|
||||||
|
});
|
||||||
|
return fmt.format(d); // 2026-05-26
|
||||||
|
}
|
||||||
|
|
||||||
|
/** key = YYYY-MM-DD → «26 мая» / «Сегодня» / «Вчера» (относительно VLA-сегодня). */
|
||||||
|
export function formatDayLabel(key: string, now: Date = new Date()): string {
|
||||||
|
const today = toLocalDateKey(now.toISOString());
|
||||||
|
if (key === today) return "Сегодня";
|
||||||
|
const yest = new Date(now.getTime() - 24 * 3600 * 1000);
|
||||||
|
if (key === toLocalDateKey(yest.toISOString())) return "Вчера";
|
||||||
|
const [y, m, d] = key.split("-").map(Number);
|
||||||
|
const dt = new Date(Date.UTC(y, m - 1, d));
|
||||||
|
return new Intl.DateTimeFormat("ru-RU", {
|
||||||
|
day: "numeric",
|
||||||
|
month: "long",
|
||||||
|
timeZone: "UTC",
|
||||||
|
}).format(dt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Группирует ленту по локальной дате; items уже отсортированы created_at DESC,
|
||||||
|
* поэтому ключи идут от свежих к старым. total — сумма works_total по дню. */
|
||||||
|
export function groupByLocalDay(items: FeedItem[]): DayGroup[] {
|
||||||
|
const map = new Map<string, DayGroup>();
|
||||||
|
for (const it of items) {
|
||||||
|
const key = toLocalDateKey(it.created_at);
|
||||||
|
let g = map.get(key);
|
||||||
|
if (!g) {
|
||||||
|
g = { key, items: [], total: 0 };
|
||||||
|
map.set(key, g);
|
||||||
|
}
|
||||||
|
g.items.push(it);
|
||||||
|
g.total += it.works_total || 0;
|
||||||
|
}
|
||||||
|
return Array.from(map.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fmtMoney(n: number): string {
|
||||||
|
return new Intl.NumberFormat("ru-RU", { maximumFractionDigits: 0 }).format(Math.round(n));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 1 → «ремонт», 2..4 → «ремонта», 5+/11..14 → «ремонтов». */
|
||||||
|
export function pluralRepairs(n: number): string {
|
||||||
|
const mod10 = n % 10;
|
||||||
|
const mod100 = n % 100;
|
||||||
|
if (mod100 >= 11 && mod100 <= 14) return "ремонтов";
|
||||||
|
if (mod10 === 1) return "ремонт";
|
||||||
|
if (mod10 >= 2 && mod10 <= 4) return "ремонта";
|
||||||
|
return "ремонтов";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 1 → «работа», 2..4 → «работы», 5+/11..14 → «работ». */
|
||||||
|
export function pluralWorks(n: number): string {
|
||||||
|
const mod10 = n % 10;
|
||||||
|
const mod100 = n % 100;
|
||||||
|
if (mod100 >= 11 && mod100 <= 14) return "работ";
|
||||||
|
if (mod10 === 1) return "работа";
|
||||||
|
if (mod10 >= 2 && mod10 <= 4) return "работы";
|
||||||
|
return "работ";
|
||||||
|
}
|
||||||
@@ -37,13 +37,17 @@ const SLOTS_GENERAL: { side: string; label: string }[] = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
const SLOT_JACK = { side: "jack", label: "Домкрат" };
|
const SLOT_JACK = { side: "jack", label: "Домкрат" };
|
||||||
|
// Шильдик замены масла — отдельный слот при выдаче/приёмке.
|
||||||
|
// Фото нужно как для сверки текущего пробега со следующим ТО, так и для
|
||||||
|
// контроля что водитель не клеит свой стикер.
|
||||||
|
const SLOT_OIL_STICKER = { side: "oil-sticker", label: "Шильдик замены масла" };
|
||||||
|
|
||||||
/** Все типы осмотров (выдача/приёмка/плановый/...) показывают одинаковый
|
/** Все типы осмотров (выдача/приёмка/плановый/...) показывают одинаковый
|
||||||
* набор слотов общих ракурсов + домкрат. Раньше «return» исключал общие
|
* набор слотов общих ракурсов + домкрат. Раньше «return» исключал общие
|
||||||
* фото в пользу скорости приёмки, но фидбек: при приёмке всё равно надо
|
* фото в пользу скорости приёмки, но фидбек: при приёмке всё равно надо
|
||||||
* фиксировать общее состояние машины, как и при выдаче/осмотре. */
|
* фиксировать общее состояние машины, как и при выдаче/осмотре. */
|
||||||
function slotsForType(_type: string): typeof SLOTS_GENERAL {
|
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> = {
|
const SEVERITY_LABELS: Record<string, string> = {
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
import { vi } from "vitest";
|
||||||
|
|
||||||
|
const { navigate } = vi.hoisted(() => ({ navigate: vi.fn() }));
|
||||||
|
|
||||||
|
vi.mock("react-router-dom", async (importOriginal) => {
|
||||||
|
const actual = await importOriginal<typeof import("react-router-dom")>();
|
||||||
|
return { ...actual, useNavigate: () => navigate };
|
||||||
|
});
|
||||||
|
vi.mock("@/api/repairsCreate", () => ({
|
||||||
|
searchCars: vi.fn().mockResolvedValue([]),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import CarSelectPage from "@/pages/repairs/CarSelectPage";
|
||||||
|
|
||||||
|
beforeEach(() => navigate.mockClear());
|
||||||
|
|
||||||
|
test("«Машина не из парка» → ввод номера → navigate в external-режим со state (номер trim'ится)", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<CarSelectPage />);
|
||||||
|
|
||||||
|
await user.click(screen.getByText("+ Машина не из парка"));
|
||||||
|
await user.type(screen.getByPlaceholderText("Х999ХХ199"), " х999хх199 ");
|
||||||
|
await user.type(screen.getByPlaceholderText("Toyota Camry"), "Toyota Camry");
|
||||||
|
await user.click(screen.getByText("Продолжить →"));
|
||||||
|
|
||||||
|
expect(navigate).toHaveBeenCalledWith("/repairs/new-external", {
|
||||||
|
state: { plate: "х999хх199", make: "Toyota Camry" },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("марка опциональна → make=null если поле пустое", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<CarSelectPage />);
|
||||||
|
|
||||||
|
await user.click(screen.getByText("+ Машина не из парка"));
|
||||||
|
await user.type(screen.getByPlaceholderText("Х999ХХ199"), "А001АА125");
|
||||||
|
await user.click(screen.getByText("Продолжить →"));
|
||||||
|
|
||||||
|
expect(navigate).toHaveBeenCalledWith("/repairs/new-external", {
|
||||||
|
state: { plate: "А001АА125", make: null },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("«Продолжить» заблокирована без номера", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<CarSelectPage />);
|
||||||
|
await user.click(screen.getByText("+ Машина не из парка"));
|
||||||
|
expect(screen.getByText("Продолжить →").closest("button")).toBeDisabled();
|
||||||
|
});
|
||||||
@@ -18,6 +18,15 @@ export default function CarSelectPage() {
|
|||||||
const [cars, setCars] = useState<CarBrief[]>([]);
|
const [cars, setCars] = useState<CarBrief[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [extOpen, setExtOpen] = useState(false);
|
||||||
|
const [extPlate, setExtPlate] = useState("");
|
||||||
|
const [extMake, setExtMake] = useState("");
|
||||||
|
|
||||||
|
const continueExternal = () => {
|
||||||
|
const plate = extPlate.trim();
|
||||||
|
if (!plate) return;
|
||||||
|
navigate("/repairs/new-external", { state: { plate, make: extMake.trim() || null } });
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
@@ -62,6 +71,13 @@ export default function CarSelectPage() {
|
|||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
<main className="flex-1 container max-w-2xl py-3">
|
<main className="flex-1 container max-w-2xl py-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setExtOpen(true)}
|
||||||
|
className="w-full mb-3 flex items-center justify-center gap-1 rounded-md border border-dashed bg-card hover:bg-accent/40 transition-colors p-3 text-sm font-medium text-muted-foreground"
|
||||||
|
>
|
||||||
|
+ Машина не из парка
|
||||||
|
</button>
|
||||||
{error && (
|
{error && (
|
||||||
<div className="rounded-md border border-destructive bg-destructive/10 p-3 text-sm">
|
<div className="rounded-md border border-destructive bg-destructive/10 p-3 text-sm">
|
||||||
{error}
|
{error}
|
||||||
@@ -96,6 +112,41 @@ export default function CarSelectPage() {
|
|||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
</main>
|
</main>
|
||||||
|
{extOpen && (
|
||||||
|
<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 variant="ghost" size="sm" onClick={() => setExtOpen(false)}>
|
||||||
|
Отмена
|
||||||
|
</Button>
|
||||||
|
<h2 className="text-base font-semibold">Машина с улицы</h2>
|
||||||
|
</header>
|
||||||
|
<main className="flex-1 container max-w-2xl py-4 space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="text-sm font-medium">Госномер *</label>
|
||||||
|
<Input
|
||||||
|
autoFocus
|
||||||
|
value={extPlate}
|
||||||
|
onChange={(e) => setExtPlate(e.target.value)}
|
||||||
|
placeholder="Х999ХХ199"
|
||||||
|
className="mt-1"
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && continueExternal()}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-sm font-medium">Марка и модель (необязательно)</label>
|
||||||
|
<Input
|
||||||
|
value={extMake}
|
||||||
|
onChange={(e) => setExtMake(e.target.value)}
|
||||||
|
placeholder="Toyota Camry"
|
||||||
|
className="mt-1"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Button className="w-full" disabled={!extPlate.trim()} onClick={continueExternal}>
|
||||||
|
Продолжить →
|
||||||
|
</Button>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,12 +15,14 @@
|
|||||||
* Сохранение: POST /repairs с `Idempotency-Key` (UUID v4 в state).
|
* Сохранение: POST /repairs с `Idempotency-Key` (UUID v4 в state).
|
||||||
*/
|
*/
|
||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { useNavigate, useParams } from "react-router-dom";
|
import { useNavigate, useParams, useLocation } from "react-router-dom";
|
||||||
import { ChevronLeft, Plus, Trash2, Pencil, Camera } from "lucide-react";
|
import { ChevronLeft, Plus, Trash2, Pencil, Camera } from "lucide-react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { repairCanSubmit, repairSubmitWhyDisabled } from "@/lib/repairForm";
|
||||||
|
import WorksPickerModal from "@/components/repairs/WorksPickerModal";
|
||||||
import {
|
import {
|
||||||
createRepair,
|
createRepair,
|
||||||
getCarContext,
|
getCarContext,
|
||||||
@@ -41,6 +43,10 @@ interface PhotoState {
|
|||||||
tag: "auto" | "part" | "other";
|
tag: "auto" | "part" | "other";
|
||||||
status: "uploading" | "uploaded" | "error";
|
status: "uploading" | "uploaded" | "error";
|
||||||
errorMessage?: string;
|
errorMessage?: string;
|
||||||
|
// Превью локального файла через URL.createObjectURL — отдаётся в <img>
|
||||||
|
// вместо плейсхолдера «Загружено». Освобождается через revokeObjectURL
|
||||||
|
// при удалении и при размонтировании страницы.
|
||||||
|
previewUrl?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface WorkRow {
|
interface WorkRow {
|
||||||
@@ -50,7 +56,10 @@ interface WorkRow {
|
|||||||
work_catalog_id: number;
|
work_catalog_id: number;
|
||||||
name: string; // снапшот имени из прайса
|
name: string; // снапшот имени из прайса
|
||||||
price_catalog: number;
|
price_catalog: number;
|
||||||
price_applied: number;
|
// "" допустим в процессе редактирования — иначе React при очистке inputа
|
||||||
|
// сразу подставляет "0" и его приходится курсором обходить, см. жалобу
|
||||||
|
// механиков. На submit пустое трактуется как 0 (или как ошибка валидации).
|
||||||
|
price_applied: number | "";
|
||||||
unlocked: boolean; // карандашик разблокировал поле
|
unlocked: boolean; // карандашик разблокировал поле
|
||||||
override_comment: string;
|
override_comment: string;
|
||||||
}
|
}
|
||||||
@@ -63,13 +72,19 @@ interface PartRow {
|
|||||||
|
|
||||||
interface OilChangeState {
|
interface OilChangeState {
|
||||||
enabled: boolean;
|
enabled: boolean;
|
||||||
mileage_at_change: number | null;
|
|
||||||
mileage_is_dirty: boolean; // У24: мягкая подписка с шапочным
|
|
||||||
next_in_km: number;
|
next_in_km: number;
|
||||||
sticker: PhotoState | null;
|
sticker: PhotoState | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Цены ремонта — целые рубли без копеек. 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 {
|
function uuid4(): string {
|
||||||
// crypto.randomUUID требует secure context; mechanic.pptaxi.ru — https.
|
// crypto.randomUUID требует secure context; mechanic.pptaxi.ru — https.
|
||||||
return (crypto as any).randomUUID
|
return (crypto as any).randomUUID
|
||||||
@@ -81,6 +96,9 @@ function uuid4(): string {
|
|||||||
export default function CreateRepairPage() {
|
export default function CreateRepairPage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { carId: carIdRaw } = useParams<{ carId: string }>();
|
const { carId: carIdRaw } = useParams<{ carId: string }>();
|
||||||
|
const location = useLocation();
|
||||||
|
const isExternal = !carIdRaw;
|
||||||
|
const externalState = location.state as { plate: string; make: string | null } | null;
|
||||||
const carId = carIdRaw ? Number(carIdRaw) : 0;
|
const carId = carIdRaw ? Number(carIdRaw) : 0;
|
||||||
|
|
||||||
// Idempotency-Key для этой формы — стабилен между ре-сабмитами (У20).
|
// Idempotency-Key для этой формы — стабилен между ре-сабмитами (У20).
|
||||||
@@ -95,8 +113,6 @@ export default function CreateRepairPage() {
|
|||||||
const [parts, setParts] = useState<PartRow[]>([]);
|
const [parts, setParts] = useState<PartRow[]>([]);
|
||||||
const [oilChange, setOilChange] = useState<OilChangeState>({
|
const [oilChange, setOilChange] = useState<OilChangeState>({
|
||||||
enabled: false,
|
enabled: false,
|
||||||
mileage_at_change: null,
|
|
||||||
mileage_is_dirty: false,
|
|
||||||
next_in_km: 10000,
|
next_in_km: 10000,
|
||||||
sticker: null,
|
sticker: null,
|
||||||
});
|
});
|
||||||
@@ -109,6 +125,24 @@ export default function CreateRepairPage() {
|
|||||||
|
|
||||||
// Initial: подгрузить контекст машины.
|
// Initial: подгрузить контекст машины.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (isExternal) {
|
||||||
|
if (!externalState) {
|
||||||
|
// Прямой заход/рефреш без данных — возвращаем к выбору машины.
|
||||||
|
navigate("/repairs/new", { replace: true });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setCtx({
|
||||||
|
id: 0,
|
||||||
|
plate: externalState.plate,
|
||||||
|
brand: externalState.make,
|
||||||
|
model: null,
|
||||||
|
mileage_starline: null,
|
||||||
|
driver_id: null,
|
||||||
|
driver_name: null,
|
||||||
|
});
|
||||||
|
setMileage(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (!carId) return;
|
if (!carId) return;
|
||||||
getCarContext(carId)
|
getCarContext(carId)
|
||||||
.then((c) => {
|
.then((c) => {
|
||||||
@@ -116,15 +150,12 @@ export default function CreateRepairPage() {
|
|||||||
setMileage(c.mileage_starline);
|
setMileage(c.mileage_starline);
|
||||||
})
|
})
|
||||||
.catch((e) => setCtxError((e as Error).message || "Не удалось загрузить машину"));
|
.catch((e) => setCtxError((e as Error).message || "Не удалось загрузить машину"));
|
||||||
}, [carId]);
|
|
||||||
|
|
||||||
// У24: мягкая подписка пробега блока масла на шапочный.
|
|
||||||
useEffect(() => {
|
|
||||||
if (oilChange.enabled && !oilChange.mileage_is_dirty) {
|
|
||||||
setOilChange((oc) => ({ ...oc, mileage_at_change: mileage }));
|
|
||||||
}
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [mileage, oilChange.enabled]);
|
}, [carId, isExternal]);
|
||||||
|
|
||||||
|
// У24 упрощено: пробег ввода в форме теперь один — главный «Пробег (км)»
|
||||||
|
// в шапке. На submit подставляется и в oil_change.mileage_at_change, чтобы
|
||||||
|
// не заставлять механика вводить одно и то же дважды.
|
||||||
|
|
||||||
// ── Photo upload ─────────────────────────────────────────────────────────
|
// ── Photo upload ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -132,6 +163,7 @@ export default function CreateRepairPage() {
|
|||||||
if (!files || files.length === 0) return;
|
if (!files || files.length === 0) return;
|
||||||
for (const file of Array.from(files)) {
|
for (const file of Array.from(files)) {
|
||||||
const ext = (file.name.split(".").pop() || "jpg").toLowerCase();
|
const ext = (file.name.split(".").pop() || "jpg").toLowerCase();
|
||||||
|
const previewUrl = URL.createObjectURL(file);
|
||||||
const placeholder: PhotoState = {
|
const placeholder: PhotoState = {
|
||||||
presign: {
|
presign: {
|
||||||
photo_uuid: uuid4(),
|
photo_uuid: uuid4(),
|
||||||
@@ -143,6 +175,7 @@ export default function CreateRepairPage() {
|
|||||||
},
|
},
|
||||||
tag: "auto",
|
tag: "auto",
|
||||||
status: "uploading",
|
status: "uploading",
|
||||||
|
previewUrl,
|
||||||
};
|
};
|
||||||
if (target === "gallery") setPhotos((arr) => [...arr, placeholder]);
|
if (target === "gallery") setPhotos((arr) => [...arr, placeholder]);
|
||||||
else setOilChange((oc) => ({ ...oc, sticker: { ...placeholder, tag: "auto" } }));
|
else setOilChange((oc) => ({ ...oc, sticker: { ...placeholder, tag: "auto" } }));
|
||||||
@@ -150,7 +183,7 @@ export default function CreateRepairPage() {
|
|||||||
try {
|
try {
|
||||||
const presign = await presignPhoto(ext, placeholder.presign.photo_uuid);
|
const presign = await presignPhoto(ext, placeholder.presign.photo_uuid);
|
||||||
await uploadPhotoToTmp(file, presign);
|
await uploadPhotoToTmp(file, presign);
|
||||||
const updated: PhotoState = { presign, tag: "auto", status: "uploaded" };
|
const updated: PhotoState = { presign, tag: "auto", status: "uploaded", previewUrl };
|
||||||
if (target === "gallery") {
|
if (target === "gallery") {
|
||||||
setPhotos((arr) =>
|
setPhotos((arr) =>
|
||||||
arr.map((p) => (p.presign.photo_uuid === presign.photo_uuid ? updated : p)),
|
arr.map((p) => (p.presign.photo_uuid === presign.photo_uuid ? updated : p)),
|
||||||
@@ -179,7 +212,11 @@ export default function CreateRepairPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const removePhoto = (photoUuid: string) =>
|
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 ─────────────────────────────────────────────────────────
|
// ── Works picker ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -196,7 +233,7 @@ export default function CreateRepairPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const addWorkFromCatalog = (w: MechWork) => {
|
const addWorkFromCatalog = (w: MechWork) => {
|
||||||
const price = Number(w.price);
|
const price = Math.round(Number(w.price));
|
||||||
setWorks((arr) => [
|
setWorks((arr) => [
|
||||||
...arr,
|
...arr,
|
||||||
{
|
{
|
||||||
@@ -241,7 +278,14 @@ export default function CreateRepairPage() {
|
|||||||
setPartsDraft({ name: q, suggestions: [] });
|
setPartsDraft({ name: q, suggestions: [] });
|
||||||
if (!q.trim()) return;
|
if (!q.trim()) return;
|
||||||
const list = await suggestParts(q);
|
const list = await suggestParts(q);
|
||||||
setPartsDraft({ name: q, suggestions: list.map((s) => s.name) });
|
// У43 race-fix: пока запрос для "К" летел, юзер дописал до "Кепу" — поздний
|
||||||
|
// ответ не должен перезаписывать .name старым значением (это и есть
|
||||||
|
// «текст частично сам стирается»). Применяем suggestions только если
|
||||||
|
// ввод не менялся; иначе тихо роняем ответ.
|
||||||
|
setPartsDraft((prev) => {
|
||||||
|
if (prev.name !== q) return prev;
|
||||||
|
return { name: q, suggestions: list.map((s) => s.name) };
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const addPart = (name: string) => {
|
const addPart = (name: string) => {
|
||||||
@@ -256,20 +300,8 @@ export default function CreateRepairPage() {
|
|||||||
|
|
||||||
// ── Submit ───────────────────────────────────────────────────────────────
|
// ── Submit ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const canSubmit = () =>
|
const canSubmit = () => repairCanSubmit(photos, works);
|
||||||
photos.length > 0 &&
|
const submitWhyDisabled = (): string => repairSubmitWhyDisabled(photos, works);
|
||||||
photos.every((p) => p.status === "uploaded") &&
|
|
||||||
works.length > 0 &&
|
|
||||||
works.every((w) => !w.unlocked || w.override_comment.trim().length > 0);
|
|
||||||
|
|
||||||
const submitWhyDisabled = (): string => {
|
|
||||||
if (photos.length === 0) return "Добавьте хотя бы одно фото";
|
|
||||||
if (photos.some((p) => p.status !== "uploaded")) return "Дождитесь окончания загрузки фото";
|
|
||||||
if (works.length === 0) return "Добавьте хотя бы одну работу";
|
|
||||||
const unlockedNoComment = works.find((w) => w.unlocked && !w.override_comment.trim());
|
|
||||||
if (unlockedNoComment) return "Укажите комментарий к ручной правке цены";
|
|
||||||
return "";
|
|
||||||
};
|
|
||||||
|
|
||||||
const onSubmit = async () => {
|
const onSubmit = async () => {
|
||||||
const reason = submitWhyDisabled();
|
const reason = submitWhyDisabled();
|
||||||
@@ -287,7 +319,9 @@ export default function CreateRepairPage() {
|
|||||||
}));
|
}));
|
||||||
const result = await createRepair(
|
const result = await createRepair(
|
||||||
{
|
{
|
||||||
car_id: carId,
|
...(isExternal
|
||||||
|
? { external_car: { plate: externalState!.plate, make: externalState!.make } }
|
||||||
|
: { car_id: carId }),
|
||||||
mileage,
|
mileage,
|
||||||
works: works.map((w) => ({
|
works: works.map((w) => ({
|
||||||
work_catalog_id: w.work_catalog_id,
|
work_catalog_id: w.work_catalog_id,
|
||||||
@@ -300,7 +334,8 @@ export default function CreateRepairPage() {
|
|||||||
oil_change: oilChange.enabled
|
oil_change: oilChange.enabled
|
||||||
? {
|
? {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
mileage_at_change: oilChange.mileage_at_change,
|
// Один источник истины — главный пробег ремонта (см. У24).
|
||||||
|
mileage_at_change: mileage,
|
||||||
next_in_km: oilChange.next_in_km,
|
next_in_km: oilChange.next_in_km,
|
||||||
sticker_photo_uuid:
|
sticker_photo_uuid:
|
||||||
oilChange.sticker?.status === "uploaded"
|
oilChange.sticker?.status === "uploaded"
|
||||||
@@ -364,7 +399,11 @@ export default function CreateRepairPage() {
|
|||||||
<div className="font-medium">{ctx.plate}</div>
|
<div className="font-medium">{ctx.plate}</div>
|
||||||
<div className="text-muted-foreground">
|
<div className="text-muted-foreground">
|
||||||
{[ctx.brand, ctx.model].filter(Boolean).join(" ")}
|
{[ctx.brand, ctx.model].filter(Boolean).join(" ")}
|
||||||
{ctx.driver_name ? ` · ${ctx.driver_name}` : ` · Без водителя`}
|
{isExternal
|
||||||
|
? " · С улицы"
|
||||||
|
: ctx.driver_name
|
||||||
|
? ` · ${ctx.driver_name}`
|
||||||
|
: " · Без водителя"}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
@@ -395,17 +434,28 @@ export default function CreateRepairPage() {
|
|||||||
<div className="grid grid-cols-3 gap-2 mt-2">
|
<div className="grid grid-cols-3 gap-2 mt-2">
|
||||||
{photos.map((p) => (
|
{photos.map((p) => (
|
||||||
<div key={p.presign.photo_uuid} className="relative aspect-square border rounded-md bg-muted overflow-hidden">
|
<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" && (
|
{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" && (
|
{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 || "Ошибка"}
|
{p.errorMessage || "Ошибка"}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{p.status === "uploaded" && (
|
{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>
|
</div>
|
||||||
)}
|
)}
|
||||||
<button
|
<button
|
||||||
@@ -449,11 +499,21 @@ export default function CreateRepairPage() {
|
|||||||
key={w.rowKey}
|
key={w.rowKey}
|
||||||
className={`rounded-md border p-2 ${w.unlocked ? "bg-amber-50 border-amber-300" : ""}`}
|
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="flex-1 min-w-0">
|
||||||
<div className="text-sm font-medium truncate">{w.name}</div>
|
<div
|
||||||
<div className="text-xs text-muted-foreground">
|
className="text-sm font-medium leading-snug break-words"
|
||||||
Прайс: {w.price_catalog} ₽
|
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>
|
</div>
|
||||||
<div className="flex items-center gap-1">
|
<div className="flex items-center gap-1">
|
||||||
@@ -462,15 +522,19 @@ export default function CreateRepairPage() {
|
|||||||
min={0}
|
min={0}
|
||||||
value={w.price_applied}
|
value={w.price_applied}
|
||||||
disabled={!w.unlocked}
|
disabled={!w.unlocked}
|
||||||
onChange={(e) =>
|
onChange={(e) => {
|
||||||
|
const v = e.target.value;
|
||||||
|
// Пустое поле остаётся пустым в стейте (не сбрасываем в 0),
|
||||||
|
// чтобы юзер мог сразу набрать новую цену поверх.
|
||||||
|
const next: number | "" = v === "" ? "" : Number(v);
|
||||||
setWorks((arr) =>
|
setWorks((arr) =>
|
||||||
arr.map((row) =>
|
arr.map((row) =>
|
||||||
row.rowKey === w.rowKey
|
row.rowKey === w.rowKey
|
||||||
? { ...row, price_applied: Number(e.target.value) }
|
? { ...row, price_applied: next }
|
||||||
: row,
|
: row,
|
||||||
),
|
),
|
||||||
)
|
);
|
||||||
}
|
}}
|
||||||
className="w-24"
|
className="w-24"
|
||||||
/>
|
/>
|
||||||
<Button
|
<Button
|
||||||
@@ -505,7 +569,7 @@ export default function CreateRepairPage() {
|
|||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
{works.length > 0 && (
|
{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>
|
</section>
|
||||||
|
|
||||||
@@ -579,21 +643,6 @@ export default function CreateRepairPage() {
|
|||||||
</label>
|
</label>
|
||||||
{oilChange.enabled && (
|
{oilChange.enabled && (
|
||||||
<div className="mt-3 space-y-3">
|
<div className="mt-3 space-y-3">
|
||||||
<div>
|
|
||||||
<Label className="text-sm">Пробег на момент замены</Label>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
min={0}
|
|
||||||
value={oilChange.mileage_at_change ?? ""}
|
|
||||||
onChange={(e) =>
|
|
||||||
setOilChange((oc) => ({
|
|
||||||
...oc,
|
|
||||||
mileage_at_change: e.target.value === "" ? null : Number(e.target.value),
|
|
||||||
mileage_is_dirty: true,
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
<div>
|
||||||
<Label className="text-sm">Следующая замена через (км)</Label>
|
<Label className="text-sm">Следующая замена через (км)</Label>
|
||||||
<Input
|
<Input
|
||||||
@@ -607,17 +656,34 @@ export default function CreateRepairPage() {
|
|||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<Label className="text-sm">Фото стикера (одно)</Label>
|
<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">
|
<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 == null ? (
|
{oilChange.sticker?.previewUrl ? (
|
||||||
<span className="text-sm text-muted-foreground">Тап чтобы загрузить</span>
|
<img
|
||||||
) : oilChange.sticker.status === "uploading" ? (
|
src={oilChange.sticker.previewUrl}
|
||||||
"Загрузка…"
|
alt=""
|
||||||
) : oilChange.sticker.status === "error" ? (
|
className="absolute inset-0 w-full h-full object-contain bg-muted"
|
||||||
<span className="text-sm text-destructive">
|
/>
|
||||||
Ошибка: {oilChange.sticker.errorMessage}
|
|
||||||
</span>
|
|
||||||
) : (
|
) : (
|
||||||
<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
|
<input
|
||||||
type="file"
|
type="file"
|
||||||
@@ -633,42 +699,15 @@ export default function CreateRepairPage() {
|
|||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
{/* Works picker modal */}
|
{/* Works picker modal — общий компонент (см. WorksPickerModal) */}
|
||||||
{worksPicker.open && (
|
{worksPicker.open && (
|
||||||
<div className="fixed inset-0 z-50 bg-background/95 flex flex-col">
|
<WorksPickerModal
|
||||||
<header className="border-b p-3 flex items-center gap-2">
|
query={worksPicker.q}
|
||||||
<Button variant="ghost" size="sm" onClick={() => setWorksPicker({ open: false, q: "", results: [] })}>
|
results={worksPicker.results}
|
||||||
Отмена
|
onQuery={queryWorks}
|
||||||
</Button>
|
onPick={addWorkFromCatalog}
|
||||||
<Input
|
onClose={() => setWorksPicker({ open: false, q: "", results: [] })}
|
||||||
autoFocus
|
/>
|
||||||
placeholder="Поиск работы…"
|
|
||||||
value={worksPicker.q}
|
|
||||||
onChange={(e) => queryWorks(e.target.value)}
|
|
||||||
/>
|
|
||||||
</header>
|
|
||||||
<main className="flex-1 overflow-y-auto">
|
|
||||||
<ul className="divide-y">
|
|
||||||
{worksPicker.results.map((w) => (
|
|
||||||
<li key={w.id}>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => addWorkFromCatalog(w)}
|
|
||||||
className="w-full text-left p-3 hover:bg-accent/40 flex items-baseline 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>
|
|
||||||
</button>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
{worksPicker.results.length === 0 && (
|
|
||||||
<li className="p-6 text-center text-sm text-muted-foreground">
|
|
||||||
Нет работ по запросу
|
|
||||||
</li>
|
|
||||||
)}
|
|
||||||
</ul>
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,525 @@
|
|||||||
|
/**
|
||||||
|
* Правка ремонта в 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";
|
||||||
|
import WorksPickerModal from "@/components/repairs/WorksPickerModal";
|
||||||
|
|
||||||
|
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;
|
||||||
|
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, 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,
|
||||||
|
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: mileage, 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">
|
||||||
|
<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>
|
||||||
|
)}
|
||||||
|
</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 — общий компонент (см. WorksPickerModal) */}
|
||||||
|
{worksPicker.open && (
|
||||||
|
<WorksPickerModal
|
||||||
|
query={worksPicker.q}
|
||||||
|
results={worksPicker.results}
|
||||||
|
onQuery={queryWorks}
|
||||||
|
onPick={pickWork}
|
||||||
|
onClose={() => setWorksPicker({ open: false, q: "", results: [] })}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -7,13 +7,15 @@
|
|||||||
*
|
*
|
||||||
* Пустая лента — плейсхолдер «В парке пока нет ремонтов» (У41).
|
* Пустая лента — плейсхолдер «В парке пока нет ремонтов» (У41).
|
||||||
*/
|
*/
|
||||||
import { useCallback, useEffect, useRef } from "react";
|
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { ChevronLeft, Plus, Wrench } from "lucide-react";
|
import { ChevronLeft, Plus, Wrench } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { useRepairsFeed } from "@/hooks/useRepairsFeed";
|
import { useRepairsFeed } from "@/hooks/useRepairsFeed";
|
||||||
import { formatFeedTimestamp } from "@/lib/timeFormat";
|
import { formatFeedTimestamp } from "@/lib/timeFormat";
|
||||||
import type { FeedItem } from "@/api/repairsFeed";
|
import { getRepairsMonthStats, type FeedItem } from "@/api/repairsFeed";
|
||||||
|
import { groupByLocalDay, formatDayLabel, fmtMoney, pluralRepairs, pluralWorks } from "@/lib/repairsFeed";
|
||||||
|
|
||||||
export default function RepairsFeedPage() {
|
export default function RepairsFeedPage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
@@ -28,6 +30,17 @@ export default function RepairsFeedPage() {
|
|||||||
isFetching,
|
isFetching,
|
||||||
} = useRepairsFeed();
|
} = useRepairsFeed();
|
||||||
|
|
||||||
|
// Сумма и количество ремонтов за текущий месяц (отдельный endpoint —
|
||||||
|
// не зависит от пагинации ленты).
|
||||||
|
const monthStatsQuery = useQuery({
|
||||||
|
queryKey: ["repairs-month-stats"],
|
||||||
|
queryFn: getRepairsMonthStats,
|
||||||
|
staleTime: 60_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Группировка items по локальной дате (Asia/Vladivostok).
|
||||||
|
const grouped = useMemo(() => groupByLocalDay(items), [items]);
|
||||||
|
|
||||||
// IntersectionObserver для бесконечной прокрутки.
|
// IntersectionObserver для бесконечной прокрутки.
|
||||||
const sentinelRef = useRef<HTMLDivElement | null>(null);
|
const sentinelRef = useRef<HTMLDivElement | null>(null);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -83,8 +96,21 @@ export default function RepairsFeedPage() {
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<main className="flex-1 container max-w-2xl py-3 space-y-2">
|
<main className="flex-1 container max-w-2xl py-3 space-y-2">
|
||||||
{/* Refresh tap-area для не-touch юзкейса; жест pull-to-refresh — в PR-8. */}
|
{/* Итого слева — сумма работ и количество ремонтов за текущий месяц
|
||||||
<div className="flex items-center justify-end">
|
(с 1-го числа по now). Обновить справа. */}
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="text-sm">
|
||||||
|
<span className="text-muted-foreground">За этот месяц:</span>{" "}
|
||||||
|
<span className="font-semibold tabular-nums">
|
||||||
|
{fmtMoney(monthStatsQuery.data?.total ?? 0)} ₽
|
||||||
|
</span>
|
||||||
|
{(monthStatsQuery.data?.count ?? 0) > 0 && (
|
||||||
|
<span className="text-xs text-muted-foreground ml-2">
|
||||||
|
({monthStatsQuery.data!.count}{" "}
|
||||||
|
{pluralRepairs(monthStatsQuery.data!.count)})
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={handleRefresh}
|
onClick={handleRefresh}
|
||||||
@@ -113,9 +139,16 @@ export default function RepairsFeedPage() {
|
|||||||
|
|
||||||
{items.length > 0 && (
|
{items.length > 0 && (
|
||||||
<ul className="space-y-2">
|
<ul className="space-y-2">
|
||||||
{items.map((item) => (
|
{grouped.map((group) => (
|
||||||
<li key={item.id}>
|
<li key={group.key}>
|
||||||
<RepairRow item={item} onOpen={() => handleOpen(item)} />
|
<DaySeparator dateKey={group.key} total={group.total} count={group.items.length} />
|
||||||
|
<ul className="space-y-2 mt-2">
|
||||||
|
{group.items.map((item) => (
|
||||||
|
<li key={item.id}>
|
||||||
|
<RepairRow item={item} onOpen={() => handleOpen(item)} />
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
@@ -138,6 +171,23 @@ export default function RepairsFeedPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Группировка по локальной дате (VLA), форматирование сумм/склонений —
|
||||||
|
// в @/lib/repairsFeed (покрыто юнит-тестами).
|
||||||
|
|
||||||
|
function DaySeparator({ dateKey, total, count }: { dateKey: string; total: number; count: number }) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-2 pt-3 pb-1 text-xs">
|
||||||
|
<span className="font-medium text-foreground">{formatDayLabel(dateKey)}</span>
|
||||||
|
<div className="flex-1 border-t border-dashed border-border" />
|
||||||
|
<span className="tabular-nums text-muted-foreground">
|
||||||
|
{fmtMoney(total)} ₽
|
||||||
|
<span className="ml-1">({count} {pluralRepairs(count)})</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
function RepairRow({ item, onOpen }: { item: FeedItem; onOpen: () => void }) {
|
function RepairRow({ item, onOpen }: { item: FeedItem; onOpen: () => void }) {
|
||||||
const carLine = [item.car_plate, item.car_make, item.car_model]
|
const carLine = [item.car_plate, item.car_make, item.car_model]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
@@ -163,7 +213,14 @@ function RepairRow({ item, onOpen }: { item: FeedItem; onOpen: () => void }) {
|
|||||||
</div>
|
</div>
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<div className="flex items-baseline justify-between gap-2">
|
<div className="flex items-baseline justify-between gap-2">
|
||||||
<div className="font-medium truncate">{carLine}</div>
|
<div className="font-medium truncate">
|
||||||
|
{carLine}
|
||||||
|
{item.is_external && (
|
||||||
|
<span className="ml-1.5 align-middle text-[10px] font-semibold uppercase tracking-wide text-amber-700 bg-amber-100 rounded px-1 py-0.5">
|
||||||
|
с улицы
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
<div className="text-xs text-muted-foreground flex-shrink-0">
|
<div className="text-xs text-muted-foreground flex-shrink-0">
|
||||||
{formatFeedTimestamp(item.created_at)}
|
{formatFeedTimestamp(item.created_at)}
|
||||||
</div>
|
</div>
|
||||||
@@ -176,7 +233,12 @@ function RepairRow({ item, onOpen }: { item: FeedItem; onOpen: () => void }) {
|
|||||||
<div className="text-xs text-muted-foreground truncate">
|
<div className="text-xs text-muted-foreground truncate">
|
||||||
Механик: {item.mechanic_name}
|
Механик: {item.mechanic_name}
|
||||||
</div>
|
</div>
|
||||||
<WorksLine works={item.works_preview.map((w) => w.name)} extra={item.works_extra} />
|
<div className="flex items-baseline justify-between gap-2">
|
||||||
|
<WorksLine works={item.works_preview.map((w) => w.name)} extra={item.works_extra} />
|
||||||
|
<div className="text-sm font-semibold tabular-nums flex-shrink-0">
|
||||||
|
{fmtMoney(item.works_total || 0)} ₽
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
@@ -196,17 +258,6 @@ function WorksLine({ works, extra }: { works: string[]; extra: number }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function pluralWorks(n: number): string {
|
|
||||||
// 1 → «работа», 2..4 → «работы», 5+ → «работ»
|
|
||||||
const mod10 = n % 10;
|
|
||||||
const mod100 = n % 100;
|
|
||||||
if (mod100 >= 11 && mod100 <= 14) return "работ";
|
|
||||||
if (mod10 === 1) return "работа";
|
|
||||||
if (mod10 >= 2 && mod10 <= 4) return "работы";
|
|
||||||
return "работ";
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
function EmptyState({ onAdd }: { onAdd: () => void }) {
|
function EmptyState({ onAdd }: { onAdd: () => void }) {
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col items-center justify-center text-center py-16 px-4 space-y-4">
|
<div className="flex flex-col items-center justify-center text-center py-16 px-4 space-y-4">
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
import "@testing-library/jest-dom/vitest";
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
|
||||||
|
test("vitest + RTL + jsdom harness works", () => {
|
||||||
|
render(<div>привет</div>);
|
||||||
|
expect(screen.getByText("привет")).toBeInTheDocument();
|
||||||
|
});
|
||||||
@@ -29,5 +29,6 @@
|
|||||||
"baseUrl": ".",
|
"baseUrl": ".",
|
||||||
"paths": { "@/*": ["./src/*"] }
|
"paths": { "@/*": ["./src/*"] }
|
||||||
},
|
},
|
||||||
"include": ["src"]
|
"include": ["src"],
|
||||||
|
"exclude": ["src/**/*.test.ts", "src/**/*.test.tsx", "src/test"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
/// <reference types="vitest/config" />
|
||||||
|
import { defineConfig } from "vitest/config";
|
||||||
|
import react from "@vitejs/plugin-react";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
// Отдельный конфиг для тестов — без VitePWA-плагина (он не нужен в jsdom и
|
||||||
|
// только шумит). Алиас `@` и React-плагин обязательны для компонентных тестов.
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
resolve: {
|
||||||
|
alias: { "@": path.resolve(__dirname, "src") },
|
||||||
|
},
|
||||||
|
test: {
|
||||||
|
environment: "jsdom",
|
||||||
|
globals: true,
|
||||||
|
setupFiles: ["./src/test/setup.ts"],
|
||||||
|
css: false,
|
||||||
|
include: ["src/**/*.test.{ts,tsx}"],
|
||||||
|
},
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user