Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ab4e9e74e | ||
|
|
01c36ce935 | ||
|
|
0ec8f0b540 | ||
|
|
bd1a4a31bd | ||
|
|
b419a456fe | ||
|
|
08ebc09814 | ||
|
|
e5a2874ba7 | ||
|
|
adad929769 | ||
|
|
479b9699ea | ||
|
|
b7dc826f0f | ||
|
|
15d7f34689 | ||
|
|
0fba967cd8 | ||
|
|
66ef403bc0 | ||
|
|
0a164634f8 | ||
|
|
372dc0ede7 | ||
|
|
d769845d88 | ||
|
|
6f76809e9e | ||
|
|
9a116ad94e | ||
|
|
f74f3688ae | ||
|
|
a7032692f1 | ||
|
|
34d3554f72 | ||
|
|
19b91d65c8 | ||
|
|
54ba4edb94 | ||
|
|
19dc1b31a6 | ||
|
|
cc76cc5698 | ||
|
|
100a29f8c7 | ||
|
|
f7ccc7ce77 | ||
|
|
416ea3391b | ||
|
|
b2969f36c3 | ||
|
|
fab8b4496b | ||
|
|
8c9caedb03 | ||
|
|
d0ebd9ddf5 | ||
|
|
7e6817b3ff | ||
|
|
3d875642f8 | ||
|
|
10492e52a4 | ||
|
|
fd0ec64da9 | ||
|
|
3b7b2ae56d | ||
|
|
205078c5ce | ||
|
|
8eac0b74fc | ||
|
|
9642eb6e45 | ||
|
|
087693877d | ||
|
|
85f3a5c682 | ||
|
|
a5bd7308b5 | ||
|
|
9b4aa504ec | ||
|
|
9b991a244b | ||
|
|
ed16b89353 | ||
|
|
4c03f17448 | ||
|
|
98806d1e92 | ||
|
|
577ec37a2f | ||
|
|
71783f3724 | ||
|
|
d208838bb3 | ||
|
|
c7c989d886 | ||
|
|
b4e0dd6d65 | ||
|
|
7e2cf0c9c8 | ||
|
|
e0083b894f | ||
|
|
abdf0a2dea | ||
|
|
56f1a2774b | ||
|
|
924dd7966a | ||
|
|
102a2525db | ||
|
|
8893710254 | ||
|
|
ab9ddf7289 | ||
|
|
bd7665fb1d | ||
|
|
df709c58e5 | ||
|
|
3c6dacb29b | ||
|
|
7775e74108 | ||
|
|
da0436cee8 |
@@ -38,3 +38,4 @@ Thumbs.db
|
|||||||
# IDE
|
# IDE
|
||||||
.idea/
|
.idea/
|
||||||
.vscode/
|
.vscode/
|
||||||
|
.superpowers/
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ mechanic-pwa/ ← корень git репо
|
|||||||
└── README.md
|
└── README.md
|
||||||
```
|
```
|
||||||
|
|
||||||
> **Внимание:** backend-модуль `mechanic` (Phase B-F плана) живёт **не в этом репо**, а в виде ветки `feat/mechanic-mvp` внутри репозитория `taxi-dashboard` (Premium CRM). Этот репо — только frontend + специфика, документация и ops.
|
> **Внимание:** backend-модуль `mechanic` (Phase B-F плана) живёт **не в этом репо**, а в виде ветки `feat/mechanic-mvp` внутри репозитория [`premium-crm`](http://100.64.0.9:3001/tremble7681/premium-crm). Этот репо — только frontend + специфика, документация и ops.
|
||||||
|
|
||||||
## Текущая фаза
|
## Текущая фаза
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,30 @@
|
|||||||
# Premium Mechanic PWA — Implementation State
|
# Premium Mechanic PWA — Implementation State
|
||||||
|
|
||||||
> Last updated: 2026-05-17 (Phase 1 MVP code-complete, awaiting production deploy)
|
> Last updated: 2026-05-17 (Phase 1 MVP LIVE IN PRODUCTION)
|
||||||
|
|
||||||
## Status: **READY TO DEPLOY** (Phase J prep done, awaiting explicit user OK)
|
## Status: 🟢 **DEPLOYED — Phase 1 MVP LIVE on https://mechanic.pptaxi.ru**
|
||||||
|
|
||||||
Backend (Phases B-F) and Frontend (Phases G-I) are feature-complete and pushed to Gitea. Deployment is the only step left — it requires SSH into `root@100.64.0.12` (prod VDS), Docker compose restart, and Caddy reload. **Not executed automatically.** See "Deployment runbook" section below for the exact steps.
|
All 4 deployment phases executed successfully:
|
||||||
|
|
||||||
|
- ✅ **J1 Backend**: `git push vds feat/mechanic-mvp` → checkout on VDS → `docker build` → rolling restart blue+green → healthz 5/5 green on `https://crm.pptaxi.ru/api/v1/mechanic/healthz`
|
||||||
|
- ✅ **J2 Frontend**: `scp dist/` → VDS at `/opt/sites/mechanic-pwa/dist/` (448K) → added Caddy block + bind mount → `docker compose up -d --force-recreate caddy` → Let's Encrypt cert auto-issued → HTTPS 200 on `https://mechanic.pptaxi.ru/`
|
||||||
|
- ✅ **J3a Merge**: `feat/mechanic-mvp` → `main` (ff-only) in BOTH repos, pushed to Gitea + VDS
|
||||||
|
- ✅ **J3b Prod sync**: VDS now on `main` branch, healthz still green
|
||||||
|
|
||||||
|
**Smoke checks passed:**
|
||||||
|
| Check | Result |
|
||||||
|
|---|---|
|
||||||
|
| `GET https://mechanic.pptaxi.ru/` | 200 OK, text/html, served from SPA |
|
||||||
|
| `GET /manifest.webmanifest` | JSON with `"name": "Premium Механик"` |
|
||||||
|
| `GET /api/v1/mechanic/healthz` (via mechanic.pptaxi.ru) | `{"status":"ok"}` |
|
||||||
|
| `GET /api/v1/mechanic/me` (no auth) | 401 |
|
||||||
|
| `GET /api/v1/mechanic/vehicles` (no auth) | 401 |
|
||||||
|
| `GET /icons/icon-192.png` | 200 image/png, 2326 bytes |
|
||||||
|
| `GET /sw.js` (service worker) | 200 text/javascript |
|
||||||
|
| `GET /vehicles/12345` (SPA route) | 200 text/html (index.html fallback) |
|
||||||
|
| `crm.pptaxi.ru/api/v1/mechanic/healthz` x5 | 5/5 ok (both blue+green serving) |
|
||||||
|
|
||||||
|
**Remaining manual smoke (mobile, J3 step 8):** open `https://mechanic.pptaxi.ru` on Android Chrome / iOS Safari, login with test mechanic account, create inspection, snap photo, verify MinIO upload + thumbnail appears, verify "Add to Home Screen" works. *Not automated — you'll do that on a phone.*
|
||||||
|
|
||||||
## What is done
|
## What is done
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
# Премиум Водитель — PWA (дизайн)
|
||||||
|
|
||||||
|
**Дата:** 2026-06-18
|
||||||
|
**Статус:** дизайн согласован (брейншторм + визуальный компаньон). Код не начат.
|
||||||
|
**Цель:** PWA-приложение водителя «Премиум Водитель» — вход по телефону (код через TG/MAX), просмотр баланса (счета из CRM-леджера), пополнение через Т-Банк (СБП/карта), история пополнений. Поверхность для уже построенного бэкенда (Фаза 1 платежей + авторизация водителя в `crm2/app/modules/payments`).
|
||||||
|
|
||||||
|
## Размещение и стек
|
||||||
|
- Новый PWA — **сиблинг** `PremiumDriverApp/driver-pwa/frontend/` (рядом с `mechanic-pwa/`), на том же стеке: **React + Vite + vite-plugin-pwa + TypeScript + Tailwind + @tanstack/react-query + ky + zod + react-router-dom + react-hook-form + zustand + sonner (тосты) + lucide-react + vitest**. Структура `src/{api,components,pages,hooks,lib,store}` как у mechanic-pwa.
|
||||||
|
- Хостинг: **app.pptaxi.ru** (статика + Caddy; деплой как у mechanic — build → dist → tar/rsync, см. mechanic deploy flow).
|
||||||
|
- Имя приложения (везде в UI, манифест PWA, заголовок): **«Премиум Водитель»**.
|
||||||
|
|
||||||
|
## Визуальный язык — Cream Minimal
|
||||||
|
- Палитра (без жёлтого): фон `#F3EEE3` (cream), карточка/поверхность `#FBF8F1`, линия-разделитель `#E4DCCB`, чернила `#1C1B19`, вторичный текст `#7C7361`/opacity. Кнопки primary — тёмные `#1C1B19` с текстом `#F3EEE3`. Долг (минус) `#C0493A`, плюс/депозит `#3B6E4A`.
|
||||||
|
- Типографика: **Inter** (один шрифт), без эмодзи. Иконки — lucide (тонкие, монохром).
|
||||||
|
- Скругления 12–16px, тонкие 1px-границы, мягкие тени минимально. Крупные тап-таргеты (мобайл-фёрст). App-like / edit-first: минимум лишних кнопок, экран сам реагирует.
|
||||||
|
|
||||||
|
## Экраны (MVP)
|
||||||
|
1. **Вход.**
|
||||||
|
- Шаг 1: поле телефона `+7 ___ ___-__-__` → «Получить код». → `POST /api/driver/auth/request {phone}`.
|
||||||
|
- Если ответ `code_sent` → шаг 2: ввод кода (свой цифровой кейпад) → `POST /api/driver/auth/verify {phone, code}` → сохраняем driver JWT → на «Баланс».
|
||||||
|
- Если ответ `onboarding` → экран «Подключите бота»: две кнопки **Telegram** / **MAX** (открывают `deep_links.tg`/`.max`); подсказка «нажмите Старт у бота, затем вернитесь и запросите код снова». Кнопка «Я подключил — запросить код».
|
||||||
|
2. **Баланс** (компоновка B: hero + список).
|
||||||
|
- Шапка: «Премиум Водитель» + инициалы водителя.
|
||||||
|
- **Hero-блок «Общий долг»** — крупная сумма (сумма отрицательных счетов).
|
||||||
|
- **Список счетов** (bucket из `/api/driver/balance`): название + подпись (марка/госномер для аренды, «N неоплаченных» для штрафов) + значение (минус — красный, плюс — зелёный).
|
||||||
|
- Кнопка **«Пополнить»** (primary). Тап по счёту/кнопке → «Пополнение» с предвыбранным счётом.
|
||||||
|
- Внизу/в меню: «История», «Выйти».
|
||||||
|
3. **Пополнение** (компоновка C: свой кейпад).
|
||||||
|
- Заголовок «Пополнить · <счёт>». Крупная сумма. Строка «к оплате X ₽ (комиссия Y ₽)» — пересчёт на лету по ставке (получаем из ответа `/topup` или показываем оценку и уточняем).
|
||||||
|
- **Свой цифровой кейпад** (1–9, 0, ·, ⌫) — без системной клавиатуры; крупные клавиши. Быстрые суммы 500/1000/2000 (чипы).
|
||||||
|
- Сегмент **СБП / Картой**.
|
||||||
|
- Кнопка **«Оплатить»** → `POST /api/driver/topup {bucket, amount, method}` → получаем `{order_id, pay_url}`.
|
||||||
|
4. **Оплата / статус** (вариант A: авто-статус, без QR).
|
||||||
|
- Иконка «СБП», сумма к оплате, кнопка **«Оплатить через СБП»** (или «Оплатить картой») → открывает `pay_url` (СБП deep-link `qr.nspk.ru/...` → приложение банка; карта → форма `pay.tbank.ru`). **QR не показываем, «оплата с другого устройства» убрана** — водитель платит на том же телефоне через приложение банка.
|
||||||
|
- Под кнопкой — авто-статус «Ожидаем оплату…» (спиннер). Приложение **опрашивает статус** платежа; при `PAID` → экран **«Оплачено»** (зелёная галочка, «<счёт> пополнен на N ₽») → кнопка «На главную» (баланс перезапрашивается).
|
||||||
|
5. **История пополнений.**
|
||||||
|
- Список из `driver_payments` водителя: дата, счёт, сумма, статус (Оплачено/Ожидает/Отклонён), способ. Пусто → «Пока нет пополнений».
|
||||||
|
6. **Выход** — очистка JWT, возврат на «Вход».
|
||||||
|
|
||||||
|
## Поток данных / API (crm2 BFF, префикс `/api`)
|
||||||
|
Готово (Фаза 1 + авторизация):
|
||||||
|
- `POST /driver/auth/request {phone}` → `{status:"code_sent",channel}` | `{status:"onboarding",deep_links:{tg,max}}`
|
||||||
|
- `POST /driver/auth/verify {phone, code}` → `{token, driver_id}`
|
||||||
|
- `GET /driver/balance` (Bearer) → `{accounts:[{bucket, balance}]}`
|
||||||
|
- `POST /driver/topup {bucket, amount, method}` (Bearer) → `{order_id, pay_url, commission, total}`
|
||||||
|
|
||||||
|
**Нужно добавить на бэкенде (зависимость этого PWA — отдельные backend-задачи):**
|
||||||
|
- `GET /driver/payments` (Bearer) → история пополнений водителя (из `driver_payments`: order_id, bucket, amount, commission, method, status, created_at, paid_at).
|
||||||
|
- `GET /driver/payment/{order_id}` (Bearer) → `{status}` для авто-опроса статуса оплаты (NEW/FORM/PAID/REJECTED). (Альтернатива: опрашивать `/driver/balance` и сравнивать — но явный статус надёжнее и показывает «Оплачено».)
|
||||||
|
- (Опц.) В `/driver/topup` вернуть и `commission_rate`, чтобы кейпад считал «к оплате» локально до запроса.
|
||||||
|
|
||||||
|
## Сессия / клиент
|
||||||
|
- driver JWT (typ='driver', 30 дн) хранится в `localStorage`; `ky`-инстанс добавляет `Authorization: Bearer`. На 401 → разлогин (на «Вход»).
|
||||||
|
- `@tanstack/react-query` для balance/history (кэш + рефетч); `zod` валидирует ответы; `zustand` — сессия (token, driver_id). Тосты ошибок — `sonner`.
|
||||||
|
- База API из env (`VITE_API_BASE`, по умолчанию `https://crm.pptaxi.ru/api`). CORS: бэкенд должен разрешить origin `https://app.pptaxi.ru` для `/api/driver/*` (backend-задача).
|
||||||
|
|
||||||
|
## PWA
|
||||||
|
- `vite-plugin-pwa`: manifest (name «Премиум Водитель», cream theme `#F3EEE3`, иконки 192/512, standalone, портрет), service worker (precache оболочки, network-first для API). Устанавливается на телефон без сторов (по ссылке app.pptaxi.ru → «На экран Домой»).
|
||||||
|
|
||||||
|
## Обработка ошибок
|
||||||
|
- Телефон не найден (404) → «Номер не найден. Обратитесь в парк.» Неверный код (401) → «Неверный или просроченный код» + повтор. Платёж не создан → тост + остаёмся на «Пополнении». Авто-опрос: таймаут N минут → «Не дождались оплаты» + кнопка «Проверить ещё раз»/«Вернуться».
|
||||||
|
|
||||||
|
## Тестирование
|
||||||
|
- vitest + @testing-library/react: рендер экранов, кейпад (ввод/⌫/быстрые суммы, пересчёт «к оплате»), форма телефона/кода, маппинг ответов API (zod-схемы), guard приватных роутов (нет токена → «Вход»), авто-статус (мок таймера/опроса → success). API мокается (msw или ky-mock), без сети.
|
||||||
|
|
||||||
|
## Скоуп / порядок
|
||||||
|
MVP-экраны: Вход (+онбординг) · Баланс · Пополнение · Оплата/статус · История · Выход. **Вне MVP:** push-уведомления, вывод средств, профиль/настройки, мультиязычность.
|
||||||
|
Порядок сборки (для плана): каркас приложения+PWA+API-клиент+сессия → Вход/онбординг → Баланс → Пополнение(кейпад) → Оплата/авто-статус → История → деплой app.pptaxi.ru. Бэкенд-зависимости (`/driver/payments`, `/driver/payment/{order_id}`, CORS) — отдельные мелкие задачи в crm2 (сделать до/параллельно соответствующим экранам).
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
VITE_API_BASE=https://crm.pptaxi.ru/api
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
*.tsbuildinfo
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||||
|
<meta name="theme-color" content="#F3EEE3" />
|
||||||
|
<link rel="manifest" href="/manifest.webmanifest" />
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet" />
|
||||||
|
<title>Премиум Водитель</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
{
|
||||||
|
"name": "driver-pwa",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.1.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc -b && vite build",
|
||||||
|
"preview": "vite preview",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"test": "vitest run",
|
||||||
|
"test:watch": "vitest"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@tanstack/react-query": "^5.51.0",
|
||||||
|
"ky": "^1.7.2",
|
||||||
|
"lucide-react": "^0.454.0",
|
||||||
|
"react": "^18.3.1",
|
||||||
|
"react-dom": "^18.3.1",
|
||||||
|
"react-router-dom": "^6.26.0",
|
||||||
|
"sonner": "^1.5.0",
|
||||||
|
"zod": "^3.23.8",
|
||||||
|
"zustand": "^4.5.5"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@testing-library/jest-dom": "^6.5.0",
|
||||||
|
"@testing-library/react": "^16.0.1",
|
||||||
|
"@testing-library/user-event": "^14.5.2",
|
||||||
|
"@types/node": "^22.5.0",
|
||||||
|
"@types/react": "^18.3.5",
|
||||||
|
"@types/react-dom": "^18.3.0",
|
||||||
|
"@vitejs/plugin-react": "^4.3.1",
|
||||||
|
"autoprefixer": "^10.4.20",
|
||||||
|
"jsdom": "^25.0.0",
|
||||||
|
"postcss": "^8.4.45",
|
||||||
|
"tailwindcss": "^3.4.10",
|
||||||
|
"typescript": "^5.5.4",
|
||||||
|
"vite": "^5.4.2",
|
||||||
|
"vite-plugin-pwa": "^0.20.5",
|
||||||
|
"vitest": "^2.0.5"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export default { plugins: { tailwindcss: {}, autoprefixer: {} } };
|
||||||
|
After Width: | Height: | Size: 909 B |
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"name": "Премиум Водитель",
|
||||||
|
"short_name": "Премиум",
|
||||||
|
"start_url": "/",
|
||||||
|
"display": "standalone",
|
||||||
|
"orientation": "portrait",
|
||||||
|
"background_color": "#F3EEE3",
|
||||||
|
"theme_color": "#F3EEE3",
|
||||||
|
"icons": [
|
||||||
|
{ "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
|
||||||
|
{ "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" }
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
// Генерация PWA-иконок «Премиум Водитель» без сторонних либ (zlib PNG-энкодер).
|
||||||
|
// Дизайн: кремовый фон #F3EEE3, тёмная скруглённая плитка #1C1B19,
|
||||||
|
// внутри белая «карта» #F6F2E9 с тёмной полосой (финансовый мотив). Без жёлтого/текста.
|
||||||
|
import zlib from "node:zlib";
|
||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
const CREAM = [243, 238, 227];
|
||||||
|
const INK = [28, 27, 25];
|
||||||
|
const CARD = [246, 242, 233];
|
||||||
|
|
||||||
|
function crc32(buf) {
|
||||||
|
let c = ~0;
|
||||||
|
for (let i = 0; i < buf.length; i++) {
|
||||||
|
c ^= buf[i];
|
||||||
|
for (let k = 0; k < 8; k++) c = (c >>> 1) ^ (0xedb88320 & -(c & 1));
|
||||||
|
}
|
||||||
|
return (~c) >>> 0;
|
||||||
|
}
|
||||||
|
function chunk(type, data) {
|
||||||
|
const t = Buffer.from(type, "ascii");
|
||||||
|
const len = Buffer.alloc(4); len.writeUInt32BE(data.length, 0);
|
||||||
|
const body = Buffer.concat([t, data]);
|
||||||
|
const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(body), 0);
|
||||||
|
return Buffer.concat([len, body, crc]);
|
||||||
|
}
|
||||||
|
function encodePng(N, rgba) {
|
||||||
|
const sig = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
||||||
|
const ihdr = Buffer.alloc(13);
|
||||||
|
ihdr.writeUInt32BE(N, 0); ihdr.writeUInt32BE(N, 4); ihdr[8] = 8; ihdr[9] = 6;
|
||||||
|
const stride = N * 4;
|
||||||
|
const raw = Buffer.alloc(N * (stride + 1));
|
||||||
|
for (let y = 0; y < N; y++) {
|
||||||
|
raw[y * (stride + 1)] = 0;
|
||||||
|
rgba.copy(raw, y * (stride + 1) + 1, y * stride, y * stride + stride);
|
||||||
|
}
|
||||||
|
return Buffer.concat([sig, chunk("IHDR", ihdr), chunk("IDAT", zlib.deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]);
|
||||||
|
}
|
||||||
|
function inRoundRect(px, py, x0, y0, x1, y1, r) {
|
||||||
|
if (px < x0 || px >= x1 || py < y0 || py >= y1) return false;
|
||||||
|
const cx = px < x0 + r ? x0 + r : px >= x1 - r ? x1 - r : px;
|
||||||
|
const cy = py < y0 + r ? y0 + r : py >= y1 - r ? y1 - r : py;
|
||||||
|
const dx = px - cx, dy = py - cy;
|
||||||
|
return dx * dx + dy * dy <= r * r;
|
||||||
|
}
|
||||||
|
|
||||||
|
function draw(N) {
|
||||||
|
const buf = Buffer.alloc(N * N * 4);
|
||||||
|
// tile (centered ~64%)
|
||||||
|
const tile = Math.round(N * 0.64), tx0 = Math.round((N - tile) / 2), ty0 = tx0;
|
||||||
|
const tx1 = tx0 + tile, ty1 = ty0 + tile, tr = Math.round(tile * 0.24);
|
||||||
|
// card inside tile
|
||||||
|
const cw = Math.round(tile * 0.62), ch = Math.round(tile * 0.42);
|
||||||
|
const cx0 = Math.round((N - cw) / 2), cy0 = Math.round((N - ch) / 2);
|
||||||
|
const cx1 = cx0 + cw, cy1 = cy0 + ch, cr = Math.round(ch * 0.18);
|
||||||
|
// stripe near top of card
|
||||||
|
const sy0 = cy0 + Math.round(ch * 0.22), sy1 = sy0 + Math.round(ch * 0.14);
|
||||||
|
for (let y = 0; y < N; y++) {
|
||||||
|
for (let x = 0; x < N; x++) {
|
||||||
|
let col = CREAM;
|
||||||
|
if (inRoundRect(x, y, tx0, ty0, tx1, ty1, tr)) col = INK;
|
||||||
|
if (inRoundRect(x, y, cx0, cy0, cx1, cy1, cr)) col = CARD;
|
||||||
|
if (x >= cx0 && x < cx1 && y >= sy0 && y < sy1) col = INK;
|
||||||
|
const o = (y * N + x) * 4;
|
||||||
|
buf[o] = col[0]; buf[o + 1] = col[1]; buf[o + 2] = col[2]; buf[o + 3] = 255;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return encodePng(N, buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
const dir = path.resolve("public/icons");
|
||||||
|
fs.mkdirSync(dir, { recursive: true });
|
||||||
|
for (const N of [192, 512]) {
|
||||||
|
fs.writeFileSync(path.join(dir, `icon-${N}.png`), draw(N));
|
||||||
|
console.log(`wrote icon-${N}.png`);
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { describe, it, expect, beforeEach } from "vitest";
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import { MemoryRouter } from "react-router-dom";
|
||||||
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import App from "./App";
|
||||||
|
import { useAuth } from "@/store/auth";
|
||||||
|
|
||||||
|
function renderAt(path: string) {
|
||||||
|
const qc = new QueryClient();
|
||||||
|
return render(
|
||||||
|
<QueryClientProvider client={qc}>
|
||||||
|
<MemoryRouter initialEntries={[path]}>
|
||||||
|
<App />
|
||||||
|
</MemoryRouter>
|
||||||
|
</QueryClientProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("routing guard", () => {
|
||||||
|
beforeEach(() => useAuth.getState().clear());
|
||||||
|
it("redirects to login when no token", () => {
|
||||||
|
renderAt("/");
|
||||||
|
expect(screen.getByText(/Вход в приложение/i)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { Navigate, Route, Routes } from "react-router-dom";
|
||||||
|
import { useAuth } from "@/store/auth";
|
||||||
|
import { LoginPage } from "@/pages/LoginPage";
|
||||||
|
import { TgWaitPage } from "@/pages/TgWaitPage";
|
||||||
|
import { OnboardingPage } from "@/pages/OnboardingPage";
|
||||||
|
import { BalancePage } from "@/pages/BalancePage";
|
||||||
|
import { TopupPage } from "@/pages/TopupPage";
|
||||||
|
import { PaymentPage } from "@/pages/PaymentPage";
|
||||||
|
import { HistoryPage } from "@/pages/HistoryPage";
|
||||||
|
|
||||||
|
function RequireAuth({ children }: { children: ReactNode }) {
|
||||||
|
const token = useAuth((s) => s.token);
|
||||||
|
return token ? <>{children}</> : <Navigate to="/login" replace />;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function App() {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-md min-h-full px-4 pt-3 pb-8">
|
||||||
|
<Routes>
|
||||||
|
<Route path="/login" element={<LoginPage />} />
|
||||||
|
<Route path="/tg-wait" element={<TgWaitPage />} />
|
||||||
|
<Route path="/onboarding" element={<OnboardingPage />} />
|
||||||
|
<Route path="/" element={<RequireAuth><BalancePage /></RequireAuth>} />
|
||||||
|
<Route path="/topup" element={<RequireAuth><TopupPage /></RequireAuth>} />
|
||||||
|
<Route path="/pay/:orderId" element={<RequireAuth><PaymentPage /></RequireAuth>} />
|
||||||
|
<Route path="/history" element={<RequireAuth><HistoryPage /></RequireAuth>} />
|
||||||
|
<Route path="*" element={<Navigate to="/" replace />} />
|
||||||
|
</Routes>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import ky, { type KyInstance } from "ky";
|
||||||
|
import { useAuth } from "@/store/auth";
|
||||||
|
|
||||||
|
const API_BASE = import.meta.env.VITE_API_BASE ?? "https://crm.pptaxi.ru/api";
|
||||||
|
|
||||||
|
export const api: KyInstance = ky.create({
|
||||||
|
prefixUrl: API_BASE,
|
||||||
|
timeout: 30_000,
|
||||||
|
retry: { limit: 2, methods: ["get"] },
|
||||||
|
hooks: {
|
||||||
|
beforeRequest: [
|
||||||
|
(request) => {
|
||||||
|
const token = useAuth.getState().token;
|
||||||
|
if (token) request.headers.set("Authorization", `Bearer ${token}`);
|
||||||
|
},
|
||||||
|
],
|
||||||
|
beforeError: [
|
||||||
|
(error) => {
|
||||||
|
if (error.response?.status === 401) useAuth.getState().clear();
|
||||||
|
return error;
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { BalanceSchema, TopupSchema, PaymentsSchema, AuthRequestSchema, TgSessionSchema, TgPollSchema } from "./driver";
|
||||||
|
|
||||||
|
describe("driver api schemas", () => {
|
||||||
|
it("parses balance", () => {
|
||||||
|
const v = BalanceSchema.parse({ accounts: [{ bucket: "Долг аренда", balance: -3200 }] });
|
||||||
|
expect(v.accounts[0].bucket).toBe("Долг аренда");
|
||||||
|
});
|
||||||
|
it("parses topup", () => {
|
||||||
|
const v = TopupSchema.parse({ order_id: "o1", pay_url: "https://x", commission: 52, total: 1052 });
|
||||||
|
expect(v.pay_url).toBe("https://x");
|
||||||
|
});
|
||||||
|
it("parses auth request onboarding + code_sent", () => {
|
||||||
|
expect(AuthRequestSchema.parse({ status: "code_sent", channel: "tg" }).status).toBe("code_sent");
|
||||||
|
const o = AuthRequestSchema.parse({ status: "onboarding", deep_links: { tg: "t", max: "m" } });
|
||||||
|
expect(o.status === "onboarding" && o.deep_links.tg).toBe("t");
|
||||||
|
// prod: MAX bot not configured → backend omits `max`, must still parse (regression guard)
|
||||||
|
const tgOnly = AuthRequestSchema.parse({ status: "onboarding", deep_links: { tg: "t" } });
|
||||||
|
expect(tgOnly.status === "onboarding" && tgOnly.deep_links.tg).toBe("t");
|
||||||
|
});
|
||||||
|
it("parses payments history", () => {
|
||||||
|
const v = PaymentsSchema.parse({ payments: [{ order_id: "o1", bucket: "b", amount: 100,
|
||||||
|
commission: 5.2, method: "qr", status: "PAID", created_at: "2026-06-18T09:00:00Z", paid_at: null }] });
|
||||||
|
expect(v.payments[0].status).toBe("PAID");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("tg verified-login schemas", () => {
|
||||||
|
it("parses tg session", () => {
|
||||||
|
const v = TgSessionSchema.parse({ pair_session: "S", deep_link: "https://t.me/x?start=S" });
|
||||||
|
expect(v.pair_session).toBe("S");
|
||||||
|
});
|
||||||
|
it("parses tg poll states", () => {
|
||||||
|
expect(TgPollSchema.parse({ status: "pending" }).status).toBe("pending");
|
||||||
|
expect(TgPollSchema.parse({ status: "expired" }).status).toBe("expired");
|
||||||
|
const a = TgPollSchema.parse({ status: "authenticated", token: "T", driver_id: 7 });
|
||||||
|
expect(a.status === "authenticated" && a.token).toBe("T");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
import { api } from "./client";
|
||||||
|
|
||||||
|
export const AuthRequestSchema = z.union([
|
||||||
|
z.object({ status: z.literal("code_sent"), channel: z.string() }),
|
||||||
|
z.object({ status: z.literal("onboarding"), deep_links: z.object({ tg: z.string().optional(), max: z.string().optional() }) }),
|
||||||
|
]);
|
||||||
|
export type AuthRequest = z.infer<typeof AuthRequestSchema>;
|
||||||
|
|
||||||
|
export const VerifySchema = z.object({ token: z.string(), driver_id: z.number() });
|
||||||
|
export const BalanceSchema = z.object({
|
||||||
|
accounts: z.array(z.object({ bucket: z.string(), balance: z.number() })),
|
||||||
|
});
|
||||||
|
export const TopupSchema = z.object({
|
||||||
|
order_id: z.string(), pay_url: z.string(), commission: z.number(), total: z.number(),
|
||||||
|
});
|
||||||
|
export const PaymentStateSchema = z.object({ order_id: z.string(), status: z.string() });
|
||||||
|
export const CommissionSchema = z.object({ rate: z.number() });
|
||||||
|
export const PaymentsSchema = z.object({
|
||||||
|
payments: z.array(z.object({
|
||||||
|
order_id: z.string(), bucket: z.string(), amount: z.number(), commission: z.number(),
|
||||||
|
method: z.string(), status: z.string(),
|
||||||
|
created_at: z.string().nullable(), paid_at: z.string().nullable(),
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const TgSessionSchema = z.object({
|
||||||
|
pair_session: z.string(),
|
||||||
|
deep_link: z.string().nullable(),
|
||||||
|
});
|
||||||
|
export const TgPollSchema = z.union([
|
||||||
|
z.object({ status: z.literal("pending") }),
|
||||||
|
z.object({ status: z.literal("expired") }),
|
||||||
|
z.object({ status: z.literal("authenticated"), token: z.string(), driver_id: z.number() }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const tgSession = async () =>
|
||||||
|
TgSessionSchema.parse(await api.post("driver/auth/tg/session").json());
|
||||||
|
export const tgPoll = async (pairSession: string) =>
|
||||||
|
TgPollSchema.parse(await api.get("driver/auth/tg/poll", { searchParams: { pair_session: pairSession } }).json());
|
||||||
|
|
||||||
|
export const authRequest = async (phone: string) =>
|
||||||
|
AuthRequestSchema.parse(await api.post("driver/auth/request", { json: { phone } }).json());
|
||||||
|
export const authVerify = async (phone: string, code: string) =>
|
||||||
|
VerifySchema.parse(await api.post("driver/auth/verify", { json: { phone, code } }).json());
|
||||||
|
export const getBalance = async () =>
|
||||||
|
BalanceSchema.parse(await api.get("driver/balance").json());
|
||||||
|
export const topup = async (bucket: string, amount: number, method: "qr" | "card") =>
|
||||||
|
TopupSchema.parse(await api.post("driver/topup", { json: { bucket, amount, method } }).json());
|
||||||
|
export const getPaymentState = async (orderId: string) =>
|
||||||
|
PaymentStateSchema.parse(await api.get(`driver/payment/${orderId}`).json());
|
||||||
|
export const getPayments = async () =>
|
||||||
|
PaymentsSchema.parse(await api.get("driver/payments").json());
|
||||||
|
export const getCommission = async () =>
|
||||||
|
CommissionSchema.parse(await api.get("driver/commission").json());
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
export function AppHeader() {
|
||||||
|
return (
|
||||||
|
<header className="mb-4">
|
||||||
|
<span className="text-sm font-bold">Премиум Водитель</span>
|
||||||
|
</header>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
interface Props { value: string; options: { value: string; label: string }[]; onChange: (v: string) => void; }
|
||||||
|
export function Segment({ value, options, onChange }: Props) {
|
||||||
|
return (
|
||||||
|
<div className="flex gap-1.5">
|
||||||
|
{options.map((o) => (
|
||||||
|
<button
|
||||||
|
key={o.value}
|
||||||
|
type="button"
|
||||||
|
onClick={() => onChange(o.value)}
|
||||||
|
className={`flex-1 py-2.5 rounded-xl2 text-xs border ${
|
||||||
|
value === o.value ? "bg-ink text-cream border-ink font-bold" : "bg-surface border-line text-muted"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{o.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export function Spinner() {
|
||||||
|
return <span className="inline-block w-3.5 h-3.5 border-2 border-line border-t-ink rounded-full animate-spin" />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
// src/hooks/usePairPoll.test.tsx
|
||||||
|
import { renderHook, waitFor } from "@testing-library/react";
|
||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
|
import { usePairPoll } from "./usePairPoll";
|
||||||
|
import * as driver from "@/api/driver";
|
||||||
|
import { useAuth } from "@/store/auth";
|
||||||
|
|
||||||
|
beforeEach(() => { useAuth.getState().clear(); vi.restoreAllMocks(); });
|
||||||
|
|
||||||
|
describe("usePairPoll", () => {
|
||||||
|
it("sets session on authenticated", async () => {
|
||||||
|
vi.spyOn(driver, "tgPoll").mockResolvedValue({ status: "authenticated", token: "T", driver_id: 7 } as any);
|
||||||
|
const { result } = renderHook(() => usePairPoll("SESS"));
|
||||||
|
await waitFor(() => expect(result.current.status).toBe("authenticated"));
|
||||||
|
expect(useAuth.getState().token).toBe("T");
|
||||||
|
expect(useAuth.getState().driverId).toBe(7);
|
||||||
|
});
|
||||||
|
it("stays pending then expired", async () => {
|
||||||
|
vi.spyOn(driver, "tgPoll").mockResolvedValue({ status: "expired" } as any);
|
||||||
|
const { result } = renderHook(() => usePairPoll("SESS"));
|
||||||
|
await waitFor(() => expect(result.current.status).toBe("expired"));
|
||||||
|
});
|
||||||
|
it("does nothing when session is null", () => {
|
||||||
|
const spy = vi.spyOn(driver, "tgPoll");
|
||||||
|
const { result } = renderHook(() => usePairPoll(null));
|
||||||
|
expect(result.current.status).toBe("pending");
|
||||||
|
expect(spy).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
// src/hooks/usePairPoll.ts
|
||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import { tgPoll } from "@/api/driver";
|
||||||
|
import { useAuth } from "@/store/auth";
|
||||||
|
|
||||||
|
type Status = "pending" | "authenticated" | "expired";
|
||||||
|
const INTERVAL_MS = 2000;
|
||||||
|
const TIMEOUT_MS = 5 * 60 * 1000;
|
||||||
|
|
||||||
|
export function usePairPoll(pairSession: string | null): { status: Status } {
|
||||||
|
const [status, setStatus] = useState<Status>("pending");
|
||||||
|
const setSession = useAuth((s) => s.setSession);
|
||||||
|
const startedAt = useRef<number>(0);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!pairSession) return;
|
||||||
|
let alive = true;
|
||||||
|
let timer: ReturnType<typeof setTimeout>;
|
||||||
|
startedAt.current = Date.now();
|
||||||
|
|
||||||
|
const tick = async () => {
|
||||||
|
if (!alive) return;
|
||||||
|
try {
|
||||||
|
const r = await tgPoll(pairSession);
|
||||||
|
if (!alive) return;
|
||||||
|
if (r.status === "authenticated") {
|
||||||
|
setSession(r.token, r.driver_id);
|
||||||
|
setStatus("authenticated");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (r.status === "expired") { setStatus("expired"); return; }
|
||||||
|
} catch {
|
||||||
|
// transient — keep polling until timeout
|
||||||
|
}
|
||||||
|
if (Date.now() - startedAt.current > TIMEOUT_MS) { setStatus("expired"); return; }
|
||||||
|
timer = setTimeout(tick, INTERVAL_MS);
|
||||||
|
};
|
||||||
|
tick();
|
||||||
|
return () => { alive = false; clearTimeout(timer); };
|
||||||
|
}, [pairSession, setSession]);
|
||||||
|
|
||||||
|
return { status };
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { getPaymentState } from "@/api/driver";
|
||||||
|
|
||||||
|
const TERMINAL = new Set(["PAID", "CONFIRMED", "REJECTED", "REVERSED", "REFUNDED", "CANCELED", "AUTH_FAIL"]);
|
||||||
|
|
||||||
|
export function usePaymentStatus(orderId: string) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["payment", orderId],
|
||||||
|
queryFn: () => getPaymentState(orderId),
|
||||||
|
refetchInterval: (q) => (q.state.data && TERMINAL.has(q.state.data.status) ? false : 1500),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
@tailwind base;
|
||||||
|
@tailwind components;
|
||||||
|
@tailwind utilities;
|
||||||
|
|
||||||
|
html, body, #root { height: 100%; }
|
||||||
|
body { @apply bg-cream text-ink font-sans antialiased; margin: 0; }
|
||||||
|
button { font-family: inherit; }
|
||||||
|
|
||||||
|
@layer components {
|
||||||
|
.btn-primary { @apply bg-ink text-cream rounded-xl2 py-3.5 px-4 text-sm font-bold text-center w-full active:opacity-90 disabled:opacity-50; }
|
||||||
|
.btn-ghost { @apply border border-ink text-ink rounded-xl2 py-3 px-4 text-sm font-semibold text-center w-full; }
|
||||||
|
.card { @apply bg-surface border border-line rounded-2xl; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { keypadReduce, withCommission } from "./amount";
|
||||||
|
|
||||||
|
describe("amount keypad", () => {
|
||||||
|
it("appends digits, ignores leading zero, caps length", () => {
|
||||||
|
expect(keypadReduce("0", "5")).toBe("5");
|
||||||
|
expect(keypadReduce("100", "0")).toBe("1000");
|
||||||
|
expect(keypadReduce("", "0")).toBe("");
|
||||||
|
expect(keypadReduce("999999", "9")).toBe("999999");
|
||||||
|
});
|
||||||
|
it("backspace removes last digit", () => {
|
||||||
|
expect(keypadReduce("105", "back")).toBe("10");
|
||||||
|
expect(keypadReduce("", "back")).toBe("");
|
||||||
|
});
|
||||||
|
it("withCommission computes total at given rate", () => {
|
||||||
|
expect(withCommission(1000, 0.052)).toEqual({ commission: 52, total: 1052 });
|
||||||
|
expect(withCommission(333, 0.052)).toEqual({ commission: 17.32, total: 350.32 });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
const MAX_DIGITS = 6;
|
||||||
|
|
||||||
|
export function keypadReduce(current: string, key: string): string {
|
||||||
|
if (key === "back") return current.slice(0, -1);
|
||||||
|
if (!/^\d$/.test(key)) return current;
|
||||||
|
if (current === "0") return key === "0" ? "0" : key; // replace leading zero
|
||||||
|
if (current === "" && key === "0") return ""; // no leading zero from empty
|
||||||
|
if (current.length >= MAX_DIGITS) return current;
|
||||||
|
return current + key;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function withCommission(base: number, rate: number): { commission: number; total: number } {
|
||||||
|
const commission = Math.round(base * rate * 100) / 100;
|
||||||
|
const total = Math.round((base + commission) * 100) / 100;
|
||||||
|
return { commission, total };
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { formatMoney, formatPhone, digitsOnly } from "./format";
|
||||||
|
|
||||||
|
describe("format", () => {
|
||||||
|
it("formatMoney groups thousands and adds ₽", () => {
|
||||||
|
expect(formatMoney(1000)).toBe("1 000 ₽");
|
||||||
|
expect(formatMoney(-3200)).toBe("−3 200 ₽");
|
||||||
|
expect(formatMoney(0)).toBe("0 ₽");
|
||||||
|
});
|
||||||
|
it("digitsOnly strips non-digits", () => {
|
||||||
|
expect(digitsOnly("+7 (914) 305-44-00")).toBe("79143054400");
|
||||||
|
});
|
||||||
|
it("formatPhone renders +7 mask progressively", () => {
|
||||||
|
expect(formatPhone("9143054400")).toBe("+7 914 305-44-00");
|
||||||
|
expect(formatPhone("914305")).toBe("+7 914 305");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
export function digitsOnly(s: string): string {
|
||||||
|
return (s || "").replace(/\D/g, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatMoney(rub: number): string {
|
||||||
|
const neg = rub < 0;
|
||||||
|
const abs = Math.abs(Math.round(rub));
|
||||||
|
const grouped = abs.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
|
||||||
|
return `${neg ? "−" : ""}${grouped} ₽`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Render a Russian mobile from up-to-10 national digits as +7 914 305-44-00. */
|
||||||
|
export function formatPhone(national10: string): string {
|
||||||
|
const d = digitsOnly(national10).slice(0, 10);
|
||||||
|
const p: string[] = ["+7"];
|
||||||
|
if (d.length > 0) p.push(" " + d.slice(0, 3));
|
||||||
|
if (d.length > 3) p.push(" " + d.slice(3, 6));
|
||||||
|
if (d.length > 6) p.push("-" + d.slice(6, 8));
|
||||||
|
if (d.length > 8) p.push("-" + d.slice(8, 10));
|
||||||
|
return p.join("");
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import React from "react";
|
||||||
|
import ReactDOM from "react-dom/client";
|
||||||
|
import { BrowserRouter } from "react-router-dom";
|
||||||
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import { Toaster } from "sonner";
|
||||||
|
import App from "./App";
|
||||||
|
import "./index.css";
|
||||||
|
|
||||||
|
const queryClient = new QueryClient({
|
||||||
|
defaultOptions: { queries: { retry: 1, staleTime: 15_000 } },
|
||||||
|
});
|
||||||
|
|
||||||
|
ReactDOM.createRoot(document.getElementById("root")!).render(
|
||||||
|
<React.StrictMode>
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<BrowserRouter>
|
||||||
|
<App />
|
||||||
|
<Toaster richColors position="top-center" />
|
||||||
|
</BrowserRouter>
|
||||||
|
</QueryClientProvider>
|
||||||
|
</React.StrictMode>
|
||||||
|
);
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { describe, it, expect, vi } from "vitest";
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import { MemoryRouter } from "react-router-dom";
|
||||||
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
|
||||||
|
vi.mock("@/api/driver", () => ({
|
||||||
|
getBalance: vi.fn(async () => ({
|
||||||
|
accounts: [
|
||||||
|
{ bucket: "Долг аренда", balance: -3200 },
|
||||||
|
{ bucket: "Депозит", balance: 5000 },
|
||||||
|
],
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { BalancePage } from "./BalancePage";
|
||||||
|
|
||||||
|
function wrap() {
|
||||||
|
const qc = new QueryClient();
|
||||||
|
return render(
|
||||||
|
<QueryClientProvider client={qc}>
|
||||||
|
<MemoryRouter><BalancePage /></MemoryRouter>
|
||||||
|
</QueryClientProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("BalancePage", () => {
|
||||||
|
it("shows hero total (sum of negatives) and account rows", async () => {
|
||||||
|
wrap();
|
||||||
|
expect(await screen.findByText("Долг аренда")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Депозит")).toBeInTheDocument();
|
||||||
|
// Appears in both the hero total and the single debt account row.
|
||||||
|
expect(screen.getAllByText("−3 200 ₽").length).toBeGreaterThan(0);
|
||||||
|
expect(screen.getByRole("button", { name: /Пополнить/i })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows an error state when balance fails to load", async () => {
|
||||||
|
const driver = await import("@/api/driver");
|
||||||
|
(driver.getBalance as any).mockRejectedValueOnce(new Error("boom"));
|
||||||
|
// re-render fresh
|
||||||
|
const { QueryClient, QueryClientProvider } = await import("@tanstack/react-query");
|
||||||
|
const { MemoryRouter } = await import("react-router-dom");
|
||||||
|
const { render, screen } = await import("@testing-library/react");
|
||||||
|
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||||
|
render(<QueryClientProvider client={qc}><MemoryRouter><BalancePage /></MemoryRouter></QueryClientProvider>);
|
||||||
|
expect(await screen.findByText(/Не удалось загрузить/i)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import { History, LogOut } from "lucide-react";
|
||||||
|
import { getBalance } from "@/api/driver";
|
||||||
|
import { formatMoney } from "@/lib/format";
|
||||||
|
import { useAuth } from "@/store/auth";
|
||||||
|
import { AppHeader } from "@/components/AppHeader";
|
||||||
|
import { Spinner } from "@/components/Spinner";
|
||||||
|
|
||||||
|
export function BalancePage() {
|
||||||
|
const nav = useNavigate();
|
||||||
|
const clear = useAuth((s) => s.clear);
|
||||||
|
const { data, isLoading, isError, refetch } = useQuery({ queryKey: ["balance"], queryFn: getBalance });
|
||||||
|
|
||||||
|
const accounts = data?.accounts ?? [];
|
||||||
|
const totalDebt = accounts.filter((a) => a.balance < 0).reduce((s, a) => s + a.balance, 0);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<AppHeader />
|
||||||
|
<div className="card p-4 mb-4 text-center">
|
||||||
|
<p className="text-muted text-xs mb-1">Общий долг</p>
|
||||||
|
<p className={`text-2xl font-extrabold ${totalDebt < 0 ? "text-neg" : ""}`}>{formatMoney(totalDebt)}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="flex justify-center py-10"><Spinner /></div>
|
||||||
|
) : isError ? (
|
||||||
|
<div className="text-center py-8">
|
||||||
|
<p className="text-muted text-sm mb-3">Не удалось загрузить баланс</p>
|
||||||
|
<button className="btn-ghost" onClick={() => refetch()}>Повторить</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="mb-4">
|
||||||
|
{accounts.map((a) => (
|
||||||
|
<button
|
||||||
|
key={a.bucket}
|
||||||
|
onClick={() => nav("/topup", { state: { bucket: a.bucket } })}
|
||||||
|
className="w-full flex justify-between items-center py-3 border-b border-line last:border-0 text-left"
|
||||||
|
>
|
||||||
|
<span className="text-sm">{a.bucket}</span>
|
||||||
|
<b className={a.balance < 0 ? "text-neg" : "text-pos"}>{formatMoney(a.balance)}</b>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<button className="btn-primary" onClick={() => nav("/topup")}>Пополнить</button>
|
||||||
|
|
||||||
|
<div className="flex justify-center gap-6 mt-6 text-muted text-xs">
|
||||||
|
<button className="flex items-center gap-1.5" onClick={() => nav("/history")}>
|
||||||
|
<History size={15} /> История
|
||||||
|
</button>
|
||||||
|
<button className="flex items-center gap-1.5" onClick={() => { clear(); nav("/login"); }}>
|
||||||
|
<LogOut size={15} /> Выйти
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { describe, it, expect, vi } from "vitest";
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import { MemoryRouter } from "react-router-dom";
|
||||||
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
|
||||||
|
vi.mock("@/api/driver", () => ({
|
||||||
|
getPayments: vi.fn(async () => ({ payments: [
|
||||||
|
{ order_id: "o1", bucket: "Долг аренда", amount: 1000, commission: 52, method: "qr", status: "PAID", created_at: "2026-06-18T09:00:00Z", paid_at: "2026-06-18T09:01:00Z" },
|
||||||
|
] })),
|
||||||
|
}));
|
||||||
|
import { HistoryPage } from "./HistoryPage";
|
||||||
|
|
||||||
|
function wrap() {
|
||||||
|
const qc = new QueryClient();
|
||||||
|
return render(<QueryClientProvider client={qc}><MemoryRouter><HistoryPage /></MemoryRouter></QueryClientProvider>);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("HistoryPage", () => {
|
||||||
|
it("lists payments with amount + status", async () => {
|
||||||
|
wrap();
|
||||||
|
expect(await screen.findByText("Долг аренда")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("1 000 ₽")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/Оплачено/i)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import { getPayments } from "@/api/driver";
|
||||||
|
import { formatMoney } from "@/lib/format";
|
||||||
|
import { Spinner } from "@/components/Spinner";
|
||||||
|
|
||||||
|
const STATUS_RU: Record<string, string> = {
|
||||||
|
PAID: "Оплачено", NEW: "Ожидает", FORM: "Ожидает", CONFIRMED: "Оплачено", REJECTED: "Отклонён",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function HistoryPage() {
|
||||||
|
const nav = useNavigate();
|
||||||
|
const { data, isLoading, isError } = useQuery({ queryKey: ["payments"], queryFn: getPayments });
|
||||||
|
const rows = data?.payments ?? [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="pt-2">
|
||||||
|
<button className="text-muted text-xs mb-3" onClick={() => nav("/")}>‹ Назад</button>
|
||||||
|
<h1 className="text-lg font-extrabold mb-4">История пополнений</h1>
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="flex justify-center py-10"><Spinner /></div>
|
||||||
|
) : isError ? (
|
||||||
|
<p className="text-muted text-sm">Не удалось загрузить историю</p>
|
||||||
|
) : rows.length === 0 ? (
|
||||||
|
<p className="text-muted text-sm">Пока нет пополнений</p>
|
||||||
|
) : (
|
||||||
|
rows.map((p) => (
|
||||||
|
<div key={p.order_id} className="flex justify-between items-center py-3 border-b border-line">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm">{p.bucket}</p>
|
||||||
|
<p className="text-muted text-xs">
|
||||||
|
{p.created_at ? new Date(p.created_at).toLocaleDateString("ru-RU") : ""} · {STATUS_RU[p.status] ?? p.status}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<b>{formatMoney(p.amount)}</b>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
import { MemoryRouter } from "react-router-dom";
|
||||||
|
|
||||||
|
vi.mock("@/api/driver", () => ({
|
||||||
|
authRequest: vi.fn(async () => ({ status: "code_sent", channel: "tg" })),
|
||||||
|
authVerify: vi.fn(async () => ({ token: "T", driver_id: 7 })),
|
||||||
|
tgSession: vi.fn(async () => ({ pair_session: "sess123", deep_link: null })),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { LoginPage } from "./LoginPage";
|
||||||
|
import * as driver from "@/api/driver";
|
||||||
|
import { useAuth } from "@/store/auth";
|
||||||
|
|
||||||
|
const wrap = () => render(<MemoryRouter><LoginPage /></MemoryRouter>);
|
||||||
|
|
||||||
|
describe("LoginPage", () => {
|
||||||
|
beforeEach(() => useAuth.getState().clear());
|
||||||
|
it("requests code then verifies and stores session", async () => {
|
||||||
|
wrap();
|
||||||
|
expect(screen.getByText(/Вход в приложение/i)).toBeInTheDocument();
|
||||||
|
await userEvent.click(screen.getByRole("button", { name: /Войти по коду/i }));
|
||||||
|
await userEvent.type(screen.getByPlaceholderText(/телефон/i), "9143054400");
|
||||||
|
await userEvent.click(screen.getByRole("button", { name: /Получить код/i }));
|
||||||
|
expect(driver.authRequest).toHaveBeenCalledWith("79143054400");
|
||||||
|
const codeInput = await screen.findByPlaceholderText(/код/i);
|
||||||
|
await userEvent.type(codeInput, "123456");
|
||||||
|
await userEvent.click(screen.getByRole("button", { name: /Войти/i }));
|
||||||
|
expect(driver.authVerify).toHaveBeenCalledWith("79143054400", "123456");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { authRequest, authVerify, tgSession } from "@/api/driver";
|
||||||
|
import { digitsOnly, formatPhone } from "@/lib/format";
|
||||||
|
import { useAuth } from "@/store/auth";
|
||||||
|
import { Spinner } from "@/components/Spinner";
|
||||||
|
|
||||||
|
export function LoginPage() {
|
||||||
|
const nav = useNavigate();
|
||||||
|
const setSession = useAuth((s) => s.setSession);
|
||||||
|
const [phone, setPhone] = useState(""); // national 10 digits
|
||||||
|
const [code, setCode] = useState("");
|
||||||
|
const [step, setStep] = useState<"phone" | "code">("phone");
|
||||||
|
const [channel, setChannel] = useState<string>("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [mode, setMode] = useState<"choose" | "code">("choose");
|
||||||
|
const e164 = "7" + phone;
|
||||||
|
|
||||||
|
async function loginViaTelegram() {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const r = await tgSession();
|
||||||
|
sessionStorage.setItem("pp-pair-session", r.pair_session);
|
||||||
|
if (r.deep_link) { window.location.href = r.deep_link; }
|
||||||
|
nav("/tg-wait");
|
||||||
|
} catch {
|
||||||
|
toast.error("Не удалось начать вход. Попробуйте «по коду».");
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requestCode() {
|
||||||
|
if (phone.length < 10) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const r = await authRequest(e164);
|
||||||
|
if (r.status === "onboarding") {
|
||||||
|
sessionStorage.setItem("pp-onboarding", JSON.stringify({ ...r.deep_links, phone }));
|
||||||
|
nav("/onboarding");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setChannel(r.channel);
|
||||||
|
setStep("code");
|
||||||
|
} catch (err: unknown) {
|
||||||
|
const status = (err as { response?: { status?: number } })?.response?.status;
|
||||||
|
const msg =
|
||||||
|
status === 404 ? "Номер не найден. Обратитесь в парк." :
|
||||||
|
status === 429 ? "Слишком часто. Попробуйте позже." :
|
||||||
|
"Не удалось отправить код";
|
||||||
|
toast.error(msg);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function verify() {
|
||||||
|
if (code.length < 4) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const r = await authVerify(e164, code);
|
||||||
|
setSession(r.token, r.driver_id);
|
||||||
|
nav("/");
|
||||||
|
} catch {
|
||||||
|
toast.error("Неверный или просроченный код");
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="pt-16">
|
||||||
|
<h1 className="text-xl font-extrabold mb-1">Премиум Водитель</h1>
|
||||||
|
<p className="text-muted text-sm mb-8">Вход в приложение</p>
|
||||||
|
|
||||||
|
{mode === "choose" ? (
|
||||||
|
<>
|
||||||
|
<button className="btn-primary" disabled={busy} onClick={loginViaTelegram}>
|
||||||
|
{busy ? <Spinner /> : "Войти через Telegram"}
|
||||||
|
</button>
|
||||||
|
<p className="text-muted text-xs mt-3">Telegram подтвердит ваш номер автоматически.</p>
|
||||||
|
<button className="btn-ghost mt-4" onClick={() => setMode("code")}>Войти по коду</button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{step === "phone" ? (
|
||||||
|
<>
|
||||||
|
<input
|
||||||
|
inputMode="numeric"
|
||||||
|
placeholder="Номер телефона"
|
||||||
|
value={phone ? formatPhone(phone) : ""}
|
||||||
|
onChange={(e) => setPhone(digitsOnly(e.target.value).replace(/^7/, "").slice(0, 10))}
|
||||||
|
className="card w-full px-4 py-3 mb-3 text-base bg-white"
|
||||||
|
/>
|
||||||
|
<button className="btn-primary" disabled={busy || phone.length < 10} onClick={requestCode}>
|
||||||
|
{busy ? <Spinner /> : "Получить код"}
|
||||||
|
</button>
|
||||||
|
<p className="text-muted text-xs mt-3">Код придёт в Telegram или MAX.</p>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<p className="text-sm mb-2">Код отправлен в {channel === "max" ? "MAX" : "Telegram"}.</p>
|
||||||
|
<input
|
||||||
|
inputMode="numeric"
|
||||||
|
placeholder="Код из сообщения"
|
||||||
|
value={code}
|
||||||
|
onChange={(e) => setCode(digitsOnly(e.target.value).slice(0, 6))}
|
||||||
|
className="card w-full px-4 py-3 mb-3 text-base tracking-widest bg-white"
|
||||||
|
/>
|
||||||
|
<button className="btn-primary" disabled={busy || code.length < 4} onClick={verify}>
|
||||||
|
{busy ? <Spinner /> : "Войти"}
|
||||||
|
</button>
|
||||||
|
<button className="btn-ghost mt-2" onClick={() => setStep("phone")}>Изменить номер</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { describe, it, expect, beforeEach } from "vitest";
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import { MemoryRouter } from "react-router-dom";
|
||||||
|
import { OnboardingPage } from "./OnboardingPage";
|
||||||
|
|
||||||
|
describe("OnboardingPage", () => {
|
||||||
|
beforeEach(() =>
|
||||||
|
sessionStorage.setItem("pp-onboarding", JSON.stringify({ tg: "https://t.me/b?start=x", max: "https://max.ru/b?start=x", phone: "9143054400" }))
|
||||||
|
);
|
||||||
|
it("shows both bot links + back-to-code action", () => {
|
||||||
|
render(<MemoryRouter><OnboardingPage /></MemoryRouter>);
|
||||||
|
expect(screen.getByText(/Подключите бот/i)).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole("link", { name: /Telegram/i })).toHaveAttribute("href", "https://t.me/b?start=x");
|
||||||
|
expect(screen.getByRole("link", { name: /MAX/i })).toHaveAttribute("href", "https://max.ru/b?start=x");
|
||||||
|
expect(screen.getByRole("button", { name: /запросить код/i })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
it("renders only Telegram when max is absent", () => {
|
||||||
|
sessionStorage.setItem("pp-onboarding", JSON.stringify({ tg: "https://t.me/ppdriver_bot?start=x", phone: "9143054400" }));
|
||||||
|
render(<MemoryRouter><OnboardingPage /></MemoryRouter>);
|
||||||
|
expect(screen.getByRole("link", { name: /Telegram/i })).toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole("link", { name: /MAX/i })).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
|
||||||
|
export function OnboardingPage() {
|
||||||
|
const nav = useNavigate();
|
||||||
|
const raw = sessionStorage.getItem("pp-onboarding");
|
||||||
|
const data = raw ? (JSON.parse(raw) as { tg?: string; max?: string; phone: string }) : null;
|
||||||
|
if (!data) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="pt-16">
|
||||||
|
<h1 className="text-xl font-extrabold mb-1">Подключите бот</h1>
|
||||||
|
<p className="text-muted text-sm mb-8">
|
||||||
|
Чтобы получать код входа, откройте бот и нажмите «Старт». Затем вернитесь и запросите код снова.
|
||||||
|
</p>
|
||||||
|
{data.tg && (
|
||||||
|
<a href={data.tg} target="_blank" rel="noopener" className="btn-primary mb-3 no-underline block">
|
||||||
|
Подключить Telegram
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
{data.max && (
|
||||||
|
<a href={data.max} target="_blank" rel="noopener" className="btn-ghost mb-6 no-underline block">
|
||||||
|
Подключить MAX
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
<button className="btn-ghost" onClick={() => nav("/login")}>
|
||||||
|
Я подключил — запросить код
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { describe, it, expect, vi } from "vitest";
|
||||||
|
import { render, screen, waitFor } from "@testing-library/react";
|
||||||
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import { MemoryRouter, Routes, Route } from "react-router-dom";
|
||||||
|
|
||||||
|
const states = ["FORM", "PAID"];
|
||||||
|
vi.mock("@/api/driver", () => ({
|
||||||
|
getPaymentState: vi.fn(async () => ({ order_id: "o9", status: states.shift() ?? "PAID" })),
|
||||||
|
}));
|
||||||
|
import { PaymentPage } from "./PaymentPage";
|
||||||
|
|
||||||
|
function wrap() {
|
||||||
|
const qc = new QueryClient();
|
||||||
|
return render(
|
||||||
|
<QueryClientProvider client={qc}>
|
||||||
|
<MemoryRouter initialEntries={[{ pathname: "/pay/o9", state: { payUrl: "https://qr.nspk.ru/x", total: 1052, bucket: "Долг аренда", base: 1000 } }]}>
|
||||||
|
<Routes><Route path="/pay/:orderId" element={<PaymentPage />} /></Routes>
|
||||||
|
</MemoryRouter>
|
||||||
|
</QueryClientProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("PaymentPage", () => {
|
||||||
|
it("shows pay button and flips to success on PAID", async () => {
|
||||||
|
wrap();
|
||||||
|
expect(screen.getByRole("link", { name: /Оплатить/i })).toHaveAttribute("href", "https://qr.nspk.ru/x");
|
||||||
|
await waitFor(() => expect(screen.getByText(/Оплачено/i)).toBeInTheDocument(), { timeout: 3000 });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { useEffect } from "react";
|
||||||
|
import { useLocation, useNavigate, useParams } from "react-router-dom";
|
||||||
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { Check } from "lucide-react";
|
||||||
|
import { formatMoney } from "@/lib/format";
|
||||||
|
import { Spinner } from "@/components/Spinner";
|
||||||
|
import { usePaymentStatus } from "@/hooks/usePaymentStatus";
|
||||||
|
|
||||||
|
export function PaymentPage() {
|
||||||
|
const { orderId = "" } = useParams();
|
||||||
|
const nav = useNavigate();
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const st = (useLocation().state as { payUrl?: string; total?: number; bucket?: string; base?: number } | null) ?? {};
|
||||||
|
const { data } = usePaymentStatus(orderId);
|
||||||
|
const paid = data?.status === "PAID";
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (paid) qc.invalidateQueries({ queryKey: ["balance"] });
|
||||||
|
}, [paid, qc]);
|
||||||
|
|
||||||
|
if (paid) {
|
||||||
|
return (
|
||||||
|
<div className="pt-24 flex flex-col items-center text-center">
|
||||||
|
<span className="w-14 h-14 rounded-full bg-pos text-white flex items-center justify-center mb-3"><Check size={28} /></span>
|
||||||
|
<p className="text-lg font-extrabold">Оплачено</p>
|
||||||
|
<p className="text-muted text-xs mt-1">{st.bucket} пополнен на {formatMoney(st.base ?? 0)}</p>
|
||||||
|
<button className="btn-primary mt-8" onClick={() => nav("/")}>На главную</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="pt-10 flex flex-col items-center text-center">
|
||||||
|
<span className="w-12 h-12 rounded-xl2 bg-ink text-cream flex items-center justify-center font-extrabold mb-4">СБП</span>
|
||||||
|
<p className="text-lg font-extrabold">{formatMoney(st.total ?? 0)}</p>
|
||||||
|
<p className="text-muted text-xs mb-6">{st.bucket}</p>
|
||||||
|
<a className="btn-primary no-underline" href={st.payUrl} target="_blank" rel="noopener">Оплатить</a>
|
||||||
|
<p className="text-muted text-xs mt-2">Откроется ваше приложение банка</p>
|
||||||
|
<div className="flex items-center gap-2 mt-6 text-muted text-xs"><Spinner /> Ожидаем оплату…</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { useEffect } from "react";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import { usePairPoll } from "@/hooks/usePairPoll";
|
||||||
|
import { Spinner } from "@/components/Spinner";
|
||||||
|
|
||||||
|
export function TgWaitPage() {
|
||||||
|
const nav = useNavigate();
|
||||||
|
const pairSession = sessionStorage.getItem("pp-pair-session");
|
||||||
|
const { status } = usePairPoll(pairSession);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!pairSession) { nav("/login", { replace: true }); }
|
||||||
|
}, [pairSession, nav]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (status === "authenticated") { sessionStorage.removeItem("pp-pair-session"); nav("/", { replace: true }); }
|
||||||
|
if (status === "expired") { sessionStorage.removeItem("pp-pair-session"); nav("/login", { replace: true, state: { expired: true } }); }
|
||||||
|
}, [status, nav]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="pt-16 text-center">
|
||||||
|
<h1 className="text-xl font-extrabold mb-2">Премиум Водитель</h1>
|
||||||
|
<p className="text-muted text-sm mb-8">Подтвердите номер в Telegram — нажмите «Поделиться номером», затем вернитесь сюда.</p>
|
||||||
|
<Spinner />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { describe, it, expect, vi } from "vitest";
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
import { MemoryRouter } from "react-router-dom";
|
||||||
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
|
||||||
|
vi.mock("@/api/driver", () => ({
|
||||||
|
topup: vi.fn(async () => ({ order_id: "o9", pay_url: "https://qr.nspk.ru/x", commission: 52, total: 1052 })),
|
||||||
|
getCommission: vi.fn(async () => ({ rate: 0.052 })),
|
||||||
|
}));
|
||||||
|
import { TopupPage } from "./TopupPage";
|
||||||
|
import * as driver from "@/api/driver";
|
||||||
|
|
||||||
|
const wrap = () => {
|
||||||
|
const qc = new QueryClient();
|
||||||
|
return render(
|
||||||
|
<QueryClientProvider client={qc}>
|
||||||
|
<MemoryRouter><TopupPage /></MemoryRouter>
|
||||||
|
</QueryClientProvider>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("TopupPage", () => {
|
||||||
|
it("keypad builds amount, shows total, and submits topup", async () => {
|
||||||
|
wrap();
|
||||||
|
await userEvent.click(screen.getByRole("button", { name: "1" }));
|
||||||
|
await userEvent.click(screen.getByRole("button", { name: "0" }));
|
||||||
|
await userEvent.click(screen.getByRole("button", { name: "0" }));
|
||||||
|
await userEvent.click(screen.getByRole("button", { name: "0" }));
|
||||||
|
expect(screen.getByTestId("amount").textContent).toBe("1 000 ₽");
|
||||||
|
expect(screen.getByTestId("total").textContent).toContain("1 052");
|
||||||
|
await userEvent.click(screen.getByRole("button", { name: /Оплатить/i }));
|
||||||
|
expect(driver.topup).toHaveBeenCalledWith("Долг аренда", 1000, "qr");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useLocation, useNavigate } from "react-router-dom";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { Delete } from "lucide-react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { topup, getCommission } from "@/api/driver";
|
||||||
|
import { keypadReduce, withCommission } from "@/lib/amount";
|
||||||
|
import { formatMoney } from "@/lib/format";
|
||||||
|
import { Segment } from "@/components/Segment";
|
||||||
|
import { Spinner } from "@/components/Spinner";
|
||||||
|
|
||||||
|
const QUICK = ["500", "1000", "2000"];
|
||||||
|
const KEYS = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "·", "0", "back"];
|
||||||
|
|
||||||
|
export function TopupPage() {
|
||||||
|
const nav = useNavigate();
|
||||||
|
const loc = useLocation();
|
||||||
|
const bucket = (loc.state as { bucket?: string } | null)?.bucket ?? "Долг аренда";
|
||||||
|
const [raw, setRaw] = useState("");
|
||||||
|
const [method, setMethod] = useState("qr");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const { data: commission } = useQuery({ queryKey: ["commission"], queryFn: getCommission });
|
||||||
|
const rate = commission?.rate ?? 0.052; // fallback only while loading
|
||||||
|
|
||||||
|
const base = raw ? parseInt(raw, 10) : 0;
|
||||||
|
const { commission: fee, total } = withCommission(base, rate);
|
||||||
|
|
||||||
|
function press(k: string) {
|
||||||
|
if (k === "·") return;
|
||||||
|
setRaw((r) => keypadReduce(r, k));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pay() {
|
||||||
|
if (base <= 0) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const r = await topup(bucket, base, method as "qr" | "card");
|
||||||
|
nav(`/pay/${r.order_id}`, { state: { payUrl: r.pay_url, total: r.total, bucket, base } });
|
||||||
|
} catch {
|
||||||
|
toast.error("Не удалось создать платёж");
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="pt-2">
|
||||||
|
<button className="text-muted text-xs mb-3" onClick={() => nav(-1)}>‹ {bucket}</button>
|
||||||
|
<p data-testid="amount" className="text-3xl font-extrabold text-center mt-2">{formatMoney(base)}</p>
|
||||||
|
<p data-testid="total" className="text-muted text-xs text-center mb-3">
|
||||||
|
к оплате {formatMoney(total)} (комиссия {formatMoney(fee)})
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="flex gap-1.5 mb-3">
|
||||||
|
{QUICK.map((q) => (
|
||||||
|
<button key={q} className="flex-1 py-2 rounded-xl2 text-xs bg-surface border border-line" onClick={() => setRaw(q)}>
|
||||||
|
{q}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-3 gap-2 mb-4">
|
||||||
|
{KEYS.map((k) => (
|
||||||
|
<button
|
||||||
|
key={k}
|
||||||
|
aria-label={k}
|
||||||
|
className="bg-surface border border-line rounded-xl2 py-3 text-lg font-semibold flex items-center justify-center"
|
||||||
|
onClick={() => press(k)}
|
||||||
|
>
|
||||||
|
{k === "back" ? <Delete size={18} /> : k}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-4">
|
||||||
|
<Segment value={method} onChange={setMethod} options={[{ value: "qr", label: "СБП" }, { value: "card", label: "Картой" }]} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button className="btn-primary" disabled={busy || base <= 0} onClick={pay}>
|
||||||
|
{busy ? <Spinner /> : "Оплатить"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { create } from "zustand";
|
||||||
|
import { persist } from "zustand/middleware";
|
||||||
|
|
||||||
|
interface AuthState {
|
||||||
|
token: string | null;
|
||||||
|
driverId: number | null;
|
||||||
|
setSession: (token: string, driverId: number) => void;
|
||||||
|
clear: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useAuth = create<AuthState>()(
|
||||||
|
persist(
|
||||||
|
(set) => ({
|
||||||
|
token: null,
|
||||||
|
driverId: null,
|
||||||
|
setSession: (token, driverId) => set({ token, driverId }),
|
||||||
|
clear: () => set({ token: null, driverId: null }),
|
||||||
|
}),
|
||||||
|
{ name: "pp-driver-auth" }
|
||||||
|
)
|
||||||
|
);
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
import "@testing-library/jest-dom/vitest";
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
/// <reference types="vite/client" />
|
||||||
|
|
||||||
|
interface ImportMetaEnv {
|
||||||
|
readonly VITE_API_BASE?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ImportMeta {
|
||||||
|
readonly env: ImportMetaEnv;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
/** @type {import('tailwindcss').Config} */
|
||||||
|
export default {
|
||||||
|
content: ["./index.html", "./src/**/*.{ts,tsx}"],
|
||||||
|
theme: {
|
||||||
|
extend: {
|
||||||
|
colors: {
|
||||||
|
cream: "#F3EEE3", surface: "#FBF8F1", line: "#E4DCCB",
|
||||||
|
ink: "#1C1B19", muted: "#7C7361", neg: "#C0493A", pos: "#3B6E4A",
|
||||||
|
},
|
||||||
|
fontFamily: { sans: ["Inter", "system-ui", "sans-serif"] },
|
||||||
|
borderRadius: { xl2: "14px" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: [],
|
||||||
|
};
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2021", "useDefineForClassFields": true, "lib": ["ES2021", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "ESNext", "skipLibCheck": true, "moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true,
|
||||||
|
"noEmit": true, "jsx": "react-jsx", "strict": true, "noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true, "noFallthroughCasesInSwitch": true,
|
||||||
|
"baseUrl": ".", "paths": { "@/*": ["src/*"] }, "types": ["vitest/globals", "@testing-library/jest-dom"]
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"files": [],
|
||||||
|
"references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }]
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022", "lib": ["ES2023"], "module": "ESNext", "skipLibCheck": true,
|
||||||
|
"moduleResolution": "bundler", "allowImportingTsExtensions": true, "isolatedModules": true,
|
||||||
|
"noEmit": true, "strict": true
|
||||||
|
},
|
||||||
|
"include": ["vite.config.ts", "vitest.config.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { defineConfig } from "vite";
|
||||||
|
import react from "@vitejs/plugin-react";
|
||||||
|
import { VitePWA } from "vite-plugin-pwa";
|
||||||
|
import path from "path";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [
|
||||||
|
react(),
|
||||||
|
VitePWA({ registerType: "autoUpdate", manifest: false, includeAssets: ["icons/*.png"] }),
|
||||||
|
],
|
||||||
|
resolve: { alias: { "@": path.resolve(__dirname, "src") } },
|
||||||
|
server: { port: 5174 },
|
||||||
|
});
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { defineConfig } from "vitest/config";
|
||||||
|
import react from "@vitejs/plugin-react";
|
||||||
|
import path from "path";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
resolve: { alias: { "@": path.resolve(__dirname, "src") } },
|
||||||
|
test: { globals: true, environment: "jsdom", setupFiles: ["./src/test/setup.ts"] },
|
||||||
|
});
|
||||||
@@ -3,8 +3,16 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
|
<link rel="icon" type="image/png" sizes="16x16" href="/icons/favicon-16.png" />
|
||||||
|
<link rel="icon" type="image/png" sizes="32x32" href="/icons/favicon-32.png" />
|
||||||
|
<link rel="icon" type="image/png" sizes="48x48" href="/icons/favicon-48.png" />
|
||||||
|
<link rel="icon" type="image/png" sizes="192x192" href="/icons/icon-192.png" />
|
||||||
|
<link rel="apple-touch-icon" sizes="180x180" href="/icons/apple-touch-icon.png" />
|
||||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover" />
|
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover" />
|
||||||
<meta name="theme-color" content="#2a2a2a" />
|
<meta name="theme-color" content="#000000" />
|
||||||
|
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||||
|
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||||
|
<meta name="apple-mobile-web-app-title" content="Mechanic" />
|
||||||
<link rel="manifest" href="/manifest.webmanifest" />
|
<link rel="manifest" href="/manifest.webmanifest" />
|
||||||
<title>Premium Механик</title>
|
<title>Premium Механик</title>
|
||||||
</head>
|
</head>
|
||||||
|
|||||||
@@ -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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
{
|
||||||
|
"_meta": {
|
||||||
|
"source": "Ttc.dll #US heap, contiguous block at offsets 0xc2e24–0xc3084",
|
||||||
|
"confidence": "HIGH — full block scanned; order is the binary storage order which matches app display order (repository pattern typically loads in definition order)",
|
||||||
|
"notes": [
|
||||||
|
"Items 0–12 are general exterior damage types (user-selectable for any zone)",
|
||||||
|
"Items 13–18 appear to be salon-specific (Грязный салон, Запах табака, etc.) — shown only for interior zones (44–46 seats, salon)",
|
||||||
|
"Установлено/Снято (19–20) and Контроль (21) are semi-system states used for equipment completeness zones (33–48 area)",
|
||||||
|
"Штат (25) appears to be a system/staff marker, not user-selectable",
|
||||||
|
"Порез, Прокол, Порвано are tire-specific damage types for zones 17–20",
|
||||||
|
"Есть/Нет повреждений found in binary (0x4599a/0x4597a) — likely used for salon damage yes/no toggle, not in the standard list"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"damage_types_ordered": [
|
||||||
|
"Вмятина",
|
||||||
|
"Царапина",
|
||||||
|
"Трещина",
|
||||||
|
"Повреждено",
|
||||||
|
"Скол",
|
||||||
|
"Отсутствует",
|
||||||
|
"Прожжено",
|
||||||
|
"Погнуто",
|
||||||
|
"Требуется мойка",
|
||||||
|
"Не работает",
|
||||||
|
"Порез",
|
||||||
|
"Прокол",
|
||||||
|
"Порвано",
|
||||||
|
"Пятна",
|
||||||
|
"Грязный салон",
|
||||||
|
"Запах табака",
|
||||||
|
"Повреждение салонных ковриков",
|
||||||
|
"Повреждение обшивки дверей",
|
||||||
|
"Сломанные ручки",
|
||||||
|
"Установлено",
|
||||||
|
"Снято",
|
||||||
|
"Контроль",
|
||||||
|
"Требуется химчистка",
|
||||||
|
"Затертость",
|
||||||
|
"Грыжа",
|
||||||
|
"Штат"
|
||||||
|
],
|
||||||
|
"exterior_selectable": [
|
||||||
|
"Вмятина",
|
||||||
|
"Царапина",
|
||||||
|
"Трещина",
|
||||||
|
"Повреждено",
|
||||||
|
"Скол",
|
||||||
|
"Отсутствует",
|
||||||
|
"Прожжено",
|
||||||
|
"Погнуто",
|
||||||
|
"Требуется мойка",
|
||||||
|
"Не работает",
|
||||||
|
"Порез",
|
||||||
|
"Прокол",
|
||||||
|
"Порвано",
|
||||||
|
"Пятна",
|
||||||
|
"Затертость",
|
||||||
|
"Грыжа"
|
||||||
|
],
|
||||||
|
"salon_selectable": [
|
||||||
|
"Вмятина",
|
||||||
|
"Царапина",
|
||||||
|
"Трещина",
|
||||||
|
"Повреждено",
|
||||||
|
"Скол",
|
||||||
|
"Отсутствует",
|
||||||
|
"Прожжено",
|
||||||
|
"Погнуто",
|
||||||
|
"Требуется мойка",
|
||||||
|
"Не работает",
|
||||||
|
"Пятна",
|
||||||
|
"Грязный салон",
|
||||||
|
"Запах табака",
|
||||||
|
"Повреждение салонных ковриков",
|
||||||
|
"Повреждение обшивки дверей",
|
||||||
|
"Сломанные ручки",
|
||||||
|
"Требуется химчистка",
|
||||||
|
"Затертость",
|
||||||
|
"Грыжа"
|
||||||
|
],
|
||||||
|
"severity_scale": {
|
||||||
|
"positions": 3,
|
||||||
|
"labels": ["Легкое", "Среднее", "Тяжелое"],
|
||||||
|
"values": [0, 1, 2],
|
||||||
|
"widget": "SeekBar (vehicleInspectionDegreeSelect / newDamageSeekBarDamageDegree)",
|
||||||
|
"api_field": "degree (lowercase, in JSON contract)",
|
||||||
|
"default": "Легкое (index 0)",
|
||||||
|
"source_note": "Легкое found at 0x59d79 (adjacent to 'Добавить повреждение' button label = default/initial value); Среднее+Тяжелое found together at 0xc39e8–0xc39f8 (loading state transitions)"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,401 @@
|
|||||||
|
{
|
||||||
|
"0": {
|
||||||
|
"x": 278.11,
|
||||||
|
"y": 88.77,
|
||||||
|
"w": 262.74,
|
||||||
|
"h": 45.43,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"52": {
|
||||||
|
"x": 699.8,
|
||||||
|
"y": 296.93,
|
||||||
|
"w": 41.31,
|
||||||
|
"h": 70.61,
|
||||||
|
"rotation": -90
|
||||||
|
},
|
||||||
|
"51": {
|
||||||
|
"x": 81.04,
|
||||||
|
"y": 295.79,
|
||||||
|
"w": 41.4,
|
||||||
|
"h": 71.68,
|
||||||
|
"rotation": 90
|
||||||
|
},
|
||||||
|
"1": {
|
||||||
|
"x": 488.5,
|
||||||
|
"y": 132.88,
|
||||||
|
"w": 50.92,
|
||||||
|
"h": 20.77,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"2": {
|
||||||
|
"x": 279.61,
|
||||||
|
"y": 132.82,
|
||||||
|
"w": 50.93,
|
||||||
|
"h": 21.24,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"3": {
|
||||||
|
"x": 350.0,
|
||||||
|
"y": 130.0,
|
||||||
|
"w": 120.0,
|
||||||
|
"h": 22.0,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"30": {
|
||||||
|
"x": 509.22,
|
||||||
|
"y": 734.61,
|
||||||
|
"w": 130.89,
|
||||||
|
"h": 41.63,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"31": {
|
||||||
|
"x": 182.12,
|
||||||
|
"y": 734.5,
|
||||||
|
"w": 129.26,
|
||||||
|
"h": 41.56,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"28": {
|
||||||
|
"x": 170.41,
|
||||||
|
"y": 496.19,
|
||||||
|
"w": 6.35,
|
||||||
|
"h": 8.34,
|
||||||
|
"rotation": 90
|
||||||
|
},
|
||||||
|
"29": {
|
||||||
|
"x": 645.28,
|
||||||
|
"y": 496.19,
|
||||||
|
"w": 6.53,
|
||||||
|
"h": 8.58,
|
||||||
|
"rotation": -90
|
||||||
|
},
|
||||||
|
"11": {
|
||||||
|
"x": 278.5,
|
||||||
|
"y": 477.86,
|
||||||
|
"w": 465.53,
|
||||||
|
"h": 152.09,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"10": {
|
||||||
|
"x": 78.52,
|
||||||
|
"y": 478.98,
|
||||||
|
"w": 91.6,
|
||||||
|
"h": 150.99,
|
||||||
|
"rotation": 90
|
||||||
|
},
|
||||||
|
"4": {
|
||||||
|
"x": 300.72,
|
||||||
|
"y": 311.52,
|
||||||
|
"w": 219.3,
|
||||||
|
"h": 146.72,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"5": {
|
||||||
|
"x": 305.05,
|
||||||
|
"y": 442.76,
|
||||||
|
"w": 210.67,
|
||||||
|
"h": 127.13,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"22": {
|
||||||
|
"x": 281.48,
|
||||||
|
"y": 1063.81,
|
||||||
|
"w": 260.16,
|
||||||
|
"h": 59.34,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"49": {
|
||||||
|
"x": 87.78,
|
||||||
|
"y": 826.98,
|
||||||
|
"w": 50.54,
|
||||||
|
"h": 99.5,
|
||||||
|
"rotation": 90
|
||||||
|
},
|
||||||
|
"50": {
|
||||||
|
"x": 684.83,
|
||||||
|
"y": 827.25,
|
||||||
|
"w": 49.78,
|
||||||
|
"h": 99.71,
|
||||||
|
"rotation": -90
|
||||||
|
},
|
||||||
|
"33": {
|
||||||
|
"x": 284.24,
|
||||||
|
"y": 1038.88,
|
||||||
|
"w": 29.65,
|
||||||
|
"h": 22.7,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"32": {
|
||||||
|
"x": 507.74,
|
||||||
|
"y": 1038.78,
|
||||||
|
"w": 29.66,
|
||||||
|
"h": 22.69,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"21": {
|
||||||
|
"x": 303.29,
|
||||||
|
"y": 841.39,
|
||||||
|
"w": 215.88,
|
||||||
|
"h": 236.13,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"38": {
|
||||||
|
"x": 510.42,
|
||||||
|
"y": 195.83,
|
||||||
|
"w": 26.67,
|
||||||
|
"h": 821.6,
|
||||||
|
"rotation": -90
|
||||||
|
},
|
||||||
|
"39": {
|
||||||
|
"x": 281.9,
|
||||||
|
"y": 195.94,
|
||||||
|
"w": 26.67,
|
||||||
|
"h": 14.24,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"23": {
|
||||||
|
"x": 316.23,
|
||||||
|
"y": 766.98,
|
||||||
|
"w": 187.94,
|
||||||
|
"h": 89.25,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"6": {
|
||||||
|
"x": 78.13,
|
||||||
|
"y": 314.95,
|
||||||
|
"w": 91.98,
|
||||||
|
"h": 168.83,
|
||||||
|
"rotation": 90
|
||||||
|
},
|
||||||
|
"7": {
|
||||||
|
"x": 651.97,
|
||||||
|
"y": 314.84,
|
||||||
|
"w": 92.1,
|
||||||
|
"h": 168.93,
|
||||||
|
"rotation": -90
|
||||||
|
},
|
||||||
|
"8": {
|
||||||
|
"x": 81.05,
|
||||||
|
"y": 734.43,
|
||||||
|
"w": 104.0,
|
||||||
|
"h": 176.79,
|
||||||
|
"rotation": 90
|
||||||
|
},
|
||||||
|
"9": {
|
||||||
|
"x": 590.75,
|
||||||
|
"y": 666.97,
|
||||||
|
"w": 150.45,
|
||||||
|
"h": 244.25,
|
||||||
|
"rotation": -90
|
||||||
|
},
|
||||||
|
"12": {
|
||||||
|
"x": 81.53,
|
||||||
|
"y": 628.12,
|
||||||
|
"w": 99.38,
|
||||||
|
"h": 147.01,
|
||||||
|
"rotation": 90
|
||||||
|
},
|
||||||
|
"13": {
|
||||||
|
"x": 641.53,
|
||||||
|
"y": 627.6,
|
||||||
|
"w": 99.42,
|
||||||
|
"h": 147.14,
|
||||||
|
"rotation": -90
|
||||||
|
},
|
||||||
|
"16": {
|
||||||
|
"x": 325.94,
|
||||||
|
"y": 563.11,
|
||||||
|
"w": 168.93,
|
||||||
|
"h": 208.89,
|
||||||
|
"rotation": 90
|
||||||
|
},
|
||||||
|
"14": {
|
||||||
|
"x": 72.11,
|
||||||
|
"y": 471.33,
|
||||||
|
"w": 5.0,
|
||||||
|
"h": 161.47,
|
||||||
|
"rotation": 90
|
||||||
|
},
|
||||||
|
"47": {
|
||||||
|
"x": 72.83,
|
||||||
|
"y": 615.64,
|
||||||
|
"w": 5.6,
|
||||||
|
"h": 124.59,
|
||||||
|
"rotation": 90
|
||||||
|
},
|
||||||
|
"15": {
|
||||||
|
"x": 744.0,
|
||||||
|
"y": 461.0,
|
||||||
|
"w": 6.0,
|
||||||
|
"h": 171.5,
|
||||||
|
"rotation": -90
|
||||||
|
},
|
||||||
|
"48": {
|
||||||
|
"x": 744.0,
|
||||||
|
"y": 632.5,
|
||||||
|
"w": 6.0,
|
||||||
|
"h": 107.5,
|
||||||
|
"rotation": -90
|
||||||
|
},
|
||||||
|
"27": {
|
||||||
|
"x": 596.56,
|
||||||
|
"y": 643.76,
|
||||||
|
"w": 50.37,
|
||||||
|
"h": 84.35,
|
||||||
|
"rotation": -90
|
||||||
|
},
|
||||||
|
"26": {
|
||||||
|
"x": 175.44,
|
||||||
|
"y": 643.75,
|
||||||
|
"w": 50.57,
|
||||||
|
"h": 84.4,
|
||||||
|
"rotation": 90
|
||||||
|
},
|
||||||
|
"24": {
|
||||||
|
"x": 171.07,
|
||||||
|
"y": 526.12,
|
||||||
|
"w": 53.81,
|
||||||
|
"h": 105.33,
|
||||||
|
"rotation": 90
|
||||||
|
},
|
||||||
|
"25": {
|
||||||
|
"x": 597.45,
|
||||||
|
"y": 526.06,
|
||||||
|
"w": 53.57,
|
||||||
|
"h": 105.33,
|
||||||
|
"rotation": -90
|
||||||
|
},
|
||||||
|
"18": {
|
||||||
|
"x": 42.7,
|
||||||
|
"y": 369.77,
|
||||||
|
"w": 89.47,
|
||||||
|
"h": 88.82,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"43": {
|
||||||
|
"x": 56.05,
|
||||||
|
"y": 382.97,
|
||||||
|
"w": 63.97,
|
||||||
|
"h": 63.6,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"17": {
|
||||||
|
"x": 688.66,
|
||||||
|
"y": 369.75,
|
||||||
|
"w": 89.51,
|
||||||
|
"h": 88.83,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"42": {
|
||||||
|
"x": 702.04,
|
||||||
|
"y": 382.95,
|
||||||
|
"w": 63.97,
|
||||||
|
"h": 63.61,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"20": {
|
||||||
|
"x": 42.55,
|
||||||
|
"y": 751.33,
|
||||||
|
"w": 90.63,
|
||||||
|
"h": 88.87,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"40": {
|
||||||
|
"x": 56.71,
|
||||||
|
"y": 764.4,
|
||||||
|
"w": 61.8,
|
||||||
|
"h": 62.63,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"19": {
|
||||||
|
"x": 688.96,
|
||||||
|
"y": 751.25,
|
||||||
|
"w": 89.2,
|
||||||
|
"h": 88.92,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"41": {
|
||||||
|
"x": 701.6,
|
||||||
|
"y": 763.49,
|
||||||
|
"w": 64.65,
|
||||||
|
"h": 64.46,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"44": {
|
||||||
|
"x": 42.66,
|
||||||
|
"y": 0.0,
|
||||||
|
"w": 426.67,
|
||||||
|
"h": 512.0,
|
||||||
|
"rotation": 90
|
||||||
|
},
|
||||||
|
"45": {
|
||||||
|
"x": 42.66,
|
||||||
|
"y": 0.0,
|
||||||
|
"w": 426.67,
|
||||||
|
"h": 512.0,
|
||||||
|
"rotation": 90
|
||||||
|
},
|
||||||
|
"46": {
|
||||||
|
"x": 42.66,
|
||||||
|
"y": 0.0,
|
||||||
|
"w": 426.67,
|
||||||
|
"h": 512.0,
|
||||||
|
"rotation": 90
|
||||||
|
},
|
||||||
|
"34": {
|
||||||
|
"x": 0.0,
|
||||||
|
"y": 76.0,
|
||||||
|
"w": 512.0,
|
||||||
|
"h": 360.0,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"35": {
|
||||||
|
"x": 0.0,
|
||||||
|
"y": 76.0,
|
||||||
|
"w": 512.0,
|
||||||
|
"h": 360.0,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"36": {
|
||||||
|
"x": 0.0,
|
||||||
|
"y": 76.0,
|
||||||
|
"w": 512.0,
|
||||||
|
"h": 360.0,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"37": {
|
||||||
|
"x": 0.0,
|
||||||
|
"y": 76.0,
|
||||||
|
"w": 512.0,
|
||||||
|
"h": 360.0,
|
||||||
|
"rotation": 0
|
||||||
|
},
|
||||||
|
"53": {
|
||||||
|
"x": 185.83,
|
||||||
|
"y": 719.15,
|
||||||
|
"w": 42.97,
|
||||||
|
"h": 94.96,
|
||||||
|
"rotation": 90
|
||||||
|
},
|
||||||
|
"54": {
|
||||||
|
"x": 594.89,
|
||||||
|
"y": 723.2,
|
||||||
|
"w": 46.0,
|
||||||
|
"h": 101.37,
|
||||||
|
"rotation": -90
|
||||||
|
},
|
||||||
|
"55": {
|
||||||
|
"x": 170.0,
|
||||||
|
"y": 450.0,
|
||||||
|
"w": 60.0,
|
||||||
|
"h": 130.0,
|
||||||
|
"rotation": 90
|
||||||
|
},
|
||||||
|
"56": {
|
||||||
|
"x": 595.0,
|
||||||
|
"y": 450.0,
|
||||||
|
"w": 55.0,
|
||||||
|
"h": 130.0,
|
||||||
|
"rotation": -90
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
{
|
||||||
|
"_meta": {
|
||||||
|
"source": "Ttc.dll #US heap, offsets 0x751c7–0x75a81 (consecutive UTF-16 LE strings)",
|
||||||
|
"confidence": "HIGH — 57 strings appear in exact sequential order in a single contiguous block, matching the 57 class IDs (0..56) in exterior_scheme_complete.svg",
|
||||||
|
"geographic_check": "confirmed: zone 0 (front bumper) at SVG Y=119 (top), zone 22 (rear bumper) at Y=1064 (bottom); left-side zones have small X, right-side zones have large X",
|
||||||
|
"note_typo": "zone 15 has a typo in the vendor binary: 'правй порог' (missing 'ы') — preserve as-is for matching but display as 'правый порог'",
|
||||||
|
"note_zones_34_57": "zones 34–37 are fog lights (противотуманки), zones 38–39 mirrors, 40–43 disks, 44–46 salon seats, 47–48 rear sill extensions, 49–56 bumper sub-parts and pillars"
|
||||||
|
},
|
||||||
|
"0": "передний бампер",
|
||||||
|
"1": "передняя правая фара",
|
||||||
|
"2": "передняя левая фара",
|
||||||
|
"3": "радиатор",
|
||||||
|
"4": "капот",
|
||||||
|
"5": "лобовое стекло",
|
||||||
|
"6": "переднее левое крыло",
|
||||||
|
"7": "переднее правое крыло",
|
||||||
|
"8": "заднее левое крыло",
|
||||||
|
"9": "заднее правое крыло",
|
||||||
|
"10": "передняя левая дверь",
|
||||||
|
"11": "передняя правая дверь",
|
||||||
|
"12": "задняя левая дверь",
|
||||||
|
"13": "задняя правая дверь",
|
||||||
|
"14": "левый порог",
|
||||||
|
"15": "правый порог",
|
||||||
|
"16": "крыша",
|
||||||
|
"17": "передняя правая резина",
|
||||||
|
"18": "передняя левая резина",
|
||||||
|
"19": "задняя правая резина",
|
||||||
|
"20": "задняя левая резина",
|
||||||
|
"21": "багажник",
|
||||||
|
"22": "задний бампер",
|
||||||
|
"23": "заднее стекло",
|
||||||
|
"24": "переднее левое стекло",
|
||||||
|
"25": "переднее правое стекло",
|
||||||
|
"26": "заднее левое стекло",
|
||||||
|
"27": "заднее правое стекло",
|
||||||
|
"28": "передняя левая форточка",
|
||||||
|
"29": "передняя правая форточка",
|
||||||
|
"30": "задняя правая форточка",
|
||||||
|
"31": "задняя левая форточка",
|
||||||
|
"32": "задняя правая фара",
|
||||||
|
"33": "задняя левая фара",
|
||||||
|
"34": "передняя правая противотуманка",
|
||||||
|
"35": "передняя левая противотуманка",
|
||||||
|
"36": "задняя правая противотуманка",
|
||||||
|
"37": "задняя левая противотуманка",
|
||||||
|
"38": "правое зеркало",
|
||||||
|
"39": "левое зеркало",
|
||||||
|
"40": "задний левый диск",
|
||||||
|
"41": "задний правый диск",
|
||||||
|
"42": "передний правый диск",
|
||||||
|
"43": "передний левый диск",
|
||||||
|
"44": "водительское сидение",
|
||||||
|
"45": "пассажирское сидение",
|
||||||
|
"46": "задний диван",
|
||||||
|
"47": "задний левый порог",
|
||||||
|
"48": "задний правый порог",
|
||||||
|
"49": "задняя левая часть бампера",
|
||||||
|
"50": "задняя правая часть бампера",
|
||||||
|
"51": "передняя левая часть бампера",
|
||||||
|
"52": "передняя правая часть бампера",
|
||||||
|
"53": "задняя левая стойка",
|
||||||
|
"54": "задняя правая стойка",
|
||||||
|
"55": "передняя левая стойка",
|
||||||
|
"56": "передняя правая стойка"
|
||||||
|
}
|
||||||
|
Before Width: | Height: | Size: 9.3 KiB After Width: | Height: | Size: 514 B |
|
After Width: | Height: | Size: 8.3 KiB |
|
After Width: | Height: | Size: 410 B |
|
After Width: | Height: | Size: 889 B |
|
After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 9.2 KiB |
|
Before Width: | Height: | Size: 6.1 KiB After Width: | Height: | Size: 86 KiB |
|
After Width: | Height: | Size: 56 KiB |
@@ -4,10 +4,11 @@
|
|||||||
"start_url": "/",
|
"start_url": "/",
|
||||||
"display": "standalone",
|
"display": "standalone",
|
||||||
"orientation": "portrait",
|
"orientation": "portrait",
|
||||||
"background_color": "#f5f1ea",
|
"background_color": "#000000",
|
||||||
"theme_color": "#2a2a2a",
|
"theme_color": "#000000",
|
||||||
"icons": [
|
"icons": [
|
||||||
{ "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
|
{ "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },
|
||||||
{ "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" }
|
{ "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },
|
||||||
|
{ "src": "/icons/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 129 KiB |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 52 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
@@ -1,10 +1,18 @@
|
|||||||
import { Routes, Route, Navigate } from "react-router-dom";
|
import { Routes, Route, Navigate } from "react-router-dom";
|
||||||
import { useAuth } from "@/store/auth";
|
import { useAuth } from "@/store/auth";
|
||||||
|
import { useMeSync } from "@/hooks/useMeSync";
|
||||||
import Login from "@/pages/Login";
|
import Login from "@/pages/Login";
|
||||||
|
import ActionMenu from "@/pages/ActionMenu";
|
||||||
import Home from "@/pages/Home";
|
import Home from "@/pages/Home";
|
||||||
import VehicleCard from "@/pages/VehicleCard";
|
import VehicleCard from "@/pages/VehicleCard";
|
||||||
import InspectionEditor from "@/pages/InspectionEditor";
|
import InspectionEditor from "@/pages/InspectionEditor";
|
||||||
import InspectionReview from "@/pages/InspectionReview";
|
import InspectionReview from "@/pages/InspectionReview";
|
||||||
|
import TtStateDetail from "@/pages/TtStateDetail";
|
||||||
|
import RepairsFeedPage from "@/pages/repairs/RepairsFeedPage";
|
||||||
|
import RepairDetailPage from "@/pages/repairs/RepairDetailPage";
|
||||||
|
import EditRepairPage from "@/pages/repairs/EditRepairPage";
|
||||||
|
import CarSelectPage from "@/pages/repairs/CarSelectPage";
|
||||||
|
import CreateRepairPage from "@/pages/repairs/CreateRepairPage";
|
||||||
|
|
||||||
function RequireAuth({ children }: { children: React.ReactNode }) {
|
function RequireAuth({ children }: { children: React.ReactNode }) {
|
||||||
const token = useAuth((s) => s.token);
|
const token = useAuth((s) => s.token);
|
||||||
@@ -13,13 +21,27 @@ function RequireAuth({ children }: { children: React.ReactNode }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
|
// У35: фоновая сверка прав механика раз в 5 минут — выкидывает на /login
|
||||||
|
// с сообщением «Доступ отозван», если админ снял can_login_pwa или вывел
|
||||||
|
// пользователя из отдела механиков.
|
||||||
|
useMeSync();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/login" element={<Login />} />
|
<Route path="/login" element={<Login />} />
|
||||||
<Route path="/" element={<RequireAuth><Home /></RequireAuth>} />
|
<Route path="/" element={<RequireAuth><ActionMenu /></RequireAuth>} />
|
||||||
|
<Route path="/vehicles" element={<RequireAuth><Home /></RequireAuth>} />
|
||||||
<Route path="/vehicles/:id" element={<RequireAuth><VehicleCard /></RequireAuth>} />
|
<Route path="/vehicles/:id" element={<RequireAuth><VehicleCard /></RequireAuth>} />
|
||||||
<Route path="/inspections/:id/edit" element={<RequireAuth><InspectionEditor /></RequireAuth>} />
|
<Route path="/inspections/:id/edit" element={<RequireAuth><InspectionEditor /></RequireAuth>} />
|
||||||
<Route path="/inspections/:id" element={<RequireAuth><InspectionReview /></RequireAuth>} />
|
<Route path="/inspections/:id" element={<RequireAuth><InspectionReview /></RequireAuth>} />
|
||||||
|
<Route path="/tt-states/:id" element={<RequireAuth><TtStateDetail /></RequireAuth>} />
|
||||||
|
{/* Раздел «Ремонт» — активируется в PR-5 (Фича 1). */}
|
||||||
|
<Route path="/repairs" element={<RequireAuth><RepairsFeedPage /></RequireAuth>} />
|
||||||
|
<Route path="/repairs/new" element={<RequireAuth><CarSelectPage /></RequireAuth>} />
|
||||||
|
<Route path="/repairs/new/:carId" element={<RequireAuth><CreateRepairPage /></RequireAuth>} />
|
||||||
|
<Route path="/repairs/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>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -5,26 +5,52 @@ export interface LoginInput {
|
|||||||
password: string;
|
password: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** OAuth2-shaped login response, extended with backend's 2FA signaling fields. */
|
||||||
export interface LoginOutput {
|
export interface LoginOutput {
|
||||||
access_token: string;
|
access_token?: string | null;
|
||||||
token_type: string;
|
token_type: string;
|
||||||
|
requires_2fa?: boolean;
|
||||||
|
partial_token?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TwoFactorInput {
|
||||||
|
partial_token: string;
|
||||||
|
code: string;
|
||||||
|
remember_device: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function login(input: LoginInput): Promise<LoginOutput> {
|
export async function login(input: LoginInput): Promise<LoginOutput> {
|
||||||
// OAuth2 password flow — form-urlencoded, NOT JSON, NOT under /api/v1/mechanic/
|
|
||||||
const body = new URLSearchParams();
|
const body = new URLSearchParams();
|
||||||
body.set("username", input.username);
|
body.set("username", input.username);
|
||||||
body.set("password", input.password);
|
body.set("password", input.password);
|
||||||
|
// PWA — длинная сессия (30 дней) чтобы механики не вводили пароль каждые 8 ч.
|
||||||
|
body.set("long_session", "true");
|
||||||
|
|
||||||
const res = await fetch("/api/auth/login", {
|
const res = await fetch("/api/auth/login", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
body,
|
body,
|
||||||
|
// Critical: include credentials so the 30-day trusted_device cookie is
|
||||||
|
// sent back to backend on subsequent logins (lets us skip 2FA next time).
|
||||||
|
credentials: "include",
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
throw new Error(`Login failed: ${res.status}`);
|
throw new Error(`Login failed: ${res.status}`);
|
||||||
}
|
}
|
||||||
return res.json() as Promise<LoginOutput>;
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function login2fa(input: TwoFactorInput): Promise<LoginOutput> {
|
||||||
|
const res = await fetch("/api/auth/2fa", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ ...input, long_session: true }),
|
||||||
|
credentials: "include", // accept the trusted_device cookie on Set-Cookie
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`2FA failed: ${res.status}`);
|
||||||
|
}
|
||||||
|
return res.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function logout(): void {
|
export function logout(): void {
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ export interface InspectionCreateInput {
|
|||||||
vehicle_id: number;
|
vehicle_id: number;
|
||||||
type: InspectionType;
|
type: InspectionType;
|
||||||
driver_id?: number;
|
driver_id?: number;
|
||||||
|
mileage?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PhotoSummary {
|
export interface PhotoSummary {
|
||||||
@@ -26,6 +27,7 @@ export interface PhotoSummary {
|
|||||||
slot_index: number;
|
slot_index: number;
|
||||||
storage_key: string;
|
storage_key: string;
|
||||||
thumb_key?: string | null;
|
thumb_key?: string | null;
|
||||||
|
annotated_key?: string | null;
|
||||||
width?: number | null;
|
width?: number | null;
|
||||||
height?: number | null;
|
height?: number | null;
|
||||||
status: string;
|
status: string;
|
||||||
@@ -36,6 +38,7 @@ export interface MarkerSummary {
|
|||||||
id: number;
|
id: number;
|
||||||
inspection_id: number;
|
inspection_id: number;
|
||||||
photo_id?: number | null;
|
photo_id?: number | null;
|
||||||
|
tt_image_id?: string | null;
|
||||||
side?: string | null;
|
side?: string | null;
|
||||||
x?: number | null;
|
x?: number | null;
|
||||||
y?: number | null;
|
y?: number | null;
|
||||||
@@ -48,9 +51,22 @@ export interface MarkerSummary {
|
|||||||
created_at: string;
|
created_at: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface VehicleBrief {
|
||||||
|
id: number;
|
||||||
|
license_plate: string;
|
||||||
|
vin?: string | null;
|
||||||
|
make?: string | null;
|
||||||
|
model?: string | null;
|
||||||
|
year?: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
export interface InspectionDetail {
|
export interface InspectionDetail {
|
||||||
id: number;
|
id: number;
|
||||||
vehicle_id: number;
|
vehicle_id: number;
|
||||||
|
/** Сводка по машине (гос.номер / марка / модель / год). Backend attaches её
|
||||||
|
в get_inspection_by_id_with_relations, чтобы карточка осмотра могла
|
||||||
|
показать машину без второго запроса. */
|
||||||
|
vehicle?: VehicleBrief | null;
|
||||||
type: InspectionType;
|
type: InspectionType;
|
||||||
performed_by: number;
|
performed_by: number;
|
||||||
driver_id?: number | null;
|
driver_id?: number | null;
|
||||||
@@ -62,6 +78,9 @@ export interface InspectionDetail {
|
|||||||
meta: Record<string, unknown>;
|
meta: Record<string, unknown>;
|
||||||
photos: PhotoSummary[];
|
photos: PhotoSummary[];
|
||||||
markers: MarkerSummary[];
|
markers: MarkerSummary[];
|
||||||
|
mileage?: number | null;
|
||||||
|
/** ФИО механика, выполнившего осмотр (lookup users.full_name по performed_by). */
|
||||||
|
inspector_name?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createInspection(
|
export async function createInspection(
|
||||||
@@ -76,7 +95,7 @@ export async function getInspection(id: number): Promise<InspectionDetail> {
|
|||||||
|
|
||||||
export async function patchInspection(
|
export async function patchInspection(
|
||||||
id: number,
|
id: number,
|
||||||
body: { status?: InspectionStatus; notes?: string; finished_at?: string }
|
body: { status?: InspectionStatus; notes?: string; finished_at?: string; mileage?: number }
|
||||||
): Promise<InspectionDetail> {
|
): Promise<InspectionDetail> {
|
||||||
return api.patch(`inspections/${id}`, { json: body }).json<InspectionDetail>();
|
return api.patch(`inspections/${id}`, { json: body }).json<InspectionDetail>();
|
||||||
}
|
}
|
||||||
@@ -101,4 +120,12 @@ export async function createMarker(
|
|||||||
.json<MarkerSummary>();
|
.json<MarkerSummary>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function deleteInspection(inspectionId: number): Promise<void> {
|
||||||
|
await api.delete(`inspections/${inspectionId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteMarker(markerId: number): Promise<void> {
|
||||||
|
await api.delete(`markers/${markerId}`);
|
||||||
|
}
|
||||||
|
|
||||||
export type { InspectionSummary };
|
export type { InspectionSummary };
|
||||||
|
|||||||
@@ -1,10 +1,20 @@
|
|||||||
import { api } from "./client";
|
import { api } from "./client";
|
||||||
|
|
||||||
|
export interface PwaSupportContact {
|
||||||
|
tg_username: string | null;
|
||||||
|
phone: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
export interface Me {
|
export interface Me {
|
||||||
id: number;
|
id: number;
|
||||||
name: string;
|
name: string;
|
||||||
email?: string | null;
|
email?: string | null;
|
||||||
permissions: string[];
|
permissions: string[];
|
||||||
|
// Модуль СТО (У10 + У34) — расширение в backend PR-4.
|
||||||
|
is_admin: boolean;
|
||||||
|
can_login_pwa: boolean;
|
||||||
|
departments: string[];
|
||||||
|
support: PwaSupportContact;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getMe(): Promise<Me> {
|
export async function getMe(): Promise<Me> {
|
||||||
|
|||||||
@@ -14,12 +14,27 @@ export interface PhotoConfirmResponse {
|
|||||||
slot_index: number;
|
slot_index: number;
|
||||||
storage_key: string;
|
storage_key: string;
|
||||||
thumb_key?: string | null;
|
thumb_key?: string | null;
|
||||||
|
annotated_key?: string | null;
|
||||||
width?: number | null;
|
width?: number | null;
|
||||||
height?: number | null;
|
height?: number | null;
|
||||||
status: string;
|
status: string;
|
||||||
taken_at: string;
|
taken_at: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function uploadPhotoAnnotation(
|
||||||
|
inspectionId: number,
|
||||||
|
photoId: number,
|
||||||
|
blob: Blob,
|
||||||
|
): Promise<PhotoConfirmResponse> {
|
||||||
|
const form = new FormData();
|
||||||
|
form.append("file", blob, "annotation.jpg");
|
||||||
|
return api
|
||||||
|
.post(`inspections/${inspectionId}/photos/${photoId}/annotation`, {
|
||||||
|
body: form,
|
||||||
|
})
|
||||||
|
.json<PhotoConfirmResponse>();
|
||||||
|
}
|
||||||
|
|
||||||
export async function requestUploadUrl(
|
export async function requestUploadUrl(
|
||||||
inspectionId: number,
|
inspectionId: number,
|
||||||
args: { side: string; slot_index: number; content_type: string; size: number }
|
args: { side: string; slot_index: number; content_type: string; size: number }
|
||||||
|
|||||||
@@ -0,0 +1,158 @@
|
|||||||
|
import { api } from "./client";
|
||||||
|
|
||||||
|
export interface CarBrief {
|
||||||
|
id: number;
|
||||||
|
plate: string;
|
||||||
|
brand: string | null;
|
||||||
|
model: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CarContext {
|
||||||
|
id: number;
|
||||||
|
plate: string;
|
||||||
|
brand: string | null;
|
||||||
|
model: string | null;
|
||||||
|
mileage_starline: number | null;
|
||||||
|
driver_id: number | null;
|
||||||
|
driver_name: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MechWork {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
category_id: number;
|
||||||
|
price: number | string;
|
||||||
|
norma_hours: number | string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PartSuggestion {
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PresignResponse {
|
||||||
|
photo_uuid: string;
|
||||||
|
extension: string;
|
||||||
|
content_type: string;
|
||||||
|
key: string;
|
||||||
|
upload_url: string;
|
||||||
|
expires_in: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreatePhotoPayload {
|
||||||
|
photo_uuid: string;
|
||||||
|
extension: string;
|
||||||
|
tag: "auto" | "part" | "other";
|
||||||
|
sort_order: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateWorkPayload {
|
||||||
|
work_catalog_id: number;
|
||||||
|
price_applied: number;
|
||||||
|
manual_override: boolean;
|
||||||
|
override_comment: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreatePartPayload {
|
||||||
|
name: string;
|
||||||
|
qty: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateOilChangePayload {
|
||||||
|
enabled: boolean;
|
||||||
|
mileage_at_change: number | null;
|
||||||
|
next_in_km: number;
|
||||||
|
sticker_photo_uuid: string | null;
|
||||||
|
sticker_extension: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ExternalCarPayload {
|
||||||
|
plate: string;
|
||||||
|
make: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateRepairPayload {
|
||||||
|
car_id?: number;
|
||||||
|
external_car?: ExternalCarPayload;
|
||||||
|
mileage: number | null;
|
||||||
|
works: CreateWorkPayload[];
|
||||||
|
parts: CreatePartPayload[];
|
||||||
|
photos: CreatePhotoPayload[];
|
||||||
|
oil_change: CreateOilChangePayload | null;
|
||||||
|
// Работавшие механики (делёж 1/N). Если не передан — backend сидит
|
||||||
|
// одного создателя. Порядок = sort_order.
|
||||||
|
mechanic_ids?: number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Ростер механиков (пикер «Механики») ────────────────────────────────────
|
||||||
|
|
||||||
|
export interface MechanicRosterItem {
|
||||||
|
id: number;
|
||||||
|
full_name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getMechanicsRoster(): Promise<MechanicRosterItem[]> {
|
||||||
|
// prefixUrl = /api/v1/mechanic, эндпоинт под роутером /v1/mechanic/repairs →
|
||||||
|
// путь обязан включать сегмент repairs/ (как и остальные вызовы файла).
|
||||||
|
return api.get("repairs/mechanics-roster").json<MechanicRosterItem[]>();
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateRepairResponse {
|
||||||
|
id: number;
|
||||||
|
created_at_iso: string;
|
||||||
|
tg_outbox_status: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function searchCars(q: string): Promise<CarBrief[]> {
|
||||||
|
const qs = q ? `?q=${encodeURIComponent(q)}` : "";
|
||||||
|
return api.get(`cars${qs}`).json<CarBrief[]>();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getCarContext(carId: number): Promise<CarContext> {
|
||||||
|
return api.get(`cars/${carId}/context`).json<CarContext>();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function searchWorks(q: string): Promise<MechWork[]> {
|
||||||
|
const qs = q ? `?q=${encodeURIComponent(q)}` : "";
|
||||||
|
return api.get(`works${qs}`).json<MechWork[]>();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function suggestParts(q: string): Promise<PartSuggestion[]> {
|
||||||
|
return api
|
||||||
|
.get(`parts/suggest?q=${encodeURIComponent(q)}`)
|
||||||
|
.json<PartSuggestion[]>();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function presignPhoto(extension: string, photo_uuid?: string): Promise<PresignResponse> {
|
||||||
|
return api
|
||||||
|
.post("repairs/photos/presign", {
|
||||||
|
json: { extension, photo_uuid: photo_uuid ?? null },
|
||||||
|
})
|
||||||
|
.json<PresignResponse>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Залить файл по presigned PUT. ВАЖНО: Content-Type ОБЯЗАН совпадать
|
||||||
|
* со значением, которое сервер вшил в подпись (см. У18 / sto_mechanic_form.py).
|
||||||
|
*/
|
||||||
|
export async function uploadPhotoToTmp(file: File | Blob, presign: PresignResponse): Promise<void> {
|
||||||
|
const res = await fetch(presign.upload_url, {
|
||||||
|
method: "PUT",
|
||||||
|
headers: { "Content-Type": presign.content_type },
|
||||||
|
body: file,
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`Photo upload failed: ${res.status} ${res.statusText}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createRepair(
|
||||||
|
payload: CreateRepairPayload,
|
||||||
|
idempotencyKey: string,
|
||||||
|
): Promise<CreateRepairResponse> {
|
||||||
|
return api
|
||||||
|
.post("repairs", {
|
||||||
|
json: payload,
|
||||||
|
headers: { "Idempotency-Key": idempotencyKey },
|
||||||
|
})
|
||||||
|
.json<CreateRepairResponse>();
|
||||||
|
}
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
import { api } from "./client";
|
||||||
|
|
||||||
|
export interface FeedWorkBrief {
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FeedItem {
|
||||||
|
id: number;
|
||||||
|
created_at: string; // ISO
|
||||||
|
car_plate: string;
|
||||||
|
car_make: string | null;
|
||||||
|
car_model: string | null;
|
||||||
|
driver_name: string | null;
|
||||||
|
mechanic_name: string;
|
||||||
|
is_external: boolean;
|
||||||
|
works_preview: FeedWorkBrief[];
|
||||||
|
works_extra: number;
|
||||||
|
works_total: number; // сумма работ без запчастей
|
||||||
|
photo_url: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FeedResponse {
|
||||||
|
items: FeedItem[];
|
||||||
|
next_cursor: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FeedParams {
|
||||||
|
limit?: number;
|
||||||
|
cursor?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getRepairsFeed(params: FeedParams = {}): Promise<FeedResponse> {
|
||||||
|
const search = new URLSearchParams();
|
||||||
|
if (params.limit) search.set("limit", String(params.limit));
|
||||||
|
if (params.cursor) search.set("cursor", params.cursor);
|
||||||
|
const qs = search.toString();
|
||||||
|
return api
|
||||||
|
.get(`repairs${qs ? `?${qs}` : ""}`)
|
||||||
|
.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 RepairDetailMechanic {
|
||||||
|
id: number;
|
||||||
|
mechanic_id: number;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
// Работавшие механики (делёж 1/N total_sum). Может отсутствовать на
|
||||||
|
// старых ответах backend — фронт делает fallback на одного создателя.
|
||||||
|
mechanics?: RepairDetailMechanic[];
|
||||||
|
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;
|
||||||
|
// Работавшие механики. Опционально — если не передан, набор не меняется.
|
||||||
|
mechanic_ids?: number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function patchRepair(id: number, body: PatchRepairPayload): Promise<RepairDetailResponse> {
|
||||||
|
return api.patch(`repairs/${id}`, { json: body }).json<RepairDetailResponse>();
|
||||||
|
}
|
||||||
@@ -8,10 +8,16 @@ export interface VehicleSummary {
|
|||||||
model?: string | null;
|
model?: string | null;
|
||||||
year?: number | null;
|
year?: number | null;
|
||||||
last_inspection_at?: string | null;
|
last_inspection_at?: string | null;
|
||||||
|
/** Текущий статус машины из 1C Element (cars_v2.element_status):
|
||||||
|
'На линии' / 'Простой' / 'Ремонтируется' / 'Ждет ремонта' / 'ДТП' /
|
||||||
|
'Бронь' / 'Выкуп' / 'На продаже' / etc. NULL если не задан. */
|
||||||
|
status?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface VehicleDetail extends VehicleSummary {
|
export interface VehicleDetail extends VehicleSummary {
|
||||||
recent_inspections: InspectionSummary[];
|
recent_inspections: InspectionSummary[];
|
||||||
|
starline_mileage?: number | null;
|
||||||
|
starline_mileage_at?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface InspectionSummary {
|
export interface InspectionSummary {
|
||||||
@@ -20,6 +26,13 @@ export interface InspectionSummary {
|
|||||||
status: string;
|
status: string;
|
||||||
started_at: string;
|
started_at: string;
|
||||||
finished_at?: string | null;
|
finished_at?: string | null;
|
||||||
|
mileage?: number | null;
|
||||||
|
photos_count?: number;
|
||||||
|
/** Водитель, прикреплённый к машине на момент started_at (lookup в
|
||||||
|
driver_rentals_v2 по car_number + перекрывающему периоду). NULL если
|
||||||
|
на тот момент машина была свободна. */
|
||||||
|
driver_id?: number | null;
|
||||||
|
driver_name?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function listVehicles(q?: string): Promise<VehicleSummary[]> {
|
export async function listVehicles(q?: string): Promise<VehicleSummary[]> {
|
||||||
@@ -34,3 +47,79 @@ export async function listVehicles(q?: string): Promise<VehicleSummary[]> {
|
|||||||
export async function getVehicle(id: number): Promise<VehicleDetail> {
|
export async function getVehicle(id: number): Promise<VehicleDetail> {
|
||||||
return api.get(`vehicles/${id}`).json<VehicleDetail>();
|
return api.get(`vehicles/${id}`).json<VehicleDetail>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── TT-Control vendor archive (Element Mechanic) ───────────────────────────
|
||||||
|
|
||||||
|
export interface TtStateSummary {
|
||||||
|
id: number;
|
||||||
|
vendor_state_id: string;
|
||||||
|
unix_time: number | null;
|
||||||
|
mechanic_name: string | null;
|
||||||
|
mileage: number | null;
|
||||||
|
photos_count: number;
|
||||||
|
damages_count: number;
|
||||||
|
/** Водитель, прикреплённый к машине на момент unix_time (lookup в
|
||||||
|
driver_rentals_v2 по car_number + перекрывающему/предыдущему периоду).
|
||||||
|
NULL если на тот момент машина была свободна. */
|
||||||
|
driver_id?: number | null;
|
||||||
|
driver_name?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TtHistory {
|
||||||
|
vendor_vehicle_id: string | null;
|
||||||
|
plate?: string | null;
|
||||||
|
brand?: string | null;
|
||||||
|
model?: string | null;
|
||||||
|
states: TtStateSummary[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TtPhotoRef {
|
||||||
|
image_id: string;
|
||||||
|
image_with_lines_id: string | null;
|
||||||
|
unix_time: number | null;
|
||||||
|
guid: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TtDamage {
|
||||||
|
damage_type_id: number | null;
|
||||||
|
degree: number | null;
|
||||||
|
points: { x: number; y: number }[];
|
||||||
|
guid: string | null;
|
||||||
|
unix_time: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TtSidePhoto {
|
||||||
|
image_id: string;
|
||||||
|
miniature_id: string | null;
|
||||||
|
photo_type: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TtStateDetail {
|
||||||
|
id: number;
|
||||||
|
vendor_state_id: string;
|
||||||
|
unix_time: number | null;
|
||||||
|
mechanic_name: string | null;
|
||||||
|
mileage: number | null;
|
||||||
|
side_photos: TtSidePhoto[];
|
||||||
|
photos_by_zone: Record<string, TtPhotoRef[]>;
|
||||||
|
damages_by_zone: Record<string, TtDamage[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getTtHistory(vehicleId: number): Promise<TtHistory> {
|
||||||
|
return api.get(`vehicles/${vehicleId}/tt-history`).json<TtHistory>();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getTtState(stateId: number): Promise<TtStateDetail> {
|
||||||
|
return api.get(`tt-states/${stateId}`).json<TtStateDetail>();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteTtState(stateId: number): Promise<void> {
|
||||||
|
await api.delete(`tt-states/${stateId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ttImageUrl(imageId: string, withLines: boolean = false): string {
|
||||||
|
// tt-image endpoint без auth-guard'а (vendor сам публично отдаёт эти JPEG'и),
|
||||||
|
// поэтому подходит для прямого <img src=...>.
|
||||||
|
const base = import.meta.env.VITE_API_BASE ?? "/api/v1/mechanic";
|
||||||
|
return `${base}/tt-image/${imageId}${withLines ? "?lines=true" : ""}`;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,121 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { loadDamageVocabulary, damageTypeRuToEnum } from "@/data/damageVocabulary";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
open: boolean;
|
||||||
|
zoneId: number;
|
||||||
|
zoneLabel: string;
|
||||||
|
pointsCount: number;
|
||||||
|
onCancel: () => void;
|
||||||
|
onSave: (data: { damageType: string; severity: 0 | 1 | 2 }) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function DamageClassifyDialog({ open, zoneId, zoneLabel, pointsCount, onCancel, onSave }: Props) {
|
||||||
|
const [vocab, setVocab] = useState<Awaited<ReturnType<typeof loadDamageVocabulary>> | null>(null);
|
||||||
|
const [damageType, setDamageType] = useState<string | null>(null);
|
||||||
|
const [severity, setSeverity] = useState<0 | 1 | 2>(0);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
setDamageType(null);
|
||||||
|
setSeverity(0);
|
||||||
|
loadDamageVocabulary().then(setVocab);
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
if (!open) return null;
|
||||||
|
|
||||||
|
// Salon zones (44=водительское сидение, 45=пассажирское, 46=задний диван) use salon_selectable; else exterior
|
||||||
|
const isSalon = zoneId === 44 || zoneId === 45 || zoneId === 46;
|
||||||
|
// Фильтруем типы для которых нет соответствия в backend DamageType enum —
|
||||||
|
// иначе backend вернёт 422 на createMarker.
|
||||||
|
const list = vocab
|
||||||
|
? (isSalon ? vocab.salon_selectable : vocab.exterior_selectable).filter(
|
||||||
|
(dt) => damageTypeRuToEnum(dt) != null,
|
||||||
|
)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 z-50 bg-black/40 flex items-end sm:items-center justify-center p-0 sm:p-4"
|
||||||
|
onClick={onCancel}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="w-full max-w-md bg-card rounded-t-2xl sm:rounded-2xl shadow-xl flex flex-col max-h-[90vh]"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<header className="p-5 border-b">
|
||||||
|
<h2 className="text-lg font-semibold capitalize">{zoneLabel}</h2>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Точек: {pointsCount}
|
||||||
|
</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div className="p-5 border-b space-y-3">
|
||||||
|
<Label>Степень повреждения</Label>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{([0, 1, 2] as const).map((idx) => {
|
||||||
|
const label = vocab?.severity_scale.labels[idx] ?? ["Лёгкое", "Среднее", "Тяжёлое"][idx];
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={idx}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setSeverity(idx)}
|
||||||
|
className={cn(
|
||||||
|
"flex-1 py-2 px-2 rounded-md text-sm font-medium border transition-colors",
|
||||||
|
severity === idx
|
||||||
|
? "bg-primary text-primary-foreground border-primary"
|
||||||
|
: "bg-background text-foreground hover:bg-accent"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 overflow-y-auto p-5 space-y-1.5">
|
||||||
|
<Label>Тип повреждения</Label>
|
||||||
|
{!vocab && <div className="text-sm text-muted-foreground">Загружаю…</div>}
|
||||||
|
{vocab && list.map((dt) => (
|
||||||
|
<label
|
||||||
|
key={dt}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-3 px-3 py-2.5 rounded-md cursor-pointer border transition-colors",
|
||||||
|
damageType === dt
|
||||||
|
? "bg-accent border-primary"
|
||||||
|
: "border-transparent hover:bg-accent/50"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="damage_type"
|
||||||
|
value={dt}
|
||||||
|
checked={damageType === dt}
|
||||||
|
onChange={() => setDamageType(dt)}
|
||||||
|
className="shrink-0"
|
||||||
|
/>
|
||||||
|
<span className="text-sm">{dt}</span>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<footer className="p-5 border-t flex gap-2">
|
||||||
|
<Button variant="outline" onClick={onCancel} className="flex-1">
|
||||||
|
Отмена
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
disabled={!damageType}
|
||||||
|
onClick={() => damageType && onSave({ damageType, severity })}
|
||||||
|
className="flex-1"
|
||||||
|
>
|
||||||
|
Сохранить
|
||||||
|
</Button>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
photoFile: File;
|
||||||
|
zoneLabel: string;
|
||||||
|
/** Called when user submits. annotated=null если "без линий". */
|
||||||
|
onSubmit: (annotated: Blob | null) => void | Promise<void>;
|
||||||
|
onCancel: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Stroke {
|
||||||
|
pts: { x: number; y: number }[]; // in image-space pixels
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pen-on-photo step: показывает только что снятое фото, даёт обвести
|
||||||
|
* пальцем красным. Flatten в JPEG при submit. Координаты strokes в native
|
||||||
|
* пикселях фото — canvas resize'нут на тот же размер. */
|
||||||
|
export function PhotoAnnotateStep({ photoFile, zoneLabel, onSubmit, onCancel }: Props) {
|
||||||
|
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||||
|
const imgRef = useRef<HTMLImageElement | null>(null);
|
||||||
|
const [imgLoaded, setImgLoaded] = useState(false);
|
||||||
|
const [strokes, setStrokes] = useState<Stroke[]>([]);
|
||||||
|
const currentStroke = useRef<Stroke | null>(null);
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
|
||||||
|
// Load image once
|
||||||
|
useEffect(() => {
|
||||||
|
const url = URL.createObjectURL(photoFile);
|
||||||
|
const img = new Image();
|
||||||
|
img.onload = () => {
|
||||||
|
imgRef.current = img;
|
||||||
|
const canvas = canvasRef.current;
|
||||||
|
if (canvas) {
|
||||||
|
canvas.width = img.naturalWidth;
|
||||||
|
canvas.height = img.naturalHeight;
|
||||||
|
}
|
||||||
|
setImgLoaded(true);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
redraw([]);
|
||||||
|
};
|
||||||
|
img.onerror = () => URL.revokeObjectURL(url);
|
||||||
|
img.src = url;
|
||||||
|
return () => {
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
};
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [photoFile]);
|
||||||
|
|
||||||
|
function redraw(allStrokes: Stroke[]) {
|
||||||
|
const canvas = canvasRef.current;
|
||||||
|
const img = imgRef.current;
|
||||||
|
if (!canvas || !img) return;
|
||||||
|
const ctx = canvas.getContext("2d");
|
||||||
|
if (!ctx) return;
|
||||||
|
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||||
|
// Linewidth scaled to image — на 4К фото 4px тонко смотрится
|
||||||
|
const lw = Math.max(6, Math.round(canvas.width / 250));
|
||||||
|
ctx.strokeStyle = "rgb(220, 38, 38)";
|
||||||
|
ctx.lineWidth = lw;
|
||||||
|
ctx.lineCap = "round";
|
||||||
|
ctx.lineJoin = "round";
|
||||||
|
for (const s of allStrokes) {
|
||||||
|
if (s.pts.length < 2) {
|
||||||
|
// single tap → dot
|
||||||
|
if (s.pts.length === 1) {
|
||||||
|
ctx.fillStyle = "rgb(220, 38, 38)";
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(s.pts[0].x, s.pts[0].y, lw / 2, 0, Math.PI * 2);
|
||||||
|
ctx.fill();
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(s.pts[0].x, s.pts[0].y);
|
||||||
|
for (let i = 1; i < s.pts.length; i++) {
|
||||||
|
ctx.lineTo(s.pts[i].x, s.pts[i].y);
|
||||||
|
}
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-draw whenever strokes change
|
||||||
|
useEffect(() => {
|
||||||
|
if (imgLoaded) redraw(strokes);
|
||||||
|
}, [strokes, imgLoaded]);
|
||||||
|
|
||||||
|
function pointFromEvent(e: React.PointerEvent<HTMLCanvasElement>): { x: number; y: number } | null {
|
||||||
|
const canvas = canvasRef.current;
|
||||||
|
if (!canvas) return null;
|
||||||
|
const rect = canvas.getBoundingClientRect();
|
||||||
|
if (rect.width === 0 || rect.height === 0) return null;
|
||||||
|
// CSS px → canvas px
|
||||||
|
const x = ((e.clientX - rect.left) / rect.width) * canvas.width;
|
||||||
|
const y = ((e.clientY - rect.top) / rect.height) * canvas.height;
|
||||||
|
return { x, y };
|
||||||
|
}
|
||||||
|
|
||||||
|
function onPointerDown(e: React.PointerEvent<HTMLCanvasElement>) {
|
||||||
|
e.preventDefault();
|
||||||
|
(e.target as HTMLCanvasElement).setPointerCapture(e.pointerId);
|
||||||
|
const pt = pointFromEvent(e);
|
||||||
|
if (!pt) return;
|
||||||
|
currentStroke.current = { pts: [pt] };
|
||||||
|
// Immediate visual feedback: draw a partial stroke without setState
|
||||||
|
drawPartialStroke(currentStroke.current);
|
||||||
|
}
|
||||||
|
|
||||||
|
function onPointerMove(e: React.PointerEvent<HTMLCanvasElement>) {
|
||||||
|
if (!currentStroke.current) return;
|
||||||
|
const pt = pointFromEvent(e);
|
||||||
|
if (!pt) return;
|
||||||
|
currentStroke.current.pts.push(pt);
|
||||||
|
drawPartialStroke(currentStroke.current);
|
||||||
|
}
|
||||||
|
|
||||||
|
function onPointerUp(e: React.PointerEvent<HTMLCanvasElement>) {
|
||||||
|
if (!currentStroke.current) return;
|
||||||
|
try {
|
||||||
|
(e.target as HTMLCanvasElement).releasePointerCapture(e.pointerId);
|
||||||
|
} catch {
|
||||||
|
// ignore — pointer wasn't captured
|
||||||
|
}
|
||||||
|
const finished = currentStroke.current;
|
||||||
|
currentStroke.current = null;
|
||||||
|
if (finished.pts.length > 0) {
|
||||||
|
setStrokes((s) => [...s, finished]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Avoid re-running full redraw on every move — just append last segment. */
|
||||||
|
function drawPartialStroke(s: Stroke) {
|
||||||
|
const canvas = canvasRef.current;
|
||||||
|
if (!canvas || s.pts.length < 2) return;
|
||||||
|
const ctx = canvas.getContext("2d");
|
||||||
|
if (!ctx) return;
|
||||||
|
const lw = Math.max(6, Math.round(canvas.width / 250));
|
||||||
|
ctx.strokeStyle = "rgb(220, 38, 38)";
|
||||||
|
ctx.lineWidth = lw;
|
||||||
|
ctx.lineCap = "round";
|
||||||
|
ctx.lineJoin = "round";
|
||||||
|
const a = s.pts[s.pts.length - 2];
|
||||||
|
const b = s.pts[s.pts.length - 1];
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(a.x, a.y);
|
||||||
|
ctx.lineTo(b.x, b.y);
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearAll() {
|
||||||
|
setStrokes([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function undoLast() {
|
||||||
|
setStrokes((s) => s.slice(0, -1));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function finishWithAnnotation() {
|
||||||
|
const canvas = canvasRef.current;
|
||||||
|
if (!canvas) return;
|
||||||
|
setSubmitting(true);
|
||||||
|
try {
|
||||||
|
const blob = await new Promise<Blob | null>((resolve) =>
|
||||||
|
canvas.toBlob(resolve, "image/jpeg", 0.85)
|
||||||
|
);
|
||||||
|
await onSubmit(blob);
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function finishWithoutAnnotation() {
|
||||||
|
setSubmitting(true);
|
||||||
|
try {
|
||||||
|
await onSubmit(null);
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-50 bg-background flex flex-col">
|
||||||
|
<header className="p-4 border-b flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<div className="text-xs text-muted-foreground">Обведите повреждение</div>
|
||||||
|
<h2 className="text-lg font-semibold capitalize">{zoneLabel}</h2>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button
|
||||||
|
onClick={undoLast}
|
||||||
|
disabled={strokes.length === 0 || submitting}
|
||||||
|
className="text-sm px-3 py-1 border rounded-md disabled:opacity-40"
|
||||||
|
title="Отменить последний штрих"
|
||||||
|
>
|
||||||
|
↶
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={clearAll}
|
||||||
|
disabled={strokes.length === 0 || submitting}
|
||||||
|
className="text-sm px-3 py-1 border rounded-md disabled:opacity-40"
|
||||||
|
title="Очистить"
|
||||||
|
>
|
||||||
|
Очистить
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main className="flex-1 overflow-auto p-2 flex items-center justify-center bg-black">
|
||||||
|
<canvas
|
||||||
|
ref={canvasRef}
|
||||||
|
onPointerDown={onPointerDown}
|
||||||
|
onPointerMove={onPointerMove}
|
||||||
|
onPointerUp={onPointerUp}
|
||||||
|
onPointerCancel={onPointerUp}
|
||||||
|
className="max-w-full max-h-full block"
|
||||||
|
style={{ touchAction: "none", cursor: "crosshair" }}
|
||||||
|
/>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<footer className="border-t p-3 flex gap-2 bg-card">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={onCancel}
|
||||||
|
disabled={submitting}
|
||||||
|
className="flex-none"
|
||||||
|
>
|
||||||
|
Назад
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={finishWithoutAnnotation}
|
||||||
|
disabled={submitting}
|
||||||
|
className="flex-1"
|
||||||
|
>
|
||||||
|
Без линий
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={finishWithAnnotation}
|
||||||
|
disabled={submitting || strokes.length === 0}
|
||||||
|
className="flex-1"
|
||||||
|
>
|
||||||
|
{submitting ? "Сохраняю…" : "Готово"}
|
||||||
|
</Button>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
open: boolean;
|
||||||
|
zoneLabel: string;
|
||||||
|
onConfirm: () => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ZoneConfirmDialog({ open, zoneLabel, onConfirm, onCancel }: Props) {
|
||||||
|
if (!open) return null;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 z-50 bg-black/40 flex items-end sm:items-center justify-center p-0 sm:p-4"
|
||||||
|
onClick={onCancel}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="w-full max-w-sm bg-card rounded-t-2xl sm:rounded-2xl shadow-xl p-6 space-y-5"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<h2 className="text-lg font-semibold">Добавить повреждение</h2>
|
||||||
|
<p className="text-sm text-muted-foreground mt-1 capitalize">
|
||||||
|
{zoneLabel}?
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button variant="outline" onClick={onCancel} className="flex-1">
|
||||||
|
Нет
|
||||||
|
</Button>
|
||||||
|
<Button onClick={onConfirm} className="flex-1">
|
||||||
|
Да
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,307 @@
|
|||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
interface Point {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ZoneBBox {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
w: number;
|
||||||
|
h: number;
|
||||||
|
rotation?: number; // degrees, 0 / 90 / -90 / 180
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
open: boolean;
|
||||||
|
zoneId: number;
|
||||||
|
zoneLabel: string;
|
||||||
|
onConfirm: (points: Point[]) => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PADDING = 0.1;
|
||||||
|
const COMPOSITE_W = 827;
|
||||||
|
const COMPOSITE_H = 1209;
|
||||||
|
const SVG_NS = "http://www.w3.org/2000/svg";
|
||||||
|
const POINT_RADIUS = 18; // user-space units; visible on zoomed views
|
||||||
|
|
||||||
|
let bboxCache: Record<string, ZoneBBox> | null = null;
|
||||||
|
|
||||||
|
async function loadBBoxes(): Promise<Record<string, ZoneBBox>> {
|
||||||
|
if (bboxCache) return bboxCache;
|
||||||
|
const res = await fetch("/data/zone_bboxes.json");
|
||||||
|
bboxCache = await res.json();
|
||||||
|
return bboxCache!;
|
||||||
|
}
|
||||||
|
|
||||||
|
function paddedViewBox(b: ZoneBBox): string {
|
||||||
|
const rotation = b.rotation ?? 0;
|
||||||
|
const cx = b.x + b.w / 2;
|
||||||
|
const cy = b.y + b.h / 2;
|
||||||
|
let w = b.w;
|
||||||
|
let h = b.h;
|
||||||
|
if (rotation === 90 || rotation === -90) {
|
||||||
|
w = b.h;
|
||||||
|
h = b.w;
|
||||||
|
}
|
||||||
|
const padX = w * PADDING;
|
||||||
|
const padY = h * PADDING;
|
||||||
|
const minX = cx - w / 2 - padX;
|
||||||
|
const minY = cy - h / 2 - padY;
|
||||||
|
return `${minX} ${minY} ${w + 2 * padX} ${h + 2 * padY}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function rotationTransform(b: ZoneBBox): string | null {
|
||||||
|
const rotation = b.rotation ?? 0;
|
||||||
|
if (rotation === 0) return null;
|
||||||
|
const cx = b.x + b.w / 2;
|
||||||
|
const cy = b.y + b.h / 2;
|
||||||
|
return `rotate(${rotation} ${cx} ${cy})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ZoneDetailView({ open, zoneId, zoneLabel, onConfirm, onCancel }: Props) {
|
||||||
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const [svgText, setSvgText] = useState<string | null>(null);
|
||||||
|
const [points, setPoints] = useState<Point[]>([]);
|
||||||
|
|
||||||
|
// Load SVG + bboxes
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
setPoints([]);
|
||||||
|
setSvgText(null);
|
||||||
|
let cancelled = false;
|
||||||
|
|
||||||
|
Promise.all([
|
||||||
|
fetch("/scheme/exterior.svg").then((r) => r.text()),
|
||||||
|
loadBBoxes(),
|
||||||
|
]).then(([text, bboxes]) => {
|
||||||
|
if (cancelled) return;
|
||||||
|
const b = bboxes[String(zoneId)];
|
||||||
|
const finalVB = b ? paddedViewBox(b) : `0 0 ${COMPOSITE_W} ${COMPOSITE_H}`;
|
||||||
|
const rotXform = b ? rotationTransform(b) : null;
|
||||||
|
|
||||||
|
let mutated = text;
|
||||||
|
mutated = mutated.replace(/<script[\s\S]*?<\/script>/gi, "");
|
||||||
|
mutated = mutated.replace(/(<svg\b[^>]*?)\sviewBox\s*=\s*"[^"]*"/i, `$1 viewBox="${finalVB}"`);
|
||||||
|
mutated = mutated.replace(
|
||||||
|
/(<svg\b[^>]*?)\s(?:width|height)\s*=\s*"[^"]*"/gi,
|
||||||
|
"$1"
|
||||||
|
);
|
||||||
|
mutated = mutated.replace(
|
||||||
|
/<svg\b/i,
|
||||||
|
`<svg width="100%" height="100%" preserveAspectRatio="xMidYMid meet"`
|
||||||
|
);
|
||||||
|
// Wrap inner content in rotated <g> so visible orientation is correct.
|
||||||
|
// We always wrap (even with identity rotation) so the point-overlay <g>
|
||||||
|
// append target is consistent.
|
||||||
|
const openMatch = mutated.match(/<svg\b[^>]*?>/i);
|
||||||
|
const closeIdx = mutated.lastIndexOf("</svg>");
|
||||||
|
if (openMatch && closeIdx > -1) {
|
||||||
|
const openEnd = (openMatch.index ?? 0) + openMatch[0].length;
|
||||||
|
const before = mutated.slice(0, openEnd);
|
||||||
|
const inner = mutated.slice(openEnd, closeIdx);
|
||||||
|
const after = mutated.slice(closeIdx);
|
||||||
|
const xform = rotXform ? ` transform="${rotXform}"` : "";
|
||||||
|
mutated = `${before}<g data-rot="1"${xform}>${inner}</g>${after}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
setSvgText(mutated);
|
||||||
|
});
|
||||||
|
return () => { cancelled = true; };
|
||||||
|
}, [open, zoneId]);
|
||||||
|
|
||||||
|
// After SVG mounts, apply fill highlights
|
||||||
|
useEffect(() => {
|
||||||
|
if (!svgText) return;
|
||||||
|
const el = containerRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
const svg = el.querySelector("svg") as SVGSVGElement | null;
|
||||||
|
if (!svg) return;
|
||||||
|
|
||||||
|
svg.querySelectorAll("path[class]").forEach((p) => {
|
||||||
|
const cls = p.getAttribute("class") ?? "";
|
||||||
|
if (cls === String(zoneId)) {
|
||||||
|
p.setAttribute("fill", "rgba(239, 68, 68, 0.18)");
|
||||||
|
p.setAttribute("stroke", "rgb(239, 68, 68)");
|
||||||
|
p.setAttribute("stroke-width", "2");
|
||||||
|
} else {
|
||||||
|
p.setAttribute("fill", "rgba(0,0,0,0.04)");
|
||||||
|
p.setAttribute("stroke", "rgba(0,0,0,0.25)");
|
||||||
|
}
|
||||||
|
(p as SVGElement).style.pointerEvents = "none";
|
||||||
|
});
|
||||||
|
svg.querySelectorAll("path:not([class])").forEach((p) => {
|
||||||
|
(p as SVGElement).style.opacity = "0.4";
|
||||||
|
(p as SVGElement).style.pointerEvents = "none";
|
||||||
|
});
|
||||||
|
}, [svgText, zoneId]);
|
||||||
|
|
||||||
|
// Imperatively render points as SVG circles inside the rotated <g>.
|
||||||
|
// This guarantees they sit at the exact same place as the SVG content,
|
||||||
|
// regardless of letterboxing / aspect-ratio.
|
||||||
|
useEffect(() => {
|
||||||
|
const el = containerRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
const svg = el.querySelector("svg") as SVGSVGElement | null;
|
||||||
|
if (!svg) return;
|
||||||
|
const rotGroup = svg.querySelector("g[data-rot]") as SVGGElement | null;
|
||||||
|
if (!rotGroup) return;
|
||||||
|
|
||||||
|
// Remove existing overlay group if any
|
||||||
|
const existing = rotGroup.querySelector("g[data-points]");
|
||||||
|
if (existing) existing.remove();
|
||||||
|
|
||||||
|
// Build new overlay group
|
||||||
|
const group = document.createElementNS(SVG_NS, "g");
|
||||||
|
group.setAttribute("data-points", "1");
|
||||||
|
|
||||||
|
points.forEach((p, i) => {
|
||||||
|
const cx = p.x * COMPOSITE_W;
|
||||||
|
const cy = p.y * COMPOSITE_H;
|
||||||
|
const circle = document.createElementNS(SVG_NS, "circle");
|
||||||
|
circle.setAttribute("cx", String(cx));
|
||||||
|
circle.setAttribute("cy", String(cy));
|
||||||
|
circle.setAttribute("r", String(POINT_RADIUS));
|
||||||
|
circle.setAttribute("fill", "rgb(239, 68, 68)");
|
||||||
|
circle.setAttribute("stroke", "white");
|
||||||
|
circle.setAttribute("stroke-width", "3");
|
||||||
|
circle.setAttribute("data-point-index", String(i));
|
||||||
|
(circle as SVGElement).style.cursor = "pointer";
|
||||||
|
group.appendChild(circle);
|
||||||
|
|
||||||
|
const text = document.createElementNS(SVG_NS, "text");
|
||||||
|
text.setAttribute("x", String(cx));
|
||||||
|
text.setAttribute("y", String(cy));
|
||||||
|
text.setAttribute("text-anchor", "middle");
|
||||||
|
text.setAttribute("dominant-baseline", "central");
|
||||||
|
text.setAttribute("fill", "white");
|
||||||
|
text.setAttribute("font-size", "20");
|
||||||
|
text.setAttribute("font-weight", "bold");
|
||||||
|
text.setAttribute("data-point-label", String(i));
|
||||||
|
(text as SVGElement).style.pointerEvents = "none";
|
||||||
|
(text as SVGElement).style.userSelect = "none";
|
||||||
|
text.textContent = String(i + 1);
|
||||||
|
group.appendChild(text);
|
||||||
|
});
|
||||||
|
|
||||||
|
rotGroup.appendChild(group);
|
||||||
|
}, [svgText, points]);
|
||||||
|
|
||||||
|
function handleTap(e: React.MouseEvent<HTMLDivElement>) {
|
||||||
|
// If user clicked an existing point circle, remove it (if it's the last one)
|
||||||
|
const target = e.target as Element;
|
||||||
|
const pointIdxAttr = target.getAttribute?.("data-point-index");
|
||||||
|
if (pointIdxAttr != null) {
|
||||||
|
const idx = Number(pointIdxAttr);
|
||||||
|
if (idx === points.length - 1) {
|
||||||
|
setPoints((p) => p.slice(0, -1));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const el = containerRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
const svg = el.querySelector("svg") as SVGSVGElement | null;
|
||||||
|
if (!svg) return;
|
||||||
|
|
||||||
|
// getScreenCTM gives matrix from SVG root user-space to screen pixels.
|
||||||
|
// It does NOT include inner <g> transforms — so svgPt is in the rotated viewBox frame.
|
||||||
|
const pt = svg.createSVGPoint();
|
||||||
|
pt.x = e.clientX;
|
||||||
|
pt.y = e.clientY;
|
||||||
|
const ctm = svg.getScreenCTM();
|
||||||
|
if (!ctm) return;
|
||||||
|
const svgPt = pt.matrixTransform(ctm.inverse());
|
||||||
|
|
||||||
|
// Convert from the visible (rotated) frame back to the original composite frame
|
||||||
|
// so storage is in a canonical coord system.
|
||||||
|
const bboxes = bboxCache;
|
||||||
|
const b = bboxes?.[String(zoneId)] ?? null;
|
||||||
|
const original = b
|
||||||
|
? inverseRotateAroundBboxCenter({ x: svgPt.x, y: svgPt.y }, b)
|
||||||
|
: { x: svgPt.x, y: svgPt.y };
|
||||||
|
|
||||||
|
const xN = Math.max(0, Math.min(1, original.x / COMPOSITE_W));
|
||||||
|
const yN = Math.max(0, Math.min(1, original.y / COMPOSITE_H));
|
||||||
|
setPoints((prev) => [...prev, { x: xN, y: yN }]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!open) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-50 bg-background flex flex-col">
|
||||||
|
<header className="flex items-center justify-between p-4 border-b">
|
||||||
|
<div>
|
||||||
|
<div className="text-xs text-muted-foreground">Зона</div>
|
||||||
|
<h2 className="text-lg font-semibold capitalize">{zoneLabel}</h2>
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-muted-foreground">
|
||||||
|
Точек: <span className="font-semibold text-foreground">{points.length}</span>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main className="flex-1 overflow-hidden relative bg-card">
|
||||||
|
<div
|
||||||
|
ref={containerRef}
|
||||||
|
onClick={handleTap}
|
||||||
|
className="w-full h-full"
|
||||||
|
style={{ touchAction: "manipulation" }}
|
||||||
|
dangerouslySetInnerHTML={svgText ? { __html: svgText } : undefined}
|
||||||
|
/>
|
||||||
|
{!svgText && (
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center text-sm text-muted-foreground pointer-events-none">
|
||||||
|
Загружаю схему…
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<footer className="border-t p-3 flex items-center gap-3 bg-card">
|
||||||
|
<button
|
||||||
|
onClick={onCancel}
|
||||||
|
className="flex-1 flex items-center justify-center gap-2 py-3 rounded-lg border border-destructive text-destructive hover:bg-destructive/10 active:bg-destructive/20 transition-colors font-semibold"
|
||||||
|
aria-label="Отмена"
|
||||||
|
>
|
||||||
|
<span className="text-2xl leading-none">✕</span>
|
||||||
|
<span>Отмена</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => onConfirm(points)}
|
||||||
|
disabled={points.length === 0}
|
||||||
|
className={cn(
|
||||||
|
"flex-1 flex items-center justify-center gap-2 py-3 rounded-lg font-semibold transition-colors",
|
||||||
|
points.length === 0
|
||||||
|
? "bg-muted text-muted-foreground"
|
||||||
|
: "bg-primary text-primary-foreground hover:opacity-90 active:opacity-80"
|
||||||
|
)}
|
||||||
|
aria-label="Готово"
|
||||||
|
>
|
||||||
|
<span className="text-2xl leading-none">✓</span>
|
||||||
|
<span>Готово ({points.length})</span>
|
||||||
|
</button>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Convert tap point from rotated/visible viewBox frame back to original composite frame. */
|
||||||
|
function inverseRotateAroundBboxCenter(
|
||||||
|
pt: { x: number; y: number },
|
||||||
|
b: ZoneBBox
|
||||||
|
): { x: number; y: number } {
|
||||||
|
const rot = b.rotation ?? 0;
|
||||||
|
if (rot === 0) return pt;
|
||||||
|
const cx = b.x + b.w / 2;
|
||||||
|
const cy = b.y + b.h / 2;
|
||||||
|
const dx = pt.x - cx;
|
||||||
|
const dy = pt.y - cy;
|
||||||
|
const rad = (-rot * Math.PI) / 180;
|
||||||
|
const cos = Math.cos(rad);
|
||||||
|
const sin = Math.sin(rad);
|
||||||
|
return {
|
||||||
|
x: cx + dx * cos - dy * sin,
|
||||||
|
y: cy + dx * sin + dy * cos,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useMutation } from "@tanstack/react-query";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { CameraCapture } from "@/components/camera/CameraCapture";
|
||||||
|
import { AuthImg } from "@/components/AuthImg";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { uploadPhoto } from "@/api/photos";
|
||||||
|
import { createMarker, type MarkerSummary } from "@/api/inspections";
|
||||||
|
|
||||||
|
const WEAR_LEVELS: { value: string; label: string; description: string }[] = [
|
||||||
|
{
|
||||||
|
value: "cosmetic",
|
||||||
|
label: "Новая",
|
||||||
|
description: "Протектор полный, без признаков износа",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: "minor",
|
||||||
|
label: "Норма",
|
||||||
|
description: "Естественный износ, эксплуатация в норме",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: "moderate",
|
||||||
|
label: "Износ",
|
||||||
|
description: "Заметный износ, требует наблюдения",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: "severe",
|
||||||
|
label: "Менять",
|
||||||
|
description: "Критический износ, замена необходима",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
open: boolean;
|
||||||
|
inspectionId: number;
|
||||||
|
onClose: () => void;
|
||||||
|
onCreated: (marker: MarkerSummary) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TireWearDialog({
|
||||||
|
open,
|
||||||
|
inspectionId,
|
||||||
|
onClose,
|
||||||
|
onCreated,
|
||||||
|
}: Props) {
|
||||||
|
const [level, setLevel] = useState<string>("minor");
|
||||||
|
const [description, setDescription] = useState("");
|
||||||
|
const [photoId, setPhotoId] = useState<number | undefined>(undefined);
|
||||||
|
const [uploading, setUploading] = useState(false);
|
||||||
|
|
||||||
|
async function handlePhoto(file: File) {
|
||||||
|
setUploading(true);
|
||||||
|
try {
|
||||||
|
const result = await uploadPhoto(inspectionId, "free", 0, file);
|
||||||
|
setPhotoId(result.id);
|
||||||
|
toast.success("Фото загружено");
|
||||||
|
} catch {
|
||||||
|
toast.error("Ошибка загрузки фото");
|
||||||
|
} finally {
|
||||||
|
setUploading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const createMut = useMutation({
|
||||||
|
mutationFn: () =>
|
||||||
|
createMarker(inspectionId, {
|
||||||
|
side: "tires",
|
||||||
|
severity: level,
|
||||||
|
// "not-working" is the closest existing damage_type enum value.
|
||||||
|
// The semantically meaningful field here is `severity` (wear level).
|
||||||
|
damage_type: "not-working",
|
||||||
|
description:
|
||||||
|
description.trim() ||
|
||||||
|
`Состояние резины: ${WEAR_LEVELS.find((w) => w.value === level)?.label ?? level}`,
|
||||||
|
photo_id: photoId,
|
||||||
|
x: null,
|
||||||
|
y: null,
|
||||||
|
}),
|
||||||
|
onSuccess: (marker) => {
|
||||||
|
onCreated(marker);
|
||||||
|
reset();
|
||||||
|
},
|
||||||
|
onError: () => toast.error("Не удалось сохранить"),
|
||||||
|
});
|
||||||
|
|
||||||
|
function reset() {
|
||||||
|
setLevel("minor");
|
||||||
|
setDescription("");
|
||||||
|
setPhotoId(undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleClose() {
|
||||||
|
reset();
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!open) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 z-50 bg-black/40 flex items-end sm:items-center justify-center p-0 sm:p-4"
|
||||||
|
onClick={handleClose}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="w-full max-w-md bg-card rounded-t-2xl sm:rounded-2xl shadow-xl p-5 space-y-4 max-h-[90vh] overflow-y-auto"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<h2 className="text-lg font-semibold">Состояние резины</h2>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleClose}
|
||||||
|
className="text-muted-foreground hover:text-foreground text-2xl leading-none"
|
||||||
|
aria-label="Закрыть"
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Wear level — radio cards for large touch targets */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Уровень износа</Label>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{WEAR_LEVELS.map((w) => (
|
||||||
|
<label
|
||||||
|
key={w.value}
|
||||||
|
className={
|
||||||
|
"flex items-start gap-3 rounded-lg border p-3 cursor-pointer transition-colors " +
|
||||||
|
(level === w.value
|
||||||
|
? "border-primary bg-accent"
|
||||||
|
: "border-input hover:bg-accent/50")
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="tire_wear"
|
||||||
|
value={w.value}
|
||||||
|
checked={level === w.value}
|
||||||
|
onChange={() => setLevel(w.value)}
|
||||||
|
className="mt-0.5 shrink-0"
|
||||||
|
/>
|
||||||
|
<div>
|
||||||
|
<div className="font-medium text-sm">{w.label}</div>
|
||||||
|
<div className="text-xs text-muted-foreground">
|
||||||
|
{w.description}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Optional comment */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="tire_comment">Комментарий (опционально)</Label>
|
||||||
|
<Input
|
||||||
|
id="tire_comment"
|
||||||
|
value={description}
|
||||||
|
onChange={(e) => setDescription(e.target.value)}
|
||||||
|
placeholder="Например: глубина протектора ~3 мм"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Optional photo */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Фото (опционально)</Label>
|
||||||
|
{photoId ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<AuthImg
|
||||||
|
src={`photos/${photoId}/thumb`}
|
||||||
|
alt="Фото резины"
|
||||||
|
className="w-full aspect-[4/3] object-cover rounded bg-muted"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setPhotoId(undefined)}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
|
Удалить фото
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<CameraCapture
|
||||||
|
onCapture={handlePhoto}
|
||||||
|
buttonLabel={uploading ? "Загружаю…" : "Сделать фото"}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Actions */}
|
||||||
|
<div className="flex gap-2 pt-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={handleClose}
|
||||||
|
className="flex-1"
|
||||||
|
>
|
||||||
|
Отмена
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
disabled={createMut.isPending || uploading}
|
||||||
|
onClick={() => createMut.mutate()}
|
||||||
|
className="flex-1"
|
||||||
|
>
|
||||||
|
{createMut.isPending ? "Сохраняю…" : "Сохранить"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
/**
|
||||||
|
* Блок «Механики» формы ремонта — чипы работавших механиков + кнопка
|
||||||
|
* «Добавить механика» (пикер из ростера) + удаление чипа.
|
||||||
|
*
|
||||||
|
* Делёж оплаты — поровну (1/N): доля каждого механика = total_sum / N.
|
||||||
|
* Здесь показывается информативно (сумма на чел.), если передан totalSum.
|
||||||
|
*
|
||||||
|
* Состояние выбора живёт в родителе (как у WorksPickerModal): сюда
|
||||||
|
* приходит value + onChange. Ростер компонент тянет сам при первом
|
||||||
|
* открытии пикера (лениво) и кэширует на время жизни.
|
||||||
|
*/
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Plus, X } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { fmtMoney } from "@/lib/repairsFeed";
|
||||||
|
import { getMechanicsRoster, type MechanicRosterItem } from "@/api/repairsCreate";
|
||||||
|
|
||||||
|
export interface SelectedMechanic {
|
||||||
|
mechanic_id: number;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
value: SelectedMechanic[];
|
||||||
|
onChange: (next: SelectedMechanic[]) => void;
|
||||||
|
// Если задан и механиков >0 — показываем долю (1/N · totalSum).
|
||||||
|
totalSum?: number;
|
||||||
|
disabled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function MechanicsField({ value, onChange, totalSum, disabled }: Props) {
|
||||||
|
const [pickerOpen, setPickerOpen] = useState(false);
|
||||||
|
const [roster, setRoster] = useState<MechanicRosterItem[] | null>(null);
|
||||||
|
const [rosterError, setRosterError] = useState<string | null>(null);
|
||||||
|
const [q, setQ] = useState("");
|
||||||
|
|
||||||
|
const openPicker = async () => {
|
||||||
|
setPickerOpen(true);
|
||||||
|
if (roster) return;
|
||||||
|
try {
|
||||||
|
const list = await getMechanicsRoster();
|
||||||
|
setRoster(list);
|
||||||
|
setRosterError(null);
|
||||||
|
} catch (e) {
|
||||||
|
setRosterError((e as Error).message || "Не удалось загрузить список механиков");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const addMechanic = (m: MechanicRosterItem) => {
|
||||||
|
// Дедуп: один механик один раз (UNIQUE на бэке).
|
||||||
|
if (!value.some((v) => v.mechanic_id === m.id)) {
|
||||||
|
onChange([...value, { mechanic_id: m.id, name: m.full_name }]);
|
||||||
|
}
|
||||||
|
setPickerOpen(false);
|
||||||
|
setQ("");
|
||||||
|
};
|
||||||
|
|
||||||
|
const removeMechanic = (mechanicId: number) =>
|
||||||
|
onChange(value.filter((v) => v.mechanic_id !== mechanicId));
|
||||||
|
|
||||||
|
const share =
|
||||||
|
totalSum != null && value.length > 0 ? Math.round(totalSum / value.length) : null;
|
||||||
|
|
||||||
|
const filtered = (roster ?? []).filter((m) =>
|
||||||
|
q.trim() ? m.full_name.toLowerCase().includes(q.trim().toLowerCase()) : true,
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section>
|
||||||
|
<div className="flex items-baseline justify-between">
|
||||||
|
<Label className="text-sm">Механики</Label>
|
||||||
|
{!disabled && (
|
||||||
|
<Button variant="outline" size="sm" onClick={openPicker}>
|
||||||
|
<Plus className="h-3 w-3 mr-1" />
|
||||||
|
Добавить механика
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{value.length === 0 ? (
|
||||||
|
<div className="text-xs text-muted-foreground mt-2">Минимум один механик</div>
|
||||||
|
) : (
|
||||||
|
<div className="mt-2 flex flex-wrap gap-2">
|
||||||
|
{value.map((m) => (
|
||||||
|
<span
|
||||||
|
key={m.mechanic_id}
|
||||||
|
className="inline-flex items-center gap-1.5 rounded-full border bg-muted/50 pl-3 pr-1.5 py-1 text-sm"
|
||||||
|
>
|
||||||
|
<span className="leading-none">{m.name}</span>
|
||||||
|
{!disabled && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => removeMechanic(m.mechanic_id)}
|
||||||
|
className="rounded-full p-0.5 hover:bg-accent text-muted-foreground"
|
||||||
|
aria-label={`Убрать ${m.name}`}
|
||||||
|
>
|
||||||
|
<X className="h-3.5 w-3.5" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{share != null && value.length > 1 && (
|
||||||
|
<div className="mt-2 text-xs text-muted-foreground">
|
||||||
|
Делёж поровну: {fmtMoney(share)} ₽ на каждого ({value.length} мех.)
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Пикер механиков из ростера */}
|
||||||
|
{pickerOpen && (
|
||||||
|
<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={() => {
|
||||||
|
setPickerOpen(false);
|
||||||
|
setQ("");
|
||||||
|
}}
|
||||||
|
className="rounded-full px-3 py-2 text-sm hover:bg-accent"
|
||||||
|
>
|
||||||
|
Закрыть
|
||||||
|
</button>
|
||||||
|
<Input
|
||||||
|
autoFocus
|
||||||
|
placeholder="Поиск механика…"
|
||||||
|
value={q}
|
||||||
|
onChange={(e) => setQ(e.target.value)}
|
||||||
|
/>
|
||||||
|
</header>
|
||||||
|
<div className="flex-1 overflow-auto">
|
||||||
|
{rosterError && (
|
||||||
|
<div className="text-sm text-destructive bg-destructive/10 m-3 rounded-md p-3">
|
||||||
|
{rosterError}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{roster === null && !rosterError && (
|
||||||
|
<div className="text-center text-muted-foreground p-8 text-sm">Загрузка…</div>
|
||||||
|
)}
|
||||||
|
{filtered.map((m) => {
|
||||||
|
const already = value.some((v) => v.mechanic_id === m.id);
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
key={m.id}
|
||||||
|
disabled={already}
|
||||||
|
onClick={() => addMechanic(m)}
|
||||||
|
className="w-full text-left p-3 border-b hover:bg-accent/40 flex items-center justify-between gap-3 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<span className="text-sm">{m.full_name}</span>
|
||||||
|
{already && <span className="text-xs text-muted-foreground">уже добавлен</span>}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{roster !== null && !rosterError && filtered.length === 0 && (
|
||||||
|
<div className="text-center text-muted-foreground p-8 text-sm">
|
||||||
|
Ничего не найдено
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
|
interface Point {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DamageOverlay {
|
||||||
|
zoneId: number;
|
||||||
|
points: Point[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
damagedZoneIds: number[];
|
||||||
|
/** Координаты точек повреждений в композитной SVG-системе (827×1209). */
|
||||||
|
damages?: DamageOverlay[];
|
||||||
|
onZoneClick?: (zoneId: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SVG_NS = "http://www.w3.org/2000/svg";
|
||||||
|
const POINT_RADIUS = 9;
|
||||||
|
|
||||||
|
/** Композитная SVG-схема экстерьера машины с подсветкой зон + точками
|
||||||
|
* повреждений. Координаты точек в системе 827×1209 (та же что у vendor). */
|
||||||
|
export function TtDamageMap({ damagedZoneIds, damages, onZoneClick }: Props) {
|
||||||
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const [svgText, setSvgText] = useState<string | null>(null);
|
||||||
|
const damagedSet = new Set(damagedZoneIds.map(String));
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
fetch("/scheme/exterior.svg")
|
||||||
|
.then((r) => r.text())
|
||||||
|
.then((text) => {
|
||||||
|
if (cancelled) return;
|
||||||
|
let mut = text;
|
||||||
|
mut = mut.replace(/<script[\s\S]*?<\/script>/gi, "");
|
||||||
|
mut = mut.replace(
|
||||||
|
/(<svg\b[^>]*?)\s(?:width|height)\s*=\s*"[^"]*"/gi,
|
||||||
|
"$1"
|
||||||
|
);
|
||||||
|
mut = mut.replace(
|
||||||
|
/<svg\b/i,
|
||||||
|
`<svg width="100%" height="100%" preserveAspectRatio="xMidYMid meet"`
|
||||||
|
);
|
||||||
|
setSvgText(mut);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Tinting + cursors
|
||||||
|
useEffect(() => {
|
||||||
|
if (!svgText) return;
|
||||||
|
const el = containerRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
const svg = el.querySelector("svg") as SVGSVGElement | null;
|
||||||
|
if (!svg) return;
|
||||||
|
|
||||||
|
svg.querySelectorAll("path[class]").forEach((p) => {
|
||||||
|
const cls = p.getAttribute("class") ?? "";
|
||||||
|
if (damagedSet.has(cls)) {
|
||||||
|
p.setAttribute("fill", "rgba(239, 68, 68, 0.35)");
|
||||||
|
p.setAttribute("stroke", "rgb(239, 68, 68)");
|
||||||
|
p.setAttribute("stroke-width", "2");
|
||||||
|
(p as SVGElement).style.cursor = onZoneClick ? "pointer" : "default";
|
||||||
|
} else {
|
||||||
|
p.setAttribute("fill", "rgba(0,0,0,0.04)");
|
||||||
|
p.setAttribute("stroke", "rgba(0,0,0,0.25)");
|
||||||
|
p.setAttribute("stroke-width", "0.5");
|
||||||
|
(p as SVGElement).style.cursor = "default";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
svg.querySelectorAll("path:not([class])").forEach((p) => {
|
||||||
|
(p as SVGElement).style.opacity = "0.4";
|
||||||
|
(p as SVGElement).style.pointerEvents = "none";
|
||||||
|
});
|
||||||
|
}, [svgText, damagedSet, onZoneClick]);
|
||||||
|
|
||||||
|
// Point overlay — рисуем поверх SVG в его user-space (827×1209) чтобы
|
||||||
|
// точки идеально совмещались с подсвеченными зонами при любом масштабе.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!svgText) return;
|
||||||
|
const el = containerRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
const svg = el.querySelector("svg") as SVGSVGElement | null;
|
||||||
|
if (!svg) return;
|
||||||
|
|
||||||
|
const existing = svg.querySelector("g[data-tt-damage-points]");
|
||||||
|
if (existing) existing.remove();
|
||||||
|
|
||||||
|
if (!damages || damages.length === 0) return;
|
||||||
|
|
||||||
|
const group = document.createElementNS(SVG_NS, "g");
|
||||||
|
group.setAttribute("data-tt-damage-points", "1");
|
||||||
|
|
||||||
|
let counter = 1;
|
||||||
|
for (const dmg of damages) {
|
||||||
|
for (const pt of dmg.points || []) {
|
||||||
|
if (
|
||||||
|
typeof pt.x !== "number" ||
|
||||||
|
typeof pt.y !== "number" ||
|
||||||
|
!Number.isFinite(pt.x) ||
|
||||||
|
!Number.isFinite(pt.y)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const circle = document.createElementNS(SVG_NS, "circle");
|
||||||
|
circle.setAttribute("cx", String(pt.x));
|
||||||
|
circle.setAttribute("cy", String(pt.y));
|
||||||
|
circle.setAttribute("r", String(POINT_RADIUS));
|
||||||
|
circle.setAttribute("fill", "rgb(220, 38, 38)");
|
||||||
|
circle.setAttribute("stroke", "white");
|
||||||
|
circle.setAttribute("stroke-width", "2");
|
||||||
|
(circle as SVGElement).style.pointerEvents = "none";
|
||||||
|
group.appendChild(circle);
|
||||||
|
|
||||||
|
const text = document.createElementNS(SVG_NS, "text");
|
||||||
|
text.setAttribute("x", String(pt.x));
|
||||||
|
text.setAttribute("y", String(pt.y));
|
||||||
|
text.setAttribute("text-anchor", "middle");
|
||||||
|
text.setAttribute("dominant-baseline", "central");
|
||||||
|
text.setAttribute("fill", "white");
|
||||||
|
text.setAttribute("font-size", "11");
|
||||||
|
text.setAttribute("font-weight", "bold");
|
||||||
|
(text as SVGElement).style.pointerEvents = "none";
|
||||||
|
(text as SVGElement).style.userSelect = "none";
|
||||||
|
text.textContent = String(counter);
|
||||||
|
group.appendChild(text);
|
||||||
|
counter += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
svg.appendChild(group);
|
||||||
|
}, [svgText, damages]);
|
||||||
|
|
||||||
|
function handleClick(e: React.MouseEvent<HTMLDivElement>) {
|
||||||
|
if (!onZoneClick) return;
|
||||||
|
const target = e.target as Element;
|
||||||
|
const cls = target.getAttribute?.("class");
|
||||||
|
if (cls && damagedSet.has(cls)) {
|
||||||
|
const zoneId = Number(cls);
|
||||||
|
if (Number.isFinite(zoneId)) onZoneClick(zoneId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={containerRef}
|
||||||
|
onClick={handleClick}
|
||||||
|
className="w-full aspect-[827/1209] max-h-[60vh] mx-auto bg-card rounded-lg overflow-hidden"
|
||||||
|
style={{ touchAction: "manipulation" }}
|
||||||
|
dangerouslySetInnerHTML={svgText ? { __html: svgText } : undefined}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,110 +0,0 @@
|
|||||||
import { useState } from "react";
|
|
||||||
import sedanSrc from "./schemes/sedan-top.svg?raw";
|
|
||||||
|
|
||||||
interface MarkerDot {
|
|
||||||
x: number;
|
|
||||||
y: number;
|
|
||||||
severity?: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
/** Normalized 0..1 dots overlaid on the scheme. */
|
|
||||||
markers?: MarkerDot[];
|
|
||||||
/** Click handler — receives the zone id like "zone-front". */
|
|
||||||
onZoneClick?: (zoneId: string) => void;
|
|
||||||
/** Per-zone count overlays (e.g. {"zone-front": 2}). Optional. */
|
|
||||||
zoneCounts?: Record<string, number>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ZONES = [
|
|
||||||
"zone-front",
|
|
||||||
"zone-rear",
|
|
||||||
"zone-left",
|
|
||||||
"zone-right",
|
|
||||||
"zone-hood",
|
|
||||||
"zone-trunk",
|
|
||||||
"zone-roof",
|
|
||||||
];
|
|
||||||
|
|
||||||
const ZONE_LABELS: Record<string, string> = {
|
|
||||||
"zone-front": "Передний бампер",
|
|
||||||
"zone-rear": "Задний бампер",
|
|
||||||
"zone-left": "Левый бок",
|
|
||||||
"zone-right": "Правый бок",
|
|
||||||
"zone-hood": "Капот",
|
|
||||||
"zone-trunk": "Багажник",
|
|
||||||
"zone-roof": "Крыша",
|
|
||||||
};
|
|
||||||
|
|
||||||
// Approximate badge position per zone (percentage of container)
|
|
||||||
const ZONE_BADGE_POSITIONS: Record<string, { x: string; y: string }> = {
|
|
||||||
"zone-front": { x: "50%", y: "10%" },
|
|
||||||
"zone-rear": { x: "50%", y: "90%" },
|
|
||||||
"zone-left": { x: "12%", y: "50%" },
|
|
||||||
"zone-right": { x: "88%", y: "50%" },
|
|
||||||
"zone-hood": { x: "50%", y: "10%" },
|
|
||||||
"zone-trunk": { x: "50%", y: "90%" },
|
|
||||||
"zone-roof": { x: "50%", y: "50%" },
|
|
||||||
};
|
|
||||||
|
|
||||||
export function VehicleScheme({ markers = [], onZoneClick, zoneCounts }: Props) {
|
|
||||||
const [hoverZone, setHoverZone] = useState<string | null>(null);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="relative w-full max-w-xs mx-auto">
|
|
||||||
<div
|
|
||||||
className="vehicle-scheme cursor-pointer"
|
|
||||||
dangerouslySetInnerHTML={{ __html: sedanSrc }}
|
|
||||||
onClick={(e) => {
|
|
||||||
const target = e.target as Element;
|
|
||||||
const id = target.getAttribute?.("id");
|
|
||||||
if (id && ZONES.includes(id)) onZoneClick?.(id);
|
|
||||||
}}
|
|
||||||
onMouseMove={(e) => {
|
|
||||||
const target = e.target as Element;
|
|
||||||
const id = target.getAttribute?.("id");
|
|
||||||
setHoverZone(id && ZONES.includes(id) ? id : null);
|
|
||||||
}}
|
|
||||||
onMouseLeave={() => setHoverZone(null)}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* Point markers (red dots) overlaid on the scheme via normalized coords */}
|
|
||||||
{markers.map((m, i) => (
|
|
||||||
<div
|
|
||||||
key={i}
|
|
||||||
className="absolute w-3 h-3 rounded-full bg-destructive border border-white pointer-events-none"
|
|
||||||
style={{
|
|
||||||
left: `${m.x * 100}%`,
|
|
||||||
top: `${m.y * 100}%`,
|
|
||||||
transform: "translate(-50%, -50%)",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
|
|
||||||
{/* Zone counts as small badges */}
|
|
||||||
{zoneCounts &&
|
|
||||||
Object.entries(zoneCounts).map(([zone, count]) => {
|
|
||||||
if (count <= 0) return null;
|
|
||||||
const pos = ZONE_BADGE_POSITIONS[zone];
|
|
||||||
if (!pos) return null;
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={zone}
|
|
||||||
className="absolute bg-destructive text-destructive-foreground text-xs font-semibold rounded-full w-5 h-5 flex items-center justify-center pointer-events-none"
|
|
||||||
style={{
|
|
||||||
left: pos.x,
|
|
||||||
top: pos.y,
|
|
||||||
transform: "translate(-50%, -50%)",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{count}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
|
|
||||||
<div className="text-xs text-center mt-1 text-muted-foreground min-h-[1em]">
|
|
||||||
{hoverZone ? ZONE_LABELS[hoverZone] : "Тапни по зоне, чтобы добавить метку"}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
import exteriorSvgUrl from "/scheme/exterior.svg?url";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
// Zone color states
|
||||||
|
const COLOR_DEFAULT_FILL = "rgba(0, 0, 0, 0)"; // transparent
|
||||||
|
const COLOR_HOVER_FILL = "rgba(59, 130, 246, 0.20)"; // soft blue
|
||||||
|
const COLOR_HAS_DAMAGE_FILL = "rgba(239, 68, 68, 0.30)"; // red tint for zones with active damage
|
||||||
|
const COLOR_RESOLVED_FILL = "rgba(156, 163, 175, 0.30)"; // gray for resolved-only zones
|
||||||
|
|
||||||
|
export interface SchemeMarker {
|
||||||
|
id: number;
|
||||||
|
side?: string | null;
|
||||||
|
damage_type?: string | null;
|
||||||
|
severity?: string | null;
|
||||||
|
resolved: boolean;
|
||||||
|
/** Координаты точек повреждения в композитной SVG-системе (827×1209). */
|
||||||
|
polygon?: { x: number; y: number }[] | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SVG_NS = "http://www.w3.org/2000/svg";
|
||||||
|
const POINT_RADIUS = 9;
|
||||||
|
const POINT_FILL_ACTIVE = "rgb(220, 38, 38)";
|
||||||
|
const POINT_FILL_RESOLVED = "rgb(107, 114, 128)";
|
||||||
|
const COMPOSITE_W = 827;
|
||||||
|
const COMPOSITE_H = 1209;
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
markers: SchemeMarker[];
|
||||||
|
onZoneTap?: (zoneId: number) => void;
|
||||||
|
onTireWearClick?: () => void;
|
||||||
|
editable?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse "zone-23" -> 23, anything else -> null */
|
||||||
|
function parseZoneId(side: string | null | undefined): number | null {
|
||||||
|
if (!side) return null;
|
||||||
|
const m = /^zone-(\d+)$/.exec(side);
|
||||||
|
if (!m) return null;
|
||||||
|
const n = Number(m[1]);
|
||||||
|
return Number.isFinite(n) ? n : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function VendorVehicleScheme({
|
||||||
|
markers,
|
||||||
|
onZoneTap,
|
||||||
|
onTireWearClick,
|
||||||
|
editable = true,
|
||||||
|
}: Props) {
|
||||||
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const [svgText, setSvgText] = useState<string | null>(null);
|
||||||
|
const [hoverZone, setHoverZone] = useState<number | null>(null);
|
||||||
|
|
||||||
|
// Load SVG once from public/scheme/exterior.svg as a separate asset
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
fetch(exteriorSvgUrl)
|
||||||
|
.then((r) => r.text())
|
||||||
|
.then((t) => {
|
||||||
|
if (!cancelled) setSvgText(t);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (!cancelled) setSvgText("<!-- failed to load -->");
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Count damage per zone, separately track has-any vs has-only-resolved
|
||||||
|
const zoneStats = useMemo(() => {
|
||||||
|
const stats = new Map<number, { count: number; activeCount: number }>();
|
||||||
|
for (const m of markers) {
|
||||||
|
const z = parseZoneId(m.side);
|
||||||
|
if (z == null) continue;
|
||||||
|
const s = stats.get(z) ?? { count: 0, activeCount: 0 };
|
||||||
|
s.count += 1;
|
||||||
|
if (!m.resolved) s.activeCount += 1;
|
||||||
|
stats.set(z, s);
|
||||||
|
}
|
||||||
|
return stats;
|
||||||
|
}, [markers]);
|
||||||
|
|
||||||
|
const tireCount = markers.filter((m) => m.side === "tires").length;
|
||||||
|
|
||||||
|
// Apply zone fills after SVG renders or when hover/damage state changes
|
||||||
|
useEffect(() => {
|
||||||
|
if (!svgText) return;
|
||||||
|
const el = containerRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
const svg = el.querySelector("svg");
|
||||||
|
if (!svg) return;
|
||||||
|
|
||||||
|
// Strip any inline <script> the vendor included
|
||||||
|
svg.querySelectorAll("script").forEach((s) => s.remove());
|
||||||
|
|
||||||
|
// Make the SVG fill its container
|
||||||
|
svg.setAttribute("width", "100%");
|
||||||
|
svg.setAttribute("height", "100%");
|
||||||
|
svg.setAttribute("preserveAspectRatio", "xMidYMid meet");
|
||||||
|
|
||||||
|
// Reset all numeric-class paths to appropriate fill
|
||||||
|
const all = svg.querySelectorAll("path[class]");
|
||||||
|
all.forEach((p) => {
|
||||||
|
const cls = p.getAttribute("class") ?? "";
|
||||||
|
const zid = /^\d+$/.test(cls) ? Number(cls) : null;
|
||||||
|
if (zid == null) return;
|
||||||
|
|
||||||
|
const s = zoneStats.get(zid);
|
||||||
|
let fill = COLOR_DEFAULT_FILL;
|
||||||
|
if (s) {
|
||||||
|
fill = s.activeCount > 0 ? COLOR_HAS_DAMAGE_FILL : COLOR_RESOLVED_FILL;
|
||||||
|
}
|
||||||
|
if (hoverZone === zid && editable) fill = COLOR_HOVER_FILL;
|
||||||
|
|
||||||
|
p.setAttribute("fill", fill);
|
||||||
|
(p as SVGElement).style.cursor = editable ? "pointer" : "default";
|
||||||
|
(p as SVGElement).style.transition = "fill 0.15s";
|
||||||
|
});
|
||||||
|
}, [svgText, zoneStats, hoverZone, editable]);
|
||||||
|
|
||||||
|
// Overlay точек повреждений (multi-point координаты в композитной 827×1209)
|
||||||
|
useEffect(() => {
|
||||||
|
if (!svgText) return;
|
||||||
|
const el = containerRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
const svg = el.querySelector("svg") as SVGSVGElement | null;
|
||||||
|
if (!svg) return;
|
||||||
|
|
||||||
|
// Удаляем предыдущий overlay
|
||||||
|
const existing = svg.querySelector("g[data-damage-points]");
|
||||||
|
if (existing) existing.remove();
|
||||||
|
|
||||||
|
const group = document.createElementNS(SVG_NS, "g");
|
||||||
|
group.setAttribute("data-damage-points", "1");
|
||||||
|
|
||||||
|
let counter = 1;
|
||||||
|
for (const m of markers) {
|
||||||
|
const pts = m.polygon || [];
|
||||||
|
if (pts.length === 0) continue;
|
||||||
|
const fill = m.resolved ? POINT_FILL_RESOLVED : POINT_FILL_ACTIVE;
|
||||||
|
|
||||||
|
for (const pt of pts) {
|
||||||
|
if (
|
||||||
|
typeof pt.x !== "number" ||
|
||||||
|
typeof pt.y !== "number" ||
|
||||||
|
!Number.isFinite(pt.x) ||
|
||||||
|
!Number.isFinite(pt.y)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Polygon хранится в normalised 0..1 (см. ZoneDetailView). SVG viewBox
|
||||||
|
// в композитной 827×1209, поэтому умножаем перед отрисовкой.
|
||||||
|
const cx = pt.x * COMPOSITE_W;
|
||||||
|
const cy = pt.y * COMPOSITE_H;
|
||||||
|
const circle = document.createElementNS(SVG_NS, "circle");
|
||||||
|
circle.setAttribute("cx", String(cx));
|
||||||
|
circle.setAttribute("cy", String(cy));
|
||||||
|
circle.setAttribute("r", String(POINT_RADIUS));
|
||||||
|
circle.setAttribute("fill", fill);
|
||||||
|
circle.setAttribute("stroke", "white");
|
||||||
|
circle.setAttribute("stroke-width", "2");
|
||||||
|
(circle as SVGElement).style.pointerEvents = "none";
|
||||||
|
group.appendChild(circle);
|
||||||
|
|
||||||
|
const text = document.createElementNS(SVG_NS, "text");
|
||||||
|
text.setAttribute("x", String(cx));
|
||||||
|
text.setAttribute("y", String(cy));
|
||||||
|
text.setAttribute("text-anchor", "middle");
|
||||||
|
text.setAttribute("dominant-baseline", "central");
|
||||||
|
text.setAttribute("fill", "white");
|
||||||
|
text.setAttribute("font-size", "11");
|
||||||
|
text.setAttribute("font-weight", "bold");
|
||||||
|
(text as SVGElement).style.pointerEvents = "none";
|
||||||
|
(text as SVGElement).style.userSelect = "none";
|
||||||
|
text.textContent = String(counter);
|
||||||
|
group.appendChild(text);
|
||||||
|
counter += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
svg.appendChild(group);
|
||||||
|
}, [svgText, markers]);
|
||||||
|
|
||||||
|
// Walk up from event.target to find a path[class="N"] (numeric zone id)
|
||||||
|
function zoneFromEvent(e: React.MouseEvent | React.TouchEvent): number | null {
|
||||||
|
let node = e.target as Element | null;
|
||||||
|
while (node && node !== e.currentTarget) {
|
||||||
|
if (node.tagName?.toLowerCase() === "path") {
|
||||||
|
const cls = node.getAttribute("class") ?? "";
|
||||||
|
if (/^\d+$/.test(cls)) return Number(cls);
|
||||||
|
}
|
||||||
|
node = node.parentElement;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleClick(e: React.MouseEvent<HTMLDivElement>) {
|
||||||
|
if (!editable) return;
|
||||||
|
const z = zoneFromEvent(e);
|
||||||
|
if (z != null) onZoneTap?.(z);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleMove(e: React.MouseEvent<HTMLDivElement>) {
|
||||||
|
if (!editable) return;
|
||||||
|
setHoverZone(zoneFromEvent(e));
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-3">
|
||||||
|
{/* SVG container — aspect ratio matches vendor viewBox 827×1209 */}
|
||||||
|
<div
|
||||||
|
ref={containerRef}
|
||||||
|
onClick={handleClick}
|
||||||
|
onMouseMove={handleMove}
|
||||||
|
onMouseLeave={() => setHoverZone(null)}
|
||||||
|
className={cn(
|
||||||
|
"mx-auto w-full max-w-md bg-card border rounded-lg p-2 aspect-[827/1209]",
|
||||||
|
"overflow-hidden",
|
||||||
|
)}
|
||||||
|
style={{ touchAction: "manipulation" }}
|
||||||
|
dangerouslySetInnerHTML={svgText ? { __html: svgText } : undefined}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Summary line: count of zones with damage */}
|
||||||
|
{zoneStats.size > 0 && (
|
||||||
|
<div className="mx-auto max-w-md text-xs text-muted-foreground text-center">
|
||||||
|
Зон с повреждениями:{" "}
|
||||||
|
<span className="font-semibold text-foreground">{zoneStats.size}</span>
|
||||||
|
{" · "}
|
||||||
|
Всего меток:{" "}
|
||||||
|
<span className="font-semibold text-foreground">
|
||||||
|
{markers.filter((m) => parseZoneId(m.side) != null).length}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Global tire-wear button */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onTireWearClick}
|
||||||
|
disabled={!editable && !onTireWearClick}
|
||||||
|
className="w-full max-w-md mx-auto flex items-center justify-between gap-3 rounded-lg border bg-card px-4 py-3 hover:bg-accent transition-colors text-sm font-medium"
|
||||||
|
>
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<span className="text-xl">⊙</span>
|
||||||
|
<span>Состояние резины</span>
|
||||||
|
</span>
|
||||||
|
{tireCount > 0 && (
|
||||||
|
<span className="bg-destructive text-destructive-foreground text-xs font-bold rounded-full px-2 py-0.5">
|
||||||
|
{tireCount}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{editable && (
|
||||||
|
<p className="text-xs text-center text-muted-foreground">
|
||||||
|
Тапните по зоне машины, чтобы добавить метку повреждения.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 400">
|
|
||||||
<rect x="40" y="20" width="120" height="360" rx="40" ry="40"
|
|
||||||
fill="none" stroke="hsl(0 0% 16%)" stroke-width="2"/>
|
|
||||||
<rect x="55" y="60" width="90" height="60" rx="10" fill="hsl(200 30% 88%)"/>
|
|
||||||
<rect x="55" y="280" width="90" height="50" rx="10" fill="hsl(200 30% 88%)"/>
|
|
||||||
<rect x="55" y="130" width="90" height="140" fill="hsl(40 20% 92%)" stroke="hsl(0 0% 60%)" stroke-width="1"/>
|
|
||||||
<rect id="zone-front" x="40" y="20" width="120" height="40" fill="transparent"/>
|
|
||||||
<rect id="zone-rear" x="40" y="340" width="120" height="40" fill="transparent"/>
|
|
||||||
<rect id="zone-left" x="40" y="60" width="20" height="280" fill="transparent"/>
|
|
||||||
<rect id="zone-right" x="140" y="60" width="20" height="280" fill="transparent"/>
|
|
||||||
<rect id="zone-hood" x="55" y="20" width="90" height="40" fill="transparent"/>
|
|
||||||
<rect id="zone-trunk" x="55" y="340" width="90" height="40" fill="transparent"/>
|
|
||||||
<rect id="zone-roof" x="55" y="130" width="90" height="140" fill="transparent"/>
|
|
||||||
</svg>
|
|
||||||
|
Before Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1,65 @@
|
|||||||
|
export interface DamageVocabulary {
|
||||||
|
damage_types_ordered: string[];
|
||||||
|
exterior_selectable: string[];
|
||||||
|
salon_selectable: string[];
|
||||||
|
severity_scale: {
|
||||||
|
positions: number;
|
||||||
|
labels: string[];
|
||||||
|
values: number[];
|
||||||
|
default: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let cache: DamageVocabulary | null = null;
|
||||||
|
|
||||||
|
export async function loadDamageVocabulary(): Promise<DamageVocabulary> {
|
||||||
|
if (cache) return cache;
|
||||||
|
const res = await fetch("/data/damage_vocabulary.json");
|
||||||
|
const data = await res.json();
|
||||||
|
cache = {
|
||||||
|
damage_types_ordered: data.damage_types_ordered,
|
||||||
|
exterior_selectable: data.exterior_selectable,
|
||||||
|
salon_selectable: data.salon_selectable,
|
||||||
|
severity_scale: data.severity_scale,
|
||||||
|
};
|
||||||
|
return cache;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mapping русского названия из damage_vocabulary.json в DamageType enum
|
||||||
|
* нашего backend'а (см. mechanic_schemas.DamageType Literal).
|
||||||
|
* Возвращает null для типов которым нет точного соответствия —
|
||||||
|
* вызывающий код должен такие отфильтровать из UI.
|
||||||
|
*/
|
||||||
|
export const DAMAGE_RU_TO_ENUM: Record<string, string | null> = {
|
||||||
|
"Вмятина": "dent",
|
||||||
|
"Царапина": "scratch",
|
||||||
|
"Трещина": "crack",
|
||||||
|
"Повреждено": "damaged",
|
||||||
|
"Скол": "chip",
|
||||||
|
"Отсутствует": "missing",
|
||||||
|
"Прожжено": "burn",
|
||||||
|
"Погнуто": "bent",
|
||||||
|
"Требуется мойка": null,
|
||||||
|
"Не работает": "not-working",
|
||||||
|
"Порез": "cut",
|
||||||
|
"Прокол": "puncture",
|
||||||
|
"Порвано": "torn",
|
||||||
|
"Пятна": "stain",
|
||||||
|
"Грязный салон": "stain",
|
||||||
|
"Запах табака": null,
|
||||||
|
"Повреждение салонных ковриков": "damaged",
|
||||||
|
"Повреждение обшивки дверей": "damaged",
|
||||||
|
"Сломанные ручки": "damaged",
|
||||||
|
"Установлено": "removed",
|
||||||
|
"Снято": "removed",
|
||||||
|
"Контроль": null,
|
||||||
|
"Требуется химчистка": "stain",
|
||||||
|
"Затертость": "scuff",
|
||||||
|
"Грыжа": "bulge",
|
||||||
|
"Штат": null,
|
||||||
|
};
|
||||||
|
|
||||||
|
export function damageTypeRuToEnum(ru: string): string | null {
|
||||||
|
return DAMAGE_RU_TO_ENUM[ru] ?? null;
|
||||||
|
}
|
||||||