Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ab4e9e74e | ||
|
|
01c36ce935 | ||
|
|
0ec8f0b540 | ||
|
|
bd1a4a31bd | ||
|
|
b419a456fe | ||
|
|
08ebc09814 | ||
|
|
e5a2874ba7 | ||
|
|
adad929769 | ||
|
|
479b9699ea | ||
|
|
b7dc826f0f | ||
|
|
15d7f34689 | ||
|
|
0fba967cd8 | ||
|
|
66ef403bc0 | ||
|
|
0a164634f8 | ||
|
|
372dc0ede7 | ||
|
|
d769845d88 | ||
|
|
6f76809e9e | ||
|
|
9a116ad94e | ||
|
|
f74f3688ae | ||
|
|
a7032692f1 | ||
|
|
34d3554f72 | ||
|
|
19b91d65c8 | ||
|
|
54ba4edb94 | ||
|
|
19dc1b31a6 | ||
|
|
cc76cc5698 |
@@ -38,3 +38,4 @@ Thumbs.db
|
||||
# IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
.superpowers/
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,68 @@
|
||||
# Премиум Водитель — PWA (дизайн)
|
||||
|
||||
**Дата:** 2026-06-18
|
||||
**Статус:** дизайн согласован (брейншторм + визуальный компаньон). Код не начат.
|
||||
**Цель:** PWA-приложение водителя «Премиум Водитель» — вход по телефону (код через TG/MAX), просмотр баланса (счета из CRM-леджера), пополнение через Т-Банк (СБП/карта), история пополнений. Поверхность для уже построенного бэкенда (Фаза 1 платежей + авторизация водителя в `crm2/app/modules/payments`).
|
||||
|
||||
## Размещение и стек
|
||||
- Новый PWA — **сиблинг** `PremiumDriverApp/driver-pwa/frontend/` (рядом с `mechanic-pwa/`), на том же стеке: **React + Vite + vite-plugin-pwa + TypeScript + Tailwind + @tanstack/react-query + ky + zod + react-router-dom + react-hook-form + zustand + sonner (тосты) + lucide-react + vitest**. Структура `src/{api,components,pages,hooks,lib,store}` как у mechanic-pwa.
|
||||
- Хостинг: **app.pptaxi.ru** (статика + Caddy; деплой как у mechanic — build → dist → tar/rsync, см. mechanic deploy flow).
|
||||
- Имя приложения (везде в UI, манифест PWA, заголовок): **«Премиум Водитель»**.
|
||||
|
||||
## Визуальный язык — Cream Minimal
|
||||
- Палитра (без жёлтого): фон `#F3EEE3` (cream), карточка/поверхность `#FBF8F1`, линия-разделитель `#E4DCCB`, чернила `#1C1B19`, вторичный текст `#7C7361`/opacity. Кнопки primary — тёмные `#1C1B19` с текстом `#F3EEE3`. Долг (минус) `#C0493A`, плюс/депозит `#3B6E4A`.
|
||||
- Типографика: **Inter** (один шрифт), без эмодзи. Иконки — lucide (тонкие, монохром).
|
||||
- Скругления 12–16px, тонкие 1px-границы, мягкие тени минимально. Крупные тап-таргеты (мобайл-фёрст). App-like / edit-first: минимум лишних кнопок, экран сам реагирует.
|
||||
|
||||
## Экраны (MVP)
|
||||
1. **Вход.**
|
||||
- Шаг 1: поле телефона `+7 ___ ___-__-__` → «Получить код». → `POST /api/driver/auth/request {phone}`.
|
||||
- Если ответ `code_sent` → шаг 2: ввод кода (свой цифровой кейпад) → `POST /api/driver/auth/verify {phone, code}` → сохраняем driver JWT → на «Баланс».
|
||||
- Если ответ `onboarding` → экран «Подключите бота»: две кнопки **Telegram** / **MAX** (открывают `deep_links.tg`/`.max`); подсказка «нажмите Старт у бота, затем вернитесь и запросите код снова». Кнопка «Я подключил — запросить код».
|
||||
2. **Баланс** (компоновка B: hero + список).
|
||||
- Шапка: «Премиум Водитель» + инициалы водителя.
|
||||
- **Hero-блок «Общий долг»** — крупная сумма (сумма отрицательных счетов).
|
||||
- **Список счетов** (bucket из `/api/driver/balance`): название + подпись (марка/госномер для аренды, «N неоплаченных» для штрафов) + значение (минус — красный, плюс — зелёный).
|
||||
- Кнопка **«Пополнить»** (primary). Тап по счёту/кнопке → «Пополнение» с предвыбранным счётом.
|
||||
- Внизу/в меню: «История», «Выйти».
|
||||
3. **Пополнение** (компоновка C: свой кейпад).
|
||||
- Заголовок «Пополнить · <счёт>». Крупная сумма. Строка «к оплате X ₽ (комиссия Y ₽)» — пересчёт на лету по ставке (получаем из ответа `/topup` или показываем оценку и уточняем).
|
||||
- **Свой цифровой кейпад** (1–9, 0, ·, ⌫) — без системной клавиатуры; крупные клавиши. Быстрые суммы 500/1000/2000 (чипы).
|
||||
- Сегмент **СБП / Картой**.
|
||||
- Кнопка **«Оплатить»** → `POST /api/driver/topup {bucket, amount, method}` → получаем `{order_id, pay_url}`.
|
||||
4. **Оплата / статус** (вариант A: авто-статус, без QR).
|
||||
- Иконка «СБП», сумма к оплате, кнопка **«Оплатить через СБП»** (или «Оплатить картой») → открывает `pay_url` (СБП deep-link `qr.nspk.ru/...` → приложение банка; карта → форма `pay.tbank.ru`). **QR не показываем, «оплата с другого устройства» убрана** — водитель платит на том же телефоне через приложение банка.
|
||||
- Под кнопкой — авто-статус «Ожидаем оплату…» (спиннер). Приложение **опрашивает статус** платежа; при `PAID` → экран **«Оплачено»** (зелёная галочка, «<счёт> пополнен на N ₽») → кнопка «На главную» (баланс перезапрашивается).
|
||||
5. **История пополнений.**
|
||||
- Список из `driver_payments` водителя: дата, счёт, сумма, статус (Оплачено/Ожидает/Отклонён), способ. Пусто → «Пока нет пополнений».
|
||||
6. **Выход** — очистка JWT, возврат на «Вход».
|
||||
|
||||
## Поток данных / API (crm2 BFF, префикс `/api`)
|
||||
Готово (Фаза 1 + авторизация):
|
||||
- `POST /driver/auth/request {phone}` → `{status:"code_sent",channel}` | `{status:"onboarding",deep_links:{tg,max}}`
|
||||
- `POST /driver/auth/verify {phone, code}` → `{token, driver_id}`
|
||||
- `GET /driver/balance` (Bearer) → `{accounts:[{bucket, balance}]}`
|
||||
- `POST /driver/topup {bucket, amount, method}` (Bearer) → `{order_id, pay_url, commission, total}`
|
||||
|
||||
**Нужно добавить на бэкенде (зависимость этого PWA — отдельные backend-задачи):**
|
||||
- `GET /driver/payments` (Bearer) → история пополнений водителя (из `driver_payments`: order_id, bucket, amount, commission, method, status, created_at, paid_at).
|
||||
- `GET /driver/payment/{order_id}` (Bearer) → `{status}` для авто-опроса статуса оплаты (NEW/FORM/PAID/REJECTED). (Альтернатива: опрашивать `/driver/balance` и сравнивать — но явный статус надёжнее и показывает «Оплачено».)
|
||||
- (Опц.) В `/driver/topup` вернуть и `commission_rate`, чтобы кейпад считал «к оплате» локально до запроса.
|
||||
|
||||
## Сессия / клиент
|
||||
- driver JWT (typ='driver', 30 дн) хранится в `localStorage`; `ky`-инстанс добавляет `Authorization: Bearer`. На 401 → разлогин (на «Вход»).
|
||||
- `@tanstack/react-query` для balance/history (кэш + рефетч); `zod` валидирует ответы; `zustand` — сессия (token, driver_id). Тосты ошибок — `sonner`.
|
||||
- База API из env (`VITE_API_BASE`, по умолчанию `https://crm.pptaxi.ru/api`). CORS: бэкенд должен разрешить origin `https://app.pptaxi.ru` для `/api/driver/*` (backend-задача).
|
||||
|
||||
## PWA
|
||||
- `vite-plugin-pwa`: manifest (name «Премиум Водитель», cream theme `#F3EEE3`, иконки 192/512, standalone, портрет), service worker (precache оболочки, network-first для API). Устанавливается на телефон без сторов (по ссылке app.pptaxi.ru → «На экран Домой»).
|
||||
|
||||
## Обработка ошибок
|
||||
- Телефон не найден (404) → «Номер не найден. Обратитесь в парк.» Неверный код (401) → «Неверный или просроченный код» + повтор. Платёж не создан → тост + остаёмся на «Пополнении». Авто-опрос: таймаут N минут → «Не дождались оплаты» + кнопка «Проверить ещё раз»/«Вернуться».
|
||||
|
||||
## Тестирование
|
||||
- vitest + @testing-library/react: рендер экранов, кейпад (ввод/⌫/быстрые суммы, пересчёт «к оплате»), форма телефона/кода, маппинг ответов API (zod-схемы), guard приватных роутов (нет токена → «Вход»), авто-статус (мок таймера/опроса → success). API мокается (msw или ky-mock), без сети.
|
||||
|
||||
## Скоуп / порядок
|
||||
MVP-экраны: Вход (+онбординг) · Баланс · Пополнение · Оплата/статус · История · Выход. **Вне MVP:** push-уведомления, вывод средств, профиль/настройки, мультиязычность.
|
||||
Порядок сборки (для плана): каркас приложения+PWA+API-клиент+сессия → Вход/онбординг → Баланс → Пополнение(кейпад) → Оплата/авто-статус → История → деплой app.pptaxi.ru. Бэкенд-зависимости (`/driver/payments`, `/driver/payment/{order_id}`, CORS) — отдельные мелкие задачи в crm2 (сделать до/параллельно соответствующим экранам).
|
||||
@@ -0,0 +1 @@
|
||||
VITE_API_BASE=https://crm.pptaxi.ru/api
|
||||
@@ -0,0 +1,5 @@
|
||||
node_modules
|
||||
dist
|
||||
.env
|
||||
.env.local
|
||||
*.tsbuildinfo
|
||||
@@ -0,0 +1,16 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#F3EEE3" />
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet" />
|
||||
<title>Премиум Водитель</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+8358
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "driver-pwa",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview",
|
||||
"lint": "eslint .",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.51.0",
|
||||
"ky": "^1.7.2",
|
||||
"lucide-react": "^0.454.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^6.26.0",
|
||||
"sonner": "^1.5.0",
|
||||
"zod": "^3.23.8",
|
||||
"zustand": "^4.5.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/jest-dom": "^6.5.0",
|
||||
"@testing-library/react": "^16.0.1",
|
||||
"@testing-library/user-event": "^14.5.2",
|
||||
"@types/node": "^22.5.0",
|
||||
"@types/react": "^18.3.5",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"@vitejs/plugin-react": "^4.3.1",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"jsdom": "^25.0.0",
|
||||
"postcss": "^8.4.45",
|
||||
"tailwindcss": "^3.4.10",
|
||||
"typescript": "^5.5.4",
|
||||
"vite": "^5.4.2",
|
||||
"vite-plugin-pwa": "^0.20.5",
|
||||
"vitest": "^2.0.5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export default { plugins: { tailwindcss: {}, autoprefixer: {} } };
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 909 B |
Binary file not shown.
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "Премиум Водитель",
|
||||
"short_name": "Премиум",
|
||||
"start_url": "/",
|
||||
"display": "standalone",
|
||||
"orientation": "portrait",
|
||||
"background_color": "#F3EEE3",
|
||||
"theme_color": "#F3EEE3",
|
||||
"icons": [
|
||||
{ "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
|
||||
{ "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// Генерация PWA-иконок «Премиум Водитель» без сторонних либ (zlib PNG-энкодер).
|
||||
// Дизайн: кремовый фон #F3EEE3, тёмная скруглённая плитка #1C1B19,
|
||||
// внутри белая «карта» #F6F2E9 с тёмной полосой (финансовый мотив). Без жёлтого/текста.
|
||||
import zlib from "node:zlib";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
const CREAM = [243, 238, 227];
|
||||
const INK = [28, 27, 25];
|
||||
const CARD = [246, 242, 233];
|
||||
|
||||
function crc32(buf) {
|
||||
let c = ~0;
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
c ^= buf[i];
|
||||
for (let k = 0; k < 8; k++) c = (c >>> 1) ^ (0xedb88320 & -(c & 1));
|
||||
}
|
||||
return (~c) >>> 0;
|
||||
}
|
||||
function chunk(type, data) {
|
||||
const t = Buffer.from(type, "ascii");
|
||||
const len = Buffer.alloc(4); len.writeUInt32BE(data.length, 0);
|
||||
const body = Buffer.concat([t, data]);
|
||||
const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(body), 0);
|
||||
return Buffer.concat([len, body, crc]);
|
||||
}
|
||||
function encodePng(N, rgba) {
|
||||
const sig = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
||||
const ihdr = Buffer.alloc(13);
|
||||
ihdr.writeUInt32BE(N, 0); ihdr.writeUInt32BE(N, 4); ihdr[8] = 8; ihdr[9] = 6;
|
||||
const stride = N * 4;
|
||||
const raw = Buffer.alloc(N * (stride + 1));
|
||||
for (let y = 0; y < N; y++) {
|
||||
raw[y * (stride + 1)] = 0;
|
||||
rgba.copy(raw, y * (stride + 1) + 1, y * stride, y * stride + stride);
|
||||
}
|
||||
return Buffer.concat([sig, chunk("IHDR", ihdr), chunk("IDAT", zlib.deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]);
|
||||
}
|
||||
function inRoundRect(px, py, x0, y0, x1, y1, r) {
|
||||
if (px < x0 || px >= x1 || py < y0 || py >= y1) return false;
|
||||
const cx = px < x0 + r ? x0 + r : px >= x1 - r ? x1 - r : px;
|
||||
const cy = py < y0 + r ? y0 + r : py >= y1 - r ? y1 - r : py;
|
||||
const dx = px - cx, dy = py - cy;
|
||||
return dx * dx + dy * dy <= r * r;
|
||||
}
|
||||
|
||||
function draw(N) {
|
||||
const buf = Buffer.alloc(N * N * 4);
|
||||
// tile (centered ~64%)
|
||||
const tile = Math.round(N * 0.64), tx0 = Math.round((N - tile) / 2), ty0 = tx0;
|
||||
const tx1 = tx0 + tile, ty1 = ty0 + tile, tr = Math.round(tile * 0.24);
|
||||
// card inside tile
|
||||
const cw = Math.round(tile * 0.62), ch = Math.round(tile * 0.42);
|
||||
const cx0 = Math.round((N - cw) / 2), cy0 = Math.round((N - ch) / 2);
|
||||
const cx1 = cx0 + cw, cy1 = cy0 + ch, cr = Math.round(ch * 0.18);
|
||||
// stripe near top of card
|
||||
const sy0 = cy0 + Math.round(ch * 0.22), sy1 = sy0 + Math.round(ch * 0.14);
|
||||
for (let y = 0; y < N; y++) {
|
||||
for (let x = 0; x < N; x++) {
|
||||
let col = CREAM;
|
||||
if (inRoundRect(x, y, tx0, ty0, tx1, ty1, tr)) col = INK;
|
||||
if (inRoundRect(x, y, cx0, cy0, cx1, cy1, cr)) col = CARD;
|
||||
if (x >= cx0 && x < cx1 && y >= sy0 && y < sy1) col = INK;
|
||||
const o = (y * N + x) * 4;
|
||||
buf[o] = col[0]; buf[o + 1] = col[1]; buf[o + 2] = col[2]; buf[o + 3] = 255;
|
||||
}
|
||||
}
|
||||
return encodePng(N, buf);
|
||||
}
|
||||
|
||||
const dir = path.resolve("public/icons");
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
for (const N of [192, 512]) {
|
||||
fs.writeFileSync(path.join(dir, `icon-${N}.png`), draw(N));
|
||||
console.log(`wrote icon-${N}.png`);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import App from "./App";
|
||||
import { useAuth } from "@/store/auth";
|
||||
|
||||
function renderAt(path: string) {
|
||||
const qc = new QueryClient();
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
<App />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe("routing guard", () => {
|
||||
beforeEach(() => useAuth.getState().clear());
|
||||
it("redirects to login when no token", () => {
|
||||
renderAt("/");
|
||||
expect(screen.getByText(/Вход в приложение/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { Navigate, Route, Routes } from "react-router-dom";
|
||||
import { useAuth } from "@/store/auth";
|
||||
import { LoginPage } from "@/pages/LoginPage";
|
||||
import { TgWaitPage } from "@/pages/TgWaitPage";
|
||||
import { OnboardingPage } from "@/pages/OnboardingPage";
|
||||
import { BalancePage } from "@/pages/BalancePage";
|
||||
import { TopupPage } from "@/pages/TopupPage";
|
||||
import { PaymentPage } from "@/pages/PaymentPage";
|
||||
import { HistoryPage } from "@/pages/HistoryPage";
|
||||
|
||||
function RequireAuth({ children }: { children: ReactNode }) {
|
||||
const token = useAuth((s) => s.token);
|
||||
return token ? <>{children}</> : <Navigate to="/login" replace />;
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<div className="mx-auto max-w-md min-h-full px-4 pt-3 pb-8">
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/tg-wait" element={<TgWaitPage />} />
|
||||
<Route path="/onboarding" element={<OnboardingPage />} />
|
||||
<Route path="/" element={<RequireAuth><BalancePage /></RequireAuth>} />
|
||||
<Route path="/topup" element={<RequireAuth><TopupPage /></RequireAuth>} />
|
||||
<Route path="/pay/:orderId" element={<RequireAuth><PaymentPage /></RequireAuth>} />
|
||||
<Route path="/history" element={<RequireAuth><HistoryPage /></RequireAuth>} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import ky, { type KyInstance } from "ky";
|
||||
import { useAuth } from "@/store/auth";
|
||||
|
||||
const API_BASE = import.meta.env.VITE_API_BASE ?? "https://crm.pptaxi.ru/api";
|
||||
|
||||
export const api: KyInstance = ky.create({
|
||||
prefixUrl: API_BASE,
|
||||
timeout: 30_000,
|
||||
retry: { limit: 2, methods: ["get"] },
|
||||
hooks: {
|
||||
beforeRequest: [
|
||||
(request) => {
|
||||
const token = useAuth.getState().token;
|
||||
if (token) request.headers.set("Authorization", `Bearer ${token}`);
|
||||
},
|
||||
],
|
||||
beforeError: [
|
||||
(error) => {
|
||||
if (error.response?.status === 401) useAuth.getState().clear();
|
||||
return error;
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { BalanceSchema, TopupSchema, PaymentsSchema, AuthRequestSchema, TgSessionSchema, TgPollSchema } from "./driver";
|
||||
|
||||
describe("driver api schemas", () => {
|
||||
it("parses balance", () => {
|
||||
const v = BalanceSchema.parse({ accounts: [{ bucket: "Долг аренда", balance: -3200 }] });
|
||||
expect(v.accounts[0].bucket).toBe("Долг аренда");
|
||||
});
|
||||
it("parses topup", () => {
|
||||
const v = TopupSchema.parse({ order_id: "o1", pay_url: "https://x", commission: 52, total: 1052 });
|
||||
expect(v.pay_url).toBe("https://x");
|
||||
});
|
||||
it("parses auth request onboarding + code_sent", () => {
|
||||
expect(AuthRequestSchema.parse({ status: "code_sent", channel: "tg" }).status).toBe("code_sent");
|
||||
const o = AuthRequestSchema.parse({ status: "onboarding", deep_links: { tg: "t", max: "m" } });
|
||||
expect(o.status === "onboarding" && o.deep_links.tg).toBe("t");
|
||||
// prod: MAX bot not configured → backend omits `max`, must still parse (regression guard)
|
||||
const tgOnly = AuthRequestSchema.parse({ status: "onboarding", deep_links: { tg: "t" } });
|
||||
expect(tgOnly.status === "onboarding" && tgOnly.deep_links.tg).toBe("t");
|
||||
});
|
||||
it("parses payments history", () => {
|
||||
const v = PaymentsSchema.parse({ payments: [{ order_id: "o1", bucket: "b", amount: 100,
|
||||
commission: 5.2, method: "qr", status: "PAID", created_at: "2026-06-18T09:00:00Z", paid_at: null }] });
|
||||
expect(v.payments[0].status).toBe("PAID");
|
||||
});
|
||||
});
|
||||
|
||||
describe("tg verified-login schemas", () => {
|
||||
it("parses tg session", () => {
|
||||
const v = TgSessionSchema.parse({ pair_session: "S", deep_link: "https://t.me/x?start=S" });
|
||||
expect(v.pair_session).toBe("S");
|
||||
});
|
||||
it("parses tg poll states", () => {
|
||||
expect(TgPollSchema.parse({ status: "pending" }).status).toBe("pending");
|
||||
expect(TgPollSchema.parse({ status: "expired" }).status).toBe("expired");
|
||||
const a = TgPollSchema.parse({ status: "authenticated", token: "T", driver_id: 7 });
|
||||
expect(a.status === "authenticated" && a.token).toBe("T");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { z } from "zod";
|
||||
import { api } from "./client";
|
||||
|
||||
export const AuthRequestSchema = z.union([
|
||||
z.object({ status: z.literal("code_sent"), channel: z.string() }),
|
||||
z.object({ status: z.literal("onboarding"), deep_links: z.object({ tg: z.string().optional(), max: z.string().optional() }) }),
|
||||
]);
|
||||
export type AuthRequest = z.infer<typeof AuthRequestSchema>;
|
||||
|
||||
export const VerifySchema = z.object({ token: z.string(), driver_id: z.number() });
|
||||
export const BalanceSchema = z.object({
|
||||
accounts: z.array(z.object({ bucket: z.string(), balance: z.number() })),
|
||||
});
|
||||
export const TopupSchema = z.object({
|
||||
order_id: z.string(), pay_url: z.string(), commission: z.number(), total: z.number(),
|
||||
});
|
||||
export const PaymentStateSchema = z.object({ order_id: z.string(), status: z.string() });
|
||||
export const CommissionSchema = z.object({ rate: z.number() });
|
||||
export const PaymentsSchema = z.object({
|
||||
payments: z.array(z.object({
|
||||
order_id: z.string(), bucket: z.string(), amount: z.number(), commission: z.number(),
|
||||
method: z.string(), status: z.string(),
|
||||
created_at: z.string().nullable(), paid_at: z.string().nullable(),
|
||||
})),
|
||||
});
|
||||
|
||||
export const TgSessionSchema = z.object({
|
||||
pair_session: z.string(),
|
||||
deep_link: z.string().nullable(),
|
||||
});
|
||||
export const TgPollSchema = z.union([
|
||||
z.object({ status: z.literal("pending") }),
|
||||
z.object({ status: z.literal("expired") }),
|
||||
z.object({ status: z.literal("authenticated"), token: z.string(), driver_id: z.number() }),
|
||||
]);
|
||||
|
||||
export const tgSession = async () =>
|
||||
TgSessionSchema.parse(await api.post("driver/auth/tg/session").json());
|
||||
export const tgPoll = async (pairSession: string) =>
|
||||
TgPollSchema.parse(await api.get("driver/auth/tg/poll", { searchParams: { pair_session: pairSession } }).json());
|
||||
|
||||
export const authRequest = async (phone: string) =>
|
||||
AuthRequestSchema.parse(await api.post("driver/auth/request", { json: { phone } }).json());
|
||||
export const authVerify = async (phone: string, code: string) =>
|
||||
VerifySchema.parse(await api.post("driver/auth/verify", { json: { phone, code } }).json());
|
||||
export const getBalance = async () =>
|
||||
BalanceSchema.parse(await api.get("driver/balance").json());
|
||||
export const topup = async (bucket: string, amount: number, method: "qr" | "card") =>
|
||||
TopupSchema.parse(await api.post("driver/topup", { json: { bucket, amount, method } }).json());
|
||||
export const getPaymentState = async (orderId: string) =>
|
||||
PaymentStateSchema.parse(await api.get(`driver/payment/${orderId}`).json());
|
||||
export const getPayments = async () =>
|
||||
PaymentsSchema.parse(await api.get("driver/payments").json());
|
||||
export const getCommission = async () =>
|
||||
CommissionSchema.parse(await api.get("driver/commission").json());
|
||||
@@ -0,0 +1,7 @@
|
||||
export function AppHeader() {
|
||||
return (
|
||||
<header className="mb-4">
|
||||
<span className="text-sm font-bold">Премиум Водитель</span>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
interface Props { value: string; options: { value: string; label: string }[]; onChange: (v: string) => void; }
|
||||
export function Segment({ value, options, onChange }: Props) {
|
||||
return (
|
||||
<div className="flex gap-1.5">
|
||||
{options.map((o) => (
|
||||
<button
|
||||
key={o.value}
|
||||
type="button"
|
||||
onClick={() => onChange(o.value)}
|
||||
className={`flex-1 py-2.5 rounded-xl2 text-xs border ${
|
||||
value === o.value ? "bg-ink text-cream border-ink font-bold" : "bg-surface border-line text-muted"
|
||||
}`}
|
||||
>
|
||||
{o.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export function Spinner() {
|
||||
return <span className="inline-block w-3.5 h-3.5 border-2 border-line border-t-ink rounded-full animate-spin" />;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// src/hooks/usePairPoll.test.tsx
|
||||
import { renderHook, waitFor } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { usePairPoll } from "./usePairPoll";
|
||||
import * as driver from "@/api/driver";
|
||||
import { useAuth } from "@/store/auth";
|
||||
|
||||
beforeEach(() => { useAuth.getState().clear(); vi.restoreAllMocks(); });
|
||||
|
||||
describe("usePairPoll", () => {
|
||||
it("sets session on authenticated", async () => {
|
||||
vi.spyOn(driver, "tgPoll").mockResolvedValue({ status: "authenticated", token: "T", driver_id: 7 } as any);
|
||||
const { result } = renderHook(() => usePairPoll("SESS"));
|
||||
await waitFor(() => expect(result.current.status).toBe("authenticated"));
|
||||
expect(useAuth.getState().token).toBe("T");
|
||||
expect(useAuth.getState().driverId).toBe(7);
|
||||
});
|
||||
it("stays pending then expired", async () => {
|
||||
vi.spyOn(driver, "tgPoll").mockResolvedValue({ status: "expired" } as any);
|
||||
const { result } = renderHook(() => usePairPoll("SESS"));
|
||||
await waitFor(() => expect(result.current.status).toBe("expired"));
|
||||
});
|
||||
it("does nothing when session is null", () => {
|
||||
const spy = vi.spyOn(driver, "tgPoll");
|
||||
const { result } = renderHook(() => usePairPoll(null));
|
||||
expect(result.current.status).toBe("pending");
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
// src/hooks/usePairPoll.ts
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { tgPoll } from "@/api/driver";
|
||||
import { useAuth } from "@/store/auth";
|
||||
|
||||
type Status = "pending" | "authenticated" | "expired";
|
||||
const INTERVAL_MS = 2000;
|
||||
const TIMEOUT_MS = 5 * 60 * 1000;
|
||||
|
||||
export function usePairPoll(pairSession: string | null): { status: Status } {
|
||||
const [status, setStatus] = useState<Status>("pending");
|
||||
const setSession = useAuth((s) => s.setSession);
|
||||
const startedAt = useRef<number>(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (!pairSession) return;
|
||||
let alive = true;
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
startedAt.current = Date.now();
|
||||
|
||||
const tick = async () => {
|
||||
if (!alive) return;
|
||||
try {
|
||||
const r = await tgPoll(pairSession);
|
||||
if (!alive) return;
|
||||
if (r.status === "authenticated") {
|
||||
setSession(r.token, r.driver_id);
|
||||
setStatus("authenticated");
|
||||
return;
|
||||
}
|
||||
if (r.status === "expired") { setStatus("expired"); return; }
|
||||
} catch {
|
||||
// transient — keep polling until timeout
|
||||
}
|
||||
if (Date.now() - startedAt.current > TIMEOUT_MS) { setStatus("expired"); return; }
|
||||
timer = setTimeout(tick, INTERVAL_MS);
|
||||
};
|
||||
tick();
|
||||
return () => { alive = false; clearTimeout(timer); };
|
||||
}, [pairSession, setSession]);
|
||||
|
||||
return { status };
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { getPaymentState } from "@/api/driver";
|
||||
|
||||
const TERMINAL = new Set(["PAID", "CONFIRMED", "REJECTED", "REVERSED", "REFUNDED", "CANCELED", "AUTH_FAIL"]);
|
||||
|
||||
export function usePaymentStatus(orderId: string) {
|
||||
return useQuery({
|
||||
queryKey: ["payment", orderId],
|
||||
queryFn: () => getPaymentState(orderId),
|
||||
refetchInterval: (q) => (q.state.data && TERMINAL.has(q.state.data.status) ? false : 1500),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
html, body, #root { height: 100%; }
|
||||
body { @apply bg-cream text-ink font-sans antialiased; margin: 0; }
|
||||
button { font-family: inherit; }
|
||||
|
||||
@layer components {
|
||||
.btn-primary { @apply bg-ink text-cream rounded-xl2 py-3.5 px-4 text-sm font-bold text-center w-full active:opacity-90 disabled:opacity-50; }
|
||||
.btn-ghost { @apply border border-ink text-ink rounded-xl2 py-3 px-4 text-sm font-semibold text-center w-full; }
|
||||
.card { @apply bg-surface border border-line rounded-2xl; }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { keypadReduce, withCommission } from "./amount";
|
||||
|
||||
describe("amount keypad", () => {
|
||||
it("appends digits, ignores leading zero, caps length", () => {
|
||||
expect(keypadReduce("0", "5")).toBe("5");
|
||||
expect(keypadReduce("100", "0")).toBe("1000");
|
||||
expect(keypadReduce("", "0")).toBe("");
|
||||
expect(keypadReduce("999999", "9")).toBe("999999");
|
||||
});
|
||||
it("backspace removes last digit", () => {
|
||||
expect(keypadReduce("105", "back")).toBe("10");
|
||||
expect(keypadReduce("", "back")).toBe("");
|
||||
});
|
||||
it("withCommission computes total at given rate", () => {
|
||||
expect(withCommission(1000, 0.052)).toEqual({ commission: 52, total: 1052 });
|
||||
expect(withCommission(333, 0.052)).toEqual({ commission: 17.32, total: 350.32 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
const MAX_DIGITS = 6;
|
||||
|
||||
export function keypadReduce(current: string, key: string): string {
|
||||
if (key === "back") return current.slice(0, -1);
|
||||
if (!/^\d$/.test(key)) return current;
|
||||
if (current === "0") return key === "0" ? "0" : key; // replace leading zero
|
||||
if (current === "" && key === "0") return ""; // no leading zero from empty
|
||||
if (current.length >= MAX_DIGITS) return current;
|
||||
return current + key;
|
||||
}
|
||||
|
||||
export function withCommission(base: number, rate: number): { commission: number; total: number } {
|
||||
const commission = Math.round(base * rate * 100) / 100;
|
||||
const total = Math.round((base + commission) * 100) / 100;
|
||||
return { commission, total };
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { formatMoney, formatPhone, digitsOnly } from "./format";
|
||||
|
||||
describe("format", () => {
|
||||
it("formatMoney groups thousands and adds ₽", () => {
|
||||
expect(formatMoney(1000)).toBe("1 000 ₽");
|
||||
expect(formatMoney(-3200)).toBe("−3 200 ₽");
|
||||
expect(formatMoney(0)).toBe("0 ₽");
|
||||
});
|
||||
it("digitsOnly strips non-digits", () => {
|
||||
expect(digitsOnly("+7 (914) 305-44-00")).toBe("79143054400");
|
||||
});
|
||||
it("formatPhone renders +7 mask progressively", () => {
|
||||
expect(formatPhone("9143054400")).toBe("+7 914 305-44-00");
|
||||
expect(formatPhone("914305")).toBe("+7 914 305");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
export function digitsOnly(s: string): string {
|
||||
return (s || "").replace(/\D/g, "");
|
||||
}
|
||||
|
||||
export function formatMoney(rub: number): string {
|
||||
const neg = rub < 0;
|
||||
const abs = Math.abs(Math.round(rub));
|
||||
const grouped = abs.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
|
||||
return `${neg ? "−" : ""}${grouped} ₽`;
|
||||
}
|
||||
|
||||
/** Render a Russian mobile from up-to-10 national digits as +7 914 305-44-00. */
|
||||
export function formatPhone(national10: string): string {
|
||||
const d = digitsOnly(national10).slice(0, 10);
|
||||
const p: string[] = ["+7"];
|
||||
if (d.length > 0) p.push(" " + d.slice(0, 3));
|
||||
if (d.length > 3) p.push(" " + d.slice(3, 6));
|
||||
if (d.length > 6) p.push("-" + d.slice(6, 8));
|
||||
if (d.length > 8) p.push("-" + d.slice(8, 10));
|
||||
return p.join("");
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import { BrowserRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { Toaster } from "sonner";
|
||||
import App from "./App";
|
||||
import "./index.css";
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: 1, staleTime: 15_000 } },
|
||||
});
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root")!).render(
|
||||
<React.StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
<Toaster richColors position="top-center" />
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
</React.StrictMode>
|
||||
);
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
|
||||
vi.mock("@/api/driver", () => ({
|
||||
getBalance: vi.fn(async () => ({
|
||||
accounts: [
|
||||
{ bucket: "Долг аренда", balance: -3200 },
|
||||
{ bucket: "Депозит", balance: 5000 },
|
||||
],
|
||||
})),
|
||||
}));
|
||||
|
||||
import { BalancePage } from "./BalancePage";
|
||||
|
||||
function wrap() {
|
||||
const qc = new QueryClient();
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<MemoryRouter><BalancePage /></MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe("BalancePage", () => {
|
||||
it("shows hero total (sum of negatives) and account rows", async () => {
|
||||
wrap();
|
||||
expect(await screen.findByText("Долг аренда")).toBeInTheDocument();
|
||||
expect(screen.getByText("Депозит")).toBeInTheDocument();
|
||||
// Appears in both the hero total and the single debt account row.
|
||||
expect(screen.getAllByText("−3 200 ₽").length).toBeGreaterThan(0);
|
||||
expect(screen.getByRole("button", { name: /Пополнить/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows an error state when balance fails to load", async () => {
|
||||
const driver = await import("@/api/driver");
|
||||
(driver.getBalance as any).mockRejectedValueOnce(new Error("boom"));
|
||||
// re-render fresh
|
||||
const { QueryClient, QueryClientProvider } = await import("@tanstack/react-query");
|
||||
const { MemoryRouter } = await import("react-router-dom");
|
||||
const { render, screen } = await import("@testing-library/react");
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
render(<QueryClientProvider client={qc}><MemoryRouter><BalancePage /></MemoryRouter></QueryClientProvider>);
|
||||
expect(await screen.findByText(/Не удалось загрузить/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { History, LogOut } from "lucide-react";
|
||||
import { getBalance } from "@/api/driver";
|
||||
import { formatMoney } from "@/lib/format";
|
||||
import { useAuth } from "@/store/auth";
|
||||
import { AppHeader } from "@/components/AppHeader";
|
||||
import { Spinner } from "@/components/Spinner";
|
||||
|
||||
export function BalancePage() {
|
||||
const nav = useNavigate();
|
||||
const clear = useAuth((s) => s.clear);
|
||||
const { data, isLoading, isError, refetch } = useQuery({ queryKey: ["balance"], queryFn: getBalance });
|
||||
|
||||
const accounts = data?.accounts ?? [];
|
||||
const totalDebt = accounts.filter((a) => a.balance < 0).reduce((s, a) => s + a.balance, 0);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<AppHeader />
|
||||
<div className="card p-4 mb-4 text-center">
|
||||
<p className="text-muted text-xs mb-1">Общий долг</p>
|
||||
<p className={`text-2xl font-extrabold ${totalDebt < 0 ? "text-neg" : ""}`}>{formatMoney(totalDebt)}</p>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex justify-center py-10"><Spinner /></div>
|
||||
) : isError ? (
|
||||
<div className="text-center py-8">
|
||||
<p className="text-muted text-sm mb-3">Не удалось загрузить баланс</p>
|
||||
<button className="btn-ghost" onClick={() => refetch()}>Повторить</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="mb-4">
|
||||
{accounts.map((a) => (
|
||||
<button
|
||||
key={a.bucket}
|
||||
onClick={() => nav("/topup", { state: { bucket: a.bucket } })}
|
||||
className="w-full flex justify-between items-center py-3 border-b border-line last:border-0 text-left"
|
||||
>
|
||||
<span className="text-sm">{a.bucket}</span>
|
||||
<b className={a.balance < 0 ? "text-neg" : "text-pos"}>{formatMoney(a.balance)}</b>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button className="btn-primary" onClick={() => nav("/topup")}>Пополнить</button>
|
||||
|
||||
<div className="flex justify-center gap-6 mt-6 text-muted text-xs">
|
||||
<button className="flex items-center gap-1.5" onClick={() => nav("/history")}>
|
||||
<History size={15} /> История
|
||||
</button>
|
||||
<button className="flex items-center gap-1.5" onClick={() => { clear(); nav("/login"); }}>
|
||||
<LogOut size={15} /> Выйти
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
|
||||
vi.mock("@/api/driver", () => ({
|
||||
getPayments: vi.fn(async () => ({ payments: [
|
||||
{ order_id: "o1", bucket: "Долг аренда", amount: 1000, commission: 52, method: "qr", status: "PAID", created_at: "2026-06-18T09:00:00Z", paid_at: "2026-06-18T09:01:00Z" },
|
||||
] })),
|
||||
}));
|
||||
import { HistoryPage } from "./HistoryPage";
|
||||
|
||||
function wrap() {
|
||||
const qc = new QueryClient();
|
||||
return render(<QueryClientProvider client={qc}><MemoryRouter><HistoryPage /></MemoryRouter></QueryClientProvider>);
|
||||
}
|
||||
|
||||
describe("HistoryPage", () => {
|
||||
it("lists payments with amount + status", async () => {
|
||||
wrap();
|
||||
expect(await screen.findByText("Долг аренда")).toBeInTheDocument();
|
||||
expect(screen.getByText("1 000 ₽")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Оплачено/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { getPayments } from "@/api/driver";
|
||||
import { formatMoney } from "@/lib/format";
|
||||
import { Spinner } from "@/components/Spinner";
|
||||
|
||||
const STATUS_RU: Record<string, string> = {
|
||||
PAID: "Оплачено", NEW: "Ожидает", FORM: "Ожидает", CONFIRMED: "Оплачено", REJECTED: "Отклонён",
|
||||
};
|
||||
|
||||
export function HistoryPage() {
|
||||
const nav = useNavigate();
|
||||
const { data, isLoading, isError } = useQuery({ queryKey: ["payments"], queryFn: getPayments });
|
||||
const rows = data?.payments ?? [];
|
||||
|
||||
return (
|
||||
<div className="pt-2">
|
||||
<button className="text-muted text-xs mb-3" onClick={() => nav("/")}>‹ Назад</button>
|
||||
<h1 className="text-lg font-extrabold mb-4">История пополнений</h1>
|
||||
{isLoading ? (
|
||||
<div className="flex justify-center py-10"><Spinner /></div>
|
||||
) : isError ? (
|
||||
<p className="text-muted text-sm">Не удалось загрузить историю</p>
|
||||
) : rows.length === 0 ? (
|
||||
<p className="text-muted text-sm">Пока нет пополнений</p>
|
||||
) : (
|
||||
rows.map((p) => (
|
||||
<div key={p.order_id} className="flex justify-between items-center py-3 border-b border-line">
|
||||
<div>
|
||||
<p className="text-sm">{p.bucket}</p>
|
||||
<p className="text-muted text-xs">
|
||||
{p.created_at ? new Date(p.created_at).toLocaleDateString("ru-RU") : ""} · {STATUS_RU[p.status] ?? p.status}
|
||||
</p>
|
||||
</div>
|
||||
<b>{formatMoney(p.amount)}</b>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
|
||||
vi.mock("@/api/driver", () => ({
|
||||
authRequest: vi.fn(async () => ({ status: "code_sent", channel: "tg" })),
|
||||
authVerify: vi.fn(async () => ({ token: "T", driver_id: 7 })),
|
||||
tgSession: vi.fn(async () => ({ pair_session: "sess123", deep_link: null })),
|
||||
}));
|
||||
|
||||
import { LoginPage } from "./LoginPage";
|
||||
import * as driver from "@/api/driver";
|
||||
import { useAuth } from "@/store/auth";
|
||||
|
||||
const wrap = () => render(<MemoryRouter><LoginPage /></MemoryRouter>);
|
||||
|
||||
describe("LoginPage", () => {
|
||||
beforeEach(() => useAuth.getState().clear());
|
||||
it("requests code then verifies and stores session", async () => {
|
||||
wrap();
|
||||
expect(screen.getByText(/Вход в приложение/i)).toBeInTheDocument();
|
||||
await userEvent.click(screen.getByRole("button", { name: /Войти по коду/i }));
|
||||
await userEvent.type(screen.getByPlaceholderText(/телефон/i), "9143054400");
|
||||
await userEvent.click(screen.getByRole("button", { name: /Получить код/i }));
|
||||
expect(driver.authRequest).toHaveBeenCalledWith("79143054400");
|
||||
const codeInput = await screen.findByPlaceholderText(/код/i);
|
||||
await userEvent.type(codeInput, "123456");
|
||||
await userEvent.click(screen.getByRole("button", { name: /Войти/i }));
|
||||
expect(driver.authVerify).toHaveBeenCalledWith("79143054400", "123456");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
import { authRequest, authVerify, tgSession } from "@/api/driver";
|
||||
import { digitsOnly, formatPhone } from "@/lib/format";
|
||||
import { useAuth } from "@/store/auth";
|
||||
import { Spinner } from "@/components/Spinner";
|
||||
|
||||
export function LoginPage() {
|
||||
const nav = useNavigate();
|
||||
const setSession = useAuth((s) => s.setSession);
|
||||
const [phone, setPhone] = useState(""); // national 10 digits
|
||||
const [code, setCode] = useState("");
|
||||
const [step, setStep] = useState<"phone" | "code">("phone");
|
||||
const [channel, setChannel] = useState<string>("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [mode, setMode] = useState<"choose" | "code">("choose");
|
||||
const e164 = "7" + phone;
|
||||
|
||||
async function loginViaTelegram() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await tgSession();
|
||||
sessionStorage.setItem("pp-pair-session", r.pair_session);
|
||||
if (r.deep_link) { window.location.href = r.deep_link; }
|
||||
nav("/tg-wait");
|
||||
} catch {
|
||||
toast.error("Не удалось начать вход. Попробуйте «по коду».");
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function requestCode() {
|
||||
if (phone.length < 10) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await authRequest(e164);
|
||||
if (r.status === "onboarding") {
|
||||
sessionStorage.setItem("pp-onboarding", JSON.stringify({ ...r.deep_links, phone }));
|
||||
nav("/onboarding");
|
||||
return;
|
||||
}
|
||||
setChannel(r.channel);
|
||||
setStep("code");
|
||||
} catch (err: unknown) {
|
||||
const status = (err as { response?: { status?: number } })?.response?.status;
|
||||
const msg =
|
||||
status === 404 ? "Номер не найден. Обратитесь в парк." :
|
||||
status === 429 ? "Слишком часто. Попробуйте позже." :
|
||||
"Не удалось отправить код";
|
||||
toast.error(msg);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function verify() {
|
||||
if (code.length < 4) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await authVerify(e164, code);
|
||||
setSession(r.token, r.driver_id);
|
||||
nav("/");
|
||||
} catch {
|
||||
toast.error("Неверный или просроченный код");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="pt-16">
|
||||
<h1 className="text-xl font-extrabold mb-1">Премиум Водитель</h1>
|
||||
<p className="text-muted text-sm mb-8">Вход в приложение</p>
|
||||
|
||||
{mode === "choose" ? (
|
||||
<>
|
||||
<button className="btn-primary" disabled={busy} onClick={loginViaTelegram}>
|
||||
{busy ? <Spinner /> : "Войти через Telegram"}
|
||||
</button>
|
||||
<p className="text-muted text-xs mt-3">Telegram подтвердит ваш номер автоматически.</p>
|
||||
<button className="btn-ghost mt-4" onClick={() => setMode("code")}>Войти по коду</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{step === "phone" ? (
|
||||
<>
|
||||
<input
|
||||
inputMode="numeric"
|
||||
placeholder="Номер телефона"
|
||||
value={phone ? formatPhone(phone) : ""}
|
||||
onChange={(e) => setPhone(digitsOnly(e.target.value).replace(/^7/, "").slice(0, 10))}
|
||||
className="card w-full px-4 py-3 mb-3 text-base bg-white"
|
||||
/>
|
||||
<button className="btn-primary" disabled={busy || phone.length < 10} onClick={requestCode}>
|
||||
{busy ? <Spinner /> : "Получить код"}
|
||||
</button>
|
||||
<p className="text-muted text-xs mt-3">Код придёт в Telegram или MAX.</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm mb-2">Код отправлен в {channel === "max" ? "MAX" : "Telegram"}.</p>
|
||||
<input
|
||||
inputMode="numeric"
|
||||
placeholder="Код из сообщения"
|
||||
value={code}
|
||||
onChange={(e) => setCode(digitsOnly(e.target.value).slice(0, 6))}
|
||||
className="card w-full px-4 py-3 mb-3 text-base tracking-widest bg-white"
|
||||
/>
|
||||
<button className="btn-primary" disabled={busy || code.length < 4} onClick={verify}>
|
||||
{busy ? <Spinner /> : "Войти"}
|
||||
</button>
|
||||
<button className="btn-ghost mt-2" onClick={() => setStep("phone")}>Изменить номер</button>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { OnboardingPage } from "./OnboardingPage";
|
||||
|
||||
describe("OnboardingPage", () => {
|
||||
beforeEach(() =>
|
||||
sessionStorage.setItem("pp-onboarding", JSON.stringify({ tg: "https://t.me/b?start=x", max: "https://max.ru/b?start=x", phone: "9143054400" }))
|
||||
);
|
||||
it("shows both bot links + back-to-code action", () => {
|
||||
render(<MemoryRouter><OnboardingPage /></MemoryRouter>);
|
||||
expect(screen.getByText(/Подключите бот/i)).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: /Telegram/i })).toHaveAttribute("href", "https://t.me/b?start=x");
|
||||
expect(screen.getByRole("link", { name: /MAX/i })).toHaveAttribute("href", "https://max.ru/b?start=x");
|
||||
expect(screen.getByRole("button", { name: /запросить код/i })).toBeInTheDocument();
|
||||
});
|
||||
it("renders only Telegram when max is absent", () => {
|
||||
sessionStorage.setItem("pp-onboarding", JSON.stringify({ tg: "https://t.me/ppdriver_bot?start=x", phone: "9143054400" }));
|
||||
render(<MemoryRouter><OnboardingPage /></MemoryRouter>);
|
||||
expect(screen.getByRole("link", { name: /Telegram/i })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("link", { name: /MAX/i })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
export function OnboardingPage() {
|
||||
const nav = useNavigate();
|
||||
const raw = sessionStorage.getItem("pp-onboarding");
|
||||
const data = raw ? (JSON.parse(raw) as { tg?: string; max?: string; phone: string }) : null;
|
||||
if (!data) return null;
|
||||
|
||||
return (
|
||||
<div className="pt-16">
|
||||
<h1 className="text-xl font-extrabold mb-1">Подключите бот</h1>
|
||||
<p className="text-muted text-sm mb-8">
|
||||
Чтобы получать код входа, откройте бот и нажмите «Старт». Затем вернитесь и запросите код снова.
|
||||
</p>
|
||||
{data.tg && (
|
||||
<a href={data.tg} target="_blank" rel="noopener" className="btn-primary mb-3 no-underline block">
|
||||
Подключить Telegram
|
||||
</a>
|
||||
)}
|
||||
{data.max && (
|
||||
<a href={data.max} target="_blank" rel="noopener" className="btn-ghost mb-6 no-underline block">
|
||||
Подключить MAX
|
||||
</a>
|
||||
)}
|
||||
<button className="btn-ghost" onClick={() => nav("/login")}>
|
||||
Я подключил — запросить код
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { MemoryRouter, Routes, Route } from "react-router-dom";
|
||||
|
||||
const states = ["FORM", "PAID"];
|
||||
vi.mock("@/api/driver", () => ({
|
||||
getPaymentState: vi.fn(async () => ({ order_id: "o9", status: states.shift() ?? "PAID" })),
|
||||
}));
|
||||
import { PaymentPage } from "./PaymentPage";
|
||||
|
||||
function wrap() {
|
||||
const qc = new QueryClient();
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<MemoryRouter initialEntries={[{ pathname: "/pay/o9", state: { payUrl: "https://qr.nspk.ru/x", total: 1052, bucket: "Долг аренда", base: 1000 } }]}>
|
||||
<Routes><Route path="/pay/:orderId" element={<PaymentPage />} /></Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe("PaymentPage", () => {
|
||||
it("shows pay button and flips to success on PAID", async () => {
|
||||
wrap();
|
||||
expect(screen.getByRole("link", { name: /Оплатить/i })).toHaveAttribute("href", "https://qr.nspk.ru/x");
|
||||
await waitFor(() => expect(screen.getByText(/Оплачено/i)).toBeInTheDocument(), { timeout: 3000 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useEffect } from "react";
|
||||
import { useLocation, useNavigate, useParams } from "react-router-dom";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { Check } from "lucide-react";
|
||||
import { formatMoney } from "@/lib/format";
|
||||
import { Spinner } from "@/components/Spinner";
|
||||
import { usePaymentStatus } from "@/hooks/usePaymentStatus";
|
||||
|
||||
export function PaymentPage() {
|
||||
const { orderId = "" } = useParams();
|
||||
const nav = useNavigate();
|
||||
const qc = useQueryClient();
|
||||
const st = (useLocation().state as { payUrl?: string; total?: number; bucket?: string; base?: number } | null) ?? {};
|
||||
const { data } = usePaymentStatus(orderId);
|
||||
const paid = data?.status === "PAID";
|
||||
|
||||
useEffect(() => {
|
||||
if (paid) qc.invalidateQueries({ queryKey: ["balance"] });
|
||||
}, [paid, qc]);
|
||||
|
||||
if (paid) {
|
||||
return (
|
||||
<div className="pt-24 flex flex-col items-center text-center">
|
||||
<span className="w-14 h-14 rounded-full bg-pos text-white flex items-center justify-center mb-3"><Check size={28} /></span>
|
||||
<p className="text-lg font-extrabold">Оплачено</p>
|
||||
<p className="text-muted text-xs mt-1">{st.bucket} пополнен на {formatMoney(st.base ?? 0)}</p>
|
||||
<button className="btn-primary mt-8" onClick={() => nav("/")}>На главную</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="pt-10 flex flex-col items-center text-center">
|
||||
<span className="w-12 h-12 rounded-xl2 bg-ink text-cream flex items-center justify-center font-extrabold mb-4">СБП</span>
|
||||
<p className="text-lg font-extrabold">{formatMoney(st.total ?? 0)}</p>
|
||||
<p className="text-muted text-xs mb-6">{st.bucket}</p>
|
||||
<a className="btn-primary no-underline" href={st.payUrl} target="_blank" rel="noopener">Оплатить</a>
|
||||
<p className="text-muted text-xs mt-2">Откроется ваше приложение банка</p>
|
||||
<div className="flex items-center gap-2 mt-6 text-muted text-xs"><Spinner /> Ожидаем оплату…</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { usePairPoll } from "@/hooks/usePairPoll";
|
||||
import { Spinner } from "@/components/Spinner";
|
||||
|
||||
export function TgWaitPage() {
|
||||
const nav = useNavigate();
|
||||
const pairSession = sessionStorage.getItem("pp-pair-session");
|
||||
const { status } = usePairPoll(pairSession);
|
||||
|
||||
useEffect(() => {
|
||||
if (!pairSession) { nav("/login", { replace: true }); }
|
||||
}, [pairSession, nav]);
|
||||
|
||||
useEffect(() => {
|
||||
if (status === "authenticated") { sessionStorage.removeItem("pp-pair-session"); nav("/", { replace: true }); }
|
||||
if (status === "expired") { sessionStorage.removeItem("pp-pair-session"); nav("/login", { replace: true, state: { expired: true } }); }
|
||||
}, [status, nav]);
|
||||
|
||||
return (
|
||||
<div className="pt-16 text-center">
|
||||
<h1 className="text-xl font-extrabold mb-2">Премиум Водитель</h1>
|
||||
<p className="text-muted text-sm mb-8">Подтвердите номер в Telegram — нажмите «Поделиться номером», затем вернитесь сюда.</p>
|
||||
<Spinner />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
|
||||
vi.mock("@/api/driver", () => ({
|
||||
topup: vi.fn(async () => ({ order_id: "o9", pay_url: "https://qr.nspk.ru/x", commission: 52, total: 1052 })),
|
||||
getCommission: vi.fn(async () => ({ rate: 0.052 })),
|
||||
}));
|
||||
import { TopupPage } from "./TopupPage";
|
||||
import * as driver from "@/api/driver";
|
||||
|
||||
const wrap = () => {
|
||||
const qc = new QueryClient();
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<MemoryRouter><TopupPage /></MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
|
||||
describe("TopupPage", () => {
|
||||
it("keypad builds amount, shows total, and submits topup", async () => {
|
||||
wrap();
|
||||
await userEvent.click(screen.getByRole("button", { name: "1" }));
|
||||
await userEvent.click(screen.getByRole("button", { name: "0" }));
|
||||
await userEvent.click(screen.getByRole("button", { name: "0" }));
|
||||
await userEvent.click(screen.getByRole("button", { name: "0" }));
|
||||
expect(screen.getByTestId("amount").textContent).toBe("1 000 ₽");
|
||||
expect(screen.getByTestId("total").textContent).toContain("1 052");
|
||||
await userEvent.click(screen.getByRole("button", { name: /Оплатить/i }));
|
||||
expect(driver.topup).toHaveBeenCalledWith("Долг аренда", 1000, "qr");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { useState } from "react";
|
||||
import { useLocation, useNavigate } from "react-router-dom";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Delete } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { topup, getCommission } from "@/api/driver";
|
||||
import { keypadReduce, withCommission } from "@/lib/amount";
|
||||
import { formatMoney } from "@/lib/format";
|
||||
import { Segment } from "@/components/Segment";
|
||||
import { Spinner } from "@/components/Spinner";
|
||||
|
||||
const QUICK = ["500", "1000", "2000"];
|
||||
const KEYS = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "·", "0", "back"];
|
||||
|
||||
export function TopupPage() {
|
||||
const nav = useNavigate();
|
||||
const loc = useLocation();
|
||||
const bucket = (loc.state as { bucket?: string } | null)?.bucket ?? "Долг аренда";
|
||||
const [raw, setRaw] = useState("");
|
||||
const [method, setMethod] = useState("qr");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const { data: commission } = useQuery({ queryKey: ["commission"], queryFn: getCommission });
|
||||
const rate = commission?.rate ?? 0.052; // fallback only while loading
|
||||
|
||||
const base = raw ? parseInt(raw, 10) : 0;
|
||||
const { commission: fee, total } = withCommission(base, rate);
|
||||
|
||||
function press(k: string) {
|
||||
if (k === "·") return;
|
||||
setRaw((r) => keypadReduce(r, k));
|
||||
}
|
||||
|
||||
async function pay() {
|
||||
if (base <= 0) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await topup(bucket, base, method as "qr" | "card");
|
||||
nav(`/pay/${r.order_id}`, { state: { payUrl: r.pay_url, total: r.total, bucket, base } });
|
||||
} catch {
|
||||
toast.error("Не удалось создать платёж");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="pt-2">
|
||||
<button className="text-muted text-xs mb-3" onClick={() => nav(-1)}>‹ {bucket}</button>
|
||||
<p data-testid="amount" className="text-3xl font-extrabold text-center mt-2">{formatMoney(base)}</p>
|
||||
<p data-testid="total" className="text-muted text-xs text-center mb-3">
|
||||
к оплате {formatMoney(total)} (комиссия {formatMoney(fee)})
|
||||
</p>
|
||||
|
||||
<div className="flex gap-1.5 mb-3">
|
||||
{QUICK.map((q) => (
|
||||
<button key={q} className="flex-1 py-2 rounded-xl2 text-xs bg-surface border border-line" onClick={() => setRaw(q)}>
|
||||
{q}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2 mb-4">
|
||||
{KEYS.map((k) => (
|
||||
<button
|
||||
key={k}
|
||||
aria-label={k}
|
||||
className="bg-surface border border-line rounded-xl2 py-3 text-lg font-semibold flex items-center justify-center"
|
||||
onClick={() => press(k)}
|
||||
>
|
||||
{k === "back" ? <Delete size={18} /> : k}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="mb-4">
|
||||
<Segment value={method} onChange={setMethod} options={[{ value: "qr", label: "СБП" }, { value: "card", label: "Картой" }]} />
|
||||
</div>
|
||||
|
||||
<button className="btn-primary" disabled={busy || base <= 0} onClick={pay}>
|
||||
{busy ? <Spinner /> : "Оплатить"}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
|
||||
interface AuthState {
|
||||
token: string | null;
|
||||
driverId: number | null;
|
||||
setSession: (token: string, driverId: number) => void;
|
||||
clear: () => void;
|
||||
}
|
||||
|
||||
export const useAuth = create<AuthState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
token: null,
|
||||
driverId: null,
|
||||
setSession: (token, driverId) => set({ token, driverId }),
|
||||
clear: () => set({ token: null, driverId: null }),
|
||||
}),
|
||||
{ name: "pp-driver-auth" }
|
||||
)
|
||||
);
|
||||
@@ -0,0 +1 @@
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_API_BASE?: string;
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
export default {
|
||||
content: ["./index.html", "./src/**/*.{ts,tsx}"],
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
cream: "#F3EEE3", surface: "#FBF8F1", line: "#E4DCCB",
|
||||
ink: "#1C1B19", muted: "#7C7361", neg: "#C0493A", pos: "#3B6E4A",
|
||||
},
|
||||
fontFamily: { sans: ["Inter", "system-ui", "sans-serif"] },
|
||||
borderRadius: { xl2: "14px" },
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
};
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2021", "useDefineForClassFields": true, "lib": ["ES2021", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext", "skipLibCheck": true, "moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true,
|
||||
"noEmit": true, "jsx": "react-jsx", "strict": true, "noUnusedLocals": true,
|
||||
"noUnusedParameters": true, "noFallthroughCasesInSwitch": true,
|
||||
"baseUrl": ".", "paths": { "@/*": ["src/*"] }, "types": ["vitest/globals", "@testing-library/jest-dom"]
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022", "lib": ["ES2023"], "module": "ESNext", "skipLibCheck": true,
|
||||
"moduleResolution": "bundler", "allowImportingTsExtensions": true, "isolatedModules": true,
|
||||
"noEmit": true, "strict": true
|
||||
},
|
||||
"include": ["vite.config.ts", "vitest.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { VitePWA } from "vite-plugin-pwa";
|
||||
import path from "path";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
react(),
|
||||
VitePWA({ registerType: "autoUpdate", manifest: false, includeAssets: ["icons/*.png"] }),
|
||||
],
|
||||
resolve: { alias: { "@": path.resolve(__dirname, "src") } },
|
||||
server: { port: 5174 },
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import path from "path";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
resolve: { alias: { "@": path.resolve(__dirname, "src") } },
|
||||
test: { globals: true, environment: "jsdom", setupFiles: ["./src/test/setup.ts"] },
|
||||
});
|
||||
Reference in New Issue
Block a user