Compare commits

...
Author SHA1 Message Date
tremble7681andclaude-flow 5ab4e9e74e fix(pwa): TgWaitPage redirects to login when no pairing session
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-19 23:07:06 +10:00
tremble7681 01c36ce935 feat(pwa): Telegram login primary + code fallback + TgWaitPage 2026-06-19 23:00:31 +10:00
tremble7681 0ec8f0b540 feat(pwa): usePairPoll hook (polls tg pairing, sets session) 2026-06-19 22:56:26 +10:00
tremble7681 bd1a4a31bd feat(pwa): tg verified-login api (tgSession/tgPoll) + schemas 2026-06-19 22:52:52 +10:00
tremble7681andclaude-flow b419a456fe fix(pwa): onboarding deep_links — make tg/max optional (MAX not configured in prod)
Backend omits channels without a configured username; strict zod schema
threw on missing 'max', surfacing as 'Не удалось отправить код' instead of
routing to the onboarding screen. Make both optional + regression test.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 23:05:12 +10:00
tremble7681andclaude-flow 08ebc09814 docs(pwa): plan fix (keypad reduce) + gitignore tsbuildinfo
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 22:23:32 +10:00
tremble7681andclaude-flow e5a2874ba7 feat(driver-pwa): onboarding renders only configured bot channels
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 22:05:08 +10:00
tremble7681andclaude-flow adad929769 feat(driver-pwa): friendly toast on 429 (rate-limited code request)
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 20:33:46 +10:00
tremble7681andclaude-flow 479b9699ea feat(driver-pwa): top-up fetches commission rate from backend (no hardcoded rate)
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 20:27:39 +10:00
tremble7681andclaude-flow b7dc826f0f feat(driver-pwa): real MVP PWA icons (192/512, cream+card motif) + generator
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 20:10:33 +10:00
tremble7681andclaude-flow 15d7f34689 polish(driver-pwa): error states, typed catch, drop dead avatar, terminal poll
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 19:59:38 +10:00
tremble7681andclaude-flow 0fba967cd8 feat(driver-pwa): PWA manifest + placeholder icons
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 19:42:18 +10:00
tremble7681andclaude-flow 66ef403bc0 feat(driver-pwa): payments history screen
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 19:39:58 +10:00
tremble7681andclaude-flow 0a164634f8 feat(driver-pwa): payment screen + auto status polling
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 19:36:49 +10:00
tremble7681andclaude-flow 372dc0ede7 feat(driver-pwa): top-up with custom keypad
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 19:34:00 +10:00
tremble7681andclaude-flow d769845d88 feat(driver-pwa): balance screen (hero total + accounts)
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 19:30:59 +10:00
tremble7681andclaude-flow 6f76809e9e feat(driver-pwa): onboarding (connect TG/MAX bot)
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 19:27:21 +10:00
tremble7681andclaude-flow 9a116ad94e feat(driver-pwa): login (phone -> TG/MAX code)
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 19:24:37 +10:00
tremble7681andclaude-flow f74f3688ae feat(driver-pwa): shared UI + router with auth guard
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 19:21:10 +10:00
tremble7681andclaude-flow a7032692f1 feat(driver-pwa): auth store + ky client + typed driver API (zod)
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 19:17:12 +10:00
tremble7681andclaude-flow 34d3554f72 feat(driver-pwa): pure money/phone/amount helpers + tests
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 19:13:16 +10:00
tremble7681andclaude-flow 19b91d65c8 feat(driver-pwa): design tokens, entry, test setup
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 19:10:48 +10:00
tremble7681andclaude-flow 54ba4edb94 chore(driver-pwa): scaffold Vite+PWA+Tailwind project
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 19:08:41 +10:00
tremble7681andclaude-flow 19dc1b31a6 docs(driver-pwa): Премиум Водитель PWA implementation plan
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 18:58:30 +10:00
tremble7681andclaude-flow cc76cc5698 docs(driver-pwa): Премиум Водитель PWA design spec
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-18 18:47:04 +10:00
tremble7681andclaude-flow 100a29f8c7 fix(repairs): ростер механиков по пути repairs/mechanics-roster
prefixUrl=/api/v1/mechanic, эндпоинт под роутером /v1/mechanic/repairs →
путь обязан включать repairs/ (иначе 404, пикер механиков не грузился). Код-ревью #1.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-10 20:07:52 +03:00
tremble7681andclaude-flow f7ccc7ce77 feat(repairs): блок «Механики» — несколько механиков на ремонт, делёж 1/N
MechanicsField (чипы + пикер ростера) в Create/Edit; mechanic_ids в payload;
RepairDetail показывает работавших + долю 1/N. Ростер: GET /v1/mechanic/mechanics-roster.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-10 19:39:36 +03:00
tremble7681andclaude-flow 416ea3391b feat(pwa): rename Салон→Салон перед, add Салон зад + Багажник slots
Extract photo slots to tested lib/inspectionSlots; rename interior label,
add interior-rear + trunk slots (all inspection types). 3 new tests.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-05 18:49:31 +03:00
tremble7681andclaude-flow b2969f36c3 refactor(pwa): extract shared WorksPickerModal from Create/EditRepairPage
The two repair forms genuinely diverged in UX (inline price-unlock + photos
vs modal override, no photos), so a single merged form would be worse. The
real duplication was the works-catalog picker modal — extracted into one
tested presentational component, removing ~75 duplicated lines.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-05 17:32:11 +03:00
tremble7681andclaude-flow fab8b4496b test(pwa): add vitest+RTL harness and extract tested lib helpers
- vitest + @testing-library + jsdom; `npm test`; test files excluded from tsc build
- extract date-grouping/format (lib/repairsFeed) and submit-gating (lib/repairForm)
  out of RepairsFeedPage/CreateRepairPage into tested modules
- 29 tests: VLA day-grouping, plural/money format, repair-form validation,
  CarSelectPage external-car entry flow

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-05 17:28:49 +03:00
tremble7681andclaude-flow 8c9caedb03 feat(repairs): 'с улицы' badge in PWA feed
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-05 14:14:27 +03:00
tremble7681andclaude-flow d0ebd9ddf5 feat(repairs): external mode in create form + /repairs/new-external route
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-05 14:12:57 +03:00
tremble7681andclaude-flow 7e6817b3ff feat(repairs): street-car entry button + sheet on car select
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-05 14:11:03 +03:00
tremble7681andclaude-flow 3d875642f8 feat(repairs): external_car in create payload type
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-05 14:09:45 +03:00
tremble7681 10492e52a4 feat(repairs): month-to-date header + per-day separators
Header 'Итого' (sum of loaded items) -> 'За этот месяц' (sum + count
from 1st VLAT to now) via new /v1/mechanic/repairs/stats/month endpoint.

List now grouped by local day with a dashed separator showing date
('Сегодня' / 'Вчера' / '26 мая') + day total + repair count.

Bundle: index-BKRX_okx.js
2026-05-26 23:27:54 +10:00
tremble7681 fd0ec64da9 feat(pwa/repairs): show price per row + total sum header
В каждой карточке ленты ремонтов справа от строки работ выводим сумму
работ (works_total из бэка, без запчастей). Шапка над лентой переехала:
слева «Итого: NNN ₽ (X ремонтов)», справа кнопка «Обновить» (раньше
была одна сверху-справа).
2026-05-25 21:52:24 +10:00
tremble7681 3b7b2ae56d fix(pwa/repairs): allow clearing price input without sticky 0
В CreateRepairPage поле «Цена применённая» хранило цифру через
price_applied: number. При удалении символов React сразу подставлял 0
и его нельзя было стереть — приходилось каретку перед нулём ставить
руками. Поменяли тип на number | "" в WorkRow и в onChange оставляем
пустую строку в стейте, пока юзер не ввёл новую цифру. На submit и в
сумму "" трактуется как 0 (Number("") === 0).

EditRepairPage не задет — там цена правится через модалку, цена там
уже жила как string (useState(String(...))) и пустое было допустимо.
2026-05-25 21:43:07 +10:00
tremble7681 205078c5ce fix(pwa/repairs): drop duplicate mileage input under «Замена масла»
При создании/редактировании ремонта в форме был отдельный «Пробег на
момент замены» внутри блока замены масла — auto-sync от шапочного с
soft-dirty флагом по У24. На практике это всё равно заставляло механика
вводить значение дважды, если шапочный пробег вводился вручную (StarLine
недоступен): момент включения галочки случался после ручного ввода,
soft-sync не успевал отработать или механик не понимал что поле
автозаполнилось.

Упростили: единственный пробег — «Пробег (км)» в шапке формы. На submit
он же подставляется в oil_change.mileage_at_change. Поле «Следующая через»
оставили — это интервал, а не значение пробега.

