Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db938c818d | ||
|
|
a428395071 | ||
|
|
fc4060d4d9 | ||
|
|
537548d716 | ||
|
|
e815955d46 | ||
|
|
3660b80357 | ||
|
|
173032c12e | ||
|
|
cbe9ae5d9c | ||
|
|
3a7bd749cc | ||
|
|
b04630cfd5 | ||
|
|
dfc2e45731 | ||
|
|
f4e8818bf7 | ||
|
|
5370346a89 | ||
|
|
4610a50667 |
@@ -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.
|
||||
@@ -0,0 +1,364 @@
|
||||
# Premium Mechanic PWA — Implementation State
|
||||
|
||||
> Last updated: 2026-05-17 (Phase 1 MVP code-complete, awaiting production deploy)
|
||||
|
||||
## Status: **READY TO DEPLOY** (Phase J prep done, awaiting explicit user OK)
|
||||
|
||||
Backend (Phases B-F) and Frontend (Phases G-I) are feature-complete and pushed to Gitea. Deployment is the only step left — it requires SSH into `root@100.64.0.12` (prod VDS), Docker compose restart, and Caddy reload. **Not executed automatically.** See "Deployment runbook" section below for the exact steps.
|
||||
|
||||
## 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 C–F 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.
|
||||
@@ -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?
|
||||
@@ -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...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
},
|
||||
},
|
||||
])
|
||||
@@ -0,0 +1,15 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#2a2a2a" />
|
||||
<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>
|
||||
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"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",
|
||||
"@types/node": "^24.12.4",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"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",
|
||||
"postcss": "^8.5.14",
|
||||
"tailwindcss": "^3.4.19",
|
||||
"typescript": "~6.0.2",
|
||||
"typescript-eslint": "^8.59.2",
|
||||
"vite": "^8.0.12"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
|
After Width: | Height: | Size: 9.3 KiB |
@@ -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 |
|
After Width: | Height: | Size: 2.3 KiB |
|
After Width: | Height: | Size: 6.1 KiB |
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "Premium Механик",
|
||||
"short_name": "Mechanic",
|
||||
"start_url": "/",
|
||||
"display": "standalone",
|
||||
"orientation": "portrait",
|
||||
"background_color": "#f5f1ea",
|
||||
"theme_color": "#2a2a2a",
|
||||
"icons": [
|
||||
{ "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
|
||||
{ "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" }
|
||||
]
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Routes, Route, Navigate } from "react-router-dom";
|
||||
import { useAuth } from "@/store/auth";
|
||||
import Login from "@/pages/Login";
|
||||
import Home from "@/pages/Home";
|
||||
import VehicleCard from "@/pages/VehicleCard";
|
||||
import InspectionEditor from "@/pages/InspectionEditor";
|
||||
import InspectionReview from "@/pages/InspectionReview";
|
||||
|
||||
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() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/" 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="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { useAuth } from "@/store/auth";
|
||||
|
||||
export interface LoginInput {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface LoginOutput {
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
}
|
||||
|
||||
export async function login(input: LoginInput): Promise<LoginOutput> {
|
||||
// OAuth2 password flow — form-urlencoded, NOT JSON, NOT under /api/v1/mechanic/
|
||||
const body = new URLSearchParams();
|
||||
body.set("username", input.username);
|
||||
body.set("password", input.password);
|
||||
|
||||
const res = await fetch("/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body,
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`Login failed: ${res.status}`);
|
||||
}
|
||||
return res.json() as Promise<LoginOutput>;
|
||||
}
|
||||
|
||||
export function logout(): void {
|
||||
useAuth.getState().setToken(null);
|
||||
}
|
||||
@@ -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,104 @@
|
||||
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;
|
||||
}
|
||||
|
||||
export interface PhotoSummary {
|
||||
id: number;
|
||||
side: string;
|
||||
slot_index: number;
|
||||
storage_key: string;
|
||||
thumb_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;
|
||||
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 InspectionDetail {
|
||||
id: number;
|
||||
vehicle_id: number;
|
||||
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[];
|
||||
}
|
||||
|
||||
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 }
|
||||
): 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 type { InspectionSummary };
|
||||
@@ -0,0 +1,12 @@
|
||||
import { api } from "./client";
|
||||
|
||||
export interface Me {
|
||||
id: number;
|
||||
name: string;
|
||||
email?: string | null;
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
export async function getMe(): Promise<Me> {
|
||||
return api.get("me").json<Me>();
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
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;
|
||||
width?: number | null;
|
||||
height?: number | null;
|
||||
status: string;
|
||||
taken_at: string;
|
||||
}
|
||||
|
||||
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,36 @@
|
||||
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;
|
||||
}
|
||||
|
||||
export interface VehicleDetail extends VehicleSummary {
|
||||
recent_inspections: InspectionSummary[];
|
||||
}
|
||||
|
||||
export interface InspectionSummary {
|
||||
id: number;
|
||||
type: string;
|
||||
status: string;
|
||||
started_at: string;
|
||||
finished_at?: 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>();
|
||||
}
|
||||
|
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 |
|
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} />;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { useRef, useState, useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
interface Props {
|
||||
onCapture: (file: File) => void;
|
||||
buttonLabel?: string;
|
||||
}
|
||||
|
||||
export function CameraCapture({ onCapture, buttonLabel = "Сделать фото" }: Props) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [preview, setPreview] = useState<string | null>(null);
|
||||
|
||||
// Cleanup preview blob URL on unmount or when preview changes
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (preview) URL.revokeObjectURL(preview);
|
||||
};
|
||||
}, [preview]);
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
capture="environment"
|
||||
className="hidden"
|
||||
aria-hidden="true"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
if (preview) URL.revokeObjectURL(preview);
|
||||
setPreview(URL.createObjectURL(file));
|
||||
onCapture(file);
|
||||
// Reset input value so capturing the same file twice works
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
{preview ? (
|
||||
<div className="space-y-2">
|
||||
<img src={preview} alt="" className="w-full rounded-lg" />
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
onClick={() => inputRef.current?.click()}
|
||||
>
|
||||
Переснять
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<Button onClick={() => inputRef.current?.click()} className="w-full">
|
||||
{buttonLabel}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useState } from "react";
|
||||
import { CameraCapture } from "./CameraCapture";
|
||||
import { AuthImg } from "@/components/AuthImg";
|
||||
import { uploadPhoto } from "@/api/photos";
|
||||
import { toast } from "sonner";
|
||||
|
||||
interface Props {
|
||||
inspectionId: number;
|
||||
side: string;
|
||||
slotIndex: number;
|
||||
label: string;
|
||||
initialPhotoId?: number;
|
||||
onUploaded?: (photoId: number) => void;
|
||||
}
|
||||
|
||||
export function PhotoSlot({
|
||||
inspectionId,
|
||||
side,
|
||||
slotIndex,
|
||||
label,
|
||||
initialPhotoId,
|
||||
onUploaded,
|
||||
}: Props) {
|
||||
const [photoId, setPhotoId] = useState<number | undefined>(initialPhotoId);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
|
||||
async function handleCapture(file: File) {
|
||||
setUploading(true);
|
||||
try {
|
||||
const result = await uploadPhoto(inspectionId, side, slotIndex, file);
|
||||
setPhotoId(result.id);
|
||||
onUploaded?.(result.id);
|
||||
toast.success(`${label}: загружено`);
|
||||
} catch {
|
||||
toast.error(`${label}: ошибка загрузки`);
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="border rounded-lg p-3 bg-card space-y-2">
|
||||
<div className="text-sm font-medium">{label}</div>
|
||||
{photoId && (
|
||||
<AuthImg
|
||||
src={`photos/${photoId}/thumb`}
|
||||
alt={label}
|
||||
className="w-full aspect-[4/3] object-cover rounded bg-muted"
|
||||
/>
|
||||
)}
|
||||
<CameraCapture
|
||||
onCapture={handleCapture}
|
||||
buttonLabel={photoId ? "Заменить" : "Снять"}
|
||||
/>
|
||||
{uploading && (
|
||||
<div className="text-xs text-muted-foreground">Загружаю…</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
||||
outline:
|
||||
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-10 px-4 py-2",
|
||||
sm: "h-9 rounded-md px-3",
|
||||
lg: "h-11 rounded-md px-8",
|
||||
icon: "h-10 w-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {
|
||||
asChild?: boolean;
|
||||
}
|
||||
|
||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "button";
|
||||
return (
|
||||
<Comp
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
Button.displayName = "Button";
|
||||
|
||||
export { Button, buttonVariants };
|
||||
@@ -0,0 +1,85 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Card = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"rounded-lg border bg-card text-card-foreground shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
Card.displayName = "Card";
|
||||
|
||||
const CardHeader = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("flex flex-col space-y-1.5 p-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
CardHeader.displayName = "CardHeader";
|
||||
|
||||
const CardTitle = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLHeadingElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<h3
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"text-2xl font-semibold leading-none tracking-tight",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
CardTitle.displayName = "CardTitle";
|
||||
|
||||
const CardDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<p
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
CardDescription.displayName = "CardDescription";
|
||||
|
||||
const CardContent = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
|
||||
));
|
||||
CardContent.displayName = "CardContent";
|
||||
|
||||
const CardFooter = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("flex items-center p-6 pt-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
CardFooter.displayName = "CardFooter";
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface InputProps
|
||||
extends React.InputHTMLAttributes<HTMLInputElement> {}
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
Input.displayName = "Input";
|
||||
|
||||
export { Input };
|
||||
@@ -0,0 +1,23 @@
|
||||
import * as React from "react";
|
||||
import * as LabelPrimitive from "@radix-ui/react-label";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const labelVariants = cva(
|
||||
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||
);
|
||||
|
||||
const Label = React.forwardRef<
|
||||
React.ElementRef<typeof LabelPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
|
||||
VariantProps<typeof labelVariants>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<LabelPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(labelVariants(), className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
Label.displayName = LabelPrimitive.Root.displayName;
|
||||
|
||||
export { Label };
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Toaster as SonnerToaster } from "sonner";
|
||||
|
||||
type ToasterProps = React.ComponentProps<typeof SonnerToaster>;
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
return (
|
||||
<SonnerToaster
|
||||
className="toaster group"
|
||||
toastOptions={{
|
||||
classNames: {
|
||||
toast:
|
||||
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
|
||||
description: "group-[.toast]:text-muted-foreground",
|
||||
actionButton:
|
||||
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
|
||||
cancelButton:
|
||||
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
|
||||
},
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export { Toaster };
|
||||
@@ -0,0 +1,110 @@
|
||||
import { useState } from "react";
|
||||
import sedanSrc from "./schemes/sedan-top.svg?raw";
|
||||
|
||||
interface MarkerDot {
|
||||
x: number;
|
||||
y: number;
|
||||
severity?: string | null;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
/** Normalized 0..1 dots overlaid on the scheme. */
|
||||
markers?: MarkerDot[];
|
||||
/** Click handler — receives the zone id like "zone-front". */
|
||||
onZoneClick?: (zoneId: string) => void;
|
||||
/** Per-zone count overlays (e.g. {"zone-front": 2}). Optional. */
|
||||
zoneCounts?: Record<string, number>;
|
||||
}
|
||||
|
||||
const ZONES = [
|
||||
"zone-front",
|
||||
"zone-rear",
|
||||
"zone-left",
|
||||
"zone-right",
|
||||
"zone-hood",
|
||||
"zone-trunk",
|
||||
"zone-roof",
|
||||
];
|
||||
|
||||
const ZONE_LABELS: Record<string, string> = {
|
||||
"zone-front": "Передний бампер",
|
||||
"zone-rear": "Задний бампер",
|
||||
"zone-left": "Левый бок",
|
||||
"zone-right": "Правый бок",
|
||||
"zone-hood": "Капот",
|
||||
"zone-trunk": "Багажник",
|
||||
"zone-roof": "Крыша",
|
||||
};
|
||||
|
||||
// Approximate badge position per zone (percentage of container)
|
||||
const ZONE_BADGE_POSITIONS: Record<string, { x: string; y: string }> = {
|
||||
"zone-front": { x: "50%", y: "10%" },
|
||||
"zone-rear": { x: "50%", y: "90%" },
|
||||
"zone-left": { x: "12%", y: "50%" },
|
||||
"zone-right": { x: "88%", y: "50%" },
|
||||
"zone-hood": { x: "50%", y: "10%" },
|
||||
"zone-trunk": { x: "50%", y: "90%" },
|
||||
"zone-roof": { x: "50%", y: "50%" },
|
||||
};
|
||||
|
||||
export function VehicleScheme({ markers = [], onZoneClick, zoneCounts }: Props) {
|
||||
const [hoverZone, setHoverZone] = useState<string | null>(null);
|
||||
|
||||
return (
|
||||
<div className="relative w-full max-w-xs mx-auto">
|
||||
<div
|
||||
className="vehicle-scheme cursor-pointer"
|
||||
dangerouslySetInnerHTML={{ __html: sedanSrc }}
|
||||
onClick={(e) => {
|
||||
const target = e.target as Element;
|
||||
const id = target.getAttribute?.("id");
|
||||
if (id && ZONES.includes(id)) onZoneClick?.(id);
|
||||
}}
|
||||
onMouseMove={(e) => {
|
||||
const target = e.target as Element;
|
||||
const id = target.getAttribute?.("id");
|
||||
setHoverZone(id && ZONES.includes(id) ? id : null);
|
||||
}}
|
||||
onMouseLeave={() => setHoverZone(null)}
|
||||
/>
|
||||
|
||||
{/* Point markers (red dots) overlaid on the scheme via normalized coords */}
|
||||
{markers.map((m, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="absolute w-3 h-3 rounded-full bg-destructive border border-white pointer-events-none"
|
||||
style={{
|
||||
left: `${m.x * 100}%`,
|
||||
top: `${m.y * 100}%`,
|
||||
transform: "translate(-50%, -50%)",
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* Zone counts as small badges */}
|
||||
{zoneCounts &&
|
||||
Object.entries(zoneCounts).map(([zone, count]) => {
|
||||
if (count <= 0) return null;
|
||||
const pos = ZONE_BADGE_POSITIONS[zone];
|
||||
if (!pos) return null;
|
||||
return (
|
||||
<div
|
||||
key={zone}
|
||||
className="absolute bg-destructive text-destructive-foreground text-xs font-semibold rounded-full w-5 h-5 flex items-center justify-center pointer-events-none"
|
||||
style={{
|
||||
left: pos.x,
|
||||
top: pos.y,
|
||||
transform: "translate(-50%, -50%)",
|
||||
}}
|
||||
>
|
||||
{count}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
<div className="text-xs text-center mt-1 text-muted-foreground min-h-[1em]">
|
||||
{hoverZone ? ZONE_LABELS[hoverZone] : "Тапни по зоне, чтобы добавить метку"}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 400">
|
||||
<rect x="40" y="20" width="120" height="360" rx="40" ry="40"
|
||||
fill="none" stroke="hsl(0 0% 16%)" stroke-width="2"/>
|
||||
<rect x="55" y="60" width="90" height="60" rx="10" fill="hsl(200 30% 88%)"/>
|
||||
<rect x="55" y="280" width="90" height="50" rx="10" fill="hsl(200 30% 88%)"/>
|
||||
<rect x="55" y="130" width="90" height="140" fill="hsl(40 20% 92%)" stroke="hsl(0 0% 60%)" stroke-width="1"/>
|
||||
<rect id="zone-front" x="40" y="20" width="120" height="40" fill="transparent"/>
|
||||
<rect id="zone-rear" x="40" y="340" width="120" height="40" fill="transparent"/>
|
||||
<rect id="zone-left" x="40" y="60" width="20" height="280" fill="transparent"/>
|
||||
<rect id="zone-right" x="140" y="60" width="20" height="280" fill="transparent"/>
|
||||
<rect id="zone-hood" x="55" y="20" width="90" height="40" fill="transparent"/>
|
||||
<rect id="zone-trunk" x="55" y="340" width="90" height="40" fill="transparent"/>
|
||||
<rect id="zone-roof" x="55" y="130" width="90" height="140" fill="transparent"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1,35 @@
|
||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
|
||||
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 40 30% 95%; /* cream */
|
||||
--foreground: 0 0% 16%; /* near-black */
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 0 0% 16%;
|
||||
--primary: 0 0% 16%;
|
||||
--primary-foreground: 40 30% 95%;
|
||||
--secondary: 40 20% 88%;
|
||||
--secondary-foreground: 0 0% 16%;
|
||||
--muted: 40 20% 92%;
|
||||
--muted-foreground: 0 0% 40%;
|
||||
--accent: 40 20% 90%;
|
||||
--accent-foreground: 0 0% 16%;
|
||||
--destructive: 0 70% 50%;
|
||||
--destructive-foreground: 40 30% 95%;
|
||||
--border: 40 15% 85%;
|
||||
--input: 40 15% 85%;
|
||||
--ring: 0 0% 16%;
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* { @apply border-border; }
|
||||
body {
|
||||
@apply bg-background text-foreground font-sans;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { type ClassValue, clsx } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
@@ -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: 30_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,89 @@
|
||||
import { useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { listVehicles } from "@/api/vehicles";
|
||||
import { getMe } from "@/api/me";
|
||||
import { logout } from "@/api/auth";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export default function Home() {
|
||||
const [q, setQ] = useState("");
|
||||
const navigate = useNavigate();
|
||||
|
||||
const meQuery = useQuery({
|
||||
queryKey: ["me"],
|
||||
queryFn: getMe,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
|
||||
const vehiclesQuery = useQuery({
|
||||
queryKey: ["vehicles", q],
|
||||
queryFn: () => listVehicles(q || undefined),
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background">
|
||||
<header className="flex items-center justify-between p-4 border-b">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold">Premium Механик</h1>
|
||||
{meQuery.data && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{meQuery.data.name}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
logout();
|
||||
navigate("/login", { replace: true });
|
||||
}}
|
||||
>
|
||||
Выйти
|
||||
</Button>
|
||||
</header>
|
||||
|
||||
<main className="p-4">
|
||||
<h2 className="text-lg font-semibold mb-3">Машины</h2>
|
||||
<Input
|
||||
placeholder="Поиск по номеру или VIN"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
className="mb-4"
|
||||
/>
|
||||
|
||||
{vehiclesQuery.isLoading ? (
|
||||
<div className="text-sm text-muted-foreground">Загружаю…</div>
|
||||
) : vehiclesQuery.isError ? (
|
||||
<div className="text-sm text-destructive">Не удалось загрузить.</div>
|
||||
) : (vehiclesQuery.data ?? []).length === 0 ? (
|
||||
<div className="text-sm text-muted-foreground">Ничего не найдено.</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{(vehiclesQuery.data ?? []).map((v) => (
|
||||
<Card
|
||||
key={v.id}
|
||||
className="p-4 cursor-pointer hover:shadow-md transition-shadow"
|
||||
onClick={() => navigate(`/vehicles/${v.id}`)}
|
||||
>
|
||||
<div className="font-semibold text-lg">{v.license_plate}</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{[v.make, v.model, v.year].filter(Boolean).join(" ") || "—"}
|
||||
</div>
|
||||
{v.last_inspection_at && (
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
Последний осмотр:{" "}
|
||||
{new Date(v.last_inspection_at).toLocaleDateString("ru-RU")}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
getInspection,
|
||||
patchInspection,
|
||||
createMarker,
|
||||
type MarkerSummary,
|
||||
} from "@/api/inspections";
|
||||
import { PhotoSlot } from "@/components/camera/PhotoSlot";
|
||||
import { VehicleScheme } from "@/components/vehicle-scheme/VehicleScheme";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
|
||||
const SLOTS: { side: string; label: string }[] = [
|
||||
{ side: "front", label: "Перед" },
|
||||
{ side: "rear", label: "Зад" },
|
||||
{ side: "left", label: "Левый бок" },
|
||||
{ side: "right", label: "Правый бок" },
|
||||
{ side: "vin", label: "VIN" },
|
||||
{ side: "odometer", label: "Одометр" },
|
||||
{ side: "interior", label: "Салон" },
|
||||
{ side: "free", label: "Свободное" },
|
||||
];
|
||||
|
||||
const SEVERITY_LABELS: Record<string, string> = {
|
||||
cosmetic: "косметика",
|
||||
minor: "лёгкое",
|
||||
moderate: "среднее",
|
||||
severe: "тяжёлое",
|
||||
};
|
||||
|
||||
const DAMAGE_TYPE_LABELS: Record<string, string> = {
|
||||
damaged: "повреждено",
|
||||
scratch: "царапина",
|
||||
chip: "скол",
|
||||
dent: "вмятина",
|
||||
crack: "трещина",
|
||||
scuff: "затёртость",
|
||||
burn: "прожог",
|
||||
stain: "пятно",
|
||||
bent: "погнуто",
|
||||
torn: "порвано",
|
||||
cut: "порез",
|
||||
puncture: "прокол",
|
||||
bulge: "грыжа",
|
||||
missing: "отсутствует",
|
||||
removed: "снято",
|
||||
"not-working": "не работает",
|
||||
};
|
||||
|
||||
function humanizeMarkerSide(side: string | null | undefined): string {
|
||||
if (!side) return "—";
|
||||
const zoneMap: Record<string, string> = {
|
||||
"zone-front": "Передний бампер",
|
||||
"zone-rear": "Задний бампер",
|
||||
"zone-left": "Левый бок",
|
||||
"zone-right": "Правый бок",
|
||||
"zone-hood": "Капот",
|
||||
"zone-trunk": "Багажник",
|
||||
"zone-roof": "Крыша",
|
||||
};
|
||||
return zoneMap[side] ?? side;
|
||||
}
|
||||
|
||||
export default function InspectionEditor() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const insId = Number(id);
|
||||
const navigate = useNavigate();
|
||||
const qc = useQueryClient();
|
||||
|
||||
const { data: ins, isLoading, isError } = useQuery({
|
||||
queryKey: ["inspection", insId],
|
||||
queryFn: () => getInspection(insId),
|
||||
});
|
||||
|
||||
const finalize = useMutation({
|
||||
mutationFn: () => patchInspection(insId, { status: "completed" }),
|
||||
onSuccess: () => {
|
||||
toast.success("Осмотр завершён");
|
||||
navigate(`/inspections/${insId}`);
|
||||
},
|
||||
onError: () => toast.error("Не удалось завершить"),
|
||||
});
|
||||
|
||||
const addZoneMarker = useMutation({
|
||||
mutationFn: (zone: string) =>
|
||||
createMarker(insId, {
|
||||
side: zone,
|
||||
damage_type: "damaged",
|
||||
severity: "minor",
|
||||
description: "Метка со схемы",
|
||||
}),
|
||||
onSuccess: () => {
|
||||
void qc.invalidateQueries({ queryKey: ["inspection", insId] });
|
||||
toast.success("Метка добавлена");
|
||||
},
|
||||
onError: () => toast.error("Ошибка"),
|
||||
});
|
||||
|
||||
if (isLoading) return <div className="p-8 text-muted-foreground">Загружаю…</div>;
|
||||
if (isError || !ins)
|
||||
return <div className="p-8 text-destructive">Осмотр не найден.</div>;
|
||||
|
||||
// Photos lookup by side+slot for initialPhotoId
|
||||
const photosBySide = new Map<string, typeof ins.photos[0]>();
|
||||
for (const p of ins.photos) photosBySide.set(`${p.side}-${p.slot_index}`, p);
|
||||
|
||||
// Point markers (x/y populated) drawn as dots on the scheme
|
||||
const dots = ins.markers
|
||||
.filter((m: MarkerSummary) => m.x != null && m.y != null)
|
||||
.map((m: MarkerSummary) => ({
|
||||
x: Number(m.x),
|
||||
y: Number(m.y),
|
||||
severity: m.severity ?? "minor",
|
||||
}));
|
||||
|
||||
// Zone counts (markers with side="zone-*", no x/y)
|
||||
const zoneCounts: Record<string, number> = {};
|
||||
for (const m of ins.markers) {
|
||||
if (m.side?.startsWith("zone-")) {
|
||||
zoneCounts[m.side] = (zoneCounts[m.side] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
const editable = ins.status === "in_progress";
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background p-4 space-y-4">
|
||||
<button
|
||||
onClick={() => navigate(-1)}
|
||||
className="text-sm text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
← Назад
|
||||
</button>
|
||||
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold">
|
||||
Осмотр #{ins.id}{" "}
|
||||
<span className="text-muted-foreground text-base">({ins.type})</span>
|
||||
</h1>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{new Date(ins.started_at).toLocaleString("ru-RU")}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card className="p-4">
|
||||
<h2 className="text-sm font-semibold text-muted-foreground mb-2">
|
||||
Схема — тапни по зоне, чтобы добавить метку
|
||||
</h2>
|
||||
<VehicleScheme
|
||||
markers={dots}
|
||||
zoneCounts={zoneCounts}
|
||||
onZoneClick={editable ? (zone) => addZoneMarker.mutate(zone) : undefined}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-muted-foreground mb-2">Фото</h2>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{SLOTS.map((s) => (
|
||||
<PhotoSlot
|
||||
key={`${s.side}-0`}
|
||||
inspectionId={insId}
|
||||
side={s.side}
|
||||
slotIndex={0}
|
||||
label={s.label}
|
||||
initialPhotoId={photosBySide.get(`${s.side}-0`)?.id}
|
||||
onUploaded={() =>
|
||||
void qc.invalidateQueries({ queryKey: ["inspection", insId] })
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{ins.markers.length > 0 && (
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-muted-foreground mb-2">
|
||||
Метки ({ins.markers.length})
|
||||
</h2>
|
||||
<ul className="space-y-1">
|
||||
{ins.markers.map((m: MarkerSummary) => (
|
||||
<li key={m.id}>
|
||||
<Card className="p-3 text-sm">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<span className="font-medium">
|
||||
{humanizeMarkerSide(m.side)}
|
||||
</span>
|
||||
{" — "}
|
||||
<span>
|
||||
{m.damage_type
|
||||
? (DAMAGE_TYPE_LABELS[m.damage_type] ?? m.damage_type)
|
||||
: "—"}
|
||||
</span>
|
||||
{m.severity && (
|
||||
<>
|
||||
{" — "}
|
||||
<span className="text-muted-foreground">
|
||||
{SEVERITY_LABELS[m.severity] ?? m.severity}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{m.carried_over_from_id && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
перенесено
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{m.description && (
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
{m.description}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{editable && (
|
||||
<Button
|
||||
className="w-full"
|
||||
onClick={() => finalize.mutate()}
|
||||
disabled={finalize.isPending}
|
||||
>
|
||||
{finalize.isPending ? "Завершаем…" : "Завершить осмотр"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { getInspection, type MarkerSummary, type PhotoSummary } from "@/api/inspections";
|
||||
import { AuthImg } from "@/components/AuthImg";
|
||||
import { Card } from "@/components/ui/card";
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
in_progress: "В работе",
|
||||
completed: "Завершён",
|
||||
cancelled: "Отменён",
|
||||
};
|
||||
|
||||
export default function InspectionReview() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const insId = Number(id);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { data: ins, isLoading, isError } = useQuery({
|
||||
queryKey: ["inspection", insId],
|
||||
queryFn: () => getInspection(insId),
|
||||
});
|
||||
|
||||
if (isLoading) return <div className="p-8 text-muted-foreground">Загружаю…</div>;
|
||||
if (isError || !ins)
|
||||
return <div className="p-8 text-destructive">Осмотр не найден.</div>;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background p-4 space-y-4">
|
||||
<button
|
||||
onClick={() => navigate(-1)}
|
||||
className="text-sm text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
← Назад
|
||||
</button>
|
||||
|
||||
<h1 className="text-xl font-semibold">Осмотр #{ins.id}</h1>
|
||||
|
||||
<Card className="p-4 text-sm space-y-1">
|
||||
<div>
|
||||
<span className="font-semibold">Тип: </span>
|
||||
{ins.type}
|
||||
</div>
|
||||
<div>
|
||||
<span className="font-semibold">Статус: </span>
|
||||
{STATUS_LABELS[ins.status] ?? ins.status}
|
||||
</div>
|
||||
<div>
|
||||
<span className="font-semibold">Начат: </span>
|
||||
{new Date(ins.started_at).toLocaleString("ru-RU")}
|
||||
</div>
|
||||
{ins.finished_at && (
|
||||
<div>
|
||||
<span className="font-semibold">Завершён: </span>
|
||||
{new Date(ins.finished_at).toLocaleString("ru-RU")}
|
||||
</div>
|
||||
)}
|
||||
{ins.notes && (
|
||||
<div>
|
||||
<span className="font-semibold">Заметки: </span>
|
||||
{ins.notes}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-muted-foreground mb-2">
|
||||
Фото ({ins.photos.length})
|
||||
</h2>
|
||||
{ins.photos.length === 0 ? (
|
||||
<div className="text-sm text-muted-foreground">Нет фото.</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{ins.photos.map((p: PhotoSummary) => (
|
||||
<Card key={p.id} className="overflow-hidden">
|
||||
<AuthImg
|
||||
src={`photos/${p.id}/thumb`}
|
||||
alt={p.side}
|
||||
className="w-full aspect-[4/3] object-cover bg-muted"
|
||||
/>
|
||||
<div className="text-xs text-muted-foreground p-2">{p.side}</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-muted-foreground mb-2">
|
||||
Метки ({ins.markers.length})
|
||||
</h2>
|
||||
{ins.markers.length === 0 ? (
|
||||
<div className="text-sm text-muted-foreground">Нет меток.</div>
|
||||
) : (
|
||||
<ul className="space-y-1">
|
||||
{ins.markers.map((m: MarkerSummary) => (
|
||||
<li key={m.id}>
|
||||
<Card className="p-3 text-sm">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<span>{m.side ?? "—"}</span>
|
||||
{" — "}
|
||||
<span>{m.damage_type ?? "—"}</span>
|
||||
{m.severity && (
|
||||
<span className="text-muted-foreground">
|
||||
{" — "}
|
||||
{m.severity}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{m.resolved && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
устранено
|
||||
</span>
|
||||
)}
|
||||
{m.carried_over_from_id && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
перенесено
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{m.description && (
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
{m.description}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { login } from "@/api/auth";
|
||||
import { useAuth } from "@/store/auth";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
|
||||
export default function Login() {
|
||||
const navigate = useNavigate();
|
||||
const setToken = useAuth((s) => s.setToken);
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
|
||||
const m = useMutation({
|
||||
mutationFn: login,
|
||||
onSuccess: (data) => {
|
||||
setToken(data.access_token);
|
||||
toast.success("Вход выполнен");
|
||||
navigate("/", { replace: true });
|
||||
},
|
||||
onError: () => toast.error("Неверный логин или пароль"),
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-background p-4">
|
||||
<div className="w-full max-w-sm bg-card rounded-2xl shadow-sm p-6 space-y-4">
|
||||
<h1 className="text-2xl font-semibold text-foreground">Premium Механик</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Войдите учётной записью TaxiDashboard.
|
||||
</p>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
m.mutate({ username, password });
|
||||
}}
|
||||
className="space-y-3"
|
||||
>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="username">Логин</Label>
|
||||
<Input
|
||||
id="username"
|
||||
type="text"
|
||||
autoComplete="username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="password">Пароль</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" disabled={m.isPending} className="w-full">
|
||||
{m.isPending ? "Входим…" : "Войти"}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { useQuery, useMutation } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { getVehicle } from "@/api/vehicles";
|
||||
import { createInspection, type InspectionType } from "@/api/inspections";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
|
||||
const INSPECTION_TYPE_LABELS: Record<InspectionType, string> = {
|
||||
handover: "Передача",
|
||||
return: "Приёмка",
|
||||
periodic: "Плановый",
|
||||
"ad-hoc": "Свободный",
|
||||
initial: "Первичный",
|
||||
seizure: "Изъятие",
|
||||
"equipment-change": "Комплектация",
|
||||
"pre-repair": "В ремонт",
|
||||
"post-repair": "Из ремонта",
|
||||
};
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
in_progress: "В работе",
|
||||
completed: "Завершён",
|
||||
cancelled: "Отменён",
|
||||
};
|
||||
|
||||
export default function VehicleCard() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const vehicleId = Number(id);
|
||||
|
||||
const { data: v, isLoading, isError } = useQuery({
|
||||
queryKey: ["vehicle", vehicleId],
|
||||
queryFn: () => getVehicle(vehicleId),
|
||||
});
|
||||
|
||||
const startInspection = useMutation({
|
||||
mutationFn: (type: InspectionType) =>
|
||||
createInspection({ vehicle_id: vehicleId, type }),
|
||||
onSuccess: (inspection) => {
|
||||
navigate(`/inspections/${inspection.id}/edit`);
|
||||
},
|
||||
onError: () => toast.error("Не удалось создать осмотр"),
|
||||
});
|
||||
|
||||
if (isLoading)
|
||||
return <div className="p-8 text-muted-foreground">Загружаю…</div>;
|
||||
if (isError || !v)
|
||||
return <div className="p-8 text-destructive">Машина не найдена.</div>;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background p-4 space-y-4">
|
||||
<button
|
||||
onClick={() => navigate("/")}
|
||||
className="text-sm text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
← К списку
|
||||
</button>
|
||||
|
||||
<Card className="p-4">
|
||||
<div className="text-xl font-semibold">{v.license_plate}</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{[v.make, v.model, v.year].filter(Boolean).join(" ") || "—"}
|
||||
</div>
|
||||
{v.vin && (
|
||||
<div className="text-xs text-muted-foreground mt-1">VIN: {v.vin}</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-muted-foreground mb-2">
|
||||
Начать осмотр
|
||||
</h2>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<Button
|
||||
onClick={() => startInspection.mutate("handover")}
|
||||
disabled={startInspection.isPending}
|
||||
>
|
||||
Передача
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => startInspection.mutate("return")}
|
||||
disabled={startInspection.isPending}
|
||||
>
|
||||
Приёмка
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => startInspection.mutate("periodic")}
|
||||
disabled={startInspection.isPending}
|
||||
>
|
||||
Плановый
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => startInspection.mutate("ad-hoc")}
|
||||
disabled={startInspection.isPending}
|
||||
>
|
||||
Свободный
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => startInspection.mutate("initial")}
|
||||
disabled={startInspection.isPending}
|
||||
>
|
||||
Первичный
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => startInspection.mutate("seizure")}
|
||||
disabled={startInspection.isPending}
|
||||
>
|
||||
Изъятие
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => startInspection.mutate("equipment-change")}
|
||||
disabled={startInspection.isPending}
|
||||
>
|
||||
Комплектация
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => startInspection.mutate("pre-repair")}
|
||||
disabled={startInspection.isPending}
|
||||
>
|
||||
В ремонт
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => startInspection.mutate("post-repair")}
|
||||
disabled={startInspection.isPending}
|
||||
>
|
||||
Из ремонта
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-muted-foreground mb-2">
|
||||
Прошлые осмотры
|
||||
</h2>
|
||||
{v.recent_inspections.length === 0 ? (
|
||||
<Card className="p-4 text-sm text-muted-foreground">
|
||||
Осмотров ещё не было.
|
||||
</Card>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{v.recent_inspections.map((i) => (
|
||||
<Card
|
||||
key={i.id}
|
||||
className="p-3 cursor-pointer hover:shadow-md transition-shadow"
|
||||
onClick={() => navigate(`/inspections/${i.id}`)}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="font-medium">
|
||||
{INSPECTION_TYPE_LABELS[i.type as InspectionType] ?? i.type}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{STATUS_LABELS[i.status] ?? i.status}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
{new Date(i.started_at).toLocaleString("ru-RU")}
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
|
||||
interface AuthState {
|
||||
token: string | null;
|
||||
setToken: (t: string | null) => void;
|
||||
}
|
||||
|
||||
export const useAuth = create<AuthState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
token: null,
|
||||
setToken: (t) => set({ token: t }),
|
||||
}),
|
||||
{ name: "mechanic-auth" }
|
||||
)
|
||||
);
|
||||
@@ -0,0 +1,53 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
export default {
|
||||
darkMode: ["class"],
|
||||
content: ["./index.html", "./src/**/*.{ts,tsx}"],
|
||||
theme: {
|
||||
container: {
|
||||
center: true,
|
||||
padding: "1rem",
|
||||
},
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ["Inter", "system-ui", "sans-serif"],
|
||||
},
|
||||
colors: {
|
||||
border: "hsl(var(--border))",
|
||||
input: "hsl(var(--input))",
|
||||
ring: "hsl(var(--ring))",
|
||||
background: "hsl(var(--background))",
|
||||
foreground: "hsl(var(--foreground))",
|
||||
primary: {
|
||||
DEFAULT: "hsl(var(--primary))",
|
||||
foreground: "hsl(var(--primary-foreground))",
|
||||
},
|
||||
secondary: {
|
||||
DEFAULT: "hsl(var(--secondary))",
|
||||
foreground: "hsl(var(--secondary-foreground))",
|
||||
},
|
||||
destructive: {
|
||||
DEFAULT: "hsl(var(--destructive))",
|
||||
foreground: "hsl(var(--destructive-foreground))",
|
||||
},
|
||||
muted: {
|
||||
DEFAULT: "hsl(var(--muted))",
|
||||
foreground: "hsl(var(--muted-foreground))",
|
||||
},
|
||||
accent: {
|
||||
DEFAULT: "hsl(var(--accent))",
|
||||
foreground: "hsl(var(--accent-foreground))",
|
||||
},
|
||||
card: {
|
||||
DEFAULT: "hsl(var(--card))",
|
||||
foreground: "hsl(var(--card-foreground))",
|
||||
},
|
||||
},
|
||||
borderRadius: {
|
||||
lg: "var(--radius)",
|
||||
md: "calc(var(--radius) - 2px)",
|
||||
sm: "calc(var(--radius) - 4px)",
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"types": ["vite/client"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Strict */
|
||||
"strict": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
|
||||
/* Path alias */
|
||||
"ignoreDeprecations": "6.0",
|
||||
"baseUrl": ".",
|
||||
"paths": { "@/*": ["./src/*"] }
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "esnext",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { VitePWA } from "vite-plugin-pwa";
|
||||
import path from "node:path";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
react(),
|
||||
VitePWA({
|
||||
registerType: "autoUpdate",
|
||||
includeAssets: ["icons/*.png"],
|
||||
manifest: false, // we ship our own at public/manifest.webmanifest
|
||||
workbox: {
|
||||
globPatterns: ["**/*.{js,css,html,svg,png,woff2}"],
|
||||
runtimeCaching: [
|
||||
{
|
||||
urlPattern: /\/api\//,
|
||||
handler: "NetworkOnly",
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
],
|
||||
resolve: {
|
||||
alias: { "@": path.resolve(__dirname, "src") },
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
"/api": "http://localhost:8000",
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
# Caddy fragment for Premium Mechanic PWA on mechanic.pptaxi.ru.
|
||||
# Apply on VDS 100.64.0.12 by copying/including into /etc/caddy/Caddyfile
|
||||
# (or /etc/caddy/sites-enabled/ if the main Caddyfile uses imports).
|
||||
#
|
||||
# Assumes:
|
||||
# - TaxiDashboard backend listens on 127.0.0.1:8000
|
||||
# - Frontend PWA build is rsynced to /opt/sites/mechanic-pwa/dist/
|
||||
|
||||
mechanic.pptaxi.ru {
|
||||
encode gzip zstd
|
||||
|
||||
# PWA: pass /api/* to the backend so the frontend can use relative URLs.
|
||||
handle /api/* {
|
||||
reverse_proxy 127.0.0.1:8000
|
||||
}
|
||||
|
||||
# PWA static files with SPA fallback to index.html.
|
||||
handle {
|
||||
root * /opt/sites/mechanic-pwa/dist
|
||||
try_files {path} /index.html
|
||||
file_server
|
||||
}
|
||||
|
||||
log {
|
||||
output file /var/log/caddy/mechanic.pptaxi.ru.log {
|
||||
roll_size 50mb
|
||||
roll_keep 5
|
||||
}
|
||||
}
|
||||
|
||||
header {
|
||||
# Basic security headers for a PWA
|
||||
Referrer-Policy strict-origin-when-cross-origin
|
||||
X-Content-Type-Options nosniff
|
||||
X-Frame-Options DENY
|
||||
# Camera permission for our origin only
|
||||
Permissions-Policy "camera=(self), microphone=(self), geolocation=()"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#!/bin/bash
|
||||
# Set global CORS allow-origin on MinIO instance (taxi-minio container).
|
||||
# This MinIO version does not expose per-bucket PutBucketCors; CORS is global.
|
||||
#
|
||||
# Run on VDS 100.64.0.12 as root. Idempotent — safe to re-run after origin list changes.
|
||||
set -e
|
||||
export TERM=xterm
|
||||
|
||||
ALLOWED_ORIGINS="https://mechanic.pptaxi.ru,https://crm.pptaxi.ru,http://localhost:5173,http://localhost:8000"
|
||||
|
||||
docker exec taxi-minio sh -c "
|
||||
mc alias set local http://localhost:9000 \"\$MINIO_ROOT_USER\" \"\$MINIO_ROOT_PASSWORD\" >/dev/null
|
||||
mc admin config set local api cors_allow_origin='$ALLOWED_ORIGINS'
|
||||
echo
|
||||
echo '=== verify cors_allow_origin ==='
|
||||
mc admin config get local api | tr ' ' '\n' | grep '^cors_allow_origin='
|
||||
"
|
||||