Бэкенд не трогаем — схема та же (mileage_at_change всё ещё в payload).
2026-05-25 21:29:26 +10:00
tremble7681 8eac0b74fc fix(pwa): drop stale parts-suggestion responses to stop input self-erasing
В CreateRepairPage queryPartSuggestions после await перезаписывал
partsDraft.name значением q из момента старта запроса. При быстром вводе
("К" → "Ке" → "Кеп" → "Кепу") поздно вернувшийся ответ для "К" откатывал
поле обратно на "К" — пользователи это видели как «текст частично сам
стирается». Делаем функциональный setState и роняем ответ если name уже
другой. EditRepairPage не задет (там корректный паттерн).
2026-05-25 12:44:41 +10:00
tremble7681 9642eb6e45 fix(pwa): safe-area padding for full-screen page-replacement modals
Юзер обнаружил, что при поиске работ (worksPicker в Create/EditRepairPage)
шапка с инпутом всё ещё уезжает под status-bar. Эти модалки и аналоги
(PhotoAnnotateStep, ZoneDetailView, InspectionEditor) используют
fixed inset-0 — моё прежнее правило для .fixed.top-0 их не покрывало.
Добавил отдельный селектор для .fixed.inset-0.bg-background[/\95];
bg-black/40·50·90 (диалоги, фото-вьюверы) намеренно не задеты.
2026-05-25 12:13:30 +10:00
tremble7681 087693877d fix(pwa): respect iOS safe-area-inset on body + sticky/fixed headers
В iOS PWA при viewport-fit=cover и apple-mobile-web-app-status-bar-style=
black-translucent статус-бар прозрачно накладывается на шапки страниц
(пользователи жаловались скринами с overlap «11:37» поверх «Ремонт #12»).

Body теперь имеет padding-top/bottom env(safe-area-inset-*) — fix initial-
рендер и нижних кнопок. Для sticky/fixed .top-0 хедеров отдельно overrid'им
top: env(safe-area-inset-top), т.к. sticky прилипает к top:0 viewport, а
не к содержимому body. Селектор узкий (.sticky.top-0 / .fixed.top-0) —
не задевает .fixed.inset-0 полноэкранные модалки.
2026-05-25 12:04:08 +10:00
tremble7681 85f3a5c682 wip(local): repairs Edit+Detail snapshot 2026-05-25
Untracked: EditRepairPage, RepairDetailPage
Modified: App.tsx, repairsFeed.ts, InspectionEditor.tsx, CreateRepairPage.tsx
+ public/icons docx files (oferta, 1032_*)

Snapshot to prevent loss; main untouched at a5bd730.
2026-05-25 00:18:41 +10:00
tremble7681andclaude-flow a5bd7308b5 feat(sto): activate Repair section in PWA (PR-4..PR-7)
Активация раздела «Ремонт» в Premium Мехник PWA: лента + создание ремонта,
фоновая сверка прав (У35), различающие сообщения при отказе входа (У36).

Backend для всех новых API в taxi-dashboard (отдельный commit eccaebe).
Тулится на `ENABLE_STO_MODULE=true` в backend env.

PR-4: Login + useMeSync.
- src/api/me.ts: тип Me расширен (is_admin, can_login_pwa, departments,
  support — для У35/У36).
- src/hooks/useMeSync.ts: фоновая сверка `/me` раз в 5 мин (У35). При
  403 NO_PWA_ACCESS — сброс токена, revocation info в sessionStorage.
  IndexedDB-черновики не трогаются.
- src/pages/Login.tsx: после успешного login делает getMe() и при 403
  показывает баннер «У вас нет доступа» с кликабельным TG/телефонным
  контактом (У36). Баннер также рендерится при revocation после
  фоновой сверки.
- src/App.tsx: useMeSync() подключён в корне.

PR-5: лента ремонтов.
- src/pages/ActionMenu.tsx: снят `comingSoon` с тайла «Ремонт».
- src/pages/repairs/RepairsFeedPage.tsx: лента с infinite scroll (через
  IntersectionObserver), плейсхолдер «В парке пока нет ремонтов» (У41),
  ellipsis-имена работ + плюрализация «+N работ» (У40).
- src/hooks/useRepairsFeed.ts: useInfiniteQuery + stale-while-revalidate
  + visibility refresh (У38).
- src/lib/timeFormat.ts: формат «Сегодня / Вчера / 23 мая» (У39).
- src/api/repairsFeed.ts: GET /api/v1/mechanic/repairs клиент.

PR-7: создание ремонта (online-only).
- src/api/repairsCreate.ts: searchCars, getCarContext, searchWorks,
  suggestParts, presignPhoto + uploadPhotoToTmp (PUT с правильным
  Content-Type), createRepair (POST с Idempotency-Key).
- src/pages/repairs/CarSelectPage.tsx: поиск машины с debounce 200мс.
- src/pages/repairs/CreateRepairPage.tsx: карточка создания ремонта с 5
  inline-блоками (Шапка / Пробег / Фото / Работы / Запчасти / Замена
  масла). UUID v4 как Idempotency-Key. Карандашик-разблокировка цены
  с обязательным комментарием (У19). Мягкая подписка пробега масла
  на шапочный (У24). Дефолт next_in_km=10000 (У25). Полноэкранная
  модалка поиска работ.

Routes: /repairs, /repairs/new, /repairs/new/:carId.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-24 00:16:44 +10:00
tremble7681andclaude-flow 9b4aa504ec feat(inspection): show general photo slots on приёмка (return) too
Previously slotsForType excluded all general slots for return-type
inspections and left only Домкрат, on the assumption that the car is
already familiar and приёмка should focus on damages/equipment. Feedback
from mechanics: при приёмке всё равно нужно фиксировать общее состояние
машины, иначе споры с водителем теряют доказательную базу. Now все типы
осмотров показывают одинаковый набор слотов.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-23 12:50:05 +10:00
tremble7681andclaude-flow 9b991a244b feat(mechanic): update search placeholder to госномер only
Backend search now matches only on plate, so reflect that in the input
placeholder instead of misleading 'Поиск по номеру или VIN'.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-23 12:10:30 +10:00
tremble7681 ed16b89353 inspection-editor: блок «Заметки механика» поднят под схему
Раньше textarea для заметок жил в самом низу страницы, после фото-сетки
и списка меток — на плановом осмотре приходилось много скроллить чтобы
добраться до основного поля ввода.

Перенёс Card 'Заметки механика' сразу под Card 'Схема'. На плановом осмотре
текстовое поле теперь второе на странице — не надо листать.
2026-05-20 15:39:01 +10:00
tremble7681 4c03f17448 inspection-editor: блок «Заметки механика» в форме нового/in-progress осмотра
Раньше textarea для заметок жил только в InspectionReview (завершённый
осмотр). При создании нового планового осмотра (через '/inspections/<id>/edit')
поля ввода не было — приходилось завершить осмотр, потом открыть карточку
и только там вводить.

Теперь блок есть в обеих страницах:
  - InspectionEditor (in_progress): textarea + кнопки Сохранить/Отменить
  - InspectionEditor (completed):  read-only вывод текста
  - InspectionReview: оставлен прежний редактор как был

Бонус: при нажатии «Завершить осмотр» текущий draft заметки коммитится
тем же PATCH вместе со status=completed — не теряется если механик
ввёл текст и сразу нажал завершение, не сохранив отдельно.
2026-05-20 15:35:05 +10:00
tremble7681 98806d1e92 vehicle list: цветной чип статуса (На линии / ДТП / Ремонт / Бронь)
VehicleSummary.status (cars_v2.element_status) рендерится как цветной
pill справа от гос.номера. Палитра по семантике:
  emerald — На линии (норма)
  amber   — Ремонтируется / Ждет ремонта
  red     — ДТП
  blue    — Бронь / Выкуп / На продаже / Подготовка на продажу / Ждет
            доставки до офиса (admin-операции)
  muted   — Простой и неизвестные статусы

Чип появляется в Home (списке машин) и в шапке VehicleCard. Backend
сторона — PremiumCRM 92d4317.
2026-05-20 15:17:15 +10:00
tremble7681 577ec37a2f vehicle-card: показ водителя под vendor states (Element history)
TtStateSummary.driver_id + driver_name добавлены в TS-тип. В строке
каждого Element-state'а под датой/пробегом теперь выводится '👤 ФИО'
если backend подтянул водителя. Логика идентична нашим осмотрам — общий
helper drivers_at_dates на backend (см. PremiumCRM aa55431).
2026-05-20 14:53:11 +10:00
tremble7681 71783f3724 vehicle-card: показ водителя под каждым прошлым осмотром
Под датой/пробегом каждого осмотра добавлена строка «👤 ФИО» если backend
вернул driver_name (рассчитан как rental, активный на момент started_at —
см. PremiumCRM 4700314). Раньше механик/менеджер не мог быстро понять, у
кого мы принимали машину — приходилось открывать VDS-карточку.

InspectionSummary.driver_id + driver_name добавлены в TS-тип.
2026-05-20 13:56:09 +10:00
tremble7681 d208838bb3 inspection-review: карточка машины + редактируемые заметки
1. Сверху на /inspections/<id> добавлена кликабельная карточка машины:
   гос.номер крупно + марка/модель/год + VIN. Использует новое поле
   ins.vehicle, которое backend теперь возвращает в InspectionDetail
   (см. PremiumCRM коммит a9c94d0). Клик ведёт на /vehicles/<id>.

2. Блок «Заметки механика» — textarea с локальным draft'ом и кнопкой
   «Сохранить» (видна только если draft отличается от ins.notes). Под
   капотом — PATCH /api/v1/mechanic/inspections/<id> с {notes}.
   TG-импортированные осмотры из «Подготовка авто» уже приезжают с
   заполненными notes (caption сообщения становится телом заметки), и
   теперь механик может дополнить/исправить их прямо в карточке.

3. Бонус: добавлен показ пробега (mileage) в первой info-карте.
2026-05-20 13:34:10 +10:00
tremble7681 c7c989d886 inspection-review: TT-фото только в секции «Метки», не дублировать в галерее
Counter «Фото (N)» по-прежнему учитывает TT carry-over (поэтому на 84-м
осмотре всё ещё 16), но карточки в гриде остаются только для наших MinIO-
фото + PWA-маркерных фото. TT-thumbnail рисуется один раз — inline под
своим маркером в списке.
2026-05-20 13:16:21 +10:00
tremble7681 b4e0dd6d65 inspection-review: TT-фото повреждений, счётчик и lightbox для всех маркеров
1. Photo counter теперь учитывает уникальные tt_image_id из markers, не только
   ins.photos + photo_id. На осмотрах, где почти все маркеры пришли из Element
   carry-over, счётчик показывал 1 вместо 15+ — теперь корректно.

2. В галерее «Фото» добавлена секция карточек для TT-image carry-over (label
   «из Element»). Картинки тянутся через ttImageUrl(hash), кликабельны.

3. Lightbox state поменялся с `number | null` на дискриминированный union
   { kind: 'photo', id } | { kind: 'tt', ttId }. Полноразмерное превью
   выбирает между AuthImg (наши MinIO-фото) и обычным <img> (Element).

4. Превью маркеров в секции «Метки» теперь кликабельны (раньше только грид
   с основными фото открывал lightbox). Работает и для photo_id, и для
   tt_image_id маркеров.

Backend-зависимость: MarkerOut.tt_image_id (Pydantic) и
MechanicDamageMarker.tt_image_id (ORM) добавлены в PremiumCRM коммитом
d405e17 на crm.pptaxi.ru — без них фронт получает tt_image_id=undefined.
2026-05-20 13:11:04 +10:00
tremble7681 7e2cf0c9c8 wip(mechanic): inflight damage-flow + vendor scheme + PhotoAnnotate + TT views
Маркер «вот где остановилась mechanic-сессия» — не разбито по логическим коммитам,
зафиксировано целиком чтобы не потерять при отвлечении/чекаутах.

Modified:
- pages/InspectionEditor.tsx — расширение damage-flow внутри редактора
- pages/VehicleCard.tsx — vendor data + расширение карточки
- pages/InspectionReview.tsx — обновлённый review
- api/{auth,inspections,photos,vehicles}.ts — новые endpoints для TT + photo flow
- components/damage-flow/DamageClassifyDialog.tsx — multi-step UI
- components/vehicle-scheme/VendorVehicleScheme.tsx — SVG zone interaction
- data/damageVocabulary.ts — обновлённый словарь повреждений
- frontend index.html/manifest/icons — PWA-метаданные

New (untracked):
- components/damage-flow/PhotoAnnotateStep.tsx — новый шаг flow'а
- components/tt/ — vendor TT-state UI
- pages/TtStateDetail.tsx — экран осмотра вендора
- recon/findings/damage_model.md + damage_vocabulary.json + scheme/ — recon docs

Cleanup: удалены bash-garbage 'Last' и 'dict[str' из frontend/.
2026-05-20 11:16:21 +10:00
tremble7681 e0083b894f fix(damage-flow): render points as SVG circles inside rotated <g> for exact tap alignment (eliminate HTML overlay letterboxing offset) 2026-05-18 00:53:06 +10:00
tremble7681 abdf0a2dea fix(damage-flow): rotation round-trip (store original-frame coords, display in rotated view) 2026-05-18 00:43:29 +10:00
tremble7681 56f1a2774b feat(damage-flow): rotate zoomed detail view to natural orientation (90/-90/180 per zone) 2026-05-18 00:25:59 +10:00
tremble7681 924dd7966a fix(damage-flow): precomputed zone bboxes (avoid getBBox timing); inline SVG viewBox in HTML so first paint already zoomed 2026-05-18 00:00:31 +10:00
tremble7681 102a2525db feat(mechanic-pwa): multi-step damage flow (confirm -> zone detail -> classify -> photo) 2026-05-17 23:45:34 +10:00
tremble7681 8893710254 feat(mechanic-pwa): action menu + vehicle list at /vehicles + mileage dialog + photo icon 2026-05-17 22:13:04 +10:00
tremble7681 ab9ddf7289 feat(mechanic-pwa): use vendor SVG scheme with zone-based markers (1:1 vendor coords for future import)
- Add public/scheme/exterior.svg (131 KB, viewBox 0 0 827 1209, 57 zones class="0"..class="56")
- Add public/scheme/salon.svg (53 KB, Phase 2 reserve)
- New VendorVehicleScheme: fetches SVG as separate asset (?url), strips vendor <script>,
  wires click/hover via event delegation, tints zones red/gray/blue by damage state
- AddMarkerDialog: side required, x/y optional (zone-level markers store NULL x/y)
- InspectionEditor/InspectionReview: swap CompositeVehicleScheme -> VendorVehicleScheme,
  pendingTap now {side} only, humanizeMarkerSide handles zone-{N} and legacy named zones
- Delete CompositeVehicleScheme (PNG grid + bumper suns)
- No backend changes; side=zone-{N} accepted by existing Optional[str] field
2026-05-17 20:18:46 +10:00
tremble7681 bd7665fb1d docs: update repo reference taxi-dashboard -> premium-crm 2026-05-17 19:48:48 +10:00
tremble7681andclaude-flow df709c58e5 feat(mechanic-pwa): composite unfolded scheme + tire wear dialog (replaces 5-tab view)
Single-screen grid layout showing all 5 PNG views + 4 bumper corner sun-zones + decorative
wheels at once. Tap any view for precise AddMarkerDialog; tap bumper corners for center-point
marker; global Tire Wear button opens new TireWearDialog (4-level radio cards).
Deletes MultiViewVehicleScheme. No backend changes. humanizeMarkerSide covers bumper-* and tires.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-17 19:41:13 +10:00
tremble7681andclaude-flow 3c6dacb29b feat(mechanic-pwa): multi-view vendor scheme, exact tap coords, per-marker photo upload
- Replace SVG sedan zone-click model with 5-view PNG scheme (top/front/back/left/right)
- New MultiViewVehicleScheme: tab selector, tap-to-exact-coord marker placement,
  touchAction:manipulation prevents iOS double-tap zoom, marker dots at normalized x/y
- New AddMarkerDialog: bottom-sheet modal with damage_type (16 opts), severity (4 opts),
  description, optional CameraCapture → uploadPhoto(side="free") → photo_id on submit
- InspectionEditor: removes addZoneMarker mutation and zone-count machinery; wires
  pendingTap state → dialog open/close → query invalidation
- InspectionReview: adds read-only MultiViewVehicleScheme; both pages show photo_id
  thumbnails via AuthImg in the marker list
- humanizeMarkerSide updated for new view names; keeps zone-* legacy mapping
- Deletes VehicleScheme.tsx and sedan-top.svg (no remaining imports)
- No backend changes, no new dependencies

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-17 12:21:06 +10:00
tremble7681andclaude-flow 7775e74108 feat(mechanic-pwa): 2FA flow with trusted-device cookie support
Wire frontend to backend 2FA contract: two-step state machine in Login.tsx
(credentials → totp), new login2fa() call to POST /api/auth/2fa, credentials:include
on both fetches so the 30-day trusted_device cookie travels correctly.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-17 11:58:42 +10:00
tremble7681 da0436cee8 docs(state): Phase 1 MVP LIVE — backend+frontend deployed, smoke checks green 2026-05-17 11:34:19 +10:00
tremble7681 db938c818d docs(state): Phase 1 MVP code-complete (B-I), deployment runbook ready for Phase J 2026-05-17 10:58:11 +10:00
tremble7681andclaude-flow a428395071 feat(mechanic-pwa): VehicleScheme + InspectionEditor + InspectionReview pages (Phase I4-I6)
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-17 10:54:00 +10:00
tremble7681andclaude-flow fc4060d4d9 feat(mechanic-pwa): photo upload infra (CameraCapture + PhotoSlot + AuthImg + presigned PUT)
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-17 10:48:51 +10:00
tremble7681andclaude-flow 537548d716 feat(mechanic-pwa): Login + Home + VehicleCard pages with TanStack Query + OAuth2 login
- api/auth.ts: OAuth2 password flow via form-urlencoded POST /api/auth/login (not mechanic prefix)
- api/me.ts: GET /api/v1/mechanic/me with Me interface
- api/vehicles.ts: listVehicles (unwraps {items:[]}), getVehicle with VehicleDetail + InspectionSummary
- api/inspections.ts: createInspection returning full InspectionDetail; 9-value InspectionType union
- Login.tsx: full form with Логин/Пароль labels, useMutation, toast feedback, navigate on success
- Home.tsx: vehicle list with search, /me header with user name, logout, TanStack Query
- VehicleCard.tsx: vehicle info card, all 9 inspection type buttons (ru labels), history list

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-17 10:44:39 +10:00
tremble7681andclaude-flow e815955d46 feat(mechanic-pwa): scaffold Vite+React+TS+Tailwind+shadcn+PWA+routing (Phase G G1-G5)
- Vite 8 + React 19 + TypeScript 6 project via create-vite react-ts template
- Tailwind v3.4 with shadcn-compatible cream palette (CSS vars)
- vite-plugin-pwa v1.3 with autoUpdate SW, manifest.webmanifest, 192+512 icons
- shadcn/ui components written manually (default style): button, card, input, label, sonner
- Zustand persist auth store, ky API client with Bearer token hooks
- React Router v7 routing with RequireAuth guard
- TanStack Query v5 + Toaster wired in main.tsx
- 5 stub pages: Login, Home, VehicleCard, InspectionEditor, InspectionReview
- Build: 293 KB JS / 9.4 KB CSS, clean zero-warning tsc+vite build

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-17 10:39:27 +10:00
tremble7681 3660b80357 docs(state): Phase E complete (E1-E5), next is Phase F markers 2026-05-17 10:04:34 +10:00
tremble7681 173032c12e docs(state): Phase D complete (D1-D3 + test-fakes refactor), Phase E scoping 2026-05-17 01:08:04 +10:00
tremble7681 cbe9ae5d9c docs(state): Phase D decisions resolved + vendor recon findings, B3 contract widened 2026-05-17 00:36:13 +10:00
tremble7681 3a7bd749cc docs(state): Phase C complete (C1-C3), Phase D scoping notes 2026-05-17 00:15:17 +10:00
tremble7681 b04630cfd5 docs(state): Phase B complete (B1-B4), Phase C test-infra fork documented 2026-05-16 23:28:29 +10:00
tremble7681 dfc2e45731 docs: STATE.md with handoff for next session (Phase A done, Task B1 next) 2026-05-16 22:48:05 +10:00
tremble7681 f4e8818bf7 ops(minio): script to set global CORS allow-origin (verified working) 2026-05-16 22:37:12 +10:00
tremble7681 5370346a89 feat(ops): Caddy fragment for mechanic.pptaxi.ru 2026-05-16 22:18:36 +10:00
tremble7681 4610a50667 docs: record backend layout findings from Task A1 recon 2026-05-16 22:17:42 +10:00
263 changed files with 31742 additions and 1 deletions
+1
View File
@@ -38,3 +38,4 @@ Thumbs.db
# IDE
.idea/
.vscode/
.superpowers/
+1 -1
View File
@@ -40,7 +40,7 @@ mechanic-pwa/ ← корень git репо
└── 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.
## Текущая фаза
+50
View File
@@ -0,0 +1,50 @@
# TaxiDashboard backend — найденные пути для модуля `mechanic`
Записано по результатам Task A1 (recon существующего кода `c:\NewProject\taxi-dashboard\backend\app\`).
## Корень backend
`/opt/sites/taxi-dashboard/backend/app/` (на VDS)
`c:\NewProject\taxi-dashboard\backend\app\` (локально)
## Импорты для нового модуля `mechanic`
```python
from app.models.base import Base, TimestampMixin # SQLAlchemy declarative + created_at/updated_at
from app.db import get_db, async_session, engine # async session factory + dependency
from app.auth.deps import get_current_user # OAuth2 Bearer JWT
from app.models.user import User # User модель
```
## Auth
- **OAuth2 Password Flow + Bearer JWT** (не PIN, как я ошибочно писал в спеке).
- Логин: `POST /v1/auth/login` (или похожий, нужно найти в `app/api/auth.py`) с form-data `username` + `password` → возвращает `{ "access_token": "...", "token_type": "bearer" }`.
- Дальнейшие запросы: header `Authorization: Bearer <token>`.
## Naming clash + решение
В TaxiDashboard уже есть модуль `app.api.inspections` (читает данные **CarInspection**, импортированные от вендора NaughtySoft через VendorBridge) под префиксом `/v2/inspections`.
Чтобы не конфликтовать:
- Наш новый модуль: `app/api/mechanic.py` (или `app/mechanic/router.py` как подмодуль) — префикс `/api/v1/mechanic`
- Наши новые таблицы:
- `mechanic_inspections` (наша запись осмотров через PWA)
- `mechanic_inspection_photos`
- `mechanic_damage_markers`
- Наши новые модели:
- `app/models/mechanic_inspection.py``MechanicInspection`
- `app/models/mechanic_inspection_photo.py``MechanicInspectionPhoto`
- `app/models/mechanic_damage_marker.py``MechanicDamageMarker`
Существующие `CarInspection`, `car_inspections`, `inspection_failed_photo`**не трогаем**. Они продолжают жить read-only от VendorBridge.
## Существующий стек
- Python 3.x + FastAPI + SQLAlchemy 2.x async
- PostgreSQL (видна migration via Alembic — папку проверим в первом backend-task)
- Frontend: `c:\NewProject\taxi-dashboard\frontend\` (React, существующий — НЕ наш target)
## Vehicle model
В existing `CarInspection` авто указывается через `car_number: String(100)`. Возможно есть отдельная модель `Car` в `app/models/car_v2.py` (видел в импортах). Проверим в backend task B2 при создании FK.
+384
View File
@@ -0,0 +1,384 @@
# Premium Mechanic PWA — Implementation State
> Last updated: 2026-05-17 (Phase 1 MVP LIVE IN PRODUCTION)
## Status: 🟢 **DEPLOYED — Phase 1 MVP LIVE on https://mechanic.pptaxi.ru**
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
| Phase | Task | Status | Artifact |
|---|---|---|---|
| 0 | Git infrastructure (Gitea + repos + feature branches) | ✅ DONE | repos exist, ssh keys configured |
| A | A1: Recon TaxiDashboard backend structure | ✅ DONE | `docs/backend-layout-notes.md` |
| A | A2: Caddy fragment for `mechanic.pptaxi.ru` | ✅ DONE | `ops/Caddyfile.fragment` |
| A | A3: MinIO CORS on `pp-inspections` bucket | ✅ DONE | `ops/set-minio-cors.sh`, applied, preflight 204 |
| A | A4: SQLAlchemy models (`MechanicInspection`, `MechanicInspectionPhoto`, `MechanicDamageMarker`) | ✅ DONE | commit `be0553e` on `feat/mechanic-mvp` |
| B | B1: Mechanic module skeleton + `/healthz` | ✅ DONE | commit `d2113a0` — flat `backend/app/api/mechanic.py` with `APIRouter(prefix="/v1/mechanic")`, registered in `app/main.py` with `prefix="/api"` → final URL `/api/v1/mechanic/healthz` |
| B | B2: SQLAlchemy models registered + tests | ✅ DONE | **already shipped in A4** (`be0553e`) — 38 metadata tests in `backend/tests/test_mechanic_models.py`, no extra B2 commit |
| B | B3: Pydantic schemas | ✅ DONE | commit `2739cc8` + fix `2fb978d` — 14 schemas + 6 Literals in `backend/app/api/mechanic_schemas.py`, 15 behavioral tests in `backend/tests/test_mechanic_schemas.py`; fix added `= None` defaults to `Optional[X]` fields and tightened `MarkerOut.damage_type`/`severity` to `DamageType`/`Severity` Literals |
| B | B4: Auth + DB session dependencies | ✅ DONE | commit `f0d7e83``backend/app/api/mechanic_deps.py` re-exports `get_db`+`get_current_user`, adds `require_mechanic` guard (admin OR member of any active `dept_type='svc'` department); 9 tests in `backend/tests/test_mechanic_deps.py` use fake-DB stubs (no real session needed)
| C | C1: `GET /me` endpoint | ✅ DONE | commit `a0bdcaa` + signature fix `1e5b822` — appended to `backend/app/api/mechanic.py`; returns `MeOut` from `require_mechanic` user; `permissions` is `["admin", "mechanic:inspect"]` for admins else `["mechanic:inspect"]`. Test fixtures (`client`, `override_mechanic`, `_fake_user`) in `backend/tests/test_mechanic_endpoints.py` use FastAPI `TestClient` + `app.dependency_overrides` per Option A — no real DB / no async. 6 endpoint tests. |
| C | C2: `GET /vehicles` list with `q`+`limit` search | ✅ DONE | commit `7be8783` — new `backend/app/api/mechanic_service.py` with `search_vehicles_with_last_inspection` (single aggregated subquery + outerjoin to avoid N+1 for last completed inspection per vehicle); endpoint in `mechanic.py`; new `VehicleListResponse` schema; 8 tests (6 endpoint + 2 service-stmt) with `_FakeSession.execute()` returning canned rows. Search hits plate (`CarV2.number`) + VIN only. |
| C | C3: `GET /vehicles/{id}` detail + bound /vehicles limit | ✅ DONE | commit `9109383` + style fix `90b8c66` — new `VehicleDetail(VehicleSummary)` + `InspectionSummary(_Base)` schemas; service `get_vehicle_by_id` + `recent_mechanic_inspections`; endpoint raises 404 when missing, `last_inspection_at` derived from first completed inspection in the list; applied `Query(20, ge=1, le=200)` bounds to C2's `/vehicles` limit param. 7 new tests (5 detail + 2 bounds). Service is now FastAPI-free (404 raise lives in endpoint, matching `automations.py` convention). |
| D-pre | B3 schemas widened from vendor recon (`a187a92`) | ✅ DONE | After read-only recon of `car_inspections` (14k rows, 2yr): `InspectionType` extended 4→9 (added `initial`, `seizure`, `equipment-change`, `pre-repair`, `post-repair`); `DamageType` fully replaced 7→16 (removed `rust`/`glass`/`paint` which had 0 vendor occurrences; added real-world types from vendor distribution: `damaged`, `chip`, `scuff`, `burn`, `bent`, `puncture`, `bulge`, `not-working`, etc.). `Severity` unchanged (4 values, optional — vendor populates only 3%). 2 new positive-coverage tests. Stale comment in `mechanic_damage_marker.py:54` references old DamageType values — fix in Phase F when touching that model. |
| D | D1: `POST /inspections` with inline carry-over markers | ✅ DONE | commits `39a6579` + correctness fix `ee3d370` — service `start_inspection` + `latest_completed_inspection` (with `NULLS LAST` ordering); endpoint returns 201 with full InspectionDetail via re-query with `selectinload(photos, markers)`. Carry-over: copies all **unresolved** markers from prev completed inspection (`resolved=False` filter — closed defects don't reopen), each new marker has `carried_over_from_id=source.id`, `photo_id=None`, `resolved=False`. `_FakeSession` extended with `add`/`flush`/`commit`/`refresh` write-path methods + `rows_per_call` queue for multi-SELECT service flows. 9 new tests (6 endpoint + 3 service). |
| D | D2: `GET /inspections/{id}` with photos+markers | ✅ DONE | commit `1776a81` — service `get_inspection_by_id_with_relations` (selectinload both relationships, `scalar_one_or_none`); endpoint raises 404 with `"inspection not found"` parallel to vehicle's 404. D1's inline re-query block refactored to call the same helper (DRY). 6 new tests (4 endpoint + 2 service introspecting `stmt._with_options`). |
| D | D3: `PATCH /inspections/{id}` status/notes/finished_at | ✅ DONE | commit `aefe117` — service `get_inspection_by_id` (thin `session.get` wrapper) + `patch_inspection` (auto-sets `finished_at=now(UTC)` when status→completed AND finished_at not in payload; `setattr` loop applies all `model_dump(exclude_unset=True)` fields). Endpoint re-loads via `get_inspection_by_id_with_relations` for the response. 8 new tests (6 endpoint + 2 service). Endpoint and service both named `patch_inspection` — disambiguated by module path in code, by `as svc_patch` alias in tests. |
| D | Housekeeping: extract test fakes to `mechanic_fakes.py` | ✅ DONE | commit `eedbf23` — pure refactor. Moved `_FakeResult`, `_FakeSession`, `_fake_user`, `_fake_car`, `_fake_inspection`, `_fake_inspection_orm`, `_fake_marker_orm` from `test_mechanic_endpoints.py` (was 899 lines) to new `backend/tests/mechanic_fakes.py` (207 lines). Test file dropped to 697 lines. Pytest fixtures (`client`, `override_mechanic`, `override_db`) stayed in the test file. Phase E tests will import from `mechanic_fakes` directly. |
| E | E1: MinIO async presigned PUT URL wrapper | ✅ DONE | commit `fe38981` — added `presigned_put_url(bucket, key, *, content_type, expires_sec=300)` to `app/services/storage.py`; `PresignedUploadResponse.fields` defaults to `{}`; 3 storage tests. |
| E | E2: `POST /inspections/{id}/photos/upload-url` | ✅ DONE | commit `111661b` — service `create_pending_photo` + `_storage_key_for_photo` helper in `mechanic_service.py`; endpoint in `mechanic.py` with 415-before-404 guard; UUID4 hex storage keys at `mechanic/inspections/{id}/<uuid>.<ext>`; 9 new tests (7 endpoint + 2 service). |
| E | E3: `POST /photos/{id}/confirm` | ✅ DONE | commit `724b209` — service `get_photo_by_id` + `confirm_photo` (None-safe dim update, status→ready); endpoint verifies `storage.exists`, 409 if missing, 404 covers both photo-missing and inspection-mismatch; 9 new tests (7 endpoint + 2 service). `_fake_photo_orm` factory added to `mechanic_fakes.py`. |
| E | E4: `GET /photos/{id}` + `/thumb` (302 redirect) | ✅ DONE | commit `8361ee1` — auth-guarded 302 to presigned MinIO GET URLs (1h expiry). Thumb endpoint falls back to `storage_key` when `thumb_key is None` so galleries degrade gracefully if E5 task hasn't run yet. 8 endpoint tests. |
| E | E5: async thumbnail generation | ✅ DONE | commit `b37a068``generate_and_store_thumbnail` worker (download → Pillow resize to 480px → upload → DB update) with try/except at each step (failures logged, return None, never crashes event loop). Triggered via `asyncio.create_task` from E3 confirm endpoint. `_thumb_key_for` predictable naming (`<key-base>-thumb.jpg`). `pillow_heif.register_heif_opener()` wrapped in try/except for dev-env tolerance. 6 new tests (5 storage unit + 1 endpoint trigger). |
| F | F1+F2: markers CRUD (POST/PATCH/DELETE) | ✅ DONE | commit `7275a23` — 3 endpoints (`POST /inspections/{id}/markers`, `PATCH /markers/{id}`, `DELETE /markers/{id}`). Service helpers `get_marker_by_id`/`create_marker`/`patch_marker`/`delete_marker`. Stale comment in `mechanic_damage_marker.py:54` fixed. `_FakeSession.delete()` added; `_FakeSession.refresh()` auto-sets `created_at` for server-default fields. 15 new tests. **159 mechanic tests total. Backend Phase 1 MVP feature-complete.** |
| G | G1-G5: Vite + React + TS + Tailwind + shadcn + PWA scaffold | ✅ DONE | commit `e815955` in `PremiumDriverApp/mechanic-pwa/frontend/` — 38 files, 8973 insertions. React 19 + Vite 8 + Tailwind v3 + TS strict + shadcn/ui (manually written to bypass broken @shadcn 4.7 "base-nova" style) + vite-plugin-pwa v1.3 (auto-bumped from v0.20 for Vite 8 compat). Service worker (`sw.js` + workbox, 10 precached entries). Cream palette (CSS vars from memory `feedback_design_prefs`). API client (ky) + auth store (zustand persist). 5 stub pages. **Build: 91 KB gzip JS, 0 warnings.** |
| H | H1-H3: Login + Home + VehicleCard pages | ✅ DONE | commit `537548d` — Login uses OAuth2 password flow (form-urlencoded) against `/api/auth/login` (NOT mechanic-prefixed). Home shows vehicle list with search + logout + `/me` fetch. VehicleCard has all 9 inspection-type buttons (top 4 primary, rest outline). Russian locale dates. Semantic Tailwind tokens throughout (no hex). **Build: 110 KB gzip JS.** |
| I | I1-I3: photo capture/upload infra | ✅ DONE | commit `fc4060d``api/photos.ts` with presigned PUT pattern (not POST/FormData per plan), `confirmPhoto(inspection_id, photo_id, meta)` with both IDs in path per E3 backend. `AuthImg` component (fetches with Bearer JWT → blob URL → `<img>`) solving the `<img>`-can't-send-Authorization problem. `CameraCapture` uses `<input type="file" capture="environment">` for max compat. `PhotoSlot` combines them. |
| I | I4-I6: VehicleScheme + InspectionEditor + InspectionReview | ✅ DONE | commit `a428395``sedan-top.svg` (top-view with 7 transparent zone rects), `VehicleScheme.tsx` with click+hover handlers + point-marker overlays + zone-count badges. `inspections.ts` typed with `PhotoSummary`/`MarkerSummary`. Editor wires scheme + 8 photo slots + marker list + finalize button (gated on `status==="in_progress"`); zone tap creates marker with `damage_type="damaged"`/`severity="minor"`. Review is read-only with AuthImg thumb grid. **Build: 113 KB gzip JS. Frontend Phase 1 MVP feature-complete.** |
**Branch state:** `feat/mechanic-mvp` at `b37a068`. Full stack: A4 → B1 → B3 + fix → B4 → C1 + fix → C2 → C3 + fix → B3-vendor-align → D1 + fix → D2 → D3 → test-refactor → E1 → E2 → E3 → E4 → E5. All pushed to `origin` (Gitea). See git log for full SHAs.
**Test count on branch:** **144 mechanic tests pass** (38 models + 17 schemas + 9 deps + 9 storage + 71 endpoints) in ~2.5s, no real DB needed. Pillow image-resize tests use real PIL in-memory (verify JPEG magic header + dimensions); thumbnail task end-to-end uses mocked I/O.
**Live mechanic API surface (11 routes):**
- `GET /api/v1/mechanic/healthz`
- `GET /api/v1/mechanic/me`
- `GET /api/v1/mechanic/vehicles?q=&limit=`
- `GET /api/v1/mechanic/vehicles/{vehicle_id}`
- `POST /api/v1/mechanic/inspections` — create with carry-over for type=return
- `GET /api/v1/mechanic/inspections/{inspection_id}` — full detail with photos+markers
- `PATCH /api/v1/mechanic/inspections/{inspection_id}` — partial update + auto finished_at
- `POST /api/v1/mechanic/inspections/{inspection_id}/photos/upload-url` — create pending photo row + presigned PUT URL (5min expiry)
- `POST /api/v1/mechanic/inspections/{inspection_id}/photos/{photo_id}/confirm` — verify upload, mark ready, schedule thumbnail task
- `GET /api/v1/mechanic/photos/{photo_id}` — auth-guarded 302 to presigned GET (1h)
- `GET /api/v1/mechanic/photos/{photo_id}/thumb` — same with thumb_key, falls back to original
### Phase E architecture decisions (RESOLVED 2026-05-17)
| Decision | Choice | Rationale |
|---|---|---|
| Upload pattern | PUT (single presigned URL) not POST/FormData | Simpler PWA code: `fetch(url, {method:'PUT', body:blob})`. `PresignedUploadResponse.fields` defaults to `{}` for future POST migration. |
| Storage key naming | `mechanic/inspections/{insp_id}/<uuid4hex>.<ext>` | Human-readable path + unguessable suffix. UUID4 avoids enumeration. |
| Allowed content types | `image/{jpeg,png,heic,webp}` | Whitelist; 415 on others. |
| Confirm status semantics | `status="ready"` set immediately on confirm; thumb generated async | Frontend doesn't need to poll. Galleries fall back to original via E4 endpoint. |
| Thumbnail backend | `asyncio.create_task` + Pillow (no Celery) | Pillow + 15+ existing fire-and-forget call sites; no broker setup needed. Thumb resize is ~50ms for typical photo — acceptable on event loop. |
| Thumb size | 480px max-edge, JPEG q=85 | Matches `services/download_wazzup_media.py` precedent. |
| Auth model for read URLs | Auth-required on `/photos/{id}` endpoint; presigned URLs themselves bearer-free (1h TTL) | Same as existing `media_proxy.py` convention. |
### Vendor data reality (from recon 2026-05-17 — 14,013 inspections, 2 years)
| Metric | Value | Implication |
|---|---|---|
| Inspections with damage | 1,941 / 14,013 = 13.9% | Most inspections have empty marker list — UI optimize for that |
| Median markers per inspection | 2 | Inline carry-over copy is cheap |
| p95 markers | 10 | Confirms no async needed |
| Max markers | 34 | Worst case still ~50 inserts on commit |
| Median photos per inspection | 11 (`all_photo_ids`) | Includes 9 sides + damage photos |
| Max photos per inspection | 30 | Set MinIO presigned batch size accordingly |
| Carry-over in vendor | **None — denormalized snapshot** | Our `prev_inspection_id`+`carried_over_from_id` FK approach is net improvement |
| Vendor inspection status field | **None — write-once when completed** | Our `in_progress`/`completed`/`cancelled` is greenfield, no conflicts |
## Where things live
### Repos (Gitea: `http://100.64.0.9:3001/tremble7681`)
| Repo | Local clone | Working branch |
|---|---|---|
| `mechanic-pwa` | `c:\NewProject\PremiumDriverApp\` | `feat/mechanic-mvp` |
| `taxi-dashboard` | `c:\NewProject\taxi-dashboard\` | `feat/mechanic-mvp` |
`taxi-dashboard` clone has two remotes: `origin` → Gitea, `vds` → SSH to `/opt/sites/taxi-dashboard/` on 100.64.0.12 (for pulling back-and-forth with prod).
### Reference paths (real, verified — see `docs/backend-layout-notes.md`)
- `Base`, `TimestampMixin``app.models.base`
- `get_db``app.db` (file: `app/db/__init__.py`)
- `get_current_user``app.auth.deps`
- `User``app.models.user`
- Auth flow: **OAuth2 password + Bearer JWT** (not PIN as plan originally said)
- DB init: **`Base.metadata.create_all`** at startup (not Alembic) + inline `ALTER TABLE ADD COLUMN IF NOT EXISTS` in `app/main.py` lifespan
- Backend Docker container: `taxi-backend-green` / `taxi-backend-blue` (blue/green)
- MinIO container: `taxi-minio`
- Models registered in: `app/models/__init__.py` (imports + `__all__`)
### Naming clash decision
Existing `app/api/inspections.py` + model `CarInspection` (table `car_inspections`) hold **vendor-imported read-only** data from NaughtySoft. Our new tables use the **`mechanic_`** prefix to coexist:
- `mechanic_inspections` (model `MechanicInspection`)
- `mechanic_inspection_photos` (model `MechanicInspectionPhoto`)
- `mechanic_damage_markers` (model `MechanicDamageMarker`)
### Plan-vs-reality overrides applied in Phase B (Authoritative)
Three places where the original plan (`docs/superpowers/plans/2026-05-16-premium-mechanic-phase1.md`) was overridden during execution because Phase A1 recon showed the codebase doesn't match the plan's assumptions:
| Plan said | Actual implementation | Why |
|---|---|---|
| `backend/app/mechanic/router.py` (subpackage) | `backend/app/api/mechanic.py` (flat) | TaxiDashboard uses flat `app/api/*.py` files; no subpackages |
| `backend/app/mechanic/schemas.py` (subpackage) | `backend/app/api/mechanic_schemas.py` (flat sibling) | Same convention |
| `backend/app/mechanic/deps.py` (subpackage) | `backend/app/api/mechanic_deps.py` (flat sibling) | Same convention |
| Router prefix `/api/v1/mechanic` | Router prefix `/v1/mechanic`, with `app.include_router(..., prefix="/api")` in `main.py` | Matches existing convention (`inspections.py``/v2/inspections` + include with `/api`). Final URL is identical: `/api/v1/mechanic/...` |
| `require_mechanic` checks `user.dept.lower() in (...)` | Queries `UserDepartment ⨝ Department WHERE dept_type='svc' AND is_active`, admin shortcuts before DB hit | `User` has no `dept` attribute; departments are M2M via `user_departments`. `DEPT_TYPES=['ops','svc','adm']`, `svc` = service-type (мастерская) |
When dispatching Phase CF implementers, copy this override map into their context so they don't follow the stale subpackage / dept paths from the plan.
## Phase C testing-infrastructure decision (RESOLVED — Option A in force)
Phase C runs against `FastAPI TestClient` (sync) + `app.dependency_overrides[require_mechanic]` and `app.dependency_overrides[get_db]` to inject fake user / fake session. Fake session is a `SimpleNamespace`-flavored `_FakeSession` class in `tests/test_mechanic_endpoints.py` that supports `.execute(stmt)` (returns `_FakeResult` seeded with rows) and `.get(model, pk)` (returns seeded object or `None`).
No `conftest.py`, no `pytest-asyncio`, no real DB. SQL correctness is deliberately deferred to Phase J e2e.
If Phase D/E/F needs a more complex query shape (e.g. `.scalars().one()` / `.first()`), extend `_FakeResult.scalars()` accordingly — currently it returns `self` and supports only `.all()`. See `test_mechanic_endpoints.py:_FakeResult` docstring.
## Deployment runbook (Phase J — execute manually)
**Status:** prep done, awaiting user OK. Phase 1 MVP code is on `feat/mechanic-mvp` in both Gitea repos.
### J0 — Pre-flight (verified)
- [x] Backend `requirements.txt` already has `aiobotocore>=2.13.0`, `Pillow==10.4.0`, `pillow-heif==0.18.0`.
- [x] Backend uses `Base.metadata.create_all` in lifespan (NOT Alembic) — new mechanic tables auto-create on container restart. **No migration step needed.**
- [x] MinIO bucket `pp-inspections` exists with CORS configured (Phase A3, `ops/set-minio-cors.sh` already applied).
- [x] Caddy fragment `ops/Caddyfile.fragment` ready in PremiumDriverApp repo.
- [x] Frontend `dist/` build clean: **113 KB gzip JS**, 12 KB CSS, sw.js + workbox precaching.
- [ ] **DNS**: confirm `mechanic.pptaxi.ru` resolves to the VDS IP before Caddy reload.
- [ ] **Test mechanic user exists**: need a User in the DB with `is_admin=true` OR membership in a `Department` with `dept_type='svc'`. Verify with: `SELECT u.id, u.username, u.is_admin FROM users u LEFT JOIN user_departments ud ON ud.user_id=u.id LEFT JOIN departments d ON d.id=ud.department_id WHERE u.is_admin=true OR d.dept_type='svc';`
### J1 — Backend deploy (taxi-dashboard)
**⚠️ Production touch — affects live CRM.**
Plan said `systemctl restart taxi-dashboard-backend.service` + `alembic upgrade head`**both wrong for our setup**. We use Docker blue/green + `Base.metadata.create_all`. Correct steps:
```bash
ssh root@100.64.0.12
cd /opt/sites/taxi-dashboard
# 1. Pull the mechanic branch into prod's tracking copy
git fetch origin feat/mechanic-mvp
git checkout feat/mechanic-mvp # OR merge into main first if your release process needs that
# 2. Rebuild backend image (pulls in new requirements: Pillow, pillow-heif, aiobotocore should already be installed if it wasn't a fresh deploy, but rebuild to be safe)
docker compose build backend-blue backend-green
# 3. Rolling restart (blue first, then green — preserves availability)
docker compose up -d --no-deps backend-blue
sleep 10
docker logs taxi-backend-blue --tail 50 # check for clean startup + table-create logs
docker compose up -d --no-deps backend-green
sleep 10
docker logs taxi-backend-green --tail 50
# 4. Smoke test
curl -sS https://crm.pptaxi.ru/api/v1/mechanic/healthz
# Expected: {"status":"ok"}
```
**Rollback if broken:** `git checkout main && docker compose up -d --no-deps backend-blue backend-green`. The `Base.metadata.create_all` is additive (CREATE TABLE IF NOT EXISTS) — new tables stay, no data loss.
### J2 — Frontend deploy (mechanic-pwa)
```bash
# 1. Build locally (already done; use the fresh dist/)
cd c:/NewProject/PremiumDriverApp/mechanic-pwa/frontend
npm run build
# 2. Create target dir on VDS if first deploy
ssh root@100.64.0.12 'mkdir -p /opt/sites/mechanic-pwa/dist'
# 3. Sync the built assets
rsync -avz --delete dist/ root@100.64.0.12:/opt/sites/mechanic-pwa/dist/
# 4. Install Caddy fragment (first deploy only)
ssh root@100.64.0.12
cd /opt/sites/mechanic-pwa
# (assumes PremiumDriverApp repo is checked out at /opt/sites/mechanic-pwa/repo;
# if not, scp ops/Caddyfile.fragment instead)
cp /opt/sites/mechanic-pwa/repo/ops/Caddyfile.fragment /etc/caddy/sites-enabled/mechanic.pptaxi.ru
caddy validate --config /etc/caddy/Caddyfile # OR appropriate validation cmd
systemctl reload caddy
# 5. Smoke test
curl -I https://mechanic.pptaxi.ru
# Expected: 200 OK, Content-Type: text/html
curl -sS https://mechanic.pptaxi.ru/manifest.webmanifest | head -20
# Expected: JSON with "name": "Premium Механик"
```
**Rollback:** `rm /etc/caddy/sites-enabled/mechanic.pptaxi.ru && systemctl reload caddy` removes the route; old `dist/` can be restored from previous rsync run if you take a snapshot first.
### J3 — Smoke test (manual)
Open `https://mechanic.pptaxi.ru` on a mobile browser (Android Chrome / iOS Safari):
1. Login with the test mechanic account
2. Search for any car → open card → start "Передача"
3. Tap 2 zones on the scheme → markers appear with red badges
4. Snap 1 photo (any slot) → wait for "загружено" toast → thumb appears
5. Tap "Завершить осмотр" → redirected to review page showing photo + markers
6. Verify in DB:
```sql
SELECT id, vehicle_id, type, status, performed_by, started_at, finished_at
FROM mechanic_inspections ORDER BY id DESC LIMIT 3;
SELECT id, side, slot_index, status, thumb_key IS NOT NULL AS has_thumb
FROM mechanic_inspection_photos WHERE inspection_id=<NEW_ID>;
SELECT id, side, damage_type, carried_over_from_id, resolved
FROM mechanic_damage_markers WHERE inspection_id=<NEW_ID>;
```
7. Verify in MinIO console (`https://s3-admin.pptaxi.ru`) bucket `pp-inspections`: see the `mechanic/inspections/<NEW_ID>/<uuid>.jpg` original + `<uuid>-thumb.jpg` next to it.
8. PWA install: tap browser menu → "Add to Home Screen" → opens fullscreen.
If all 8 pass → **MVP is live**. File UX issues as Gitea issues.
## Acceptance criteria (from plan §3)
- [ ] Mechanic can log in on `mechanic.pptaxi.ru` from mobile
- [ ] Find vehicle by license plate
- [ ] Open vehicle card, see recent inspections
- [ ] Start handover / return / periodic / ad-hoc inspection
- [ ] On return: carry-over markers from prev appear with `carried_over_from_id`
- [ ] Take ≥4 photos in slots, uploaded directly to MinIO via presigned PUT
- [ ] Click zones on SVG scheme → point markers added
- [ ] Finalize inspection (status=completed, finished_at auto-set)
- [ ] View read-only review with all photos + markers
- [ ] PWA installable to home screen on Android + iOS
## Next task (post-deploy)
### **Task F1 — Markers CRUD** (Phase F starts; only 2 tasks) — DONE see table above
After successful J3 smoke test, **Phase 1 MVP is complete**. Phase 2 backlog: polygon annotation editor (Konva), offline IndexedDB queue, native APK wrap, push notifications, VendorBridge data import, admin stats dashboard, QR scanner.
(From `docs/superpowers/plans/2026-05-16-premium-mechanic-phase1.md` Phase F.)
**Working dir:** `c:\NewProject\taxi-dashboard` (branch `feat/mechanic-mvp`, HEAD `b37a068`)
Phase F adds the marker endpoints — finally exposes the carry-over data we've been carefully copying since D1. After F, backend Phase 1 MVP is feature-complete and Phase G begins frontend work.
**Two endpoints:**
- `POST /inspections/{inspection_id}/markers` — create a new damage marker (request: `MarkerCreate` from B3)
- `PATCH /markers/{marker_id}` — update marker (request: `MarkerPatch` from B3)
The plan likely also wants `DELETE /markers/{marker_id}` — verify in the plan. There may also be a "resolve marker" endpoint that's just a PATCH with `resolved=True`.
**Important context:**
- `MechanicDamageMarker` has a stale comment at line 54 (refs old DamageType values like `rust`/`glass`/`paint`) — fix in F1 while touching this model area.
- `MarkerCreate` and `MarkerOut` schemas already exist in `mechanic_schemas.py` from B3.
- The carry-over markers (`carried_over_from_id IS NOT NULL`) deserve a thought: PATCH should be allowed to update them (mechanic confirms the existing damage is still there with current photo); DELETE should probably be NOT allowed on carry-overs (only on freshly-created markers) to preserve audit trail. Verify this in the plan.
**Phase F implementer pattern:** apply the same Phase D path overrides (flat `app/api/`, `MechanicDamageMarker` not `DamageMarker`, etc.). Reuse `_FakeSession` + `_fake_marker_orm` from `mechanic_fakes.py`.
### Phase D architecture decisions (RESOLVED 2026-05-17)
1. **Carry-over: inline в POST /inspections** (atomic in the same transaction). Until carry-over copy completes, the new inspection isn't "ready" for the UI — async would create race conditions and complicate testing without a meaningful payoff for ~10-20 markers per copy.
2. **`_FakeSession` write-path extension.** Add the following to the existing `_FakeSession` in `tests/test_mechanic_endpoints.py`:
- `add(obj)` — appends to `self.added` list; auto-assigns `obj.id` if not set, popping from `_next_ids` queue if provided, else incrementing `_next_id_counter` (starts at 1000 to avoid collision with test-seeded ids in the 1-99 range)
- `async flush()` — no-op + `self.flush_count += 1` (ids already assigned in `add`)
- `async commit()` — no-op + `self.commit_count += 1`
- `async refresh(obj)` — no-op + `self.refresh_count += 1`
- **`rows_per_call: Optional[list[Sequence]]`** kwarg — if provided, each `execute()` call pops one item from this queue and returns it as the result rows. This handles multi-query service flows (e.g. `start_inspection` does `select(prev_inspection)` then `select(prev_markers)`).
- Existing `execute(stmt)` and `get(model, pk)` keep their behavior.
- All extensions backward-compatible with current 83 tests.
3. **Test infrastructure: stay on Option A, do NOT add real DB.** SQL specifics (selectinload, cascade, JSONB) will be validated in Phase J e2e. aiosqlite ≠ Postgres (JSONB mismatch), testcontainers is too heavy for 3 endpoints, two-paradigm test suite is more pain than gain. Extend the mock instead (see point 2).
### Phase D path overrides (apply to D1, D2, D3)
Same flat-file pattern as Phase B-C; map plan's stale paths:
| Plan says | Use instead |
|---|---|
| `backend/app/mechanic/router.py` | `backend/app/api/mechanic.py` (append) |
| `backend/app/mechanic/service.py` | `backend/app/api/mechanic_service.py` (append) |
| `backend/app/mechanic/schemas.py` | `backend/app/api/mechanic_schemas.py` (already has all needed shapes from B3) |
| `backend/tests/test_mechanic/test_inspections.py` | `backend/tests/test_mechanic_endpoints.py` (append) |
| `Inspection` model | `MechanicInspection` (`app/models/mechanic_inspection`) |
| `DamageMarker` model | `MechanicDamageMarker` (`app/models/mechanic_damage_marker`) |
| `InspectionPhoto` model | `MechanicInspectionPhoto` (`app/models/mechanic_inspection_photo`) |
| `service.get_vehicle_or_404` (plan) | `service.get_vehicle_by_id` + endpoint-level `None`-check + `HTTPException(404)` raise (C3 fix) |
| `from fastapi import HTTPException` inline in service | At endpoint level only; service stays FastAPI-free |
| 404 raise inside endpoint via inline `from fastapi import HTTPException` | Use top-of-file import (already there from C3) |
Pydantic schemas (already shipped in B3):
- `InspectionCreate` (vehicle_id, type, driver_id) — request body for POST
- `InspectionPatch` (status, notes, finished_at) — request body for PATCH
- `InspectionDetail` (full response with photos + markers list) — response model
Phase B3 schemas use `model_config = ConfigDict(from_attributes=True)` via `_Base`, so SQLAlchemy ORM instances serialize automatically with `response_model=InspectionDetail`.
## How to resume in a new session
In a new Claude Code chat in `c:\NewProject\`, paste this prompt:
```
Продолжаем проект Premium Mechanic PWA.
Прочитай PremiumDriverApp/docs/superpowers/STATE.md — Phase 1 MVP code-complete.
Backend (14 routes, 159 тестов) + Frontend (113 KB gzip PWA) запушены на feat/mechanic-mvp.
Deployment runbook готов в STATE.md секция "Deployment runbook". Выполни J1+J2+J3:
1. SSH в root@100.64.0.12, git pull feat/mechanic-mvp, docker compose rebuild + rolling restart blue→green
2. rsync mechanic-pwa/frontend/dist/ на VDS + caddy reload mechanic.pptaxi.ru
3. Smoke test на мобильном браузере по чек-листу из runbook'а
После успешного deploy: merge feat/mechanic-mvp → main в обоих репах (PremiumDriverApp + taxi-dashboard).
```
That prompt is the **single entry point** for the next session — Claude reads STATE.md, executes the deployment runbook, runs smoke tests, merges to main.
## Remaining roadmap (Phase 1 MVP)
- ~~**Phase B** (4 tasks)~~ ✅ done — module skeleton, models, schemas, auth deps
- ~~**Phase C** (3 tasks)~~ ✅ done — GET /me, GET /vehicles, GET /vehicles/{id}
- ~~**Phase D** (3 tasks)~~ ✅ done
- ~~**Phase E** (5 tasks)~~ ✅ done
- ~~**Phase F** (2 tasks)~~ ✅ done — backend Phase 1 MVP feature-complete (14 routes, 159 tests)
- ~~**Phase G** (5 tasks)~~ ✅ done — frontend scaffold (91 KB gzip after G; 113 KB after I)
- ~~**Phase H** (3 tasks)~~ ✅ done — Login + Home + VehicleCard
- ~~**Phase I** (6 tasks)~~ ✅ done — CameraCapture + AuthImg + PhotoSlot + VehicleScheme + Editor + Review
- **Phase J** (4 tasks): code-complete, **deployment runbook ready, awaiting user OK****HERE**
**Code work is done. Phase 1 MVP delivery is one `ssh root@100.64.0.12` + Docker compose restart + rsync away.**
≈ 25 tasks left until MVP live on `mechanic.pptaxi.ru`.
## Known external dependencies
- MinIO `pp-inspections` bucket — CORS already configured, presigned uploads will work
- Caddy on 100.64.0.12 — fragment ready, will be wired during Phase J deploy
- Docker blue/green deployment on VDS — backend re-deployment will need a touch of `docker compose` (Phase J)
- Frontend deployment target: `/opt/sites/mechanic-pwa/dist/` on VDS (Phase J)
## Conventions reminder
- All new code in `feat/mechanic-mvp` branches in both repos
- All new tables use `mechanic_` prefix
- Don't touch existing `app/api/inspections.py` or `app/models/inspection.py` (vendor-imported)
- All new mechanic source lives in **flat files under `backend/app/api/`** with `mechanic_*` naming (`mechanic.py`, `mechanic_schemas.py`, `mechanic_deps.py`). No `app/mechanic/` subpackage — see "Plan-vs-reality overrides" table above.
- Router prefix is `/v1/mechanic`; `/api` is added by `include_router(..., prefix="/api")` in `main.py`. Final URLs always `/api/v1/mechanic/*`.
- Phase C+ endpoint tests: pending the test-infrastructure decision (Option A / B / C above). Do NOT introduce `pytest-asyncio`, `conftest.py`, or a real DB without first resolving that decision.
- `require_mechanic` allows admins + members of any active `Department` with `dept_type='svc'`. Use it as the default auth dep for all mechanic endpoints.
File diff suppressed because it is too large Load Diff
@@ -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 (сделать до/параллельно соответствующим экранам).
+1
View File
@@ -0,0 +1 @@
VITE_API_BASE=https://crm.pptaxi.ru/api
+5
View File
@@ -0,0 +1,5 @@
node_modules
dist
.env
.env.local
*.tsbuildinfo
+16
View File
@@ -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>
File diff suppressed because it is too large Load Diff
+42
View File
@@ -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"
}
}
+1
View File
@@ -0,0 +1 @@
export default { plugins: { tailwindcss: {}, autoprefixer: {} } };
Binary file not shown.

After

Width:  |  Height:  |  Size: 909 B

Binary file not shown.

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" }
]
}
+76
View File
@@ -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`);
}
+25
View File
@@ -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();
});
});
+32
View File
@@ -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>
);
}
+24
View File
@@ -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");
});
});
+55
View File
@@ -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),
});
}
+13
View File
@@ -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 });
});
});
+16
View File
@@ -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");
});
});
+21
View File
@@ -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("");
}
+22
View File
@@ -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");
});
});
+120
View File
@@ -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>
);
}
+21
View File
@@ -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" }
)
);
+1
View File
@@ -0,0 +1 @@
import "@testing-library/jest-dom/vitest";
+9
View File
@@ -0,0 +1,9 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_BASE?: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
+15
View File
@@ -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: [],
};
+11
View File
@@ -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"]
}
+4
View File
@@ -0,0 +1,4 @@
{
"files": [],
"references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }]
}
+8
View File
@@ -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"]
}
+13
View File
@@ -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 },
});
+9
View File
@@ -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"] },
});
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+73
View File
@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
+20
View File
@@ -0,0 +1,20 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "default",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/index.css",
"baseColor": "slate",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
}
}
+22
View File
@@ -0,0 +1,22 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
globals: globals.browser,
},
},
])
+23
View File
@@ -0,0 +1,23 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<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="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" />
<title>Premium Механик</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
+55
View File
@@ -0,0 +1,55 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest"
},
"dependencies": {
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-slot": "^1.2.4",
"@tanstack/react-query": "^5.100.10",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"ky": "^1.14.3",
"lucide-react": "^0.400.0",
"react": "^19.2.6",
"react-dom": "^19.2.6",
"react-hook-form": "^7.76.0",
"react-router-dom": "^7.15.1",
"sonner": "^1.7.4",
"tailwind-merge": "^2.6.1",
"vite-plugin-pwa": "^1.3.0",
"zod": "^3.25.76",
"zustand": "^5.0.13"
},
"devDependencies": {
"@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/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"@vitest/coverage-v8": "^4.1.8",
"autoprefixer": "^10.5.0",
"eslint": "^10.3.0",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.6.0",
"jsdom": "^29.1.1",
"postcss": "^8.5.14",
"tailwindcss": "^3.4.19",
"typescript": "~6.0.2",
"typescript-eslint": "^8.59.2",
"vite": "^8.0.12",
"vitest": "^4.1.8"
}
}
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
@@ -0,0 +1,90 @@
{
"_meta": {
"source": "Ttc.dll #US heap, contiguous block at offsets 0xc2e240xc3084",
"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 012 are general exterior damage types (user-selectable for any zone)",
"Items 1318 appear to be salon-specific (Грязный салон, Запах табака, etc.) — shown only for interior zones (4446 seats, salon)",
"Установлено/Снято (19–20) and Контроль (21) are semi-system states used for equipment completeness zones (3348 area)",
"Штат (25) appears to be a system/staff marker, not user-selectable",
"Порез, Прокол, Порвано are tire-specific damage types for zones 1720",
"Есть/Нет повреждений 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 0xc39e80xc39f8 (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 0x751c70x75a81 (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 3437 are fog lights (противотуманки), zones 3839 mirrors, 4043 disks, 4446 salon seats, 4748 rear sill extensions, 4956 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": "передняя правая стойка"
}
+10
View File
@@ -0,0 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="13" fill="#000000"/>
<!-- M: широкие диагонали, плоский «дно» с двумя углами вниз -->
<path
d="M 16 16 L 21 16 L 32 35 L 43 16 L 48 16 L 48 48 L 42 48 L 42 28 L 34 41 L 30 41 L 22 28 L 22 48 L 16 48 Z"
fill="#E6E6E6"
/>
<!-- Красный акцент-черта под буквой -->
<rect x="22" y="52" width="20" height="1.5" fill="#D32F2F"/>
</svg>

After

Width:  |  Height:  |  Size: 514 B

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 410 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 889 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

@@ -0,0 +1,14 @@
{
"name": "Premium Механик",
"short_name": "Mechanic",
"start_url": "/",
"display": "standalone",
"orientation": "portrait",
"background_color": "#000000",
"theme_color": "#000000",
"icons": [
{ "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },
{ "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" }
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

+184
View File
@@ -0,0 +1,184 @@
.counter {
font-size: 16px;
padding: 5px 10px;
border-radius: 5px;
color: var(--accent);
background: var(--accent-bg);
border: 2px solid transparent;
transition: border-color 0.3s;
margin-bottom: 24px;
&:hover {
border-color: var(--accent-border);
}
&:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
}
.hero {
position: relative;
.base,
.framework,
.vite {
inset-inline: 0;
margin: 0 auto;
}
.base {
width: 170px;
position: relative;
z-index: 0;
}
.framework,
.vite {
position: absolute;
}
.framework {
z-index: 1;
top: 34px;
height: 28px;
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
scale(1.4);
}
.vite {
z-index: 0;
top: 107px;
height: 26px;
width: auto;
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
scale(0.8);
}
}
#center {
display: flex;
flex-direction: column;
gap: 25px;
place-content: center;
place-items: center;
flex-grow: 1;
@media (max-width: 1024px) {
padding: 32px 20px 24px;
gap: 18px;
}
}
#next-steps {
display: flex;
border-top: 1px solid var(--border);
text-align: left;
& > div {
flex: 1 1 0;
padding: 32px;
@media (max-width: 1024px) {
padding: 24px 20px;
}
}
.icon {
margin-bottom: 16px;
width: 22px;
height: 22px;
}
@media (max-width: 1024px) {
flex-direction: column;
text-align: center;
}
}
#docs {
border-right: 1px solid var(--border);
@media (max-width: 1024px) {
border-right: none;
border-bottom: 1px solid var(--border);
}
}
#next-steps ul {
list-style: none;
padding: 0;
display: flex;
gap: 8px;
margin: 32px 0 0;
.logo {
height: 18px;
}
a {
color: var(--text-h);
font-size: 16px;
border-radius: 6px;
background: var(--social-bg);
display: flex;
padding: 6px 12px;
align-items: center;
gap: 8px;
text-decoration: none;
transition: box-shadow 0.3s;
&:hover {
box-shadow: var(--shadow);
}
.button-icon {
height: 18px;
width: 18px;
}
}
@media (max-width: 1024px) {
margin-top: 20px;
flex-wrap: wrap;
justify-content: center;
li {
flex: 1 1 calc(50% - 8px);
}
a {
width: 100%;
justify-content: center;
box-sizing: border-box;
}
}
}
#spacer {
height: 88px;
border-top: 1px solid var(--border);
@media (max-width: 1024px) {
height: 48px;
}
}
.ticks {
position: relative;
width: 100%;
&::before,
&::after {
content: '';
position: absolute;
top: -4.5px;
border: 5px solid transparent;
}
&::before {
left: 0;
border-left-color: var(--border);
}
&::after {
right: 0;
border-right-color: var(--border);
}
}
+48
View File
@@ -0,0 +1,48 @@
import { Routes, Route, Navigate } from "react-router-dom";
import { useAuth } from "@/store/auth";
import { useMeSync } from "@/hooks/useMeSync";
import Login from "@/pages/Login";
import ActionMenu from "@/pages/ActionMenu";
import Home from "@/pages/Home";
import VehicleCard from "@/pages/VehicleCard";
import InspectionEditor from "@/pages/InspectionEditor";
import InspectionReview from "@/pages/InspectionReview";
import TtStateDetail from "@/pages/TtStateDetail";
import RepairsFeedPage from "@/pages/repairs/RepairsFeedPage";
import RepairDetailPage from "@/pages/repairs/RepairDetailPage";
import EditRepairPage from "@/pages/repairs/EditRepairPage";
import CarSelectPage from "@/pages/repairs/CarSelectPage";
import CreateRepairPage from "@/pages/repairs/CreateRepairPage";
function RequireAuth({ children }: { children: React.ReactNode }) {
const token = useAuth((s) => s.token);
if (!token) return <Navigate to="/login" replace />;
return <>{children}</>;
}
export default function App() {
// У35: фоновая сверка прав механика раз в 5 минут — выкидывает на /login
// с сообщением «Доступ отозван», если админ снял can_login_pwa или вывел
// пользователя из отдела механиков.
useMeSync();
return (
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/" element={<RequireAuth><ActionMenu /></RequireAuth>} />
<Route path="/vehicles" element={<RequireAuth><Home /></RequireAuth>} />
<Route path="/vehicles/:id" element={<RequireAuth><VehicleCard /></RequireAuth>} />
<Route path="/inspections/:id/edit" element={<RequireAuth><InspectionEditor /></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 />} />
</Routes>
);
}
+58
View File
@@ -0,0 +1,58 @@
import { useAuth } from "@/store/auth";
export interface LoginInput {
username: string;
password: string;
}
/** OAuth2-shaped login response, extended with backend's 2FA signaling fields. */
export interface LoginOutput {
access_token?: string | null;
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> {
const body = new URLSearchParams();
body.set("username", input.username);
body.set("password", input.password);
// PWA — длинная сессия (30 дней) чтобы механики не вводили пароль каждые 8 ч.
body.set("long_session", "true");
const res = await fetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
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) {
throw new Error(`Login failed: ${res.status}`);
}
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 {
useAuth.getState().setToken(null);
}
+28
View File
@@ -0,0 +1,28 @@
import ky, { type KyInstance } from "ky";
import { useAuth } from "@/store/auth";
const API_BASE = import.meta.env.VITE_API_BASE ?? "/api/v1/mechanic";
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().setToken(null);
}
return error;
},
],
},
});
@@ -0,0 +1,131 @@
import { api } from "./client";
import type { InspectionSummary } from "./vehicles";
export type InspectionType =
| "handover"
| "return"
| "periodic"
| "ad-hoc"
| "initial"
| "seizure"
| "equipment-change"
| "pre-repair"
| "post-repair";
export type InspectionStatus = "in_progress" | "completed" | "cancelled";
export interface InspectionCreateInput {
vehicle_id: number;
type: InspectionType;
driver_id?: number;
mileage?: number;
}
export interface PhotoSummary {
id: number;
side: string;
slot_index: number;
storage_key: string;
thumb_key?: string | null;
annotated_key?: string | null;
width?: number | null;
height?: number | null;
status: string;
taken_at: string;
}
export interface MarkerSummary {
id: number;
inspection_id: number;
photo_id?: number | null;
tt_image_id?: string | null;
side?: string | null;
x?: number | null;
y?: number | null;
polygon?: { x: number; y: number }[] | null;
damage_type?: string | null;
severity?: string | null;
description?: string | null;
carried_over_from_id?: number | null;
resolved: boolean;
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 {
id: number;
vehicle_id: number;
/** Сводка по машине (гос.номер / марка / модель / год). Backend attaches её
в get_inspection_by_id_with_relations, чтобы карточка осмотра могла
показать машину без второго запроса. */
vehicle?: VehicleBrief | null;
type: InspectionType;
performed_by: number;
driver_id?: number | null;
started_at: string;
finished_at?: string | null;
status: InspectionStatus;
notes?: string | null;
prev_inspection_id?: number | null;
meta: Record<string, unknown>;
photos: PhotoSummary[];
markers: MarkerSummary[];
mileage?: number | null;
/** ФИО механика, выполнившего осмотр (lookup users.full_name по performed_by). */
inspector_name?: string | null;
}
export async function createInspection(
input: InspectionCreateInput
): Promise<InspectionDetail> {
return api.post("inspections", { json: input }).json<InspectionDetail>();
}
export async function getInspection(id: number): Promise<InspectionDetail> {
return api.get(`inspections/${id}`).json<InspectionDetail>();
}
export async function patchInspection(
id: number,
body: { status?: InspectionStatus; notes?: string; finished_at?: string; mileage?: number }
): Promise<InspectionDetail> {
return api.patch(`inspections/${id}`, { json: body }).json<InspectionDetail>();
}
export interface MarkerCreateInput {
photo_id?: number | null;
side?: string | null;
x?: number | null;
y?: number | null;
polygon?: { x: number; y: number }[] | null;
damage_type?: string | null;
severity?: string | null;
description?: string | null;
}
export async function createMarker(
inspectionId: number,
body: MarkerCreateInput
): Promise<MarkerSummary> {
return api
.post(`inspections/${inspectionId}/markers`, { json: body })
.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 };
+22
View File
@@ -0,0 +1,22 @@
import { api } from "./client";
export interface PwaSupportContact {
tg_username: string | null;
phone: string | null;
}
export interface Me {
id: number;
name: string;
email?: string | null;
permissions: string[];
// Модуль СТО (У10 + У34) — расширение в backend PR-4.
is_admin: boolean;
can_login_pwa: boolean;
departments: string[];
support: PwaSupportContact;
}
export async function getMe(): Promise<Me> {
return api.get("me").json<Me>();
}
+119
View File
@@ -0,0 +1,119 @@
import { api } from "./client";
export interface PresignedUploadResponse {
photo_id: number;
presigned_url: string;
fields: Record<string, string>;
storage_key: string;
expires_at: string;
}
export interface PhotoConfirmResponse {
id: number;
side: string;
slot_index: number;
storage_key: string;
thumb_key?: string | null;
annotated_key?: string | null;
width?: number | null;
height?: number | null;
status: 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(
inspectionId: number,
args: { side: string; slot_index: number; content_type: string; size: number }
): Promise<PresignedUploadResponse> {
return api
.post(`inspections/${inspectionId}/photos/upload-url`, { json: args })
.json<PresignedUploadResponse>();
}
/**
* PUT the file directly to MinIO via the presigned URL.
* Content-Type header MUST match the value the URL was signed with
* (we pass the same `args.content_type` to requestUploadUrl).
*/
export async function uploadToS3(
presigned: PresignedUploadResponse,
file: File,
contentType: string
): Promise<void> {
const r = await fetch(presigned.presigned_url, {
method: "PUT",
headers: { "Content-Type": contentType },
body: file,
});
if (!r.ok) {
throw new Error(`S3 upload failed: ${r.status} ${r.statusText}`);
}
}
export async function confirmPhoto(
inspectionId: number,
photoId: number,
meta: { width?: number; height?: number; actual_size?: number }
): Promise<PhotoConfirmResponse> {
return api
.post(`inspections/${inspectionId}/photos/${photoId}/confirm`, { json: meta })
.json<PhotoConfirmResponse>();
}
/**
* Full upload flow: request URL → PUT to S3 → measure dims → confirm.
* Returns the confirmed PhotoConfirmResponse (frontend uses .id mostly).
*/
export async function uploadPhoto(
inspectionId: number,
side: string,
slotIndex: number,
file: File
): Promise<PhotoConfirmResponse> {
const contentType = file.type || "image/jpeg";
const presign = await requestUploadUrl(inspectionId, {
side,
slot_index: slotIndex,
content_type: contentType,
size: file.size,
});
await uploadToS3(presign, file, contentType);
// Measure dimensions from a local object URL (revoked once loaded).
const dim = await new Promise<{ w: number; h: number }>((resolve, reject) => {
const url = URL.createObjectURL(file);
const img = new Image();
img.onload = () => {
const out = { w: img.naturalWidth, h: img.naturalHeight };
URL.revokeObjectURL(url);
resolve(out);
};
img.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error("Could not read image dimensions"));
};
img.src = url;
});
return confirmPhoto(inspectionId, presign.photo_id, {
width: dim.w,
height: dim.h,
actual_size: file.size,
});
}
@@ -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>();
}
+125
View File
@@ -0,0 +1,125 @@
import { api } from "./client";
export interface VehicleSummary {
id: number;
license_plate: string;
vin?: string | null;
make?: string | null;
model?: string | null;
year?: number | null;
last_inspection_at?: string | null;
/** Текущий статус машины из 1C Element (cars_v2.element_status):
'На линии' / 'Простой' / 'Ремонтируется' / 'Ждет ремонта' / 'ДТП' /
'Бронь' / 'Выкуп' / 'На продаже' / etc. NULL если не задан. */
status?: string | null;
}
export interface VehicleDetail extends VehicleSummary {
recent_inspections: InspectionSummary[];
starline_mileage?: number | null;
starline_mileage_at?: string | null;
}
export interface InspectionSummary {
id: number;
type: string;
status: string;
started_at: string;
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[]> {
const searchParams: Record<string, string> = {};
if (q && q.trim()) searchParams.q = q.trim();
const res = await api
.get("vehicles", { searchParams })
.json<{ items: VehicleSummary[] }>();
return res.items;
}
export async function getVehicle(id: number): Promise<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" : ""}`;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

@@ -0,0 +1,79 @@
import { useEffect, useState } from "react";
import { useAuth } from "@/store/auth";
interface Props {
/** Path relative to /api/v1/mechanic, e.g. "photos/123/thumb". */
src: string;
alt?: string;
className?: string;
/** Optional placeholder while loading. */
fallback?: React.ReactNode;
}
/**
* <img> wrapper that fetches the resource with the current Bearer token,
* turns it into a blob: URL, and renders an <img> pointing at the blob.
*
* Necessary because the mechanic photo endpoints are auth-guarded — plain
* <img src="/api/v1/mechanic/photos/123"> doesn't send the Authorization header.
*
* Cleans up the blob URL on unmount or when src changes.
*/
export function AuthImg({ src, alt = "", className, fallback }: Props) {
const token = useAuth((s) => s.token);
const [blobUrl, setBlobUrl] = useState<string | null>(null);
const [error, setError] = useState<boolean>(false);
useEffect(() => {
let cancelled = false;
let createdUrl: string | null = null;
setError(false);
setBlobUrl(null);
async function load() {
if (!token) {
setError(true);
return;
}
try {
const fullUrl = `/api/v1/mechanic/${src}`;
const res = await fetch(fullUrl, {
headers: { Authorization: `Bearer ${token}` },
redirect: "follow",
});
if (!res.ok) throw new Error(`${res.status}`);
const blob = await res.blob();
createdUrl = URL.createObjectURL(blob);
if (!cancelled) setBlobUrl(createdUrl);
} catch {
if (!cancelled) setError(true);
}
}
load();
return () => {
cancelled = true;
if (createdUrl) URL.revokeObjectURL(createdUrl);
};
}, [src, token]);
if (error) {
return (
<div className={className}>
{fallback ?? (
<span className="text-xs text-muted-foreground">нет фото</span>
)}
</div>
);
}
if (!blobUrl) {
return (
<div className={className}>
{fallback ?? (
<div className="bg-muted animate-pulse h-full w-full" />
)}
</div>
);
}
return <img src={blobUrl} alt={alt} className={className} />;
}

Some files were not shown because too many files have changed in this diff Show More