Compare commits
28
Commits
9469dd2fdc
..
v0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0244acf429 | ||
|
|
53b18c6e86 | ||
|
|
dc3434c371 | ||
|
|
3be6e61b8f | ||
|
|
7a89356f87 | ||
|
|
0c6bac8b90 | ||
|
|
82b904393d | ||
|
|
4b97395385 | ||
|
|
bb6623275c | ||
|
|
942ed3d453 | ||
|
|
2f26e4fe0d | ||
|
|
22e331e2ff | ||
|
|
ccff422f36 | ||
|
|
117e74cdfc | ||
|
|
53c852b437 | ||
|
|
24d332e063 | ||
|
|
aba4cf1ce8 | ||
|
|
cf21a5bd17 | ||
|
|
9bb385b9f0 | ||
|
|
8e58c016d2 | ||
|
|
d3ac8c242d | ||
|
|
9a65687d38 | ||
|
|
ae06f6e6e0 | ||
|
|
6b310db0b8 | ||
|
|
dedfec10d1 | ||
|
|
ff4e88edbe | ||
|
|
427ca23a43 | ||
|
|
a42f104bed |
+3
-3
@@ -9,11 +9,11 @@
|
|||||||
| Создать/перенести module/component/slice; выбрать page/entity/feature/shared; cross-slice imports | [Architecture](conventions/frontend-architecture.md) |
|
| Создать/перенести module/component/slice; выбрать page/entity/feature/shared; cross-slice imports | [Architecture](conventions/frontend-architecture.md) |
|
||||||
| Component/props, container/VM/view, form, local state/effect, loading/error/retry, Mantine/UI | [UI](conventions/frontend-ui.md) |
|
| Component/props, container/VM/view, form, local state/effect, loading/error/retry, Mantine/UI | [UI](conventions/frontend-ui.md) |
|
||||||
| Только продуктовая строка или Zod message | [Строки](conventions/frontend-ui.md#строки-и-валидация) |
|
| Только продуктовая строка или Zod message | [Строки](conventions/frontend-ui.md#строки-и-валидация) |
|
||||||
| Только TS declaration/import/export | [Код](conventions/frontend-ui.md#код-и-components) |
|
| TS declaration/import/export, domain literals, magic values | [Код](conventions/frontend-ui.md#код-и-components) + [Domain literals](conventions/frontend-ui.md#domain-literals-and-magic-values) |
|
||||||
| query/mutation, shared/api, server state/cache, generated types, Bearer/refresh | [Data](conventions/frontend-data.md) |
|
| query/mutation, shared/api, server state/cache, generated types, Bearer/refresh | [Data](conventions/frontend-data.md) |
|
||||||
| Тесты или behavior с testing risk | [Testing](conventions/frontend-testing.md) |
|
| Тесты или behavior с testing risk | [Testing](conventions/frontend-testing.md) |
|
||||||
| Новый abstraction/dependency, refactor или неоднозначный scope | [Общий выбор реализации](../../docs/development/engineering-governance.md#выбор-реализации) |
|
| Новый abstraction/dependency, refactor или неоднозначный scope | [Общий выбор реализации](../../AGENTS.md) |
|
||||||
| Request/response field, route/status/error shape, OpenAPI snapshot/generated type | [Общий contract workflow](../../docs/development/runtime-openapi-verification.md) |
|
| Request/response field, route/status/error shape, OpenAPI snapshot/generated type | [Источник HTTP-контракта](../../docs/architecture/http-api.md#источник-контракта) |
|
||||||
| Login/refresh/logout, token/cookie, auth ownership | Data + [security](../../backend/.ai/conventions/security-auth.md) + Testing |
|
| Login/refresh/logout, token/cookie, auth ownership | Data + [security](../../backend/.ai/conventions/security-auth.md) + Testing |
|
||||||
| Storybook/theme/tokens/shared UI | UI + точные [источники](SOURCES.md) дизайн-системы/каталога |
|
| Storybook/theme/tokens/shared UI | UI + точные [источники](SOURCES.md) дизайн-системы/каталога |
|
||||||
|
|
||||||
|
|||||||
+6
-6
@@ -3,12 +3,12 @@
|
|||||||
| Что нужно установить | Владелец |
|
| Что нужно установить | Владелец |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Какое implementation-решение принять | [CONVENTIONS](CONVENTIONS.md) |
|
| Какое implementation-решение принять | [CONVENTIONS](CONVENTIONS.md) |
|
||||||
| HTTP wire contract и направление генерации | Backend runtime OpenAPI → [snapshot/types workflow](../../docs/development/runtime-openapi-verification.md) |
|
| HTTP wire contract и направление генерации | Backend-owned contract → provided snapshot → [Источник HTTP-контракта](../../docs/architecture/http-api.md#источник-контракта) |
|
||||||
| Error codes/validation/error envelope | [docs: HTTP API](../../docs/AI_INDEX.md#http-api) |
|
| Error codes/validation/error envelope | [docs: HTTP API](../../docs/architecture/http-api.md) |
|
||||||
| Auth/session, token storage и refresh | [docs: Security](../../docs/AI_INDEX.md#security) |
|
| Auth/session, token storage и refresh | [Аутентификация](../../docs/domains/authentication/overview.md), [подключение брокера](../../docs/integrations/tbank.md) |
|
||||||
| Значение Money, cached snapshot, account/position/income | [docs: Domain](../../docs/AI_INDEX.md#domain) |
|
| Значение Money, cached snapshot, account/position/income | [docs: Domain](../../docs/glossary.md) |
|
||||||
| Mantine/theme/tokens и существующие stories | [docs: UI](../../docs/AI_INDEX.md#ui) |
|
| Mantine/theme/tokens и существующие stories | [Дизайн-система](../../docs/design/overview.md), [UI-каталог](../README.md#ui-каталог-storybook) |
|
||||||
| As-built behavior нужной feature | [docs: Features](../../docs/AI_INDEX.md#features) |
|
| As-built behavior нужной feature | [docs: Features](../../docs/README.md#предметные-области) |
|
||||||
| Существующие behavioral requirements, если нужны по задаче | [specs index](../../specs/AI_INDEX.md) |
|
| Существующие behavioral requirements, если нужны по задаче | [specs index](../../specs/AI_INDEX.md) |
|
||||||
| Действующие versions/scripts/check scope | package.json, lockfile, Biome/TS/dependency configs |
|
| Действующие versions/scripts/check scope | package.json, lockfile, Biome/TS/dependency configs |
|
||||||
|
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ designTokens, color roles, CSSVariablesResolver и base styles. Внешний c
|
|||||||
`shared/ui` содержит StateView/LoadingSkeleton. Existing route-aware AppShell также
|
`shared/ui` содержит StateView/LoadingSkeleton. Existing route-aware AppShell также
|
||||||
лежит в shared/ui, но не является общим catalog primitive; его расположение не
|
лежит в shared/ui, но не является общим catalog primitive; его расположение не
|
||||||
служит основанием переносить новую domain/navigation логику в shared.
|
служит основанием переносить новую domain/navigation логику в shared.
|
||||||
Изменяя foundation, прочитай [design system](../../../docs/development/design-system.md).
|
Изменяя foundation, прочитай [design system](../../../docs/design/overview.md).
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
|
|
||||||
|
|||||||
@@ -14,16 +14,19 @@ pages/features/entities и прямой T-Bank call запрещены. Снач
|
|||||||
|
|
||||||
## Типы и contract
|
## Типы и contract
|
||||||
|
|
||||||
Backend runtime OpenAPI — source; committed frontend snapshot и generated
|
Backend-owned OpenAPI contract поступает во frontend как предоставленный
|
||||||
`schema.d.ts` производны. Тип request/response бери из generated `paths`, например:
|
актуальный snapshot; generated `schema.d.ts` производен от него. Тип
|
||||||
|
request/response бери из generated `paths`, например:
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
type User = paths["/api/v1/auth/me"]["get"]["responses"][200]["content"]["application/json"];
|
type User = paths["/api/v1/auth/me"]["get"]["responses"][200]["content"]["application/json"];
|
||||||
```
|
```
|
||||||
|
|
||||||
Domain/UI type допустим, когда он отличается по смыслу, а не копирует transport DTO.
|
Domain/UI type допустим, когда он отличается по смыслу, а не копирует transport DTO.
|
||||||
Generated TS вручную не исправляется. Изменение wire shape/status/route проходит
|
Generated TS вручную не исправляется. Frontend-команды не читают соседний
|
||||||
[общий contract workflow](../../../docs/development/runtime-openapi-verification.md).
|
backend checkout и не проверяют backend runtime OpenAPI; изменение wire
|
||||||
|
shape/status/route сохраняет
|
||||||
|
[границу HTTP-контракта](../../../docs/architecture/http-api.md#источник-контракта).
|
||||||
Одна UI-модель не требует менять API. `openapi:generate` работает offline от snapshot;
|
Одна UI-модель не требует менять API. `openapi:generate` работает offline от snapshot;
|
||||||
`openapi:check` генерирует во временный каталог и сравнивает, не меняя tracked files.
|
`openapi:check` генерирует во временный каталог и сравнивает, не меняя tracked files.
|
||||||
|
|
||||||
@@ -36,10 +39,10 @@ Authorization. Auth endpoints исключены из Bearer/retry middleware. R
|
|||||||
|
|
||||||
Protected queries используют existing session-aware boundary; logout очищает
|
Protected queries используют existing session-aware boundary; logout очищает
|
||||||
session-scoped cache. При auth/token change читай [security](../../../backend/.ai/conventions/security-auth.md)
|
session-scoped cache. При auth/token change читай [security](../../../backend/.ai/conventions/security-auth.md)
|
||||||
и [authentication](../../../docs/features/authentication.md).
|
и [authentication](../../../docs/domains/authentication/overview.md).
|
||||||
Успешная connection mutation коммитит подтверждённый status и сбрасывает financial
|
Успешная connection mutation коммитит подтверждённый status и сбрасывает financial
|
||||||
GET subtree; ошибка mutation не меняет generation/cache. Это отдельная граница
|
GET subtree; ошибка mutation не меняет generation/cache. Это отдельная граница
|
||||||
от обычного фонового refetch: [connection policy](../../../docs/features/tbank-connection.md#граница-финансового-кэша).
|
от обычного фонового refetch: [connection policy](../../../docs/integrations/tbank.md#граница-финансового-кэша).
|
||||||
|
|
||||||
Default focus refetch выключен; freshness и retry определяются существующей
|
Default focus refetch выключен; freshness и retry определяются существующей
|
||||||
[query policy](../../../docs/adr/007-react-query-fetch-policy.md) и feature source.
|
[query policy](../../../docs/adr/007-react-query-fetch-policy.md) и feature source.
|
||||||
@@ -53,4 +56,5 @@ Default focus refetch выключен; freshness и retry определяют
|
|||||||
Изменяя header/retry/invalidation, проверяй наблюдаемое поведение через MSW и
|
Изменяя header/retry/invalidation, проверяй наблюдаемое поведение через MSW и
|
||||||
[Testing](frontend-testing.md); не обращайся к реальному T-Bank.
|
[Testing](frontend-testing.md); не обращайся к реальному T-Bank.
|
||||||
`npm run openapi:check`, `npm run typecheck` и targeted tests проверяют разные
|
`npm run openapi:check`, `npm run typecheck` и targeted tests проверяют разные
|
||||||
части решения. Для API semantics нужны также exact docs и contract gate.
|
части решения. Для API semantics нужны exact docs и проверки наблюдаемого
|
||||||
|
HTTP-поведения на стороне backend.
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
|
|
||||||
## Выбор проверки
|
## Выбор проверки
|
||||||
|
|
||||||
Читай при изменении тестов или behavior с [testing risk](../../../docs/development/engineering-governance.md#risk-based-testing).
|
Читай при изменении тестов, доступа, денежных расчётов, восстановления
|
||||||
|
интерфейса или исправлении подтверждённой регрессии.
|
||||||
Выбирай boundary по наблюдаемому исходу, а не внутреннему helper/component state.
|
Выбирай boundary по наблюдаемому исходу, а не внутреннему helper/component state.
|
||||||
|
|
||||||
| Изменение | Дешёвая надёжная проверка |
|
| Изменение | Дешёвая надёжная проверка |
|
||||||
@@ -28,6 +29,8 @@ MSW запускается только Vitest setup в `src/test/`, без brow
|
|||||||
Независимый case получает свой `createTestQueryClient`; rerender сохраняет
|
Независимый case получает свой `createTestQueryClient`; rerender сохраняет
|
||||||
экземпляр и seeded cache. Providers выбирай явно. Existing teardown выполняет
|
экземпляр и seeded cache. Providers выбирай явно. Existing teardown выполняет
|
||||||
RTL cleanup, auth reset и MSW reset: [test client](../../src/test/query.tsx).
|
RTL cleanup, auth reset и MSW reset: [test client](../../src/test/query.tsx).
|
||||||
|
Тестовый клиент отключает retries запросов и мутаций для предсказуемого исхода;
|
||||||
|
это не меняет [политику обновления приложения](../../../docs/adr/007-react-query-fetch-policy.md).
|
||||||
|
|
||||||
## Важные случаи
|
## Важные случаи
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ Mantine component и общую тему. Для выпадающего выбо
|
|||||||
|
|
||||||
Wrapper нужен для проектной ответственности, а не ради нового имени
|
Wrapper нужен для проектной ответственности, а не ради нового имени
|
||||||
для Button. Локальный CSS module принадлежит component; общий token вводи для
|
для Button. Локальный CSS module принадлежит component; общий token вводи для
|
||||||
реально общей роли через [design system](../../../docs/development/design-system.md).
|
реально общей роли через [design system](../../../docs/design/overview.md).
|
||||||
|
|
||||||
| Состояние | Владелец |
|
| Состояние | Владелец |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
@@ -91,6 +91,57 @@ CSF `*.stories.tsx` сохраняют default meta и прямые story export
|
|||||||
Vite/Vitest configs и `.storybook/main.ts`/`preview.tsx` имеют только
|
Vite/Vitest configs и `.storybook/main.ts`/`preview.tsx` имеют только
|
||||||
конфигурационное default-export exception. Scope исключений принадлежит biome.json.
|
конфигурационное default-export exception. Scope исключений принадлежит biome.json.
|
||||||
|
|
||||||
|
## Domain literals and magic values
|
||||||
|
|
||||||
|
Finite business vocabulary must be modeled explicitly; incidental implementation
|
||||||
|
literals stay inline. Это относится к error codes, statuses, operation/account/
|
||||||
|
instrument/transaction types, permissions, roles, feature states и бизнес-режимам.
|
||||||
|
|
||||||
|
Перед новым определением найди existing owner/type/value. В branching и comparisons
|
||||||
|
используй символическое значение владельца; не повторяй raw domain literals.
|
||||||
|
Храни словарь у domain/module/entity с соблюдением границ слоёв, без глобальной
|
||||||
|
свалки `constants.ts`. Сохраняй принятый pattern; для нового project-owned словаря
|
||||||
|
без подходящего аналога используй `as const` с derived union:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const BankErrorCode = {
|
||||||
|
InvalidDate: "BANK_INVALID_DATE",
|
||||||
|
ImmutableOperation: "BANK_IMMUTABLE_OPERATION",
|
||||||
|
} as const;
|
||||||
|
type BankErrorCode = (typeof BankErrorCode)[keyof typeof BankErrorCode];
|
||||||
|
|
||||||
|
// Вместо code === "BANK_INVALID_DATE":
|
||||||
|
if (code === BankErrorCode.InvalidDate) { /* existing handling */ }
|
||||||
|
```
|
||||||
|
|
||||||
|
Значимые numeric policies (timeout, retry, page size, threshold, coefficient)
|
||||||
|
называй по смыслу и единицам: `REQUEST_TIMEOUT_MS`, `CACHE_TTL_SECONDS`,
|
||||||
|
`MAX_RETRY_COUNT`, `PAGE_SIZE`. Оставляй inline UI labels в принятом месте,
|
||||||
|
log messages, индексы, `index + 1`, `Math.max(value, 0)`, `page ?? 1`,
|
||||||
|
`percentage * 100` и очевидные локальные детали без semantic benefit.
|
||||||
|
При неясном owner/смысле оставь значение и укажи ограничение в review.
|
||||||
|
|
||||||
|
Не мигрируй корректные existing enum/union styles массово. Не добавляй ради
|
||||||
|
правила factories, registries, schemas, loaders, abstraction layers, dependencies,
|
||||||
|
custom lint/AST rules, generation/validation scripts или тесты существования
|
||||||
|
констант. Semantic review проверяет ownership, единое написание и неизменность
|
||||||
|
wire values; обычные behavior tests проверяют поведение.
|
||||||
|
|
||||||
|
Backend API vocabulary бери из generated OpenAPI types/client, runtime values —
|
||||||
|
когда генератор их предоставляет. Не создавай ручную копию backend enum/object.
|
||||||
|
Текущий `schema.d.ts` предоставляет только types: используй indexed-access type
|
||||||
|
из `paths`; typed literals в запросах/сравнениях допустимы при отсутствии
|
||||||
|
runtime values. `ProblemDetailsDto.code` сейчас `string`: не выдумывай закрытый
|
||||||
|
frontend error enum. Развитие API source — отдельное contract-решение.
|
||||||
|
Frontend `enum` по-прежнему запрещён локальным TS/style profile.
|
||||||
|
|
||||||
|
`noMagicNumbers` включён как error в Biome. Fixtures, tests и stories исключены
|
||||||
|
из этого правила; остальные проверки для них сохраняются. Используй имена
|
||||||
|
политик/единиц и existing values. Точечное подавление допустимо для очевидного
|
||||||
|
incidental значения с объяснением, например перевода доли в проценты; не подавляй
|
||||||
|
скрытые бизнес-лимиты. Semantic magic strings проверяются conventions/review: в
|
||||||
|
установленном Biome нет такого встроенного правила, новый инструмент не добавляем.
|
||||||
|
|
||||||
## Строки и валидация
|
## Строки и валидация
|
||||||
|
|
||||||
Продуктовый текст хранится в `src/shared/i18n/locales/ru.ts`, читается через
|
Продуктовый текст хранится в `src/shared/i18n/locales/ru.ts`, читается через
|
||||||
@@ -103,5 +154,5 @@ Vite/Vitest configs и `.storybook/main.ts`/`preview.tsx` имеют тольк
|
|||||||
|
|
||||||
Type/style: `npm run typecheck`, `npm run lint`. Для risk behavior/изменения тестов
|
Type/style: `npm run typecheck`, `npm run lint`. Для risk behavior/изменения тестов
|
||||||
используй [Testing](frontend-testing.md). UI: keyboard, narrow viewport,
|
используй [Testing](frontend-testing.md). UI: keyboard, narrow viewport,
|
||||||
loading/error/empty/loaded и recovery по применимости. [Storybook](../../../docs/development/ui-catalog.md)
|
loading/error/empty/loaded и recovery по применимости. [Storybook](../../README.md#ui-каталог-storybook)
|
||||||
уже установлен; используй его как reference, но сверяй UI с задачей отдельно от build.
|
уже установлен; используй его как reference, но сверяй UI с задачей отдельно от build.
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
name: Conventional commits
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
types: [opened, synchronize, reopened, edited]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
commits:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: https://github.com/actions/checkout@v4
|
||||||
|
with:
|
||||||
|
ref: ${{ github.event.pull_request.head.sha }}
|
||||||
|
fetch-depth: 0
|
||||||
|
- uses: https://github.com/actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version-file: .nvmrc
|
||||||
|
- run: npm ci --ignore-scripts
|
||||||
|
- name: Check PR title and commits
|
||||||
|
env:
|
||||||
|
PR_TITLE: ${{ github.event.pull_request.title }}
|
||||||
|
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||||
|
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||||
|
run: |
|
||||||
|
printf '%s\n' "$PR_TITLE" | npm run commitlint -- --strict
|
||||||
|
npm run commitlint -- --strict --from "$BASE_SHA" --to "$HEAD_SHA"
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
name: Frontend security
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- '**'
|
||||||
|
pull_request:
|
||||||
|
schedule:
|
||||||
|
- cron: '17 5 * * *'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
security:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: https://github.com/actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: Record checked revision
|
||||||
|
run: git rev-parse HEAD
|
||||||
|
- name: Scan history with Gitleaks 8.30.1
|
||||||
|
run: |
|
||||||
|
curl --fail --location --silent --show-error https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_x64.tar.gz -o /tmp/gitleaks.tar.gz
|
||||||
|
echo '551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb /tmp/gitleaks.tar.gz' | sha256sum --check
|
||||||
|
mkdir -p /tmp/gitleaks-bin
|
||||||
|
tar -xzf /tmp/gitleaks.tar.gz -C /tmp/gitleaks-bin gitleaks
|
||||||
|
/tmp/gitleaks-bin/gitleaks git --log-opts=--all --redact=100 --no-banner
|
||||||
|
- uses: https://github.com/actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version-file: .nvmrc
|
||||||
|
- name: Verify pre-commit secret blocking and redaction
|
||||||
|
run: PATH=/tmp/gitleaks-bin:$PATH node --test scripts/test-pre-commit.mjs
|
||||||
|
- name: Audit runtime and development dependencies
|
||||||
|
run: npm audit --include=dev --audit-level=low
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
name: Frontend verify
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- '**'
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
verify:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: https://github.com/actions/checkout@v4
|
||||||
|
- name: Record checked revision
|
||||||
|
run: git rev-parse HEAD
|
||||||
|
- uses: https://github.com/actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version-file: .nvmrc
|
||||||
|
- run: npm ci
|
||||||
|
env:
|
||||||
|
HUSKY: '0'
|
||||||
|
- name: Run all frontend gates
|
||||||
|
run: npm run verify
|
||||||
|
env:
|
||||||
|
# OXC raw transfer allocates a ~6 GiB buffer; use the standard parser in CI.
|
||||||
|
KNIP_DISABLE_RAW_TRANSFER: '1'
|
||||||
@@ -1,2 +1,3 @@
|
|||||||
|
gitleaks git --pre-commit --staged --redact=100 --no-banner || exit $?
|
||||||
npx lint-staged
|
npx lint-staged
|
||||||
npm run deps
|
npm run deps
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
{
|
||||||
|
"git": {
|
||||||
|
"requireBranch": "release/*",
|
||||||
|
"requireCleanWorkingDir": true,
|
||||||
|
"requireUpstream": false,
|
||||||
|
"requireCommits": true,
|
||||||
|
"commitMessage": "chore(release): ${version}",
|
||||||
|
"tagName": "v${version}",
|
||||||
|
"tag": false,
|
||||||
|
"push": false
|
||||||
|
},
|
||||||
|
"npm": {
|
||||||
|
"publish": false
|
||||||
|
},
|
||||||
|
"github": {
|
||||||
|
"release": false
|
||||||
|
},
|
||||||
|
"gitlab": {
|
||||||
|
"release": false
|
||||||
|
},
|
||||||
|
"hooks": {
|
||||||
|
"after:git:init": "node scripts/check-release.cjs"
|
||||||
|
},
|
||||||
|
"plugins": {
|
||||||
|
"@release-it/conventional-changelog": {
|
||||||
|
"infile": "CHANGELOG.md",
|
||||||
|
"preset": {
|
||||||
|
"name": "conventionalcommits",
|
||||||
|
"types": [
|
||||||
|
{
|
||||||
|
"type": "chore",
|
||||||
|
"scope": "release",
|
||||||
|
"effect": "hidden"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "feat",
|
||||||
|
"section": "Features",
|
||||||
|
"effect": "bump"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "fix",
|
||||||
|
"section": "Bug Fixes",
|
||||||
|
"effect": "bump"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "perf",
|
||||||
|
"section": "Performance",
|
||||||
|
"effect": "bump"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "docs",
|
||||||
|
"section": "Documentation",
|
||||||
|
"effect": "bump"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "spec",
|
||||||
|
"section": "Specifications",
|
||||||
|
"effect": "bump"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "refactor",
|
||||||
|
"section": "Refactoring",
|
||||||
|
"effect": "bump"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "build",
|
||||||
|
"section": "Build",
|
||||||
|
"effect": "bump"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "ci",
|
||||||
|
"section": "CI",
|
||||||
|
"effect": "bump"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "test",
|
||||||
|
"section": "Tests",
|
||||||
|
"effect": "bump"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "style",
|
||||||
|
"section": "Styles",
|
||||||
|
"effect": "bump"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "chore",
|
||||||
|
"section": "Maintenance",
|
||||||
|
"effect": "bump"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "revert",
|
||||||
|
"section": "Reverts",
|
||||||
|
"effect": "bump"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"context": {
|
||||||
|
"host": "https://git.personal.ksv741.ru",
|
||||||
|
"owner": "WealthLedger",
|
||||||
|
"repository": "frontend",
|
||||||
|
"linkReferences": true,
|
||||||
|
"commit": "commit"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import "@mantine/dates/styles.css";
|
|||||||
import "dayjs/locale/ru";
|
import "dayjs/locale/ru";
|
||||||
import "../src/shared/i18n";
|
import "../src/shared/i18n";
|
||||||
import { MantineProvider } from "@mantine/core";
|
import { MantineProvider } from "@mantine/core";
|
||||||
|
import { DatesProvider } from "@mantine/dates";
|
||||||
import type { Preview } from "@storybook/react-vite";
|
import type { Preview } from "@storybook/react-vite";
|
||||||
import { cssVariablesResolver, theme } from "@/shared/theme";
|
import { cssVariablesResolver, theme } from "@/shared/theme";
|
||||||
|
|
||||||
@@ -33,7 +34,9 @@ const preview: Preview = {
|
|||||||
forceColorScheme="light"
|
forceColorScheme="light"
|
||||||
colorSchemeManager={colorSchemeManager}
|
colorSchemeManager={colorSchemeManager}
|
||||||
>
|
>
|
||||||
|
<DatesProvider settings={{ locale: "ru" }}>
|
||||||
<Story />
|
<Story />
|
||||||
|
</DatesProvider>
|
||||||
</MantineProvider>
|
</MantineProvider>
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -12,13 +12,25 @@ React/Vite-клиент; общие правила работы — в root `AGE
|
|||||||
dependency boundaries и сборки приложения/Storybook без backend.
|
dependency boundaries и сборки приложения/Storybook без backend.
|
||||||
Точные scripts принадлежат `package.json`; targeted checks — у выбранного convention.
|
Точные scripts принадлежат `package.json`; targeted checks — у выбранного convention.
|
||||||
|
|
||||||
HTTP contract changes дополнительно проходят общий
|
HTTP contract changes используют предоставленный OpenAPI snapshot; frontend
|
||||||
[contract workflow](../docs/development/runtime-openapi-verification.md).
|
локально проверяет только соответствие generated types этому snapshot:
|
||||||
|
[Источник HTTP-контракта](../docs/architecture/http-api.md#источник-контракта).
|
||||||
Generated types редактируются через их source; T-Bank доступен только через backend.
|
Generated types редактируются через их source; T-Bank доступен только через backend.
|
||||||
Frontend dependencies используют exact versions. Pre-commit запускает staged
|
Frontend dependencies используют exact versions. Pre-commit запускает staged
|
||||||
formatting и FSD checks; сообщения commits — Conventional Commits.
|
formatting и FSD checks; сообщения commits — Conventional Commits.
|
||||||
|
Если у задачи есть связанная issue этого репозитория, добавляй её номер
|
||||||
|
в конец заголовка: `ci: run full frontend verification #1`.
|
||||||
|
Без связанной issue номер необязателен: `chore(deps): update non-major dependencies`.
|
||||||
|
Формат Conventional Commits проверяет `commitlint.config.cjs`.
|
||||||
|
|
||||||
Code/style checks автоматические только в scope конфигурации. i18n, props,
|
Code/style checks автоматические только в scope конфигурации. i18n, props,
|
||||||
semantic placement и выбор полезных тестов обязательны при review.
|
semantic placement и выбор полезных тестов обязательны при review.
|
||||||
Storybook уже доступен как reference; ожидаемый UI и его состояния определяет
|
Storybook уже доступен как reference; ожидаемый UI и его состояния определяет
|
||||||
задача, а визуальное соответствие проверяется отдельно от сборки.
|
задача, а визуальное соответствие проверяется отдельно от сборки.
|
||||||
|
|
||||||
|
## Ветки и релизы
|
||||||
|
|
||||||
|
Работа — в отдельной ветке от `develop`, затем PR в `develop`; в `main` напрямую
|
||||||
|
не пушить. Release/hotfix и синхронизация веток — по [root README](../README.md#релизы-и-ветки).
|
||||||
|
Commits и заголовки PR — Conventional Commits; для спецификаций допустим `spec:`.
|
||||||
|
Перед подготовкой релиза прочитай root README; версии вручную не повышать.
|
||||||
|
|||||||
+118
@@ -0,0 +1,118 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
## 0.1.0 (2026-09-14)
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* **account-operations:** require explicit ledger filters ([7d748a6](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/7d748a65d384e76220e234aa37a21b05b81e442a))
|
||||||
|
* **accounts:** enrich brokerage account list ([fd93133](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/fd93133cfcdfd9372b2630cacaa7f5195f1beb58))
|
||||||
|
* **account:** wrap portfolio sections in Mantine Accordion ([c1a8674](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/c1a8674f164117018236bf461bd457208ac9ad00))
|
||||||
|
* add all-accounts portfolio pages ([daf1dca](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/daf1dca6666035cbca3ba020d8ae0b2a8789dc3a))
|
||||||
|
* add authorization ([3448fea](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/3448fea1407f246e0b093e64edd7b672ae8992a9))
|
||||||
|
* add bond pages and portfolio navigation ([232d7f9](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/232d7f999040e4c91c27d5b382f2fcdfc4542d5a))
|
||||||
|
* add breadcrumbs ([719a6ed](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/719a6ed8b73f8a552778a1b78f65776f02d4127c))
|
||||||
|
* add brocker account list ([6e89c1a](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/6e89c1a8f765025bd7be37b59c696d092fd4bbe4))
|
||||||
|
* add manual bank card screens ([ff4e88e](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/ff4e88edbeb9de244c2a6094ab70d9e48a4768a7))
|
||||||
|
* add operations page ([4f3ee7d](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/4f3ee7ddb289284f8a6a0677438f270e8756a3fb))
|
||||||
|
* add portfolio ([9156f29](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/9156f297073fefa2fe1c5cb9659495e2d532ac89))
|
||||||
|
* add stock pages and ticker navigation ([561222e](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/561222e4686bde1dc98454a4216025c4cbc02d65))
|
||||||
|
* add Storybook for WealthLedger components ([e63fd89](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/e63fd89a3922cd4dd7f194e33b320b4178985a5f))
|
||||||
|
* add tbank tokens ([32e21de](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/32e21de17d00de5b3a4b074a2300e6a29a81e3ae))
|
||||||
|
* add агегку events ([da55de5](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/da55de5b5008cce0ea24def664e13f3239174324))
|
||||||
|
* animate page transitions with Motion ([c906dfa](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/c906dfa2e290164e6b089764be18edc99f10e775))
|
||||||
|
* **broker-operation:** show operation type label in ledger entries ([d53ce50](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/d53ce50e2842e8d69a709b92417888ba851774b4))
|
||||||
|
* **card:** refine header and inline actions ([cf21a5b](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/cf21a5bd178a18753321811b6d8ac81ff848d676))
|
||||||
|
* **cards:** filter operations by date range ([9bb385b](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/9bb385b9f02cc780e27d9da8f30fae374ab0f08c))
|
||||||
|
* **cards:** refine controls and modal transitions ([aba4cf1](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/aba4cf1ce83ea62082f35be358c2081d797f6645))
|
||||||
|
* **cards:** show operation icons on hover ([dedfec1](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/dedfec10d1e94b76a21e0d9ee90b6cf7fea5a4a9))
|
||||||
|
* compact portfolio currency totals ([47fbc21](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/47fbc212831058f1a0f1226dd262bf5c37870e34))
|
||||||
|
* consume money projected event amounts ([1fd9a3a](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/1fd9a3a861a8b915b6c64861a018db39e2598a83))
|
||||||
|
* enforce frontend quality guardrails ([1fc269a](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/1fc269adec9f0cfeacdc365c6e59a30c4620dba7))
|
||||||
|
* establish frontend foundation ([1e13ada](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/1e13adabd32412de9707f452e42d2c65e73c106f))
|
||||||
|
* **events:** add date filters to upcoming events ([9469dd2](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/9469dd2fdc03df47c202da2afdcdadb49dbb2748))
|
||||||
|
* improve bank card expenses summary ([d3ac8c2](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/d3ac8c242de1d30cd3c4ca8e5850700192c2c259))
|
||||||
|
* improve card operations pagination and scroll behavior ([9a65687](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/9a65687d3875d264b6de088d6886e6cb916d3426))
|
||||||
|
* improve ledger event rows ([488ccad](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/488ccad540c771e862fb795edf2df6c6cea315af))
|
||||||
|
* **income:** add account income analytics ([9364568](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/93645682028947d3fbd212bc9929dd2195715c69))
|
||||||
|
* initial commit ([3331b7f](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/3331b7f684f2ccc6d3934436d0326d877d1c3899))
|
||||||
|
* polish bank operation cards and dates ([6b310db](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/6b310db0b8c37cb4cffe54acf3b7e9799f9f3ea0))
|
||||||
|
* polish stock position cards ([273778c](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/273778c4cfa6ef8bd3ab421e03c57b6e31f7d925))
|
||||||
|
* **portfolio:** add expanded layout for bond position cards ([bcf9369](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/bcf93691aa874114faf75cb9c36d1426dd7b8903))
|
||||||
|
* **portfolio:** extend instrument logo rendering to bonds ([c04025a](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/c04025a3924ad76ae06e9bbbd32df4d18c85b34a))
|
||||||
|
* **portfolio:** show stock tickers ([8f9caa9](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/8f9caa946ee99e2db2b495a384b17a0ce90ddcfd))
|
||||||
|
* **portfolio:** visualize asset allocation ([0306526](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/0306526d3330d508d817aedecf74f0b74583dea7))
|
||||||
|
* redesign portfolio position cards ([5168870](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/5168870cf2d5ac19a6d08ad8fee35f2952cdda87))
|
||||||
|
* redesign year-over-year income comparison ([91eaeb5](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/91eaeb5661706f30171f5f15bf22e419fe2ee57c))
|
||||||
|
* render stock logos with signed returns on account page ([a6d3051](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/a6d305127057bf6413825ffddba1c15b53e65a73))
|
||||||
|
* replace loading spinners with skeletons ([71a214d](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/71a214d7adfcf5fc57cd5518fb008021d50e7723))
|
||||||
|
* replace paired date inputs with range pickers ([24d332e](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/24d332e06341ccfb0d0d7046793ca145669cec44))
|
||||||
|
* show page context in browser tab titles ([2580134](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/2580134683cbe036bb07b635aab6262d3702f270))
|
||||||
|
* simplify income page filters and payments ([26f229b](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/26f229ba3e0f8335dde297bf6c4575f7014e9f28))
|
||||||
|
* **ui:** animate navigation and operation icons ([8e58c01](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/8e58c016d2dccfbdc6089480f6ccc113b6719850))
|
||||||
|
* **ui:** animate sidebar icons on hover ([ebba6ab](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/ebba6ab25dc968c278d525fd2fd4194c8422d8d1))
|
||||||
|
* **ui:** establish shared design system foundations ([d762ba5](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/d762ba50342cd96e4387a51bac12a0c4c43c648c))
|
||||||
|
* unify upcoming event cards across pages ([451400b](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/451400b63be0011a7a3b4dfd77e9365f7bcca467))
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **frontend:** complete audit remediation ([9e42148](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/9e42148f6a9ad620b4fc9f6aef9ee2d80d73702b))
|
||||||
|
* harden frontend dependency and env hygiene ([826936c](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/826936c6a4a7160b07224f0fa94b6d2d941bc6dc))
|
||||||
|
* little fixes ([2e32d22](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/2e32d226d321f2d51653f1823ade8bace17fc5e5))
|
||||||
|
* preserve cached data during refresh failures ([6d892da](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/6d892da9cec9d8522520cec3c26d343e81f4a51d))
|
||||||
|
* remove income analytics period limit ([ab1b536](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/ab1b53680d811e5b5f91e8e14a7f219274e57313))
|
||||||
|
* separate portfolio cash presentation ([3017fc8](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/3017fc810ee10f2790dbc04902ad4e2f2cbadbd4))
|
||||||
|
* stabilize frontend query cache contracts ([1250581](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/1250581ee3336e901bd01f757328ae4c4dd091c8))
|
||||||
|
* **tbank:** reset connection-derived query cache ([175727b](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/175727bc93876f950280d0ad35515a6d4acffbaf))
|
||||||
|
* **ui:** align page layouts and add navigation icons ([d7e8963](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/d7e8963d1cfabd0900051e30e33ec30284282a7c))
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
|
||||||
|
* **agents:** link audit remediation registry ([b285719](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/b285719c1bcea32e490f9d960d7893bd21ba9e81))
|
||||||
|
* **agents:** restore openspec authority ([fd72fb2](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/fd72fb2239849cb87d441c552b194b6358c9dc8a))
|
||||||
|
* **ai:** route frontend conventions by task ([bcc034f](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/bcc034f19839a1aefadad978c5bb3a89d81ebe63))
|
||||||
|
* align OpenAPI workflow guidance [#3](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/3) ([7a89356](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/7a89356f8783a14d6dde752358ee995d0dcadd66))
|
||||||
|
* define canonical OpenSpec store ([d870d53](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/d870d535d7090aa3051de6f1b0fd979eaf6d7154))
|
||||||
|
* document runtime OpenAPI verification ([7a3048c](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/7a3048c3476675528203fbe74338131723354e1d))
|
||||||
|
* refresh frontend onboarding ([be80ef2](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/be80ef2f1bffc01867ee97f5f78c0cba7764a24e))
|
||||||
|
* remove useless ([7ab043d](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/7ab043dce63a3fbacbfc9ac7d15b00dd714a541f))
|
||||||
|
* update routes to system documentation ([a42f104](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/a42f104bed4daf982f2a72f0634887e4ea067dec))
|
||||||
|
* update system documentation references ([dc3434c](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/dc3434c3716f09cfb1ef4aa3006e9db12f6b3bcf))
|
||||||
|
|
||||||
|
### Refactoring
|
||||||
|
|
||||||
|
* **account-operations:** split page state views into components ([695cda0](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/695cda0456970fe3a46d09dcec718c741ee6b18d))
|
||||||
|
* align frontend ownership boundaries ([c97f62b](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/c97f62bd983d6b5327132f4ec42e767118720913))
|
||||||
|
* centralize frontend auth query gating ([268acdf](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/268acdf2e1057ed0f6c19384bfb6477aff773d1d))
|
||||||
|
* enforce account page view model boundary ([fff36f2](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/fff36f252aa1a7bb18042c8fc2d06262b687b0b1))
|
||||||
|
* enforce semantic values and numeric lint rules ([53c852b](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/53c852b437ee1174843a4f959722239132e9150a))
|
||||||
|
* little structure refactor ([2cca503](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/2cca503519888762067c770c188ed2d977979cbb))
|
||||||
|
* refactor foundation ([da585b1](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/da585b157a5350753a91abb7f10aa00c7e9cf2c3))
|
||||||
|
* simplify local design token consumption ([8b29cdf](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/8b29cdfd98790cb3316f1db0f8933c8b6bc4b335))
|
||||||
|
* source shared design tokens from JSON ([0f50f15](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/0f50f156584b6b0bf3e473d047c3960284cf0cdd))
|
||||||
|
* use Mantine Breadcrumbs for app navigation ([3c459e6](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/3c459e66cc640cad58267cbaac2be4fbcaee4fdf))
|
||||||
|
|
||||||
|
### CI
|
||||||
|
|
||||||
|
* configure Renovate dependency updates [#5](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/5) ([4b97395](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/4b973953853785660b5c34ef96c90d518ab6c561))
|
||||||
|
* disable memory-heavy Knip raw transfer [#1](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/1) ([2f26e4f](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/2f26e4fe0d8aa4e693c3ca425db04b04afbba75f))
|
||||||
|
* run Biome on branch pushes in Gitea ([ccff422](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/ccff422f367bbcf5e19f510119dbe8b63de9b87a))
|
||||||
|
* run full frontend verification [#1](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/1) ([22e331e](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/22e331e2ff4c5f68b3273de89fe9968029a1343d))
|
||||||
|
|
||||||
|
### Tests
|
||||||
|
|
||||||
|
* allow UI scenarios more time in CI [#1](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/1) ([942ed3d](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/942ed3d453d71547dc8883924a9bb2f76f7e997f))
|
||||||
|
* keep portfolio metadata authoritative in cards ([427ca23](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/427ca23a433a20be25b1f4373f32c9e1f6f8c400))
|
||||||
|
|
||||||
|
### Maintenance
|
||||||
|
|
||||||
|
* align SDD routing and instruction commits ([3669832](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/36698322b7273b3a9eae1d078bcc9cddf2c8295b))
|
||||||
|
* codify frontend local verification ([11be786](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/11be786943024699a4eccf91a8d1ad32a6d29e5f))
|
||||||
|
* codify React component style ([d10e1dd](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/d10e1dd1827094e6e52768f0ccd2ea060aef95a1))
|
||||||
|
* configure releases and develop workflow ([53b18c6](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/53b18c6e86f433bcb967721232c150fba4f7cc9f))
|
||||||
|
* **deps:** update non-major dependencies ([0c6bac8](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/0c6bac8b902b88dc0b447b9198968e938db72c82))
|
||||||
|
* make issue references optional and use chore for dependency updates [#5](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/5) ([82b9043](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/82b904393dcf65d9876fd06d1864dddef7d70bdb))
|
||||||
|
* save pending changes ([ae06f6e](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/ae06f6e6e0f98a2be208d66105ca53ecf2d86bfd))
|
||||||
|
* secure hooks and update dependencies [#4](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/4) [#9](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/9) ([3be6e61](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/3be6e61b8fc85d4b16199dbe9910b38894159cb8))
|
||||||
|
* simplify frontend verification ([f09baa6](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/f09baa68fcecfd210f95a7bfe8a67dc3741abce8))
|
||||||
|
* simplify frontend verification ([3d9b619](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/3d9b6194c60b373996a590c4bd56653e0935e8c6))
|
||||||
|
* upgrade Node to 24 LTS ([117e74c](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/117e74cdfc29cbf63f549ea88e8106ab25300541))
|
||||||
@@ -5,7 +5,7 @@ backend; прямые вызовы T-Bank из frontend не допускают
|
|||||||
|
|
||||||
## Быстрый старт
|
## Быстрый старт
|
||||||
|
|
||||||
Требуется Node 22 (`.nvmrc`). Создайте `.env` из примера и установите
|
Требуется Node 24 (`.nvmrc`). Создайте `.env` из примера и установите
|
||||||
зависимости строго из lockfile:
|
зависимости строго из lockfile:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -17,6 +17,12 @@ npm run dev
|
|||||||
|
|
||||||
`VITE_API_BASE_URL` по умолчанию указывает на `http://localhost:3000`.
|
`VITE_API_BASE_URL` по умолчанию указывает на `http://localhost:3000`.
|
||||||
|
|
||||||
|
Для commits установите [Gitleaks](https://github.com/gitleaks/gitleaks/releases/tag/v8.30.1)
|
||||||
|
8.30.1 в `PATH` (macOS: `brew install gitleaks`). Pre-commit сначала проверяет
|
||||||
|
staged diff с полной редакцией секретов, затем запускает formatting и FSD checks.
|
||||||
|
Находка или отсутствие Gitleaks блокирует commit.
|
||||||
|
Проверка этого поведения: `node --test scripts/test-pre-commit.mjs`.
|
||||||
|
|
||||||
## Проверка
|
## Проверка
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -27,10 +33,30 @@ npm run verify
|
|||||||
Команда проверяет, что generated OpenAPI types соответствуют committed snapshot,
|
Команда проверяет, что generated OpenAPI types соответствуют committed snapshot,
|
||||||
затем запускает strict TypeScript, Biome, один coverage-backed запуск Vitest,
|
затем запускает strict TypeScript, Biome, один coverage-backed запуск Vitest,
|
||||||
Knip, dependency rules приложения и stories, сборки приложения и Storybook.
|
Knip, dependency rules приложения и stories, сборки приложения и Storybook.
|
||||||
|
Отдельный CI workflow `Frontend security` на push, pull request и ежедневно
|
||||||
|
проверяет полную доступную историю Gitleaks 8.30.1 и выполняет
|
||||||
|
`npm audit --include=dev --audit-level=low`. Любой advisory блокирует security job;
|
||||||
|
исключений frontend нет. Локально можно выполнить те же команды:
|
||||||
|
`gitleaks git --log-opts=--all --redact=100 --no-banner` и
|
||||||
|
`npm audit --include=dev --audit-level=low`. Audit требует доступа к npm registry;
|
||||||
|
проверка секретов выполняется локально и не выводит их значения.
|
||||||
|
|
||||||
|
TypeScript остаётся на 5.9.3: `openapi-typescript@7.13.0` требует peer `^5.x`.
|
||||||
|
Обновление до TypeScript 7 из Renovate dashboard откладывается до совместимого
|
||||||
|
релиза генератора; `--force`/`--legacy-peer-deps` для обхода этого ограничения
|
||||||
|
не используются.
|
||||||
Если backend-контракт изменился,
|
Если backend-контракт изменился,
|
||||||
обновите `src/shared/api/spec/openapi.json` копированием backend OpenAPI
|
обновите `src/shared/api/spec/openapi.json` копированием backend OpenAPI
|
||||||
document и затем выполните `npm run openapi:generate`.
|
document и затем выполните `npm run openapi:generate`.
|
||||||
|
|
||||||
|
## UI-каталог Storybook
|
||||||
|
|
||||||
|
После `nvm use --silent` выполните `npm run dev:catalog`; статическая сборка —
|
||||||
|
`npm run build:catalog`. Каталог использует общую тему приложения, вымышленные
|
||||||
|
данные и локальные действия без application API. Примеры не доказывают
|
||||||
|
восстановление реального запроса. Визуальные роли описаны в
|
||||||
|
[дизайн-системе](../docs/design/overview.md).
|
||||||
|
|
||||||
## Документация
|
## Документация
|
||||||
|
|
||||||
- [Router conventions](.ai/CONVENTIONS.md) и [источники](.ai/SOURCES.md)
|
- [Router conventions](.ai/CONVENTIONS.md) и [источники](.ai/SOURCES.md)
|
||||||
@@ -38,15 +64,17 @@ document и затем выполните `npm run openapi:generate`.
|
|||||||
- [UI, state, формы и компоненты](.ai/conventions/frontend-ui.md)
|
- [UI, state, формы и компоненты](.ai/conventions/frontend-ui.md)
|
||||||
- [Data/API/cache](.ai/conventions/frontend-data.md)
|
- [Data/API/cache](.ai/conventions/frontend-data.md)
|
||||||
- [Testing](.ai/conventions/frontend-testing.md)
|
- [Testing](.ai/conventions/frontend-testing.md)
|
||||||
- [Поставленный UI-каталог Storybook](../docs/development/ui-catalog.md)
|
- [UI-каталог Storybook](#ui-каталог-storybook)
|
||||||
- [Обзор поставленной системы](../docs/architecture/system-overview.md)
|
- [Обзор поставленной системы](../docs/overview.md)
|
||||||
- [Engineering governance и risk-based testing](../docs/development/engineering-governance.md)
|
- [Карта проектных фактов](../docs/README.md)
|
||||||
- [Карта проектных фактов](../docs/AI_INDEX.md)
|
|
||||||
- [Frontend workflow](../docs/development/frontend-workflow.md)
|
|
||||||
- [Remediation registry](../docs/development/audit-remediation.md)
|
|
||||||
|
|
||||||
Runtime OpenAPI backend сверяется с frontend snapshot отдельной read-only
|
Runtime OpenAPI backend сверяется с frontend snapshot отдельной read-only
|
||||||
backend командой `npm run test:openapi-contract`.
|
backend командой `npm run test:openapi-contract`.
|
||||||
Разработка идёт напрямую по задаче пользователя. Каждый affected repo проходит
|
Разработка идёт напрямую по задаче пользователя. Каждый affected repo проходит
|
||||||
свой verify; при изменении wire contract дополнительно выполняется contract check.
|
свой verify; при изменении wire contract дополнительно выполняется contract check.
|
||||||
Обязательного OpenSpec/SDD lifecycle нет.
|
Обязательного OpenSpec/SDD lifecycle нет.
|
||||||
|
|
||||||
|
Версии и ветки: [процесс релиза](../README.md#релизы-и-ветки).
|
||||||
|
|
||||||
|
Knip исключает `conventional-changelog-conventionalcommits`: release-it загружает
|
||||||
|
preset по имени из `.release-it.json`. Версия preset закреплена напрямую.
|
||||||
|
|||||||
+17
-1
@@ -27,7 +27,8 @@
|
|||||||
},
|
},
|
||||||
"style": {
|
"style": {
|
||||||
"noDefaultExport": "error",
|
"noDefaultExport": "error",
|
||||||
"useExportsLast": "error"
|
"useExportsLast": "error",
|
||||||
|
"noMagicNumbers": "error"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -57,6 +58,21 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"includes": [
|
||||||
|
"**/*.test.ts",
|
||||||
|
"**/*.test.tsx",
|
||||||
|
"**/*.stories.tsx",
|
||||||
|
"src/test/**"
|
||||||
|
],
|
||||||
|
"linter": {
|
||||||
|
"rules": {
|
||||||
|
"style": {
|
||||||
|
"noMagicNumbers": "off"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
+23
-1
@@ -1 +1,23 @@
|
|||||||
module.exports = { extends: ["@commitlint/config-conventional"] };
|
module.exports = {
|
||||||
|
extends: ["@commitlint/config-conventional"],
|
||||||
|
rules: {
|
||||||
|
"type-enum": [
|
||||||
|
2,
|
||||||
|
"always",
|
||||||
|
[
|
||||||
|
"feat",
|
||||||
|
"fix",
|
||||||
|
"perf",
|
||||||
|
"docs",
|
||||||
|
"spec",
|
||||||
|
"refactor",
|
||||||
|
"build",
|
||||||
|
"ci",
|
||||||
|
"test",
|
||||||
|
"style",
|
||||||
|
"chore",
|
||||||
|
"revert",
|
||||||
|
],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
{
|
{
|
||||||
"project": ["src/**/*.{ts,tsx}", "!src/shared/api/generated/**"]
|
"project": ["src/**/*.{ts,tsx}", "!src/shared/api/generated/**"],
|
||||||
|
"ignoreDependencies": ["conventional-changelog-conventionalcommits"]
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+3246
-1110
File diff suppressed because it is too large
Load Diff
+42
-32
@@ -1,10 +1,10 @@
|
|||||||
{
|
{
|
||||||
"name": "wealth-ledger-frontend",
|
"name": "wealth-ledger-frontend",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.0.0",
|
"version": "0.1.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "22.x"
|
"node": "24.21.0"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
@@ -24,58 +24,68 @@
|
|||||||
"verify": "npm run openapi:check && npm run typecheck && npm run lint && npm run test:coverage && npm run knip && npm run deps && npm run deps:storybook && npm run build && npm run build:catalog",
|
"verify": "npm run openapi:check && npm run typecheck && npm run lint && npm run test:coverage && npm run knip && npm run deps && npm run deps:storybook && npm run build && npm run build:catalog",
|
||||||
"prepare": "husky",
|
"prepare": "husky",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"deps:storybook": "depcruise src .storybook/preview.tsx --config .storybook/dependency-cruiser.cjs --output-type err-long"
|
"deps:storybook": "depcruise src .storybook/preview.tsx --config .storybook/dependency-cruiser.cjs --output-type err-long",
|
||||||
|
"release:preview": "release-it --dry-run --ci",
|
||||||
|
"release:prepare": "release-it --ci",
|
||||||
|
"commitlint": "commitlint"
|
||||||
},
|
},
|
||||||
"lint-staged": {
|
"lint-staged": {
|
||||||
"*.{css,html,json,md,ts,tsx}": "biome format --write --no-errors-on-unmatched"
|
"*.{css,html,json,md,ts,tsx}": "biome format --write --no-errors-on-unmatched"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@hookform/resolvers": "5.7.1",
|
"@hookform/resolvers": "5.9.1",
|
||||||
"@mantine/charts": "9.5.1",
|
"@mantine/charts": "9.6.1",
|
||||||
"@mantine/core": "9.5.1",
|
"@mantine/core": "9.6.1",
|
||||||
"@mantine/dates": "9.5.1",
|
"@mantine/dates": "9.6.1",
|
||||||
"@mantine/hooks": "9.5.1",
|
"@mantine/hooks": "9.6.1",
|
||||||
"@tanstack/react-query": "5.101.4",
|
"@tanstack/react-query": "5.102.8",
|
||||||
"dayjs": "1.11.23",
|
"dayjs": "1.11.23",
|
||||||
"i18next": "26.0.2",
|
"i18next": "26.4.2",
|
||||||
"motion": "13.2.0",
|
"motion": "13.2.0",
|
||||||
"openapi-fetch": "0.17.0",
|
"openapi-fetch": "0.17.0",
|
||||||
"openapi-react-query": "0.5.4",
|
"openapi-react-query": "0.5.4",
|
||||||
"react": "19.2.8",
|
"react": "19.3.0",
|
||||||
"react-dom": "19.2.8",
|
"react-dom": "19.3.0",
|
||||||
"react-hook-form": "7.85.0",
|
"react-hook-form": "7.88.0",
|
||||||
"react-i18next": "16.3.5",
|
"react-i18next": "17.0.14",
|
||||||
"react-is": "19.2.8",
|
"react-is": "19.3.0",
|
||||||
"react-router": "7.18.2",
|
"react-router": "8.3.1",
|
||||||
"recharts": "3.10.1",
|
"recharts": "3.10.1",
|
||||||
"zod": "3.25.76"
|
"zod": "4.6.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@babel/core": "7.29.7",
|
"@babel/core": "8.0.5",
|
||||||
"@biomejs/biome": "2.5.8",
|
"@biomejs/biome": "2.5.13",
|
||||||
"@commitlint/cli": "21.2.2",
|
"@commitlint/cli": "21.2.2",
|
||||||
"@commitlint/config-conventional": "21.2.2",
|
"@commitlint/config-conventional": "21.2.2",
|
||||||
"@rolldown/plugin-babel": "0.2.3",
|
"@release-it/conventional-changelog": "12.0.0",
|
||||||
|
"@rolldown/plugin-babel": "0.2.4",
|
||||||
"@storybook/addon-docs": "10.6.0",
|
"@storybook/addon-docs": "10.6.0",
|
||||||
"@storybook/react-vite": "10.6.0",
|
"@storybook/react-vite": "10.6.0",
|
||||||
"@testing-library/jest-dom": "6.9.1",
|
"@testing-library/jest-dom": "7.0.1",
|
||||||
"@testing-library/react": "16.3.0",
|
"@testing-library/react": "16.3.3",
|
||||||
"@types/node": "24.13.3",
|
"@types/node": "24.13.4",
|
||||||
"@types/react": "19.2.17",
|
"@types/react": "19.3.0",
|
||||||
"@types/react-dom": "19.2.3",
|
"@types/react-dom": "19.3.0",
|
||||||
"@vitejs/plugin-react": "6.0.4",
|
"@vitejs/plugin-react": "6.1.1",
|
||||||
"@vitest/coverage-v8": "4.1.10",
|
"@vitest/coverage-v8": "5.0.0",
|
||||||
"babel-plugin-react-compiler": "1.0.0",
|
"babel-plugin-react-compiler": "1.0.0",
|
||||||
|
"conventional-changelog-conventionalcommits": "10.4.0",
|
||||||
"dependency-cruiser": "18.2.0",
|
"dependency-cruiser": "18.2.0",
|
||||||
"husky": "9.1.7",
|
"husky": "9.1.7",
|
||||||
"jsdom": "27.4.0",
|
"jsdom": "30.0.1",
|
||||||
"knip": "6.32.2",
|
"knip": "6.35.1",
|
||||||
"lint-staged": "16.2.7",
|
"lint-staged": "17.5.1",
|
||||||
"msw": "2.15.0",
|
"msw": "2.15.0",
|
||||||
"openapi-typescript": "7.13.0",
|
"openapi-typescript": "7.13.0",
|
||||||
|
"release-it": "21.0.2",
|
||||||
"storybook": "10.6.0",
|
"storybook": "10.6.0",
|
||||||
"typescript": "5.9.3",
|
"typescript": "5.9.3",
|
||||||
"vite": "8.2.0",
|
"vite": "8.3.0",
|
||||||
"vitest": "4.1.10"
|
"vitest": "5.0.0"
|
||||||
|
},
|
||||||
|
"allowScripts": {
|
||||||
|
"esbuild@0.28.2": true,
|
||||||
|
"fsevents@2.3.3": true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||||
|
"extends": ["config:recommended", ":semanticCommitTypeAll(chore)"],
|
||||||
|
"timezone": "Europe/Moscow",
|
||||||
|
"labels": ["dependencies"],
|
||||||
|
"dependencyDashboard": true,
|
||||||
|
"rangeStrategy": "pin",
|
||||||
|
"packageRules": [
|
||||||
|
{
|
||||||
|
"matchUpdateTypes": ["minor", "patch"],
|
||||||
|
"groupName": "non-major dependencies"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"matchUpdateTypes": ["major"],
|
||||||
|
"dependencyDashboardApproval": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"baseBranchPatterns": ["develop"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
const assert = require("node:assert/strict");
|
||||||
|
const { execFileSync } = require("node:child_process");
|
||||||
|
const { version } = require("../package.json");
|
||||||
|
const git = (...args) => execFileSync("git", args, { encoding: "utf8" }).trim();
|
||||||
|
|
||||||
|
assert.equal(
|
||||||
|
git("status", "--porcelain"),
|
||||||
|
"",
|
||||||
|
"Commit all changes before preparing a release",
|
||||||
|
);
|
||||||
|
const tags = git(
|
||||||
|
"tag",
|
||||||
|
"--merged",
|
||||||
|
"HEAD",
|
||||||
|
"--list",
|
||||||
|
"v[0-9]*",
|
||||||
|
"--sort=-version:refname",
|
||||||
|
)
|
||||||
|
.split("\n")
|
||||||
|
.filter((tag) => /^v\d+\.\d+\.\d+$/.test(tag));
|
||||||
|
assert.equal(
|
||||||
|
version,
|
||||||
|
tags[0]?.slice(1) ?? "0.0.0",
|
||||||
|
"Version is already prepared or release tags are missing. Fetch tags; finish the existing release before preparing another.",
|
||||||
|
);
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { execFileSync, spawnSync } from "node:child_process";
|
||||||
|
import { randomBytes } from "node:crypto";
|
||||||
|
import {
|
||||||
|
existsSync,
|
||||||
|
mkdirSync,
|
||||||
|
mkdtempSync,
|
||||||
|
rmSync,
|
||||||
|
writeFileSync,
|
||||||
|
} from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { delimiter, join, resolve } from "node:path";
|
||||||
|
import { test } from "node:test";
|
||||||
|
|
||||||
|
const GITHUB_TOKEN_RANDOM_BYTES = 18;
|
||||||
|
|
||||||
|
test("pre-commit scans the index, redacts findings and fails closed", () => {
|
||||||
|
const hook = resolve(".husky/pre-commit");
|
||||||
|
const cwd = mkdtempSync(join(tmpdir(), "frontend-hook-"));
|
||||||
|
const bin = join(cwd, "bin");
|
||||||
|
const marker = join(cwd, "downstream");
|
||||||
|
const token = `ghp_${randomBytes(GITHUB_TOKEN_RANDOM_BYTES).toString("hex")}`;
|
||||||
|
const git = (...args) => execFileSync("git", args, { cwd, stdio: "pipe" });
|
||||||
|
const run = (path = `${bin}${delimiter}${process.env.PATH}`) =>
|
||||||
|
spawnSync("/bin/sh", ["-e", hook], {
|
||||||
|
cwd,
|
||||||
|
env: { ...process.env, PATH: path },
|
||||||
|
encoding: "utf8",
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
mkdirSync(bin);
|
||||||
|
for (const command of ["npx", "npm"]) {
|
||||||
|
writeFileSync(join(bin, command), "#!/bin/sh\necho ran >> downstream\n", {
|
||||||
|
mode: 0o755,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
git("init", "--quiet");
|
||||||
|
writeFileSync(join(cwd, "sample.txt"), "safe staged content\n");
|
||||||
|
git("add", "sample.txt");
|
||||||
|
// An unstaged secret must not be mistaken for the index being committed.
|
||||||
|
writeFileSync(join(cwd, "sample.txt"), `token=${token}\n`);
|
||||||
|
let result = run();
|
||||||
|
assert.equal(
|
||||||
|
result.status,
|
||||||
|
0,
|
||||||
|
"clean index must pass; install Gitleaks first",
|
||||||
|
);
|
||||||
|
assert.ok(existsSync(marker));
|
||||||
|
rmSync(marker);
|
||||||
|
git("add", "sample.txt");
|
||||||
|
result = run();
|
||||||
|
assert.equal(result.status, 1, "staged secret must block commit");
|
||||||
|
assert.ok(!`${result.stdout}${result.stderr}`.includes(token));
|
||||||
|
assert.ok(!existsSync(marker), "formatting/dependency checks must not run");
|
||||||
|
result = run(bin);
|
||||||
|
assert.notEqual(result.status, 0, "missing Gitleaks must block commit");
|
||||||
|
assert.ok(!existsSync(marker));
|
||||||
|
} finally {
|
||||||
|
rmSync(cwd, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -37,6 +37,7 @@ describe("AppRoutes", () => {
|
|||||||
["/accounts/demo", "Вход"],
|
["/accounts/demo", "Вход"],
|
||||||
["/accounts/demo/operations", "Вход"],
|
["/accounts/demo/operations", "Вход"],
|
||||||
["/settings", "Вход"],
|
["/settings", "Вход"],
|
||||||
|
["/cards?month=2026-08", "Вход"],
|
||||||
["/unknown", "Страница не найдена"],
|
["/unknown", "Страница не найдена"],
|
||||||
])("renders %s with its page title", async (path, title) => {
|
])("renders %s with its page title", async (path, title) => {
|
||||||
renderRoutes(path);
|
renderRoutes(path);
|
||||||
@@ -94,6 +95,43 @@ describe("AppRoutes", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("returns after login to cards with the selected month without T-Bank", async () => {
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/categories", () => HttpResponse.json([])),
|
||||||
|
http.post("*/api/v1/auth/login", () =>
|
||||||
|
HttpResponse.json({
|
||||||
|
accessToken: "test",
|
||||||
|
user: { id: "user-1", email: "user@example.com" },
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
http.get("*/api/v1/bank-cards", () => HttpResponse.json([])),
|
||||||
|
http.get("*/api/v1/bank-cards/summary", () =>
|
||||||
|
HttpResponse.json({
|
||||||
|
month: "2026-08",
|
||||||
|
cardId: null,
|
||||||
|
expenses: { currency: "RUB", value: "0" },
|
||||||
|
refunds: { currency: "RUB", value: "0" },
|
||||||
|
net: { currency: "RUB", value: "0" },
|
||||||
|
categories: [],
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
renderRoutes("/cards?month=2026-08");
|
||||||
|
await screen.findByRole("heading", { name: "Вход" });
|
||||||
|
fireEvent.change(screen.getByLabelText("Email"), {
|
||||||
|
target: { value: "user@example.com" },
|
||||||
|
});
|
||||||
|
fireEvent.change(screen.getByLabelText("Пароль"), {
|
||||||
|
target: { value: "a secure password" },
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Вход" }));
|
||||||
|
await screen.findByRole("heading", { name: "Добавьте первую карту" });
|
||||||
|
expect(screen.getByLabelText("Период")).toHaveTextContent(
|
||||||
|
"01.08.2026 – 31.08.2026",
|
||||||
|
);
|
||||||
|
expect(document.title).toBe("Карты — WealthLedger");
|
||||||
|
});
|
||||||
|
|
||||||
it("lazy-loads the protected shell for an authenticated accounts route", async () => {
|
it("lazy-loads the protected shell for an authenticated accounts route", async () => {
|
||||||
server.use(
|
server.use(
|
||||||
http.post("*/api/v1/auth/refresh", () =>
|
http.post("*/api/v1/auth/refresh", () =>
|
||||||
|
|||||||
@@ -4,6 +4,14 @@ import { Navigate, Route, Routes } from "react-router";
|
|||||||
import { LazyPage } from "./RouteFallback";
|
import { LazyPage } from "./RouteFallback";
|
||||||
import { Protected, Public } from "./RouteGuards";
|
import { Protected, Public } from "./RouteGuards";
|
||||||
|
|
||||||
|
const CardPage = lazy(async () => {
|
||||||
|
const { CardPage } = await import("@/pages/card");
|
||||||
|
return { default: CardPage };
|
||||||
|
});
|
||||||
|
const CardsPage = lazy(async () => {
|
||||||
|
const { CardsPage } = await import("@/pages/cards");
|
||||||
|
return { default: CardsPage };
|
||||||
|
});
|
||||||
const BondPage = lazy(async () => {
|
const BondPage = lazy(async () => {
|
||||||
const { BondPage } = await import("@/pages/bond");
|
const { BondPage } = await import("@/pages/bond");
|
||||||
return { default: BondPage };
|
return { default: BondPage };
|
||||||
@@ -93,6 +101,22 @@ const AppRoutes: FC = () => (
|
|||||||
</Protected>
|
</Protected>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
<Route
|
||||||
|
path="/cards/:cardId"
|
||||||
|
element={
|
||||||
|
<LazyPage variant="content">
|
||||||
|
<CardPage />
|
||||||
|
</LazyPage>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="/cards"
|
||||||
|
element={
|
||||||
|
<LazyPage variant="content">
|
||||||
|
<CardsPage />
|
||||||
|
</LazyPage>
|
||||||
|
}
|
||||||
|
/>
|
||||||
<Route
|
<Route
|
||||||
path="/bonds"
|
path="/bonds"
|
||||||
element={
|
element={
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { useDocumentTitle } from "@mantine/hooks";
|
|||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useMatch } from "react-router";
|
import { useMatch } from "react-router";
|
||||||
|
import { useBankCard } from "@/entities/bank-card";
|
||||||
import { useBond } from "@/entities/bond";
|
import { useBond } from "@/entities/bond";
|
||||||
import { useBrokerageAccounts } from "@/entities/brokerage-account";
|
import { useBrokerageAccounts } from "@/entities/brokerage-account";
|
||||||
import { useStock } from "@/entities/stock";
|
import { useStock } from "@/entities/stock";
|
||||||
@@ -52,14 +53,23 @@ const StockDocumentTitle: FC<InstrumentDocumentTitleProps> = (props) => {
|
|||||||
return <DocumentTitle title={data?.name ?? t("stock.share")} />;
|
return <DocumentTitle title={data?.name ?? t("stock.share")} />;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const CardDocumentTitle: FC<InstrumentDocumentTitleProps> = (props) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { data } = useBankCard(props.identifier);
|
||||||
|
return <DocumentTitle title={data?.name ?? t("bank.card")} />;
|
||||||
|
};
|
||||||
|
|
||||||
const ProtectedDocumentTitle: FC = () => {
|
const ProtectedDocumentTitle: FC = () => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const account = useMatch("/accounts/:accountId/:section?");
|
const account = useMatch("/accounts/:accountId/:section?");
|
||||||
const bond = useMatch("/bonds/:bondId");
|
const bond = useMatch("/bonds/:bondId");
|
||||||
const stock = useMatch("/stocks/:stockId");
|
const stock = useMatch("/stocks/:stockId");
|
||||||
|
const card = useMatch("/cards/:cardId");
|
||||||
|
const cards = useMatch("/cards");
|
||||||
const bonds = useMatch("/bonds");
|
const bonds = useMatch("/bonds");
|
||||||
const stocks = useMatch("/stocks");
|
const stocks = useMatch("/stocks");
|
||||||
const settings = useMatch("/settings");
|
const settings = useMatch("/settings");
|
||||||
|
if (card) return <CardDocumentTitle identifier={card.params.cardId ?? ""} />;
|
||||||
if (account)
|
if (account)
|
||||||
return (
|
return (
|
||||||
<AccountDocumentTitle
|
<AccountDocumentTitle
|
||||||
@@ -73,7 +83,9 @@ const ProtectedDocumentTitle: FC = () => {
|
|||||||
return (
|
return (
|
||||||
<DocumentTitle
|
<DocumentTitle
|
||||||
title={t(
|
title={t(
|
||||||
bonds
|
cards
|
||||||
|
? "navigation.cards"
|
||||||
|
: bonds
|
||||||
? "navigation.bonds"
|
? "navigation.bonds"
|
||||||
: stocks
|
: stocks
|
||||||
? "navigation.stocks"
|
? "navigation.stocks"
|
||||||
|
|||||||
@@ -22,8 +22,16 @@ const Protected: FC<PropsWithChildren> = (props) => {
|
|||||||
const Public: FC<PropsWithChildren> = (props) => {
|
const Public: FC<PropsWithChildren> = (props) => {
|
||||||
const { children } = props;
|
const { children } = props;
|
||||||
const { user, ready } = useAuth();
|
const { user, ready } = useAuth();
|
||||||
|
const location = useLocation();
|
||||||
|
const requested = (location.state as { returnTo?: string } | null)?.returnTo;
|
||||||
|
const returnTo =
|
||||||
|
typeof requested === "string" &&
|
||||||
|
requested.startsWith("/") &&
|
||||||
|
!requested.startsWith("//")
|
||||||
|
? requested
|
||||||
|
: "/accounts";
|
||||||
if (!ready) return <RouteSkeleton variant="shell" />;
|
if (!ready) return <RouteSkeleton variant="shell" />;
|
||||||
return user ? <Navigate to="/accounts" replace /> : children;
|
return user ? <Navigate to={returnTo} replace /> : children;
|
||||||
};
|
};
|
||||||
|
|
||||||
export { Protected, Public };
|
export { Protected, Public };
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import * as m from "motion/react-m";
|
|||||||
import type { FC, PropsWithChildren } from "react";
|
import type { FC, PropsWithChildren } from "react";
|
||||||
import { useLocation } from "react-router";
|
import { useLocation } from "react-router";
|
||||||
|
|
||||||
|
const TRANSITION_DURATION_SECONDS = 0.2;
|
||||||
|
|
||||||
const RouteTransition: FC<PropsWithChildren> = (props) => {
|
const RouteTransition: FC<PropsWithChildren> = (props) => {
|
||||||
const { children } = props;
|
const { children } = props;
|
||||||
const { pathname } = useLocation();
|
const { pathname } = useLocation();
|
||||||
@@ -14,7 +16,10 @@ const RouteTransition: FC<PropsWithChildren> = (props) => {
|
|||||||
key={pathname}
|
key={pathname}
|
||||||
initial={reduceMotion ? false : { opacity: 0 }}
|
initial={reduceMotion ? false : { opacity: 0 }}
|
||||||
animate={{ opacity: 1 }}
|
animate={{ opacity: 1 }}
|
||||||
transition={{ duration: reduceMotion ? 0 : 0.2, ease: "easeOut" }}
|
transition={{
|
||||||
|
duration: reduceMotion ? 0 : TRANSITION_DURATION_SECONDS,
|
||||||
|
ease: "easeOut",
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
</m.div>
|
</m.div>
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { AccountBreadcrumbs } from "./AccountBreadcrumbs";
|
|||||||
import { AccountScopeSwitch } from "./AccountScopeSwitch";
|
import { AccountScopeSwitch } from "./AccountScopeSwitch";
|
||||||
import { BondBreadcrumbs } from "./BondBreadcrumbs";
|
import { BondBreadcrumbs } from "./BondBreadcrumbs";
|
||||||
import { BreadcrumbTrail } from "./BreadcrumbTrail";
|
import { BreadcrumbTrail } from "./BreadcrumbTrail";
|
||||||
|
import { CardBreadcrumbs } from "./CardBreadcrumbs";
|
||||||
import { StockBreadcrumbs } from "./StockBreadcrumbs";
|
import { StockBreadcrumbs } from "./StockBreadcrumbs";
|
||||||
|
|
||||||
const AppBreadcrumbs: FC = () => {
|
const AppBreadcrumbs: FC = () => {
|
||||||
@@ -17,6 +18,8 @@ const AppBreadcrumbs: FC = () => {
|
|||||||
const events = useMatch({ path: "/accounts/:accountId/events", end: true });
|
const events = useMatch({ path: "/accounts/:accountId/events", end: true });
|
||||||
const income = useMatch({ path: "/accounts/:accountId/income", end: true });
|
const income = useMatch({ path: "/accounts/:accountId/income", end: true });
|
||||||
const account = useMatch({ path: "/accounts/:accountId", end: true });
|
const account = useMatch({ path: "/accounts/:accountId", end: true });
|
||||||
|
const card = useMatch("/cards/:cardId");
|
||||||
|
const cards = useMatch("/cards");
|
||||||
const accounts = useMatch({ path: "/accounts", end: true });
|
const accounts = useMatch({ path: "/accounts", end: true });
|
||||||
const settings = useMatch({ path: "/settings", end: true });
|
const settings = useMatch({ path: "/settings", end: true });
|
||||||
|
|
||||||
@@ -71,6 +74,8 @@ const AppBreadcrumbs: FC = () => {
|
|||||||
<AccountScopeSwitch accountId={account.params.accountId ?? ""} />
|
<AccountScopeSwitch accountId={account.params.accountId ?? ""} />
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
|
if (card) return <CardBreadcrumbs identifier={card.params.cardId ?? ""} />;
|
||||||
|
if (cards) return <BreadcrumbTrail items={[{ label: t("bank.title") }]} />;
|
||||||
if (accounts)
|
if (accounts)
|
||||||
return <BreadcrumbTrail items={[{ label: t("breadcrumbs.accounts") }]} />;
|
return <BreadcrumbTrail items={[{ label: t("breadcrumbs.accounts") }]} />;
|
||||||
if (settings)
|
if (settings)
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import type { FC } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useBankCard } from "@/entities/bank-card";
|
||||||
|
import { BreadcrumbTrail } from "./BreadcrumbTrail";
|
||||||
|
|
||||||
|
type CardBreadcrumbsProps = { identifier: string };
|
||||||
|
const CardBreadcrumbs: FC<CardBreadcrumbsProps> = (props) => {
|
||||||
|
const { data } = useBankCard(props.identifier);
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<BreadcrumbTrail
|
||||||
|
items={[
|
||||||
|
{ label: t("bank.title"), to: "/cards" },
|
||||||
|
{ label: data?.name ?? t("bank.card") },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { CardBreadcrumbs };
|
||||||
@@ -0,0 +1,424 @@
|
|||||||
|
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||||
|
import { HttpResponse, http } from "msw";
|
||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { apiClient, configureAuthClient } from "@/shared/api";
|
||||||
|
import { createQueryWrapper } from "@/test/query";
|
||||||
|
import { server } from "@/test/server";
|
||||||
|
import { useBankMutations } from "./mutations";
|
||||||
|
import {
|
||||||
|
type BankCard,
|
||||||
|
type CreateBankOperation,
|
||||||
|
useBankCard,
|
||||||
|
useBankCards,
|
||||||
|
useBankCategories,
|
||||||
|
useBankExpenses,
|
||||||
|
useBankOperation,
|
||||||
|
useBankOperations,
|
||||||
|
useBankSummary,
|
||||||
|
} from "./queries";
|
||||||
|
|
||||||
|
const card: BankCard = {
|
||||||
|
id: "a",
|
||||||
|
name: "Daily",
|
||||||
|
bankName: null,
|
||||||
|
lastFour: null,
|
||||||
|
paymentSystem: null,
|
||||||
|
openingBalance: { currency: "RUB", value: "100" },
|
||||||
|
openingDate: "2026-09-01",
|
||||||
|
balance: { currency: "RUB", value: "100" },
|
||||||
|
archivedAt: null,
|
||||||
|
version: 1,
|
||||||
|
};
|
||||||
|
const transfer: CreateBankOperation = {
|
||||||
|
id: "4e6caa65-dd52-4629-81e2-ce8a139a0612",
|
||||||
|
kind: "transfer",
|
||||||
|
cardId: "a",
|
||||||
|
targetCardId: "b",
|
||||||
|
amount: { currency: "RUB", value: "90071992547409.93" },
|
||||||
|
date: "2026-09-12",
|
||||||
|
};
|
||||||
|
|
||||||
|
function authenticate() {
|
||||||
|
configureAuthClient({
|
||||||
|
accessToken: () => "token",
|
||||||
|
refresh: async () => true,
|
||||||
|
clear: vi.fn(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function readHandlers(counts: Map<string, number>, categoryName = "Food") {
|
||||||
|
return [
|
||||||
|
http.get("*/api/v1/bank-cards", ({ request }) => {
|
||||||
|
const key = new URL(request.url).pathname + new URL(request.url).search;
|
||||||
|
counts.set(key, (counts.get(key) ?? 0) + 1);
|
||||||
|
return HttpResponse.json([card]);
|
||||||
|
}),
|
||||||
|
http.get("*/api/v1/bank-cards/*", ({ request }) => {
|
||||||
|
const url = new URL(request.url);
|
||||||
|
const key = url.pathname + url.search;
|
||||||
|
counts.set(key, (counts.get(key) ?? 0) + 1);
|
||||||
|
if (url.pathname.endsWith("/categories"))
|
||||||
|
return HttpResponse.json([
|
||||||
|
{ id: "food", name: categoryName, isDefault: true, version: 1 },
|
||||||
|
]);
|
||||||
|
if (url.pathname.endsWith("/summary"))
|
||||||
|
return HttpResponse.json({
|
||||||
|
month: url.searchParams.get("month"),
|
||||||
|
cardId: url.searchParams.get("cardId"),
|
||||||
|
expenses: { currency: "RUB", value: "0" },
|
||||||
|
refunds: { currency: "RUB", value: "0" },
|
||||||
|
net: { currency: "RUB", value: "0" },
|
||||||
|
categories: [],
|
||||||
|
});
|
||||||
|
if (
|
||||||
|
url.pathname.endsWith("/operations") ||
|
||||||
|
url.pathname.endsWith("/expenses")
|
||||||
|
)
|
||||||
|
return HttpResponse.json({
|
||||||
|
items: [],
|
||||||
|
page: 1,
|
||||||
|
total: 0,
|
||||||
|
hasNext: false,
|
||||||
|
});
|
||||||
|
if (url.pathname.includes("/operations/"))
|
||||||
|
return HttpResponse.json({ ...transfer, version: 1 });
|
||||||
|
return HttpResponse.json({ ...card, id: url.pathname.split("/").at(-1) });
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function useReadModels() {
|
||||||
|
const cards = useBankCards(true);
|
||||||
|
const a = useBankCard("a");
|
||||||
|
const b = useBankCard("b");
|
||||||
|
const categories = useBankCategories();
|
||||||
|
const history = useBankOperations("a", {
|
||||||
|
month: "2026-09",
|
||||||
|
page: 2,
|
||||||
|
limit: 20,
|
||||||
|
});
|
||||||
|
const expenses = useBankExpenses("a", { page: 1 });
|
||||||
|
const september = useBankSummary("2026-09");
|
||||||
|
const august = useBankSummary("2026-08", "b");
|
||||||
|
const original = useBankOperation("original");
|
||||||
|
return {
|
||||||
|
reads: [
|
||||||
|
cards,
|
||||||
|
a,
|
||||||
|
b,
|
||||||
|
categories,
|
||||||
|
history,
|
||||||
|
expenses,
|
||||||
|
september,
|
||||||
|
august,
|
||||||
|
original,
|
||||||
|
],
|
||||||
|
mutations: useBankMutations(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("banking API", () => {
|
||||||
|
beforeEach(authenticate);
|
||||||
|
|
||||||
|
it("loads every page for all mode and fails without exposing partial results", async () => {
|
||||||
|
const pages: number[] = [];
|
||||||
|
let fail = false;
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/a/operations", ({ request }) => {
|
||||||
|
const url = new URL(request.url);
|
||||||
|
const page = Number(url.searchParams.get("page"));
|
||||||
|
pages.push(page);
|
||||||
|
expect(url.searchParams.get("limit")).toBe("100");
|
||||||
|
expect(url.searchParams.get("month")).toBe("2026-09");
|
||||||
|
if (fail && page === 2)
|
||||||
|
return HttpResponse.json({ code: "FAILED" }, { status: 500 });
|
||||||
|
return HttpResponse.json({
|
||||||
|
items: [{ ...transfer, id: String(page) }],
|
||||||
|
total: 2,
|
||||||
|
page,
|
||||||
|
hasNext: page === 1,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const { result } = renderHook(
|
||||||
|
() => useBankOperations("a", { month: "2026-09", page: 1, limit: "all" }),
|
||||||
|
{ wrapper: createQueryWrapper().wrapper },
|
||||||
|
);
|
||||||
|
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||||
|
expect(pages).toEqual([1, 2]);
|
||||||
|
expect(result.current.data?.items.map((item) => item.id)).toEqual([
|
||||||
|
"1",
|
||||||
|
"2",
|
||||||
|
]);
|
||||||
|
fail = true;
|
||||||
|
const failed = renderHook(
|
||||||
|
() => useBankOperations("a", { month: "2026-09", page: 1, limit: "all" }),
|
||||||
|
{ wrapper: createQueryWrapper().wrapper },
|
||||||
|
);
|
||||||
|
await waitFor(() => expect(failed.result.current.isError).toBe(true));
|
||||||
|
expect(failed.result.current.data).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses session-aware banking endpoints and explicit month/page without T-Bank", async () => {
|
||||||
|
const counts = new Map<string, number>();
|
||||||
|
server.use(...readHandlers(counts));
|
||||||
|
const { result } = renderHook(useReadModels, {
|
||||||
|
wrapper: createQueryWrapper().wrapper,
|
||||||
|
});
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(result.current.reads.every((read) => read.isSuccess)).toBe(true),
|
||||||
|
);
|
||||||
|
expect([...counts.keys()]).toContain(
|
||||||
|
"/api/v1/bank-cards?includeArchived=true",
|
||||||
|
);
|
||||||
|
expect([...counts.keys()]).toContain(
|
||||||
|
"/api/v1/bank-cards/a/operations?month=2026-09&page=2&limit=20",
|
||||||
|
);
|
||||||
|
expect([...counts.keys()]).toContain(
|
||||||
|
"/api/v1/bank-cards/summary?month=2026-08&cardId=b",
|
||||||
|
);
|
||||||
|
expect(counts.size).toBe(9);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("replays the exact UUID and large Money string once across shared auth refresh", async () => {
|
||||||
|
let token = "expired";
|
||||||
|
const refresh = vi.fn(async () => {
|
||||||
|
token = "renewed";
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
configureAuthClient({ accessToken: () => token, refresh, clear: vi.fn() });
|
||||||
|
const bodies: unknown[] = [];
|
||||||
|
const headers: (string | null)[] = [];
|
||||||
|
server.use(
|
||||||
|
http.post("*/api/v1/bank-cards/operations", async ({ request }) => {
|
||||||
|
bodies.push(await request.json());
|
||||||
|
headers.push(request.headers.get("Authorization"));
|
||||||
|
return bodies.length === 1
|
||||||
|
? HttpResponse.json({ code: "UNAUTHORIZED" }, { status: 401 })
|
||||||
|
: HttpResponse.json({ ...transfer, version: 1 });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const { result } = renderHook(useBankMutations, {
|
||||||
|
wrapper: createQueryWrapper().wrapper,
|
||||||
|
});
|
||||||
|
await act(() => result.current.createOperation.mutateAsync(transfer));
|
||||||
|
expect(bodies).toEqual([transfer, transfer]);
|
||||||
|
expect(headers).toEqual(["Bearer expired", "Bearer renewed"]);
|
||||||
|
expect(refresh).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not automatically retry a network failure and preserves the form-supplied intent on repeat", async () => {
|
||||||
|
const bodies: unknown[] = [];
|
||||||
|
server.use(
|
||||||
|
http.post("*/api/v1/bank-cards/operations", async ({ request }) => {
|
||||||
|
bodies.push(await request.json());
|
||||||
|
return bodies.length === 1
|
||||||
|
? HttpResponse.error()
|
||||||
|
: HttpResponse.json({ ...transfer, version: 1 });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const { result } = renderHook(useBankMutations, {
|
||||||
|
wrapper: createQueryWrapper().wrapper,
|
||||||
|
});
|
||||||
|
await act(async () => {
|
||||||
|
await expect(
|
||||||
|
result.current.createOperation.mutateAsync(transfer),
|
||||||
|
).rejects.toThrow();
|
||||||
|
});
|
||||||
|
expect(bodies).toEqual([transfer]);
|
||||||
|
await act(() => result.current.createOperation.mutateAsync(transfer));
|
||||||
|
expect(bodies).toEqual([transfer, transfer]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the confirmed balance while a mutation is pending or fails, and on refetch failure", async () => {
|
||||||
|
server.use(...readHandlers(new Map()));
|
||||||
|
let finish: () => void = () => {};
|
||||||
|
const pending = new Promise<void>((resolve) => {
|
||||||
|
finish = resolve;
|
||||||
|
});
|
||||||
|
server.use(
|
||||||
|
http.post("*/api/v1/bank-cards/operations", async () => {
|
||||||
|
await pending;
|
||||||
|
return HttpResponse.json({ code: "INTERNAL_ERROR" }, { status: 500 });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const { result } = renderHook(
|
||||||
|
() => ({ query: useBankCard("a"), mutations: useBankMutations() }),
|
||||||
|
{ wrapper: createQueryWrapper().wrapper },
|
||||||
|
);
|
||||||
|
await waitFor(() => expect(result.current.query.isSuccess).toBe(true));
|
||||||
|
let saving: Promise<unknown>;
|
||||||
|
act(() => {
|
||||||
|
saving = result.current.mutations.createOperation
|
||||||
|
.mutateAsync(transfer)
|
||||||
|
.catch(() => undefined);
|
||||||
|
});
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(result.current.mutations.createOperation.isPending).toBe(true),
|
||||||
|
);
|
||||||
|
expect(result.current.query.data?.balance.value).toBe("100");
|
||||||
|
await act(async () => {
|
||||||
|
finish();
|
||||||
|
await saving;
|
||||||
|
});
|
||||||
|
expect(result.current.query.data?.balance.value).toBe("100");
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/a", () =>
|
||||||
|
HttpResponse.json({ code: "INTERNAL_ERROR" }, { status: 500 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await act(() => result.current.query.refetch());
|
||||||
|
expect(result.current.query.isError).toBe(true);
|
||||||
|
expect(result.current.query.data?.balance.value).toBe("100");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("refetches both cards, every month, categories, journal and source expenses after a transfer without invalidating brokerage", async () => {
|
||||||
|
const counts = new Map<string, number>();
|
||||||
|
server.use(
|
||||||
|
...readHandlers(counts),
|
||||||
|
http.post("*/api/v1/bank-cards/operations", () =>
|
||||||
|
HttpResponse.json({ ...transfer, version: 1 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const { wrapper, queryClient } = createQueryWrapper();
|
||||||
|
const brokerKey = ["get", "/api/v1/brokerage-accounts"];
|
||||||
|
queryClient.setQueryData(brokerKey, []);
|
||||||
|
const { result } = renderHook(useReadModels, { wrapper });
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(result.current.reads.every((read) => read.isSuccess)).toBe(true),
|
||||||
|
);
|
||||||
|
await act(() =>
|
||||||
|
result.current.mutations.createOperation.mutateAsync(transfer),
|
||||||
|
);
|
||||||
|
expect([...counts.values()]).toEqual(Array(9).fill(2));
|
||||||
|
expect(queryClient.getQueryState(brokerKey)?.isInvalidated).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
"BANK_VERSION_CONFLICT",
|
||||||
|
"BANK_INTENT_CONFLICT",
|
||||||
|
"BANK_REFUND_LIMIT",
|
||||||
|
])("fetches current state after %s", async (code) => {
|
||||||
|
let reads = 0;
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/a", () =>
|
||||||
|
HttpResponse.json({ ...card, version: ++reads }),
|
||||||
|
),
|
||||||
|
http.patch("*/api/v1/bank-cards/a", () =>
|
||||||
|
HttpResponse.json({ code }, { status: 409 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const { result } = renderHook(
|
||||||
|
() => ({ card: useBankCard("a"), mutations: useBankMutations() }),
|
||||||
|
{ wrapper: createQueryWrapper().wrapper },
|
||||||
|
);
|
||||||
|
await waitFor(() => expect(result.current.card.data?.version).toBe(1));
|
||||||
|
await act(async () => {
|
||||||
|
await expect(
|
||||||
|
result.current.mutations.updateCard.mutateAsync({
|
||||||
|
id: "a",
|
||||||
|
body: { name: "changed", version: 1 },
|
||||||
|
}),
|
||||||
|
).rejects.toEqual({ code });
|
||||||
|
});
|
||||||
|
await waitFor(() => expect(result.current.card.data?.version).toBe(2));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends edit/delete versions and refreshes category names without optimistic updates", async () => {
|
||||||
|
const requests: unknown[] = [];
|
||||||
|
let name = "Food";
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/categories", () =>
|
||||||
|
HttpResponse.json([{ id: "food", name, isDefault: true, version: 1 }]),
|
||||||
|
),
|
||||||
|
http.patch("*/api/v1/bank-cards/categories/food", async ({ request }) => {
|
||||||
|
const body = await request.json();
|
||||||
|
requests.push(body);
|
||||||
|
name = "Groceries";
|
||||||
|
return HttpResponse.json({
|
||||||
|
id: "food",
|
||||||
|
name,
|
||||||
|
isDefault: true,
|
||||||
|
version: 2,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
http.patch(
|
||||||
|
"*/api/v1/bank-cards/operations/original",
|
||||||
|
async ({ request }) => {
|
||||||
|
requests.push(await request.json());
|
||||||
|
return HttpResponse.json({ ...transfer, version: 2 });
|
||||||
|
},
|
||||||
|
),
|
||||||
|
http.delete("*/api/v1/bank-cards/operations/original", ({ request }) => {
|
||||||
|
requests.push(new URL(request.url).searchParams.get("version"));
|
||||||
|
return new HttpResponse(null, { status: 204 });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const { result } = renderHook(
|
||||||
|
() => ({
|
||||||
|
categories: useBankCategories(),
|
||||||
|
mutations: useBankMutations(),
|
||||||
|
}),
|
||||||
|
{ wrapper: createQueryWrapper().wrapper },
|
||||||
|
);
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(result.current.categories.data?.[0].name).toBe("Food"),
|
||||||
|
);
|
||||||
|
await act(() =>
|
||||||
|
result.current.mutations.updateCategory.mutateAsync({
|
||||||
|
id: "food",
|
||||||
|
body: { name: "Groceries", version: 1 },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(result.current.categories.data?.[0].name).toBe("Groceries"),
|
||||||
|
);
|
||||||
|
await act(() =>
|
||||||
|
result.current.mutations.updateOperation.mutateAsync({
|
||||||
|
id: "original",
|
||||||
|
body: { description: "corrected", version: 1 },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await act(() =>
|
||||||
|
result.current.mutations.deleteOperation.mutateAsync({
|
||||||
|
id: "original",
|
||||||
|
version: 2,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(requests).toEqual([
|
||||||
|
{ name: "Groceries", version: 1 },
|
||||||
|
{ description: "corrected", version: 1 },
|
||||||
|
"2",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("disables reads after session removal and retains banking data across a T-Bank API mutation", async () => {
|
||||||
|
const counts = new Map<string, number>();
|
||||||
|
server.use(
|
||||||
|
...readHandlers(counts),
|
||||||
|
http.put("*/api/v1/tbank-connection", () =>
|
||||||
|
HttpResponse.json({
|
||||||
|
connected: true,
|
||||||
|
connectedAt: "2026-09-12T00:00:00Z",
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const { wrapper, queryClient } = createQueryWrapper();
|
||||||
|
const { result, rerender } = renderHook(() => useBankCard("a"), {
|
||||||
|
wrapper,
|
||||||
|
});
|
||||||
|
await waitFor(() => expect(result.current.data?.balance.value).toBe("100"));
|
||||||
|
await apiClient.PUT("/api/v1/tbank-connection", {
|
||||||
|
body: { token: "synthetic" },
|
||||||
|
});
|
||||||
|
expect(result.current.data?.balance.value).toBe("100");
|
||||||
|
act(() => {
|
||||||
|
configureAuthClient(null);
|
||||||
|
queryClient.clear();
|
||||||
|
});
|
||||||
|
rerender();
|
||||||
|
await waitFor(() => expect(result.current.fetchStatus).toBe("idle"));
|
||||||
|
expect(result.current.data).toBeUndefined();
|
||||||
|
expect(counts.get("/api/v1/bank-cards/a")).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { apiClient, apiErrorCode } from "@/shared/api";
|
||||||
|
import type {
|
||||||
|
CreateBankCard,
|
||||||
|
CreateBankOperation,
|
||||||
|
CreateExpenseCategory,
|
||||||
|
UpdateBankCard,
|
||||||
|
UpdateBankOperation,
|
||||||
|
UpdateExpenseCategory,
|
||||||
|
} from "./queries";
|
||||||
|
|
||||||
|
async function mutationData<T>(
|
||||||
|
request: Promise<{ data?: T; error?: unknown }>,
|
||||||
|
) {
|
||||||
|
const { data, error } = await request;
|
||||||
|
if (error) throw error;
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
function useBankMutations() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const invalidate = () =>
|
||||||
|
queryClient.invalidateQueries({
|
||||||
|
predicate: ({ queryKey: [method, path] }) =>
|
||||||
|
method === "get" &&
|
||||||
|
typeof path === "string" &&
|
||||||
|
(path === "/api/v1/bank-cards" ||
|
||||||
|
path.startsWith("/api/v1/bank-cards/")),
|
||||||
|
});
|
||||||
|
const options = {
|
||||||
|
retry: false,
|
||||||
|
onSuccess: invalidate,
|
||||||
|
onError: (error: unknown) => {
|
||||||
|
if (
|
||||||
|
[
|
||||||
|
"BANK_VERSION_CONFLICT",
|
||||||
|
"BANK_WRITE_CONFLICT",
|
||||||
|
"BANK_INTENT_CONFLICT",
|
||||||
|
"BANK_REFUND_LIMIT",
|
||||||
|
"BANK_DEPENDENT_REFUNDS",
|
||||||
|
].includes(apiErrorCode(error) ?? "")
|
||||||
|
)
|
||||||
|
return invalidate();
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
|
const createCard = useMutation({
|
||||||
|
...options,
|
||||||
|
mutationFn: (body: CreateBankCard) =>
|
||||||
|
mutationData(apiClient.POST("/api/v1/bank-cards", { body })),
|
||||||
|
});
|
||||||
|
const updateCard = useMutation({
|
||||||
|
...options,
|
||||||
|
mutationFn: ({ id, body }: { id: string; body: UpdateBankCard }) =>
|
||||||
|
mutationData(
|
||||||
|
apiClient.PATCH("/api/v1/bank-cards/{id}", {
|
||||||
|
params: { path: { id } },
|
||||||
|
body,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
const createOperation = useMutation({
|
||||||
|
...options,
|
||||||
|
mutationFn: (body: CreateBankOperation) =>
|
||||||
|
mutationData(apiClient.POST("/api/v1/bank-cards/operations", { body })),
|
||||||
|
});
|
||||||
|
const updateOperation = useMutation({
|
||||||
|
...options,
|
||||||
|
mutationFn: ({ id, body }: { id: string; body: UpdateBankOperation }) =>
|
||||||
|
mutationData(
|
||||||
|
apiClient.PATCH("/api/v1/bank-cards/operations/{id}", {
|
||||||
|
params: { path: { id } },
|
||||||
|
body,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
const deleteOperation = useMutation({
|
||||||
|
...options,
|
||||||
|
mutationFn: ({ id, version }: { id: string; version: number }) =>
|
||||||
|
mutationData(
|
||||||
|
apiClient.DELETE("/api/v1/bank-cards/operations/{id}", {
|
||||||
|
params: { path: { id }, query: { version } },
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
const createCategory = useMutation({
|
||||||
|
...options,
|
||||||
|
mutationFn: (body: CreateExpenseCategory) =>
|
||||||
|
mutationData(apiClient.POST("/api/v1/bank-cards/categories", { body })),
|
||||||
|
});
|
||||||
|
const updateCategory = useMutation({
|
||||||
|
...options,
|
||||||
|
mutationFn: ({ id, body }: { id: string; body: UpdateExpenseCategory }) =>
|
||||||
|
mutationData(
|
||||||
|
apiClient.PATCH("/api/v1/bank-cards/categories/{id}", {
|
||||||
|
params: { path: { id } },
|
||||||
|
body,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
createCard,
|
||||||
|
updateCard,
|
||||||
|
createOperation,
|
||||||
|
updateOperation,
|
||||||
|
deleteOperation,
|
||||||
|
createCategory,
|
||||||
|
updateCategory,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export { useBankMutations };
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
import {
|
||||||
|
apiClient,
|
||||||
|
apiQueryClient,
|
||||||
|
type paths,
|
||||||
|
useAuthenticatedQuery,
|
||||||
|
} from "@/shared/api";
|
||||||
|
|
||||||
|
import { moneyCents } from "../model/form-validation";
|
||||||
|
|
||||||
|
type BankCard =
|
||||||
|
paths["/api/v1/bank-cards/{id}"]["get"]["responses"][200]["content"]["application/json"];
|
||||||
|
type BankOperation =
|
||||||
|
paths["/api/v1/bank-cards/operations/{id}"]["get"]["responses"][200]["content"]["application/json"];
|
||||||
|
type BankOperations =
|
||||||
|
paths["/api/v1/bank-cards/{id}/operations"]["get"]["responses"][200]["content"]["application/json"];
|
||||||
|
type BankSummary =
|
||||||
|
paths["/api/v1/bank-cards/summary"]["get"]["responses"][200]["content"]["application/json"];
|
||||||
|
type ExpenseCategory =
|
||||||
|
paths["/api/v1/bank-cards/categories"]["get"]["responses"][200]["content"]["application/json"][number];
|
||||||
|
type CreateBankCard =
|
||||||
|
paths["/api/v1/bank-cards"]["post"]["requestBody"]["content"]["application/json"];
|
||||||
|
type UpdateBankCard =
|
||||||
|
paths["/api/v1/bank-cards/{id}"]["patch"]["requestBody"]["content"]["application/json"];
|
||||||
|
type CreateBankOperation =
|
||||||
|
paths["/api/v1/bank-cards/operations"]["post"]["requestBody"]["content"]["application/json"];
|
||||||
|
type UpdateBankOperation =
|
||||||
|
paths["/api/v1/bank-cards/operations/{id}"]["patch"]["requestBody"]["content"]["application/json"];
|
||||||
|
type CreateExpenseCategory =
|
||||||
|
paths["/api/v1/bank-cards/categories"]["post"]["requestBody"]["content"]["application/json"];
|
||||||
|
type UpdateExpenseCategory =
|
||||||
|
paths["/api/v1/bank-cards/categories/{id}"]["patch"]["requestBody"]["content"]["application/json"];
|
||||||
|
|
||||||
|
const OPERATIONS_PAGE_SIZE = 100;
|
||||||
|
|
||||||
|
function useBankCards(includeArchived = false) {
|
||||||
|
return useAuthenticatedQuery(
|
||||||
|
apiQueryClient.queryOptions("get", "/api/v1/bank-cards", {
|
||||||
|
params: {
|
||||||
|
query: { includeArchived: includeArchived ? "true" : "false" },
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function useBankCard(id: string | undefined) {
|
||||||
|
return useAuthenticatedQuery({
|
||||||
|
...apiQueryClient.queryOptions("get", "/api/v1/bank-cards/{id}", {
|
||||||
|
params: { path: { id: id ?? "" } },
|
||||||
|
}),
|
||||||
|
enabled: Boolean(id),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function useBankCategories() {
|
||||||
|
return useAuthenticatedQuery(
|
||||||
|
apiQueryClient.queryOptions("get", "/api/v1/bank-cards/categories"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function useBankOperations(
|
||||||
|
id: string | undefined,
|
||||||
|
query: {
|
||||||
|
month?: string;
|
||||||
|
from?: string;
|
||||||
|
to?: string;
|
||||||
|
page: number;
|
||||||
|
limit?: number | "all";
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const all = query.limit === "all";
|
||||||
|
const params = {
|
||||||
|
path: { id: id ?? "" },
|
||||||
|
query: {
|
||||||
|
...query,
|
||||||
|
page: all ? 1 : query.page,
|
||||||
|
limit: query.limit === "all" ? OPERATIONS_PAGE_SIZE : query.limit,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const options = apiQueryClient.queryOptions(
|
||||||
|
"get",
|
||||||
|
"/api/v1/bank-cards/{id}/operations",
|
||||||
|
{ params },
|
||||||
|
);
|
||||||
|
return useAuthenticatedQuery({
|
||||||
|
queryKey: all ? ([...options.queryKey, "all"] as const) : options.queryKey,
|
||||||
|
placeholderData: (
|
||||||
|
previousData: BankOperations | undefined,
|
||||||
|
previousQuery,
|
||||||
|
) => {
|
||||||
|
const previous = previousQuery?.queryKey[2]?.params;
|
||||||
|
return !all &&
|
||||||
|
previousQuery?.queryKey.length === options.queryKey.length &&
|
||||||
|
previous?.path?.id === id &&
|
||||||
|
previous?.query?.month === query.month &&
|
||||||
|
previous?.query?.from === query.from &&
|
||||||
|
previous?.query?.to === query.to &&
|
||||||
|
previous?.query?.limit === query.limit
|
||||||
|
? previousData
|
||||||
|
: undefined;
|
||||||
|
},
|
||||||
|
queryFn: async ({ signal }) => {
|
||||||
|
const items: BankOperation[] = [];
|
||||||
|
for (let page = params.query.page; ; page++) {
|
||||||
|
const { data, error } = await apiClient.GET(
|
||||||
|
"/api/v1/bank-cards/{id}/operations",
|
||||||
|
{
|
||||||
|
params: { ...params, query: { ...params.query, page } },
|
||||||
|
signal,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (error) throw error;
|
||||||
|
if (!data) throw new Error("Missing bank operations response");
|
||||||
|
if (!all) return data;
|
||||||
|
items.push(...data.items);
|
||||||
|
if (!data.hasNext) return { ...data, items, page: 1, hasNext: false };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
enabled: Boolean(id && (query.month || (query.from && query.to))),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function useBankExpenses(
|
||||||
|
id: string | undefined,
|
||||||
|
query: { page: number; limit?: number },
|
||||||
|
) {
|
||||||
|
return useAuthenticatedQuery({
|
||||||
|
...apiQueryClient.queryOptions("get", "/api/v1/bank-cards/{id}/expenses", {
|
||||||
|
params: { path: { id: id ?? "" }, query },
|
||||||
|
}),
|
||||||
|
enabled: Boolean(id),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function sortBankSummary(data: BankSummary): BankSummary {
|
||||||
|
return {
|
||||||
|
...data,
|
||||||
|
categories: data.categories.toSorted((a, b) => {
|
||||||
|
const left = moneyCents(a.net.value);
|
||||||
|
const right = moneyCents(b.net.value);
|
||||||
|
if (left === null || right === null)
|
||||||
|
throw new Error("Invalid bank summary amount");
|
||||||
|
return left > right ? -1 : left < right ? 1 : 0;
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function useBankSummary(
|
||||||
|
period: string | { from: string; to: string },
|
||||||
|
cardId?: string,
|
||||||
|
) {
|
||||||
|
const query =
|
||||||
|
typeof period === "string"
|
||||||
|
? { month: period, cardId }
|
||||||
|
: { ...period, cardId };
|
||||||
|
return useAuthenticatedQuery({
|
||||||
|
...apiQueryClient.queryOptions("get", "/api/v1/bank-cards/summary", {
|
||||||
|
params: { query },
|
||||||
|
}),
|
||||||
|
select: sortBankSummary,
|
||||||
|
enabled: Boolean(period),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function useBankOperation(id: string | undefined) {
|
||||||
|
return useAuthenticatedQuery({
|
||||||
|
...apiQueryClient.queryOptions(
|
||||||
|
"get",
|
||||||
|
"/api/v1/bank-cards/operations/{id}",
|
||||||
|
{ params: { path: { id: id ?? "" } } },
|
||||||
|
),
|
||||||
|
enabled: Boolean(id),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
type BankCard,
|
||||||
|
type BankOperation,
|
||||||
|
type BankSummary,
|
||||||
|
type CreateBankCard,
|
||||||
|
type CreateBankOperation,
|
||||||
|
type CreateExpenseCategory,
|
||||||
|
type ExpenseCategory,
|
||||||
|
sortBankSummary,
|
||||||
|
type UpdateBankCard,
|
||||||
|
type UpdateBankOperation,
|
||||||
|
type UpdateExpenseCategory,
|
||||||
|
useBankCard,
|
||||||
|
useBankCards,
|
||||||
|
useBankCategories,
|
||||||
|
useBankExpenses,
|
||||||
|
useBankOperation,
|
||||||
|
useBankOperations,
|
||||||
|
useBankSummary,
|
||||||
|
};
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { expect, it } from "vitest";
|
||||||
|
import { type BankSummary, sortBankSummary } from "./queries";
|
||||||
|
|
||||||
|
it("orders displayed expenses descending, preserving cents, ties and source data", () => {
|
||||||
|
const values = [
|
||||||
|
"-10",
|
||||||
|
"9007199254740992.01",
|
||||||
|
"0",
|
||||||
|
"9007199254740992.02",
|
||||||
|
"-2",
|
||||||
|
"0",
|
||||||
|
];
|
||||||
|
const money = (value: string) => ({ currency: "RUB", value });
|
||||||
|
const data: BankSummary = {
|
||||||
|
month: "2026-09",
|
||||||
|
cardId: "a",
|
||||||
|
expenses: money("0"),
|
||||||
|
refunds: money("0"),
|
||||||
|
net: money("0"),
|
||||||
|
categories: values.map((value, index) => ({
|
||||||
|
categoryId: String(index),
|
||||||
|
categoryName: String(index),
|
||||||
|
expenses: money("100"),
|
||||||
|
refunds: money("0"),
|
||||||
|
net: money(value),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
expect(sortBankSummary(data).categories.map((row) => row.categoryId)).toEqual(
|
||||||
|
["3", "1", "2", "5", "4", "0"],
|
||||||
|
);
|
||||||
|
expect(data.categories.map((row) => row.net.value)).toEqual(values);
|
||||||
|
});
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
export { useBankMutations } from "./api/mutations";
|
||||||
|
export {
|
||||||
|
type BankCard,
|
||||||
|
type BankOperation,
|
||||||
|
useBankCard,
|
||||||
|
useBankCards,
|
||||||
|
useBankCategories,
|
||||||
|
useBankExpenses,
|
||||||
|
useBankOperation,
|
||||||
|
useBankOperations,
|
||||||
|
useBankSummary,
|
||||||
|
} from "./api/queries";
|
||||||
|
export {
|
||||||
|
bankDateInputValue,
|
||||||
|
bankDateSchema,
|
||||||
|
bankMoneyValue,
|
||||||
|
bankToday,
|
||||||
|
moneyCents,
|
||||||
|
positiveMoneySchema,
|
||||||
|
} from "./model/form-validation";
|
||||||
|
export { bankPeriod } from "./model/period";
|
||||||
|
export { BankCardFace } from "./ui/BankCardFace";
|
||||||
|
export { BankCardForm } from "./ui/BankCardForm";
|
||||||
|
export { BankFeedback } from "./ui/BankFeedback";
|
||||||
|
export { BankOperationIcon } from "./ui/BankOperationIcon";
|
||||||
|
export { BankPeriodPicker } from "./ui/BankPeriodPicker";
|
||||||
|
export { BankSummaryView } from "./ui/BankSummary.view";
|
||||||
|
export { CategoryManager } from "./ui/CategoryManager";
|
||||||
|
export { useBankFormFocus } from "./ui/useBankFormFocus";
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import {
|
||||||
|
bankCardSchema,
|
||||||
|
bankDateInputValue,
|
||||||
|
bankDateSchema,
|
||||||
|
bankMoneyValue,
|
||||||
|
bankMonth,
|
||||||
|
bankToday,
|
||||||
|
positiveMoneySchema,
|
||||||
|
} from "./form-validation";
|
||||||
|
|
||||||
|
afterEach(() => vi.useRealTimers());
|
||||||
|
describe("bank form input", () => {
|
||||||
|
it("keeps input bounds exact without rounding and canonicalizes leading zeros", () => {
|
||||||
|
expect(positiveMoneySchema.safeParse("92233720368547758.07").success).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
for (const invalid of [
|
||||||
|
"92233720368547758.08",
|
||||||
|
"1.001",
|
||||||
|
"0",
|
||||||
|
"-1",
|
||||||
|
"abc",
|
||||||
|
"1e3",
|
||||||
|
]) {
|
||||||
|
expect(positiveMoneySchema.safeParse(invalid).success).toBe(false);
|
||||||
|
}
|
||||||
|
expect(bankMoneyValue(" -00010,20 ")).toBe("-10.20");
|
||||||
|
const values = {
|
||||||
|
name: "A",
|
||||||
|
bankName: "",
|
||||||
|
lastFour: "",
|
||||||
|
openingBalance: "-92233720368547758.08",
|
||||||
|
openingDate: "2026-01-01",
|
||||||
|
};
|
||||||
|
expect(bankCardSchema.safeParse(values).success).toBe(true);
|
||||||
|
expect(
|
||||||
|
bankCardSchema.safeParse({
|
||||||
|
...values,
|
||||||
|
openingBalance: "-92233720368547758.09",
|
||||||
|
}).success,
|
||||||
|
).toBe(false);
|
||||||
|
expect(
|
||||||
|
bankCardSchema.safeParse({ ...values, lastFour: "123" }).success,
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
it("uses Moscow date and refuses nonexistent or future calendar days", () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
vi.setSystemTime(new Date("2026-08-31T21:30:00Z"));
|
||||||
|
expect(bankToday()).toBe("2026-09-01");
|
||||||
|
expect(bankMonth(null)).toBe("2026-09");
|
||||||
|
expect(bankMonth("2026-13")).toBe("2026-09");
|
||||||
|
expect(bankDateSchema.safeParse("2026-09-01").success).toBe(true);
|
||||||
|
expect(bankDateSchema.safeParse("2026-09-02").success).toBe(false);
|
||||||
|
expect(bankDateSchema.safeParse("2026-02-30").success).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("converts local date input without accepting impossible or unfinished dates", () => {
|
||||||
|
expect(bankDateInputValue("07.08.2026")).toBe("2026-08-07");
|
||||||
|
expect(
|
||||||
|
bankDateSchema.safeParse(bankDateInputValue("29.02.2024")).success,
|
||||||
|
).toBe(true);
|
||||||
|
for (const value of ["31.02.2026", "07.08.", ""]) {
|
||||||
|
expect(bankDateSchema.safeParse(bankDateInputValue(value)).success).toBe(
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
import { validationMessage } from "@/shared/i18n";
|
||||||
|
|
||||||
|
const ISO_MONTH_LENGTH = 7;
|
||||||
|
const MAX_CARD_NAME_LENGTH = 100;
|
||||||
|
|
||||||
|
function bankToday() {
|
||||||
|
return new Intl.DateTimeFormat("en-CA", {
|
||||||
|
timeZone: "Europe/Moscow",
|
||||||
|
year: "numeric",
|
||||||
|
month: "2-digit",
|
||||||
|
day: "2-digit",
|
||||||
|
}).format(new Date());
|
||||||
|
}
|
||||||
|
function bankDateInputValue(value: string) {
|
||||||
|
return value.replace(/^(\d{2})\.(\d{2})\.(\d{4})$/, "$3-$2-$1");
|
||||||
|
}
|
||||||
|
function bankMonth(value: string | null) {
|
||||||
|
return value && /^\d{4}-(0[1-9]|1[0-2])$/.test(value)
|
||||||
|
? value
|
||||||
|
: bankToday().slice(0, ISO_MONTH_LENGTH);
|
||||||
|
}
|
||||||
|
function bankMoneyValue(value: string) {
|
||||||
|
return value
|
||||||
|
.trim()
|
||||||
|
.replace(",", ".")
|
||||||
|
.replace(/^(-?)0+(?=\d)/, "$1");
|
||||||
|
}
|
||||||
|
function moneyCents(value: string): bigint | null {
|
||||||
|
const normalized = value.trim().replace(",", ".");
|
||||||
|
if (!/^-?\d+(\.\d{1,2})?$/.test(normalized)) return null;
|
||||||
|
const [whole, fraction = ""] = normalized.replace("-", "").split(".");
|
||||||
|
return (
|
||||||
|
BigInt(`${whole}${fraction.padEnd(2, "0")}`) *
|
||||||
|
(normalized.startsWith("-") ? -1n : 1n)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const MIN_BALANCE_KOPECKS = -9_223_372_036_854_775_808n;
|
||||||
|
const MAX_BALANCE_KOPECKS = 9_223_372_036_854_775_807n;
|
||||||
|
|
||||||
|
const moneySchema = z.string().refine(
|
||||||
|
(value) => {
|
||||||
|
const cents = moneyCents(value);
|
||||||
|
return (
|
||||||
|
cents !== null &&
|
||||||
|
cents >= MIN_BALANCE_KOPECKS &&
|
||||||
|
cents <= MAX_BALANCE_KOPECKS
|
||||||
|
);
|
||||||
|
},
|
||||||
|
{ error: validationMessage("bank.validation.money") },
|
||||||
|
);
|
||||||
|
const positiveMoneySchema = moneySchema.refine(
|
||||||
|
(value) => {
|
||||||
|
const cents = moneyCents(value);
|
||||||
|
return cents === null || cents > 0n;
|
||||||
|
},
|
||||||
|
{ error: validationMessage("bank.validation.positive") },
|
||||||
|
);
|
||||||
|
const bankDateSchema = z
|
||||||
|
.string()
|
||||||
|
.refine(
|
||||||
|
(value) =>
|
||||||
|
/^\d{4}-\d{2}-\d{2}$/.test(value) &&
|
||||||
|
value >= "0001-01-01" &&
|
||||||
|
!Number.isNaN(Date.parse(`${value}T00:00:00Z`)) &&
|
||||||
|
new Date(`${value}T00:00:00Z`).toISOString().slice(0, 10) === value &&
|
||||||
|
value <= bankToday(),
|
||||||
|
{ error: validationMessage("bank.validation.date") },
|
||||||
|
);
|
||||||
|
const bankCardSchema = z.object({
|
||||||
|
name: z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.min(1, validationMessage("bank.validation.name")(undefined))
|
||||||
|
.max(
|
||||||
|
MAX_CARD_NAME_LENGTH,
|
||||||
|
validationMessage("bank.validation.name")(undefined),
|
||||||
|
),
|
||||||
|
bankName: z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.max(
|
||||||
|
MAX_CARD_NAME_LENGTH,
|
||||||
|
validationMessage("bank.validation.bankName")(undefined),
|
||||||
|
),
|
||||||
|
lastFour: z.string().refine((value) => !value || /^\d{4}$/.test(value), {
|
||||||
|
error: validationMessage("bank.validation.lastFour"),
|
||||||
|
}),
|
||||||
|
paymentSystem: z
|
||||||
|
.enum(["", "mir", "visa", "mastercard"], {
|
||||||
|
error: validationMessage("bank.validation.paymentSystem"),
|
||||||
|
})
|
||||||
|
.optional(),
|
||||||
|
openingBalance: moneySchema,
|
||||||
|
openingDate: bankDateSchema,
|
||||||
|
});
|
||||||
|
type BankCardValues = z.infer<typeof bankCardSchema>;
|
||||||
|
|
||||||
|
export {
|
||||||
|
type BankCardValues,
|
||||||
|
bankCardSchema,
|
||||||
|
bankDateInputValue,
|
||||||
|
bankDateSchema,
|
||||||
|
bankMoneyValue,
|
||||||
|
bankMonth,
|
||||||
|
bankToday,
|
||||||
|
moneyCents,
|
||||||
|
positiveMoneySchema,
|
||||||
|
};
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import type { BankOperation } from "../api/queries";
|
||||||
|
|
||||||
|
type OperationIcon = { path: string; color: string; animation?: string };
|
||||||
|
|
||||||
|
const categoryIcons: Record<string, OperationIcon> = {
|
||||||
|
алкоголь: {
|
||||||
|
animation: "wine",
|
||||||
|
path: "M7 3h10v5a5 5 0 0 1-10 0V3Z M7 7h10v1a5 5 0 0 1-10 0V7Z M12 13v8 M8 21h8",
|
||||||
|
color: "grape",
|
||||||
|
},
|
||||||
|
вклады: {
|
||||||
|
animation: "deposit",
|
||||||
|
path: "M6 9a6 6 0 1 0 12 0a6 6 0 1 0-12 0 M10.5 12V6h2a1.5 1.5 0 0 1 0 3h-3m0 1.5h3 M4 16c0 4 16 4 16 0 M4 19c0 4 16 4 16 0",
|
||||||
|
color: "green",
|
||||||
|
},
|
||||||
|
"инвестиции и накопления": {
|
||||||
|
animation: "growth",
|
||||||
|
path: "M3 3v18h18 M6 15l5-5 4 3 6-8 M16 5h5v5",
|
||||||
|
color: "green",
|
||||||
|
},
|
||||||
|
образование: {
|
||||||
|
path: "M2 8l10-5 10 5-10 5L2 8Z M6 10v7c4 3 8 3 12 0v-7 M22 8v9",
|
||||||
|
color: "blue",
|
||||||
|
},
|
||||||
|
переводы: {
|
||||||
|
animation: "transfer",
|
||||||
|
path: "M3 7h18l-4-4 M21 17H3l4 4",
|
||||||
|
color: "blue",
|
||||||
|
},
|
||||||
|
"погашение кредита": {
|
||||||
|
animation: "repayment",
|
||||||
|
path: "M3 5h18v14H3V5Z M3 9h18 M10 18v-7h3a2 2 0 0 1 0 4H9m0 1.5h4",
|
||||||
|
color: "orange",
|
||||||
|
},
|
||||||
|
подписки: {
|
||||||
|
path: "M4 10a8 8 0 0 1 13-6l3 3 M20 3v4h-4 M20 14a8 8 0 0 1-13 6l-3-3 M4 21v-4h4",
|
||||||
|
color: "grape",
|
||||||
|
},
|
||||||
|
путешествия: {
|
||||||
|
path: "M10 3h4v7l7 5v3l-7-3v5l2 1v1l-4-1-4 1v-1l2-1v-5l-7 3v-3l7-5V3Z",
|
||||||
|
color: "blue",
|
||||||
|
},
|
||||||
|
"связь и интернет": {
|
||||||
|
animation: "wifi",
|
||||||
|
path: "M3 7a14 14 0 0 1 18 0 M6 11a9 9 0 0 1 12 0 M9 15a4 4 0 0 1 6 0 M12 19h.01",
|
||||||
|
color: "blue",
|
||||||
|
},
|
||||||
|
"снятие наличных": {
|
||||||
|
path: "M4 10V3h16v7 M7 7h10v14H7V7Z M7 11h10 M10 16h4",
|
||||||
|
color: "green",
|
||||||
|
},
|
||||||
|
ставки: {
|
||||||
|
path: "M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2Z M7 7h.01 M17 7h.01 M12 12h.01 M7 17h.01 M17 17h.01",
|
||||||
|
color: "grape",
|
||||||
|
},
|
||||||
|
страхование: {
|
||||||
|
path: "M12 2l8 4v6c0 5-8 10-8 10S4 17 4 12V6l8-4Z M8 12l3 3 5-6",
|
||||||
|
color: "green",
|
||||||
|
},
|
||||||
|
табак: {
|
||||||
|
path: "M3 14h18v5H3v-5Z M16 14v5 M8 10V8c0-2 3-2 3-4V2 M15 10V8c0-2 3-2 3-4",
|
||||||
|
color: "orange",
|
||||||
|
},
|
||||||
|
"хостинг и ии-сервисы": {
|
||||||
|
animation: "server",
|
||||||
|
path: "M3 3h18v7H3V3Z M3 14h18v7H3v-7Z M7 6.5h.01 M7 17.5h.01 M15 6.5h3 M15 17.5h3",
|
||||||
|
color: "grape",
|
||||||
|
},
|
||||||
|
"цифровые покупки": {
|
||||||
|
path: "M3 3h18v13H3V3Z M8 21h8 M12 16v5 M12 6v7 M9 10l3 3 3-3",
|
||||||
|
color: "blue",
|
||||||
|
},
|
||||||
|
продукты: {
|
||||||
|
animation: "basket",
|
||||||
|
path: "M3 9h18l-2 11H5L3 9Z M8 9l4-6 4 6 M9 13v3 M15 13v3 M10 6a2 2 0 1 0 4 0a2 2 0 1 0-4 0",
|
||||||
|
color: "green",
|
||||||
|
},
|
||||||
|
кафе: {
|
||||||
|
animation: "coffee",
|
||||||
|
path: "M4 8h12v7a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4V8Z M16 9h2a3 3 0 0 1 0 6h-2 M8 6c-2-1 2-2 0-4 M12 6c-2-1 2-2 0-4 M3 22h15",
|
||||||
|
color: "orange",
|
||||||
|
},
|
||||||
|
такси: {
|
||||||
|
path: "M4 10l2-6h12l2 6 M3 10h18v8H3v-8Z M6 18v3 M18 18v3 M6 14h2 M16 14h2 M10 4V2h4v2",
|
||||||
|
color: "yellow",
|
||||||
|
},
|
||||||
|
транспорт: {
|
||||||
|
animation: "car",
|
||||||
|
path: "M4 16H2v-4l3-1 3-4h6l4 4 4 1v4h-2 M8 16h8 M6 11h12m-6-4v4 M4 16a2 2 0 1 0 4 0a2 2 0 1 0-4 0m2-2v4m-2-2h4 M16 16a2 2 0 1 0 4 0a2 2 0 1 0-4 0m2-2v4m-2-2h4",
|
||||||
|
color: "blue",
|
||||||
|
},
|
||||||
|
жилье: { path: "M3 11l9-8 9 8 M5 10v11h14V10 M9 21v-8h6v8", color: "orange" },
|
||||||
|
здоровье: { path: "M9 3h6v6h6v6h-6v6H9v-6H3V9h6V3Z", color: "red" },
|
||||||
|
покупки: {
|
||||||
|
path: "M5 7h14l2 14H3L5 7Z M8 8V6a4 4 0 0 1 8 0v2",
|
||||||
|
color: "grape",
|
||||||
|
},
|
||||||
|
развлечения: {
|
||||||
|
path: "M9 5v14a3 3 0 1 1-3-3h3 M9 5l11-2v14a3 3 0 1 1-3-3h3 M9 9l11-2",
|
||||||
|
color: "grape",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const otherIcon: OperationIcon = {
|
||||||
|
animation: "grid",
|
||||||
|
path: "M4 4h6v6H4V4Z M14 4h6v6h-6V4Z M4 14h6v6H4v-6Z M14 14h6v6h-6v-6Z",
|
||||||
|
color: "gray",
|
||||||
|
};
|
||||||
|
const operationIcons: Record<
|
||||||
|
Exclude<BankOperation["kind"], "expense">,
|
||||||
|
OperationIcon
|
||||||
|
> = {
|
||||||
|
topup: {
|
||||||
|
animation: "topup",
|
||||||
|
path: "M20 8V5H5a2 2 0 0 1 0-4h13v4 M3 3v16a2 2 0 0 0 2 2h15V8H5 M16 12v5m-2.5-2.5h5",
|
||||||
|
color: "green",
|
||||||
|
},
|
||||||
|
transfer: {
|
||||||
|
animation: "transfer",
|
||||||
|
path: "M3 7h18l-4-4 M21 17H3l4 4",
|
||||||
|
color: "blue",
|
||||||
|
},
|
||||||
|
refund: { path: "M8 4L3 9l5 5 M3 9h11a7 7 0 0 1 0 14", color: "teal" },
|
||||||
|
};
|
||||||
|
|
||||||
|
function bankOperationAppearance(
|
||||||
|
kind: BankOperation["kind"],
|
||||||
|
categoryName?: string | null,
|
||||||
|
) {
|
||||||
|
const name = categoryName
|
||||||
|
?.trim()
|
||||||
|
.toLocaleLowerCase("ru-RU")
|
||||||
|
.replaceAll("ё", "е");
|
||||||
|
return kind === "expense"
|
||||||
|
? name && Object.hasOwn(categoryIcons, name)
|
||||||
|
? categoryIcons[name]
|
||||||
|
: otherIcon
|
||||||
|
: operationIcons[kind];
|
||||||
|
}
|
||||||
|
|
||||||
|
export { bankOperationAppearance };
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import dayjs from "dayjs";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { bankMonth } from "./form-validation";
|
||||||
|
|
||||||
|
const calendarDate = z.string().date();
|
||||||
|
function bankPeriod(params: URLSearchParams) {
|
||||||
|
const month = bankMonth(params.get("month"));
|
||||||
|
const from = params.get("from");
|
||||||
|
const to = params.get("to");
|
||||||
|
return from &&
|
||||||
|
to &&
|
||||||
|
calendarDate.safeParse(from).success &&
|
||||||
|
calendarDate.safeParse(to).success &&
|
||||||
|
from >= "0001-01-01" &&
|
||||||
|
from <= to
|
||||||
|
? { from, to }
|
||||||
|
: {
|
||||||
|
from: `${month}-01`,
|
||||||
|
to: dayjs(`${month}-01`).endOf("month").format("YYYY-MM-DD"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export { bankPeriod };
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
.face {
|
||||||
|
--card-base: #242b35;
|
||||||
|
--card-light: #485666;
|
||||||
|
position: relative;
|
||||||
|
isolation: isolate;
|
||||||
|
overflow: hidden;
|
||||||
|
box-sizing: border-box;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 28rem;
|
||||||
|
min-height: 15rem;
|
||||||
|
padding: clamp(1.1rem, 3vw, 1.6rem);
|
||||||
|
border-radius: 1.25rem;
|
||||||
|
color: #fff;
|
||||||
|
background: linear-gradient(125deg, var(--card-light), var(--card-base) 75%);
|
||||||
|
box-shadow:
|
||||||
|
inset 0 1px 0 #ffffff40,
|
||||||
|
0 8px 18px #18233118;
|
||||||
|
}
|
||||||
|
.face::before {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
z-index: -1;
|
||||||
|
width: 24rem;
|
||||||
|
height: 24rem;
|
||||||
|
border: 1px solid #ffffff20;
|
||||||
|
border-radius: 50%;
|
||||||
|
right: -13rem;
|
||||||
|
top: -9rem;
|
||||||
|
box-shadow:
|
||||||
|
0 0 0 2.5rem #ffffff08,
|
||||||
|
0 0 0 5rem #ffffff06;
|
||||||
|
}
|
||||||
|
.face[data-tone="green"] {
|
||||||
|
--card-base: #07543c;
|
||||||
|
--card-light: #21844a;
|
||||||
|
}
|
||||||
|
.face[data-tone="yellow"] {
|
||||||
|
--card-base: #edbe26;
|
||||||
|
--card-light: #ffe478;
|
||||||
|
color: #252316;
|
||||||
|
}
|
||||||
|
.face[data-tone="red"] {
|
||||||
|
--card-base: #980f28;
|
||||||
|
--card-light: #d63244;
|
||||||
|
}
|
||||||
|
.face[data-tone="blue"] {
|
||||||
|
--card-base: #073f86;
|
||||||
|
--card-light: #226db8;
|
||||||
|
}
|
||||||
|
.top,
|
||||||
|
.bottom {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
.bank {
|
||||||
|
font-size: 1.05rem;
|
||||||
|
font-weight: 750;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.archive {
|
||||||
|
font-size: 0.7rem;
|
||||||
|
border: 1px solid currentColor;
|
||||||
|
border-radius: 2rem;
|
||||||
|
padding: 0.2rem 0.5rem;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.hardware {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.7rem;
|
||||||
|
margin: 1.4rem 0 1.1rem;
|
||||||
|
}
|
||||||
|
.chip {
|
||||||
|
display: block;
|
||||||
|
width: 2.5rem;
|
||||||
|
height: 1.9rem;
|
||||||
|
border: 1px solid #a99054;
|
||||||
|
border-radius: 0.4rem;
|
||||||
|
background:
|
||||||
|
linear-gradient(
|
||||||
|
90deg,
|
||||||
|
transparent 30%,
|
||||||
|
#9b875a 31%,
|
||||||
|
transparent 33%,
|
||||||
|
transparent 66%,
|
||||||
|
#9b875a 67%,
|
||||||
|
transparent 69%
|
||||||
|
),
|
||||||
|
linear-gradient(
|
||||||
|
0deg,
|
||||||
|
transparent 32%,
|
||||||
|
#9b875a 33%,
|
||||||
|
transparent 36%,
|
||||||
|
transparent 65%,
|
||||||
|
#9b875a 66%,
|
||||||
|
transparent 69%
|
||||||
|
),
|
||||||
|
linear-gradient(135deg, #e5d6a6, #bfaa75 50%, #f1e6c4);
|
||||||
|
}
|
||||||
|
.number {
|
||||||
|
font-family: var(--mantine-font-family-monospace);
|
||||||
|
font-size: clamp(1rem, 2.3vw, 1.35rem);
|
||||||
|
letter-spacing: 0.06em;
|
||||||
|
white-space: nowrap;
|
||||||
|
margin-bottom: 1.25rem;
|
||||||
|
}
|
||||||
|
.details {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.name {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
opacity: 0.9;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.balance {
|
||||||
|
font-size: clamp(1.2rem, 2.5vw, 1.55rem);
|
||||||
|
font-weight: 650;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
margin-top: 0.2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.network {
|
||||||
|
flex-shrink: 0;
|
||||||
|
font-weight: 850;
|
||||||
|
font-style: italic;
|
||||||
|
font-size: 1.35rem;
|
||||||
|
}
|
||||||
|
.network[data-network="mastercard"] {
|
||||||
|
font-size: 0.65rem;
|
||||||
|
font-weight: 600;
|
||||||
|
font-style: normal;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.circles {
|
||||||
|
display: block;
|
||||||
|
width: 3.3rem;
|
||||||
|
height: 2rem;
|
||||||
|
margin: 0 auto 0.15rem;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
.circles::before,
|
||||||
|
.circles::after {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
width: 2rem;
|
||||||
|
height: 2rem;
|
||||||
|
border-radius: 50%;
|
||||||
|
}
|
||||||
|
.circles::before {
|
||||||
|
left: 0;
|
||||||
|
background: #eb302b;
|
||||||
|
}
|
||||||
|
.circles::after {
|
||||||
|
right: 0;
|
||||||
|
background: #ffad19;
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { SimpleGrid } from "@mantine/core";
|
||||||
|
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||||
|
import { BankCardFace } from "./BankCardFace";
|
||||||
|
|
||||||
|
const meta = {
|
||||||
|
title: "Product/BankCards/CardAppearance",
|
||||||
|
component: BankCardFace,
|
||||||
|
tags: ["autodocs"],
|
||||||
|
args: {
|
||||||
|
card: {
|
||||||
|
id: "fictional",
|
||||||
|
name: "Для повседневных покупок",
|
||||||
|
bankName: "Сбербанк",
|
||||||
|
lastFour: "4829",
|
||||||
|
paymentSystem: "mir",
|
||||||
|
openingBalance: { value: "0", currency: "RUB" },
|
||||||
|
openingDate: "2026-01-01",
|
||||||
|
balance: { value: "128450.75", currency: "RUB" },
|
||||||
|
archivedAt: null,
|
||||||
|
version: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} satisfies Meta<typeof BankCardFace>;
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof meta>;
|
||||||
|
export const Banks: Story = {
|
||||||
|
render: (args) => (
|
||||||
|
<SimpleGrid cols={{ base: 1, sm: 2 }} maw={920}>
|
||||||
|
{["Сбербанк", "Т-Банк", "Альфа-Банк", "ВТБ", null].map(
|
||||||
|
(bankName, index) => (
|
||||||
|
<BankCardFace
|
||||||
|
key={bankName ?? "unknown"}
|
||||||
|
card={{
|
||||||
|
...args.card,
|
||||||
|
bankName,
|
||||||
|
paymentSystem:
|
||||||
|
(["mir", "mastercard", "visa", "mir", null] as const)[index] ??
|
||||||
|
null,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
</SimpleGrid>
|
||||||
|
),
|
||||||
|
};
|
||||||
|
export const MissingDetails: Story = {
|
||||||
|
args: {
|
||||||
|
card: {
|
||||||
|
...meta.args.card,
|
||||||
|
bankName: null,
|
||||||
|
lastFour: null,
|
||||||
|
paymentSystem: null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
export const LongArchived: Story = {
|
||||||
|
args: {
|
||||||
|
card: {
|
||||||
|
...meta.args.card,
|
||||||
|
name: "Карта с очень длинным пользовательским названием для повседневных покупок",
|
||||||
|
bankName: "Банк с очень длинным названием без пробелов".repeat(2),
|
||||||
|
archivedAt: "2026-09-12",
|
||||||
|
paymentSystem: "mastercard",
|
||||||
|
balance: { value: "184467440737095516.14", currency: "RUB" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import type { FC } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { formatMoney } from "@/shared/lib";
|
||||||
|
import type { BankCard } from "../api/queries";
|
||||||
|
import classes from "./BankCardFace.module.css";
|
||||||
|
|
||||||
|
type BankCardFaceProps = { card: BankCard };
|
||||||
|
const BankCardFace: FC<BankCardFaceProps> = (props) => {
|
||||||
|
const { card } = props;
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const bank = card.bankName?.toLocaleLowerCase("ru") ?? "";
|
||||||
|
const tone = /сбер|sber/.test(bank)
|
||||||
|
? "green"
|
||||||
|
: /тинькофф|т[ -]?банк|t[ -]?bank|tinkoff/.test(bank)
|
||||||
|
? "yellow"
|
||||||
|
: /альфа|alfa/.test(bank)
|
||||||
|
? "red"
|
||||||
|
: /втб|vtb|газпром|gazprom/.test(bank)
|
||||||
|
? "blue"
|
||||||
|
: "graphite";
|
||||||
|
return (
|
||||||
|
<div className={classes.face} data-tone={tone}>
|
||||||
|
<div className={classes.top}>
|
||||||
|
<span className={classes.bank}>{card.bankName || t("bank.card")}</span>
|
||||||
|
{card.archivedAt && (
|
||||||
|
<span className={classes.archive}>{t("bank.archived")}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className={classes.hardware} aria-hidden="true">
|
||||||
|
<span className={classes.chip} />
|
||||||
|
<svg
|
||||||
|
aria-hidden="true"
|
||||||
|
width="24"
|
||||||
|
height="30"
|
||||||
|
viewBox="0 0 24 30"
|
||||||
|
fill="none"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
d="M7 11a8 8 0 0 1 0 8m5-12a15 15 0 0 1 0 16m5-20a23 23 0 0 1 0 24"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
strokeLinecap="round"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className={classes.number}
|
||||||
|
>{`•••• •••• •••• ${card.lastFour || "••••"}`}</div>
|
||||||
|
<div className={classes.bottom}>
|
||||||
|
<div className={classes.details}>
|
||||||
|
<div className={classes.name}>{card.name}</div>
|
||||||
|
<div className={classes.balance}>{formatMoney(card.balance)}</div>
|
||||||
|
</div>
|
||||||
|
{card.paymentSystem && (
|
||||||
|
<span className={classes.network} data-network={card.paymentSystem}>
|
||||||
|
{card.paymentSystem === "mastercard" && (
|
||||||
|
<span className={classes.circles} aria-hidden="true" />
|
||||||
|
)}
|
||||||
|
{t(`bank.paymentSystems.${card.paymentSystem}`)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { BankCardFace };
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||||
|
import { FormProvider, useForm } from "react-hook-form";
|
||||||
|
import type { BankCardValues } from "../model/form-validation";
|
||||||
|
import { BankCardFields } from "./BankCardForm.view";
|
||||||
|
|
||||||
|
const meta = {
|
||||||
|
title: "Product/BankCards/CardFields",
|
||||||
|
component: BankCardFields,
|
||||||
|
tags: ["autodocs"],
|
||||||
|
args: { archived: false },
|
||||||
|
decorators: [
|
||||||
|
(Story) => {
|
||||||
|
const methods = useForm<BankCardValues>({
|
||||||
|
defaultValues: {
|
||||||
|
name: "Учебная повседневная карта",
|
||||||
|
bankName: "Вымышленный банк",
|
||||||
|
lastFour: "1234",
|
||||||
|
openingBalance: "-92233720368547758.08",
|
||||||
|
openingDate: "2026-08-01",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return (
|
||||||
|
<FormProvider {...methods}>
|
||||||
|
<Story />
|
||||||
|
</FormProvider>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
],
|
||||||
|
parameters: {
|
||||||
|
docs: {
|
||||||
|
description: {
|
||||||
|
component:
|
||||||
|
"Поля ручной дебетовой карты на вымышленных данных. Сохранения и обращения к API нет. Архив оставляет описательные сведения доступными, а финансовые поля — только для чтения.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} satisfies Meta<typeof BankCardFields>;
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof meta>;
|
||||||
|
export const Active: Story = { name: "Независимая карта в рублях" };
|
||||||
|
export const Archived: Story = {
|
||||||
|
name: "Финансовые поля архивной карты",
|
||||||
|
args: { archived: true },
|
||||||
|
};
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
import { MantineProvider } from "@mantine/core";
|
||||||
|
import { QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||||
|
import { HttpResponse, http } from "msw";
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { configureAuthClient } from "@/shared/api";
|
||||||
|
import { createTestQueryClient } from "@/test/query";
|
||||||
|
import { server } from "@/test/server";
|
||||||
|
import type { BankCard } from "../api/queries";
|
||||||
|
import { BankCardForm } from "./BankCardForm";
|
||||||
|
|
||||||
|
const card: BankCard = {
|
||||||
|
id: "a",
|
||||||
|
name: "Основная",
|
||||||
|
bankName: "Банк",
|
||||||
|
lastFour: "1234",
|
||||||
|
paymentSystem: null,
|
||||||
|
openingBalance: { currency: "RUB", value: "100" },
|
||||||
|
balance: { currency: "RUB", value: "50" },
|
||||||
|
openingDate: "2026-01-01",
|
||||||
|
archivedAt: null,
|
||||||
|
version: 1,
|
||||||
|
};
|
||||||
|
function setup(value: BankCard) {
|
||||||
|
configureAuthClient({
|
||||||
|
accessToken: () => "test",
|
||||||
|
refresh: async () => false,
|
||||||
|
clear: () => {},
|
||||||
|
});
|
||||||
|
server.use(http.get("*/api/v1/bank-cards/a", () => HttpResponse.json(value)));
|
||||||
|
const close = vi.fn();
|
||||||
|
render(
|
||||||
|
<QueryClientProvider client={createTestQueryClient()}>
|
||||||
|
<MantineProvider env="test">
|
||||||
|
<BankCardForm card={value} onClose={close} />
|
||||||
|
</MantineProvider>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
);
|
||||||
|
return close;
|
||||||
|
}
|
||||||
|
describe("BankCardForm", () => {
|
||||||
|
it("waits for the exit transition before notifying the parent", async () => {
|
||||||
|
const close = setup(card);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Отмена" }));
|
||||||
|
expect(close).not.toHaveBeenCalled();
|
||||||
|
await waitFor(() => expect(close).toHaveBeenCalledTimes(1));
|
||||||
|
});
|
||||||
|
it("clears optional metadata on archive while omitting protected financial fields", async () => {
|
||||||
|
const close = setup({ ...card, archivedAt: "2026-09-01" });
|
||||||
|
expect(screen.getByLabelText(/Начальный остаток/)).toHaveAttribute(
|
||||||
|
"readonly",
|
||||||
|
);
|
||||||
|
expect(screen.getByLabelText(/Дата начала/)).toHaveAttribute("readonly");
|
||||||
|
fireEvent.change(screen.getByLabelText(/Банк/), { target: { value: "" } });
|
||||||
|
fireEvent.change(screen.getByLabelText(/Последние четыре/), {
|
||||||
|
target: { value: "" },
|
||||||
|
});
|
||||||
|
let body: unknown;
|
||||||
|
server.use(
|
||||||
|
http.patch("*/api/v1/bank-cards/a", async ({ request }) => {
|
||||||
|
body = await request.json();
|
||||||
|
return HttpResponse.json(card);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||||
|
expect(body).toEqual({
|
||||||
|
version: 1,
|
||||||
|
name: "Основная",
|
||||||
|
bankName: null,
|
||||||
|
lastFour: null,
|
||||||
|
paymentSystem: null,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it("loads and saves the selected payment system", async () => {
|
||||||
|
const close = setup({ ...card, paymentSystem: "mir" });
|
||||||
|
expect(
|
||||||
|
screen.getByRole("combobox", { name: /Платёжная система/ }),
|
||||||
|
).toHaveValue("МИР");
|
||||||
|
fireEvent.click(
|
||||||
|
screen.getByRole("combobox", { name: /Платёжная система/ }),
|
||||||
|
);
|
||||||
|
fireEvent.click(await screen.findByRole("option", { name: "Visa" }));
|
||||||
|
let body: unknown;
|
||||||
|
server.use(
|
||||||
|
http.patch("*/api/v1/bank-cards/a", async ({ request }) => {
|
||||||
|
body = await request.json();
|
||||||
|
return HttpResponse.json({ ...card, paymentSystem: "visa" });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||||
|
expect(body).toMatchObject({ paymentSystem: "visa" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("retains an invalid opening date draft and explains conflict with saved history", async () => {
|
||||||
|
const close = setup(card);
|
||||||
|
fireEvent.change(screen.getByLabelText(/Дата начала/), {
|
||||||
|
target: { value: "01.08.2026" },
|
||||||
|
});
|
||||||
|
server.use(
|
||||||
|
http.patch("*/api/v1/bank-cards/a", () =>
|
||||||
|
HttpResponse.json(
|
||||||
|
{ code: "BANK_OPENING_DATE_CONFLICT" },
|
||||||
|
{ status: 400 },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
await screen.findByText(
|
||||||
|
"Дата начала противоречит сохранённой истории карты.",
|
||||||
|
);
|
||||||
|
expect(screen.getByLabelText(/Дата начала/)).toHaveValue("01.08.2026");
|
||||||
|
expect(close).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
it("keeps card edit version until explicit refresh adoption", async () => {
|
||||||
|
const close = setup(card);
|
||||||
|
let version = 1;
|
||||||
|
const bodies: Record<string, unknown>[] = [];
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/a", () =>
|
||||||
|
HttpResponse.json({ ...card, version }),
|
||||||
|
),
|
||||||
|
http.patch("*/api/v1/bank-cards/a", async ({ request }) => {
|
||||||
|
const body = (await request.json()) as Record<string, unknown>;
|
||||||
|
bodies.push(body);
|
||||||
|
version = 2;
|
||||||
|
return body.version === 1
|
||||||
|
? HttpResponse.json(
|
||||||
|
{ code: "BANK_VERSION_CONFLICT" },
|
||||||
|
{ status: 409 },
|
||||||
|
)
|
||||||
|
: HttpResponse.json(card);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
fireEvent.change(screen.getByLabelText(/Название карты/), {
|
||||||
|
target: { value: "Мой черновик" },
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
await screen.findByText(/Запись уже изменена/);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Перечитать запись" }));
|
||||||
|
const adopt = await screen.findByRole("button", {
|
||||||
|
name: "Использовать актуальную версию 2",
|
||||||
|
});
|
||||||
|
expect(screen.getByLabelText(/Название карты/)).toHaveValue("Мой черновик");
|
||||||
|
fireEvent.click(adopt);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||||
|
expect(bodies.map((b) => b.version)).toEqual([1, 2]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { Button, Group, Modal, Stack, Text } from "@mantine/core";
|
||||||
|
import { type FC, useState } from "react";
|
||||||
|
import { FormProvider, useForm } from "react-hook-form";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { formatDate } from "@/shared/lib";
|
||||||
|
import { useBankMutations } from "../api/mutations";
|
||||||
|
import { type BankCard, useBankCard } from "../api/queries";
|
||||||
|
import {
|
||||||
|
type BankCardValues,
|
||||||
|
bankCardSchema,
|
||||||
|
bankMoneyValue,
|
||||||
|
bankToday,
|
||||||
|
} from "../model/form-validation";
|
||||||
|
import { BankCardFields } from "./BankCardForm.view";
|
||||||
|
import { BankFeedback } from "./BankFeedback";
|
||||||
|
import classes from "./BankForms.module.css";
|
||||||
|
import { useBankFormFocus } from "./useBankFormFocus";
|
||||||
|
|
||||||
|
type BankCardFormProps = { card?: BankCard; onClose: () => void };
|
||||||
|
const BankCardForm: FC<BankCardFormProps> = (props) => {
|
||||||
|
useBankFormFocus();
|
||||||
|
const [opened, setOpened] = useState(true);
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [intent] = useState(() => crypto.randomUUID());
|
||||||
|
const [version, setVersion] = useState(props.card?.version ?? 1);
|
||||||
|
const [error, setError] = useState<unknown>();
|
||||||
|
const [latest, setLatest] = useState<BankCard>();
|
||||||
|
const fresh = useBankCard(props.card?.id);
|
||||||
|
const mutation = useBankMutations();
|
||||||
|
const methods = useForm<BankCardValues>({
|
||||||
|
resolver: zodResolver(bankCardSchema),
|
||||||
|
defaultValues: {
|
||||||
|
name: props.card?.name ?? "",
|
||||||
|
bankName: props.card?.bankName ?? "",
|
||||||
|
lastFour: props.card?.lastFour ?? "",
|
||||||
|
paymentSystem: props.card?.paymentSystem ?? "",
|
||||||
|
openingBalance: props.card?.openingBalance.value ?? "0",
|
||||||
|
openingDate: props.card?.openingDate ?? bankToday(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const pending =
|
||||||
|
!opened ||
|
||||||
|
methods.formState.isSubmitting ||
|
||||||
|
(fresh.isFetching && Boolean(error));
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
opened={opened}
|
||||||
|
onExitTransitionEnd={props.onClose}
|
||||||
|
onClose={() => !pending && setOpened(false)}
|
||||||
|
title={t(props.card ? "bank.editCard" : "bank.addCard")}
|
||||||
|
closeButtonProps={{ "aria-label": t("bank.close"), disabled: pending }}
|
||||||
|
closeOnClickOutside={!pending}
|
||||||
|
closeOnEscape={!pending}
|
||||||
|
>
|
||||||
|
<FormProvider {...methods}>
|
||||||
|
<form
|
||||||
|
onSubmit={methods.handleSubmit(async (values) => {
|
||||||
|
setError(undefined);
|
||||||
|
try {
|
||||||
|
const metadata = {
|
||||||
|
name: values.name,
|
||||||
|
bankName: values.bankName || null,
|
||||||
|
lastFour: values.lastFour || null,
|
||||||
|
paymentSystem: values.paymentSystem || null,
|
||||||
|
};
|
||||||
|
const financial = {
|
||||||
|
openingBalance: {
|
||||||
|
currency: "RUB" as const,
|
||||||
|
value: bankMoneyValue(values.openingBalance),
|
||||||
|
},
|
||||||
|
openingDate: values.openingDate,
|
||||||
|
};
|
||||||
|
if (props.card)
|
||||||
|
await mutation.updateCard.mutateAsync({
|
||||||
|
id: props.card.id,
|
||||||
|
body: {
|
||||||
|
...metadata,
|
||||||
|
...(!props.card.archivedAt ? financial : {}),
|
||||||
|
version,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
else
|
||||||
|
await mutation.createCard.mutateAsync({
|
||||||
|
id: intent,
|
||||||
|
...metadata,
|
||||||
|
...financial,
|
||||||
|
});
|
||||||
|
setOpened(false);
|
||||||
|
} catch (failure) {
|
||||||
|
setError(failure);
|
||||||
|
}
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
<fieldset className={classes.fieldset} disabled={pending}>
|
||||||
|
<Stack>
|
||||||
|
<BankCardFields archived={Boolean(props.card?.archivedAt)} />
|
||||||
|
{error ? (
|
||||||
|
<>
|
||||||
|
<BankFeedback error={error} />
|
||||||
|
{props.card && (
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
onClick={async () => {
|
||||||
|
const response = await fresh.refetch();
|
||||||
|
if (response.data && !response.error)
|
||||||
|
setLatest(response.data);
|
||||||
|
else setError(response.error);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("bank.reloadRecord")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
{latest && (
|
||||||
|
<>
|
||||||
|
<Text>
|
||||||
|
{t("bank.versionHint", {
|
||||||
|
details: `${latest.name} · ${latest.openingBalance.value} RUB · ${formatDate(latest.openingDate)}`,
|
||||||
|
})}
|
||||||
|
</Text>
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
onClick={() => {
|
||||||
|
setVersion(latest.version);
|
||||||
|
setLatest(undefined);
|
||||||
|
setError(undefined);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("bank.adoptVersion", { version: latest.version })}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<Group>
|
||||||
|
<Button type="submit" loading={pending}>
|
||||||
|
{t("bank.save")}
|
||||||
|
</Button>
|
||||||
|
<Button variant="default" onClick={() => setOpened(false)}>
|
||||||
|
{t("bank.cancel")}
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
</Stack>
|
||||||
|
</fieldset>
|
||||||
|
</form>
|
||||||
|
</FormProvider>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { BankCardForm };
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import { Select, Stack, Text, TextInput } from "@mantine/core";
|
||||||
|
import { DateInput } from "@mantine/dates";
|
||||||
|
import type { FC } from "react";
|
||||||
|
import { Controller, useFormContext } from "react-hook-form";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import {
|
||||||
|
type BankCardValues,
|
||||||
|
bankDateInputValue,
|
||||||
|
bankDateSchema,
|
||||||
|
bankToday,
|
||||||
|
} from "../model/form-validation";
|
||||||
|
|
||||||
|
type BankCardFieldsProps = { archived: boolean };
|
||||||
|
const BankCardFields: FC<BankCardFieldsProps> = (props) => {
|
||||||
|
const {
|
||||||
|
control,
|
||||||
|
register,
|
||||||
|
formState: { errors },
|
||||||
|
} = useFormContext<BankCardValues>();
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<Stack>
|
||||||
|
<TextInput
|
||||||
|
label={t("bank.name")}
|
||||||
|
required
|
||||||
|
{...register("name")}
|
||||||
|
error={errors.name?.message}
|
||||||
|
/>
|
||||||
|
<TextInput
|
||||||
|
label={t("bank.bankName")}
|
||||||
|
{...register("bankName")}
|
||||||
|
error={errors.bankName?.message}
|
||||||
|
/>
|
||||||
|
<TextInput
|
||||||
|
label={t("bank.lastFour")}
|
||||||
|
inputMode="numeric"
|
||||||
|
{...register("lastFour")}
|
||||||
|
error={errors.lastFour?.message}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name="paymentSystem"
|
||||||
|
render={({ field }) => (
|
||||||
|
<Select
|
||||||
|
{...field}
|
||||||
|
value={field.value || null}
|
||||||
|
onChange={(value) => field.onChange(value ?? "")}
|
||||||
|
label={t("bank.paymentSystem")}
|
||||||
|
placeholder={t("bank.paymentSystemUnknown")}
|
||||||
|
clearable
|
||||||
|
data={["mir", "visa", "mastercard"].map((value) => ({
|
||||||
|
value,
|
||||||
|
label: t(`bank.paymentSystems.${value}`),
|
||||||
|
}))}
|
||||||
|
comboboxProps={{ withinPortal: false }}
|
||||||
|
error={errors.paymentSystem?.message}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<TextInput
|
||||||
|
label={t("bank.openingBalance")}
|
||||||
|
required
|
||||||
|
inputMode="decimal"
|
||||||
|
readOnly={props.archived}
|
||||||
|
{...register("openingBalance")}
|
||||||
|
error={errors.openingBalance?.message}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name="openingDate"
|
||||||
|
render={({ field }) => (
|
||||||
|
<DateInput
|
||||||
|
{...field}
|
||||||
|
label={t("bank.openingDate")}
|
||||||
|
required
|
||||||
|
valueFormat="DD.MM.YYYY"
|
||||||
|
value={
|
||||||
|
bankDateSchema.safeParse(field.value).success ? field.value : null
|
||||||
|
}
|
||||||
|
dateParser={(value) =>
|
||||||
|
bankDateSchema.safeParse(bankDateInputValue(value)).success
|
||||||
|
? bankDateInputValue(value)
|
||||||
|
: null
|
||||||
|
}
|
||||||
|
fixOnBlur={false}
|
||||||
|
onInput={(event) =>
|
||||||
|
field.onChange(bankDateInputValue(event.currentTarget.value))
|
||||||
|
}
|
||||||
|
onChange={(value) => field.onChange(value ?? "")}
|
||||||
|
onBlur={(event) => {
|
||||||
|
field.onChange(bankDateInputValue(event.currentTarget.value));
|
||||||
|
field.onBlur();
|
||||||
|
}}
|
||||||
|
maxDate={bankToday()}
|
||||||
|
popoverProps={{
|
||||||
|
withinPortal: false,
|
||||||
|
middlewares: { shift: { crossAxis: true } },
|
||||||
|
}}
|
||||||
|
readOnly={props.archived}
|
||||||
|
error={errors.openingDate?.message}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Text size="sm" c="dimmed">
|
||||||
|
{t("bank.openingHint")}
|
||||||
|
</Text>
|
||||||
|
{props.archived && <Text>{t("bank.archiveHint")}</Text>}
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { BankCardFields };
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { Alert, Button, Group, Text } from "@mantine/core";
|
||||||
|
import type { FC } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { apiErrorCode } from "@/shared/api";
|
||||||
|
|
||||||
|
type BankFeedbackProps = {
|
||||||
|
error: unknown;
|
||||||
|
retry?: () => void;
|
||||||
|
cached?: boolean;
|
||||||
|
loadingError?: boolean;
|
||||||
|
};
|
||||||
|
const BankFeedback: FC<BankFeedbackProps> = (props) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const code = apiErrorCode(props.error);
|
||||||
|
return (
|
||||||
|
<Alert color="orange" role="alert">
|
||||||
|
<Group>
|
||||||
|
<Text>
|
||||||
|
{props.cached
|
||||||
|
? t("bank.refreshError")
|
||||||
|
: t(`bank.errors.${code}` as "bank.errors.BANK_INVALID_INPUT", {
|
||||||
|
defaultValue: t(
|
||||||
|
props.loadingError ? "bank.error" : "bank.requestError",
|
||||||
|
),
|
||||||
|
})}
|
||||||
|
</Text>
|
||||||
|
{props.retry && (
|
||||||
|
<Button variant="default" onClick={props.retry}>
|
||||||
|
{t("bank.retry")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</Group>
|
||||||
|
</Alert>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { BankFeedback };
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
.fieldset {
|
||||||
|
border: 0;
|
||||||
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,365 @@
|
|||||||
|
.icon {
|
||||||
|
overflow: visible;
|
||||||
|
|
||||||
|
& path {
|
||||||
|
--motion: none;
|
||||||
|
transform-box: fill-box;
|
||||||
|
transform-origin: center;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.deposit path:nth-child(-n + 2) {
|
||||||
|
transform-box: view-box;
|
||||||
|
transform-origin: 12px 9px;
|
||||||
|
--motion: bank-operation-coin-turn 1000ms ease-in-out both;
|
||||||
|
}
|
||||||
|
|
||||||
|
.repayment path:last-child {
|
||||||
|
--motion: bank-operation-ruble-in 1000ms ease-out both;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topup path:last-child {
|
||||||
|
--motion: bank-operation-plus-in 900ms ease-out both;
|
||||||
|
}
|
||||||
|
|
||||||
|
.transfer path {
|
||||||
|
--shift: 3px;
|
||||||
|
--motion: bank-operation-exchange 700ms ease-in-out both;
|
||||||
|
&:last-child {
|
||||||
|
--shift: -3px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.growth {
|
||||||
|
& path:nth-child(2) {
|
||||||
|
stroke-dasharray: 1;
|
||||||
|
--motion: bank-operation-draw 450ms ease-out both;
|
||||||
|
}
|
||||||
|
& path:last-child {
|
||||||
|
--motion: bank-operation-arrow-rise 350ms ease-out 400ms both;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.server {
|
||||||
|
& path:nth-child(3) {
|
||||||
|
--motion: bank-operation-blink 500ms ease-in-out both;
|
||||||
|
}
|
||||||
|
& path:nth-child(4) {
|
||||||
|
--motion: bank-operation-blink 500ms ease-in-out 220ms both;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.basket {
|
||||||
|
& path:not(:last-child) {
|
||||||
|
--motion: bank-operation-settle 850ms ease-in-out both;
|
||||||
|
}
|
||||||
|
& path:last-child {
|
||||||
|
opacity: 0;
|
||||||
|
fill: currentColor;
|
||||||
|
--motion: bank-operation-grocery-drop 850ms ease-out both;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.wine {
|
||||||
|
--motion: bank-operation-cheers 1100ms ease-in-out both;
|
||||||
|
transform-origin: 12px 21px;
|
||||||
|
& path:nth-child(2) {
|
||||||
|
fill: currentColor;
|
||||||
|
fill-opacity: 0.2;
|
||||||
|
transform-origin: bottom;
|
||||||
|
--motion: bank-operation-fill-glass 1100ms ease-out both;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.coffee {
|
||||||
|
& path:nth-child(3),
|
||||||
|
& path:nth-child(4) {
|
||||||
|
--motion: bank-operation-steam 1000ms ease-out var(--delay, 0ms) both;
|
||||||
|
}
|
||||||
|
& path:nth-child(4) {
|
||||||
|
--delay: 180ms;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.grid path {
|
||||||
|
--x: -1.5px;
|
||||||
|
--y: -1.5px;
|
||||||
|
--turn: 0deg;
|
||||||
|
--motion: bank-operation-rearrange 850ms ease-in-out both;
|
||||||
|
&:nth-child(2) {
|
||||||
|
--x: 1.5px;
|
||||||
|
--turn: 90deg;
|
||||||
|
}
|
||||||
|
&:nth-child(3) {
|
||||||
|
--y: 1.5px;
|
||||||
|
}
|
||||||
|
&:nth-child(4) {
|
||||||
|
--x: 1.5px;
|
||||||
|
--y: 1.5px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.wifi path {
|
||||||
|
--motion: bank-operation-signal 450ms ease-out var(--delay, 0ms) both;
|
||||||
|
&:nth-child(1) {
|
||||||
|
--delay: 360ms;
|
||||||
|
}
|
||||||
|
&:nth-child(2) {
|
||||||
|
--delay: 240ms;
|
||||||
|
}
|
||||||
|
&:nth-child(3) {
|
||||||
|
--delay: 120ms;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.car {
|
||||||
|
--motion: bank-operation-drive 1100ms ease-in-out both;
|
||||||
|
& path:nth-child(-n + 3) {
|
||||||
|
--motion: bank-operation-suspension 275ms ease-in-out 4 both;
|
||||||
|
}
|
||||||
|
& path:nth-last-child(-n + 2) {
|
||||||
|
--motion: bank-operation-wheel-roll 1100ms ease-in-out both;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: no-preference) {
|
||||||
|
.icon[data-icon-animating] {
|
||||||
|
animation: var(--motion, none);
|
||||||
|
& path {
|
||||||
|
animation: var(--motion, none);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes :global(bank-operation-coin-turn) {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
transform: scaleX(1);
|
||||||
|
}
|
||||||
|
35%,
|
||||||
|
65% {
|
||||||
|
transform: scaleX(0.12);
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
transform: scaleX(-1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes :global(bank-operation-settle) {
|
||||||
|
0%,
|
||||||
|
30%,
|
||||||
|
100% {
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
45% {
|
||||||
|
transform: translateY(1.5px);
|
||||||
|
}
|
||||||
|
65% {
|
||||||
|
transform: translateY(-0.5px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes :global(bank-operation-ruble-in) {
|
||||||
|
0% {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(-9px) scale(0.7);
|
||||||
|
}
|
||||||
|
25% {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
65% {
|
||||||
|
transform: translateY(0) scale(1.15);
|
||||||
|
}
|
||||||
|
80% {
|
||||||
|
transform: scale(0.95);
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
opacity: 1;
|
||||||
|
transform: scale(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes :global(bank-operation-plus-in) {
|
||||||
|
0% {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(-5px) scale(0.5);
|
||||||
|
}
|
||||||
|
55% {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0) scale(1.3);
|
||||||
|
}
|
||||||
|
75% {
|
||||||
|
transform: scale(0.9);
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
opacity: 1;
|
||||||
|
transform: scale(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes :global(bank-operation-exchange) {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
transform: translateX(0);
|
||||||
|
}
|
||||||
|
45% {
|
||||||
|
transform: translateX(var(--shift));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes :global(bank-operation-draw) {
|
||||||
|
from {
|
||||||
|
stroke-dashoffset: 1;
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
stroke-dashoffset: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes :global(bank-operation-arrow-rise) {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
45% {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes :global(bank-operation-blink) {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
stroke-width: 1.6;
|
||||||
|
}
|
||||||
|
45% {
|
||||||
|
stroke: var(--mantine-color-green-6);
|
||||||
|
stroke-width: 3;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes :global(bank-operation-grocery-drop) {
|
||||||
|
0% {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(-5px);
|
||||||
|
}
|
||||||
|
20% {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
55% {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(7px);
|
||||||
|
}
|
||||||
|
80%,
|
||||||
|
100% {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(7px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes :global(bank-operation-fill-glass) {
|
||||||
|
0% {
|
||||||
|
transform: scaleY(0.05);
|
||||||
|
}
|
||||||
|
45%,
|
||||||
|
75% {
|
||||||
|
transform: scaleY(1);
|
||||||
|
fill-opacity: 0.5;
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
transform: scaleY(1);
|
||||||
|
fill-opacity: 0.2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes :global(bank-operation-cheers) {
|
||||||
|
0%,
|
||||||
|
40%,
|
||||||
|
100% {
|
||||||
|
transform: rotate(0);
|
||||||
|
}
|
||||||
|
65% {
|
||||||
|
transform: rotate(8deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes :global(bank-operation-steam) {
|
||||||
|
0% {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(2px);
|
||||||
|
}
|
||||||
|
25% {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
70% {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(-3px);
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes :global(bank-operation-rearrange) {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
transform: translate(0, 0) rotate(0);
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
transform: translate(var(--x), var(--y)) rotate(var(--turn));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes :global(bank-operation-signal) {
|
||||||
|
0% {
|
||||||
|
opacity: 0.1;
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes :global(bank-operation-drive) {
|
||||||
|
0% {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateX(-4px);
|
||||||
|
}
|
||||||
|
20% {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
80% {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateX(3px);
|
||||||
|
}
|
||||||
|
90% {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateX(4px);
|
||||||
|
}
|
||||||
|
91% {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateX(0);
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateX(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes :global(bank-operation-suspension) {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
transform: translateY(-0.5px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes :global(bank-operation-wheel-roll) {
|
||||||
|
from {
|
||||||
|
transform: rotate(0);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import { Stack } from "@mantine/core";
|
||||||
|
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||||
|
import { EntryCard } from "@/shared/ui";
|
||||||
|
import { BankOperationIcon } from "./BankOperationIcon";
|
||||||
|
|
||||||
|
const meta = {
|
||||||
|
title: "Product/BankCards/OperationIcons",
|
||||||
|
component: BankOperationIcon,
|
||||||
|
tags: ["autodocs"],
|
||||||
|
args: { kind: "expense", categoryName: "Продукты" },
|
||||||
|
} satisfies Meta<typeof BankOperationIcon>;
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof meta>;
|
||||||
|
export const Categories: Story = {
|
||||||
|
render: () => (
|
||||||
|
<Stack maw={640}>
|
||||||
|
{[
|
||||||
|
"Алкоголь",
|
||||||
|
"Вклады",
|
||||||
|
"Другое",
|
||||||
|
"Жильё",
|
||||||
|
"Здоровье",
|
||||||
|
"Инвестиции и накопления",
|
||||||
|
"Кафе",
|
||||||
|
"Образование",
|
||||||
|
"Переводы",
|
||||||
|
"Погашение кредита",
|
||||||
|
"Подписки",
|
||||||
|
"Покупки",
|
||||||
|
"Продукты",
|
||||||
|
"Путешествия",
|
||||||
|
"Развлечения",
|
||||||
|
"Связь и интернет",
|
||||||
|
"Снятие наличных",
|
||||||
|
"Ставки",
|
||||||
|
"Страхование",
|
||||||
|
"Табак",
|
||||||
|
"Такси",
|
||||||
|
"Транспорт",
|
||||||
|
"Хостинг и ИИ-сервисы",
|
||||||
|
"Цифровые покупки",
|
||||||
|
"Моя категория",
|
||||||
|
].map((name) => (
|
||||||
|
<EntryCard
|
||||||
|
key={name}
|
||||||
|
title="Расход"
|
||||||
|
metadata={`12.09.2026 · ${name}`}
|
||||||
|
initial="Р"
|
||||||
|
color="red"
|
||||||
|
icon={<BankOperationIcon kind="expense" categoryName={name} />}
|
||||||
|
value="−1 250,00 ₽"
|
||||||
|
valueLabel="Расход"
|
||||||
|
tone="negative"
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
<EntryCard
|
||||||
|
title="Пополнение"
|
||||||
|
metadata="12.09.2026"
|
||||||
|
initial="П"
|
||||||
|
color="green"
|
||||||
|
icon={<BankOperationIcon kind="topup" />}
|
||||||
|
value="+15 000,00 ₽"
|
||||||
|
valueLabel="Пополнение"
|
||||||
|
tone="positive"
|
||||||
|
/>
|
||||||
|
</Stack>
|
||||||
|
),
|
||||||
|
};
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import { render } from "@testing-library/react";
|
||||||
|
import { expect, it } from "vitest";
|
||||||
|
import { BankOperationIcon } from "./BankOperationIcon";
|
||||||
|
|
||||||
|
it("matches normalized category names, falls back after renaming and distinguishes operation kinds", () => {
|
||||||
|
const { container, rerender } = render(
|
||||||
|
<BankOperationIcon kind="expense" categoryName="Жильё" />,
|
||||||
|
);
|
||||||
|
const path = () => container.querySelector("path")?.getAttribute("d");
|
||||||
|
const housing = path();
|
||||||
|
rerender(<BankOperationIcon kind="expense" categoryName=" ЖИЛЬЕ " />);
|
||||||
|
expect(path()).toBe(housing);
|
||||||
|
rerender(<BankOperationIcon kind="expense" categoryName="Другое" />);
|
||||||
|
const fallback = path();
|
||||||
|
expect(fallback).not.toBe(housing);
|
||||||
|
for (const categoryName of ["Моя категория", "constructor", null]) {
|
||||||
|
rerender(<BankOperationIcon kind="expense" categoryName={categoryName} />);
|
||||||
|
expect(path()).toBe(fallback);
|
||||||
|
}
|
||||||
|
const paths = [fallback, housing];
|
||||||
|
for (const kind of ["topup", "transfer", "refund"] as const) {
|
||||||
|
rerender(<BankOperationIcon kind={kind} categoryName="Жильё" />);
|
||||||
|
expect(path()).toBeTruthy();
|
||||||
|
paths.push(path());
|
||||||
|
}
|
||||||
|
expect(new Set(paths).size).toBe(5);
|
||||||
|
expect(container.querySelector("svg")).toHaveAttribute("aria-hidden", "true");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("provides a distinct icon for every existing named category", () => {
|
||||||
|
const { container, rerender } = render(
|
||||||
|
<BankOperationIcon kind="expense" categoryName="Другое" />,
|
||||||
|
);
|
||||||
|
const paths = new Set([container.querySelector("path")?.getAttribute("d")]);
|
||||||
|
for (const categoryName of [
|
||||||
|
"Алкоголь",
|
||||||
|
"Вклады",
|
||||||
|
"Жильё",
|
||||||
|
"Здоровье",
|
||||||
|
"Инвестиции и накопления",
|
||||||
|
"Кафе",
|
||||||
|
"Образование",
|
||||||
|
"Переводы",
|
||||||
|
"Погашение кредита",
|
||||||
|
"Подписки",
|
||||||
|
"Покупки",
|
||||||
|
"Продукты",
|
||||||
|
"Путешествия",
|
||||||
|
"Развлечения",
|
||||||
|
"Связь и интернет",
|
||||||
|
"Снятие наличных",
|
||||||
|
"Ставки",
|
||||||
|
"Страхование",
|
||||||
|
"Табак",
|
||||||
|
"Такси",
|
||||||
|
"Транспорт",
|
||||||
|
"Хостинг и ИИ-сервисы",
|
||||||
|
"Цифровые покупки",
|
||||||
|
]) {
|
||||||
|
rerender(<BankOperationIcon kind="expense" categoryName={categoryName} />);
|
||||||
|
const path = container.querySelector("path")?.getAttribute("d");
|
||||||
|
expect(path).toBeTruthy();
|
||||||
|
expect(paths.has(path), categoryName).toBe(false);
|
||||||
|
paths.add(path);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import type { FC } from "react";
|
||||||
|
import { bindIconAnimation } from "@/shared/lib";
|
||||||
|
import type { BankOperation } from "../api/queries";
|
||||||
|
|
||||||
|
import { bankOperationAppearance } from "../model/operation-appearance";
|
||||||
|
import classes from "./BankOperationIcon.module.css";
|
||||||
|
|
||||||
|
type BankOperationIconProps = {
|
||||||
|
kind: BankOperation["kind"];
|
||||||
|
categoryName?: string | null;
|
||||||
|
};
|
||||||
|
const BankOperationIcon: FC<BankOperationIconProps> = (props) => {
|
||||||
|
const icon = bankOperationAppearance(props.kind, props.categoryName);
|
||||||
|
return (
|
||||||
|
<svg
|
||||||
|
ref={bindIconAnimation}
|
||||||
|
className={`${classes.icon} ${icon.animation ? classes[icon.animation] : ""}`}
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="1.6"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
aria-hidden="true"
|
||||||
|
focusable="false"
|
||||||
|
style={{ flexShrink: 0, color: `var(--mantine-color-${icon.color}-7)` }}
|
||||||
|
>
|
||||||
|
{icon.path.split(" M").map((part, index) => (
|
||||||
|
<path key={part} d={index ? `M${part}` : part} pathLength={1} />
|
||||||
|
))}
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { BankOperationIcon };
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { DatePickerInput } from "@mantine/dates";
|
||||||
|
import { type FC, useState } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
type BankPeriodPickerProps = {
|
||||||
|
period: { from: string; to: string };
|
||||||
|
onChange: (value: [string | null, string | null]) => void;
|
||||||
|
};
|
||||||
|
const BankPeriodPicker: FC<BankPeriodPickerProps> = (props) => {
|
||||||
|
const { period, onChange } = props;
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const scope = `${period.from}-${period.to}`;
|
||||||
|
const [draft, setDraft] = useState<{
|
||||||
|
scope: string;
|
||||||
|
value: [string | null, string | null];
|
||||||
|
}>();
|
||||||
|
const value: [string | null, string | null] =
|
||||||
|
draft?.scope === scope ? draft.value : [period.from, period.to];
|
||||||
|
return (
|
||||||
|
<DatePickerInput
|
||||||
|
type="range"
|
||||||
|
allowSingleDateInRange
|
||||||
|
label={t("bank.period")}
|
||||||
|
valueFormat="DD.MM.YYYY"
|
||||||
|
value={value}
|
||||||
|
onChange={(next) => {
|
||||||
|
setDraft({ scope, value: next });
|
||||||
|
onChange(next);
|
||||||
|
}}
|
||||||
|
popoverProps={{
|
||||||
|
returnFocus: true,
|
||||||
|
middlewares: { shift: { crossAxis: true } },
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { BankPeriodPicker };
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
.header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: var(--mantine-spacing-xs) var(--mantine-spacing-lg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.total {
|
||||||
|
font-size: var(--mantine-font-size-xl);
|
||||||
|
font-weight: 650;
|
||||||
|
letter-spacing: -0.025em;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.categories {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
grid-template-rows: repeat(var(--category-rows), auto);
|
||||||
|
grid-auto-flow: column;
|
||||||
|
column-gap: var(--mantine-spacing-xl);
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.category {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: var(--mantine-spacing-md);
|
||||||
|
padding-block: var(--mantine-spacing-sm);
|
||||||
|
border-top: 1px solid var(--mantine-color-gray-3);
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.label {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--mantine-spacing-xs);
|
||||||
|
min-width: 0;
|
||||||
|
font-size: var(--mantine-font-size-sm);
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount {
|
||||||
|
flex-shrink: 0;
|
||||||
|
max-width: 60%;
|
||||||
|
margin: 0;
|
||||||
|
font-size: var(--mantine-font-size-sm);
|
||||||
|
font-weight: 600;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
text-align: right;
|
||||||
|
min-width: 0;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 48em) {
|
||||||
|
.categories {
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
grid-template-rows: none;
|
||||||
|
grid-auto-flow: row;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||||
|
import { BankSummaryView } from "./BankSummary.view";
|
||||||
|
|
||||||
|
const money = (value: string) => ({ currency: "RUB", value });
|
||||||
|
const meta = {
|
||||||
|
title: "Product/BankCards/Summary",
|
||||||
|
component: BankSummaryView,
|
||||||
|
tags: ["autodocs"],
|
||||||
|
parameters: {
|
||||||
|
docs: {
|
||||||
|
description: {
|
||||||
|
component:
|
||||||
|
"Месячные расходы ручного учёта. Вымышленные суммы, без API и сохранения. Один итог с учётом возвратов и компактные строки категорий. Отрицательные суммы сохраняют знак.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
args: {
|
||||||
|
loading: false,
|
||||||
|
error: false,
|
||||||
|
fetching: false,
|
||||||
|
retry: () => {},
|
||||||
|
data: {
|
||||||
|
month: "2026-09",
|
||||||
|
cardId: null,
|
||||||
|
expenses: money("8500"),
|
||||||
|
refunds: money("1000"),
|
||||||
|
net: money("7500"),
|
||||||
|
categories: [
|
||||||
|
{
|
||||||
|
categoryId: "food",
|
||||||
|
categoryName: "Продукты",
|
||||||
|
expenses: money("3500"),
|
||||||
|
refunds: money("1000"),
|
||||||
|
net: money("2500"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
categoryId: "cafe",
|
||||||
|
categoryName: "Кафе",
|
||||||
|
expenses: money("2200"),
|
||||||
|
refunds: money("0"),
|
||||||
|
net: money("2200"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
categoryId: "taxi",
|
||||||
|
categoryName: "Такси",
|
||||||
|
expenses: money("1800"),
|
||||||
|
refunds: money("0"),
|
||||||
|
net: money("1800"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
categoryId: "health",
|
||||||
|
categoryName: "Здоровье",
|
||||||
|
expenses: money("1000"),
|
||||||
|
refunds: money("0"),
|
||||||
|
net: money("1000"),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} satisfies Meta<typeof BankSummaryView>;
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof meta>;
|
||||||
|
export const Loaded: Story = { name: "Расходы по категориям" };
|
||||||
|
export const RefundMonth: Story = {
|
||||||
|
name: "Возврат покупки прошлого месяца",
|
||||||
|
args: {
|
||||||
|
data: {
|
||||||
|
month: "2026-09",
|
||||||
|
cardId: null,
|
||||||
|
expenses: money("0"),
|
||||||
|
refunds: money("600"),
|
||||||
|
net: money("-600"),
|
||||||
|
categories: [
|
||||||
|
{
|
||||||
|
categoryId: "shopping",
|
||||||
|
categoryName:
|
||||||
|
"Покупки с длинным пользовательским названием категории",
|
||||||
|
expenses: money("0"),
|
||||||
|
refunds: money("600"),
|
||||||
|
net: money("-600"),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
export const Empty: Story = {
|
||||||
|
name: "Известные нули",
|
||||||
|
args: {
|
||||||
|
data: {
|
||||||
|
month: "2026-09",
|
||||||
|
cardId: null,
|
||||||
|
expenses: money("0"),
|
||||||
|
refunds: money("0"),
|
||||||
|
net: money("0"),
|
||||||
|
categories: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
export const Loading: Story = {
|
||||||
|
name: "Начальная загрузка",
|
||||||
|
args: { data: undefined, loading: true },
|
||||||
|
};
|
||||||
|
export const Failed: Story = {
|
||||||
|
name: "Ошибка без данных",
|
||||||
|
args: { data: undefined, error: true },
|
||||||
|
};
|
||||||
|
export const CachedError: Story = {
|
||||||
|
name: "Сохранённые суммы при ошибке обновления",
|
||||||
|
args: { error: true },
|
||||||
|
};
|
||||||
|
export const LongAmounts: Story = {
|
||||||
|
name: "Точный итог длиннее предела отдельного ввода",
|
||||||
|
args: {
|
||||||
|
data: {
|
||||||
|
month: "2026-09",
|
||||||
|
cardId: null,
|
||||||
|
expenses: money("184467440737095516.14"),
|
||||||
|
refunds: money("0"),
|
||||||
|
net: money("184467440737095516.14"),
|
||||||
|
categories: [
|
||||||
|
{
|
||||||
|
categoryId: "shopping",
|
||||||
|
categoryName: "Покупки",
|
||||||
|
expenses: money("184467440737095516.14"),
|
||||||
|
refunds: money("0"),
|
||||||
|
net: money("184467440737095516.14"),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import { Button, Group, Skeleton, Stack, Text, Title } from "@mantine/core";
|
||||||
|
import type { CSSProperties, FC } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { formatMoney } from "@/shared/lib";
|
||||||
|
import { LoadingSkeleton } from "@/shared/ui";
|
||||||
|
import type { BankSummary } from "../api/queries";
|
||||||
|
import { BankOperationIcon } from "./BankOperationIcon";
|
||||||
|
import classes from "./BankSummary.module.css";
|
||||||
|
|
||||||
|
type BankSummaryViewProps = {
|
||||||
|
data?: BankSummary;
|
||||||
|
loading: boolean;
|
||||||
|
error: boolean;
|
||||||
|
fetching: boolean;
|
||||||
|
retry: () => void;
|
||||||
|
all?: boolean;
|
||||||
|
};
|
||||||
|
const BankSummaryView: FC<BankSummaryViewProps> = (props) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<Stack gap="md" aria-busy={props.loading || props.fetching}>
|
||||||
|
<div className={classes.header}>
|
||||||
|
<Title order={2}>
|
||||||
|
{t(props.all ? "bank.allSummary" : "bank.summary")}
|
||||||
|
</Title>
|
||||||
|
{props.data && (
|
||||||
|
<Text className={classes.total}>
|
||||||
|
{formatMoney(props.data.net, { withZeroCents: true })}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{props.data ? (
|
||||||
|
props.data.categories.length ? (
|
||||||
|
<dl
|
||||||
|
className={classes.categories}
|
||||||
|
style={
|
||||||
|
{
|
||||||
|
"--category-rows": Math.ceil(props.data.categories.length / 2),
|
||||||
|
} as CSSProperties
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{props.data.categories.map((category) => (
|
||||||
|
<div className={classes.category} key={category.categoryId}>
|
||||||
|
<dt className={classes.label}>
|
||||||
|
<BankOperationIcon
|
||||||
|
kind="expense"
|
||||||
|
categoryName={category.categoryName}
|
||||||
|
/>
|
||||||
|
<span>{category.categoryName}</span>
|
||||||
|
</dt>
|
||||||
|
<dd className={classes.amount}>
|
||||||
|
{formatMoney(category.net, { withZeroCents: true })}
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</dl>
|
||||||
|
) : (
|
||||||
|
<Text size="sm" c="dimmed">
|
||||||
|
{t("bank.noExpenses")}
|
||||||
|
</Text>
|
||||||
|
)
|
||||||
|
) : props.loading ? (
|
||||||
|
<LoadingSkeleton label={t("bank.loading")}>
|
||||||
|
<Stack gap="sm">
|
||||||
|
<Skeleton h={32} w="35%" />
|
||||||
|
<Skeleton h={40} />
|
||||||
|
<Skeleton h={40} />
|
||||||
|
</Stack>
|
||||||
|
</LoadingSkeleton>
|
||||||
|
) : null}
|
||||||
|
{props.error && (
|
||||||
|
<Group role="alert">
|
||||||
|
<Text>{t(props.data ? "bank.refreshError" : "bank.error")}</Text>
|
||||||
|
<Button variant="default" onClick={props.retry}>
|
||||||
|
{t("bank.retry")}
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
)}
|
||||||
|
{props.data && props.fetching && (
|
||||||
|
<Text role="status">{t("bank.refreshing")}</Text>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { BankSummaryView };
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import { MantineProvider } from "@mantine/core";
|
||||||
|
import { QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||||
|
import { HttpResponse, http } from "msw";
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { configureAuthClient } from "@/shared/api";
|
||||||
|
import { createTestQueryClient } from "@/test/query";
|
||||||
|
import { server } from "@/test/server";
|
||||||
|
import { CategoryManager } from "./CategoryManager";
|
||||||
|
|
||||||
|
describe("CategoryManager", () => {
|
||||||
|
it("rejects duplicate case-insensitive and too long names then renames default identity", async () => {
|
||||||
|
configureAuthClient({
|
||||||
|
accessToken: () => "test",
|
||||||
|
refresh: async () => false,
|
||||||
|
clear: () => {},
|
||||||
|
});
|
||||||
|
let category = {
|
||||||
|
id: "default",
|
||||||
|
name: "Другое",
|
||||||
|
isDefault: true,
|
||||||
|
version: 1,
|
||||||
|
};
|
||||||
|
let creates = 0;
|
||||||
|
let body: unknown;
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/categories", () =>
|
||||||
|
HttpResponse.json([category]),
|
||||||
|
),
|
||||||
|
http.post("*/api/v1/bank-cards/categories", () => {
|
||||||
|
creates++;
|
||||||
|
return HttpResponse.json({});
|
||||||
|
}),
|
||||||
|
http.patch(
|
||||||
|
"*/api/v1/bank-cards/categories/default",
|
||||||
|
async ({ request }) => {
|
||||||
|
body = await request.json();
|
||||||
|
category = { ...category, name: "Остальное", version: 2 };
|
||||||
|
return HttpResponse.json(category);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
render(
|
||||||
|
<QueryClientProvider client={createTestQueryClient()}>
|
||||||
|
<MantineProvider env="test">
|
||||||
|
<CategoryManager onClose={() => {}} />
|
||||||
|
</MantineProvider>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
);
|
||||||
|
await screen.findByText("Другое");
|
||||||
|
fireEvent.change(screen.getByLabelText(/Название категории/), {
|
||||||
|
target: { value: " другое " },
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Добавить категорию" }));
|
||||||
|
await screen.findByText("Категория с таким названием уже есть.");
|
||||||
|
fireEvent.change(screen.getByLabelText(/Название категории/), {
|
||||||
|
target: { value: "a".repeat(81) },
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Добавить категорию" }));
|
||||||
|
await screen.findByText("Введите название от 1 до 80 символов.");
|
||||||
|
expect(creates).toBe(0);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Переименовать" }));
|
||||||
|
fireEvent.input(screen.getByLabelText(/Название категории/), {
|
||||||
|
target: { value: "Остальное" },
|
||||||
|
});
|
||||||
|
fireEvent.blur(screen.getByLabelText(/Название категории/));
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
await screen.findByText("Остальное");
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(body).toEqual({ name: "Остальное", version: 1 }),
|
||||||
|
);
|
||||||
|
expect(screen.getByText("По умолчанию")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import {
|
||||||
|
Badge,
|
||||||
|
Button,
|
||||||
|
Group,
|
||||||
|
Modal,
|
||||||
|
Stack,
|
||||||
|
Text,
|
||||||
|
TextInput,
|
||||||
|
} from "@mantine/core";
|
||||||
|
import { type FC, useState } from "react";
|
||||||
|
import {
|
||||||
|
Controller,
|
||||||
|
FormProvider,
|
||||||
|
useForm,
|
||||||
|
useFormContext,
|
||||||
|
} from "react-hook-form";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { validationMessage } from "@/shared/i18n";
|
||||||
|
import { useBankMutations } from "../api/mutations";
|
||||||
|
import { type ExpenseCategory, useBankCategories } from "../api/queries";
|
||||||
|
import { BankFeedback } from "./BankFeedback";
|
||||||
|
import classes from "./BankForms.module.css";
|
||||||
|
import { BankOperationIcon } from "./BankOperationIcon";
|
||||||
|
import { useBankFormFocus } from "./useBankFormFocus";
|
||||||
|
|
||||||
|
const MAX_CATEGORY_NAME_LENGTH = 80;
|
||||||
|
|
||||||
|
type CategoryManagerProps = {
|
||||||
|
onClose: () => void;
|
||||||
|
onCreated?: (id: string) => void;
|
||||||
|
};
|
||||||
|
type CategoryValues = { name: string };
|
||||||
|
const CategoryFields: FC = () => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const {
|
||||||
|
control,
|
||||||
|
formState: { errors },
|
||||||
|
} = useFormContext<CategoryValues>();
|
||||||
|
return (
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name="name"
|
||||||
|
render={({ field }) => (
|
||||||
|
<TextInput
|
||||||
|
label={t("bank.categoryName")}
|
||||||
|
required
|
||||||
|
{...field}
|
||||||
|
error={errors.name?.message}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
const CategoryManager: FC<CategoryManagerProps> = (props) => {
|
||||||
|
useBankFormFocus();
|
||||||
|
const [opened, setOpened] = useState(true);
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const categories = useBankCategories();
|
||||||
|
const mutation = useBankMutations();
|
||||||
|
const [editing, setEditing] = useState<ExpenseCategory>();
|
||||||
|
const [error, setError] = useState<unknown>();
|
||||||
|
const [latest, setLatest] = useState<ExpenseCategory>();
|
||||||
|
const methods = useForm<CategoryValues>({
|
||||||
|
resolver: zodResolver(
|
||||||
|
z.object({
|
||||||
|
name: z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.refine(
|
||||||
|
(value) =>
|
||||||
|
value.length > 0 && value.length <= MAX_CATEGORY_NAME_LENGTH,
|
||||||
|
{ error: validationMessage("bank.validation.category") },
|
||||||
|
)
|
||||||
|
.refine(
|
||||||
|
(value) =>
|
||||||
|
!categories.data?.some(
|
||||||
|
(c) =>
|
||||||
|
c.id !== editing?.id &&
|
||||||
|
c.name.toLocaleLowerCase("ru-RU") ===
|
||||||
|
value.toLocaleLowerCase("ru-RU"),
|
||||||
|
),
|
||||||
|
{ error: validationMessage("bank.validation.duplicate") },
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
defaultValues: { name: "" },
|
||||||
|
});
|
||||||
|
const pending = !opened || methods.formState.isSubmitting;
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
opened={opened}
|
||||||
|
onExitTransitionEnd={props.onClose}
|
||||||
|
onClose={() => !pending && setOpened(false)}
|
||||||
|
title={t("bank.categories")}
|
||||||
|
closeOnClickOutside={!pending}
|
||||||
|
closeOnEscape={!pending}
|
||||||
|
closeButtonProps={{ "aria-label": t("bank.close"), disabled: pending }}
|
||||||
|
>
|
||||||
|
<FormProvider {...methods}>
|
||||||
|
<form
|
||||||
|
onSubmit={methods.handleSubmit(async (values) => {
|
||||||
|
setError(undefined);
|
||||||
|
try {
|
||||||
|
if (editing)
|
||||||
|
await mutation.updateCategory.mutateAsync({
|
||||||
|
id: editing.id,
|
||||||
|
body: { name: values.name, version: editing.version },
|
||||||
|
});
|
||||||
|
else {
|
||||||
|
const result = await mutation.createCategory.mutateAsync({
|
||||||
|
name: values.name,
|
||||||
|
});
|
||||||
|
if (result) props.onCreated?.(result.id);
|
||||||
|
}
|
||||||
|
setEditing(undefined);
|
||||||
|
methods.reset({ name: "" });
|
||||||
|
} catch (failure) {
|
||||||
|
setError(failure);
|
||||||
|
}
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
<fieldset disabled={pending} className={classes.fieldset}>
|
||||||
|
<Stack>
|
||||||
|
{categories.data?.map((category) => (
|
||||||
|
<Group justify="space-between" key={category.id}>
|
||||||
|
<Group gap="xs">
|
||||||
|
<BankOperationIcon
|
||||||
|
kind="expense"
|
||||||
|
categoryName={category.name}
|
||||||
|
/>
|
||||||
|
<Text>{category.name}</Text>
|
||||||
|
{category.isDefault && (
|
||||||
|
<Badge>{t("bank.defaultCategory")}</Badge>
|
||||||
|
)}
|
||||||
|
</Group>
|
||||||
|
<Button
|
||||||
|
variant="subtle"
|
||||||
|
onClick={() => {
|
||||||
|
setEditing(category);
|
||||||
|
methods.reset({ name: category.name });
|
||||||
|
setError(undefined);
|
||||||
|
setLatest(undefined);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("bank.rename")}
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
))}
|
||||||
|
{categories.isLoading && (
|
||||||
|
<Text role="status">{t("bank.loading")}</Text>
|
||||||
|
)}
|
||||||
|
{categories.isError && (
|
||||||
|
<BankFeedback
|
||||||
|
loadingError
|
||||||
|
error={categories.error}
|
||||||
|
cached={Boolean(categories.data)}
|
||||||
|
retry={() => void categories.refetch()}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<CategoryFields />
|
||||||
|
{error ? (
|
||||||
|
<>
|
||||||
|
<BankFeedback error={error} />
|
||||||
|
{editing && (
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
onClick={async () => {
|
||||||
|
const response = await categories.refetch();
|
||||||
|
if (response.error) setError(response.error);
|
||||||
|
else
|
||||||
|
setLatest(
|
||||||
|
response.data?.find((c) => c.id === editing.id),
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("bank.reloadRecord")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
{latest && (
|
||||||
|
<>
|
||||||
|
<Text>{t("bank.versionHint", { details: latest.name })}</Text>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
setEditing(latest);
|
||||||
|
setLatest(undefined);
|
||||||
|
setError(undefined);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("bank.adoptVersion", { version: latest.version })}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<Group>
|
||||||
|
<Button type="submit" loading={pending}>
|
||||||
|
{t(editing ? "bank.save" : "bank.addCategory")}
|
||||||
|
</Button>
|
||||||
|
{editing && (
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
onClick={() => {
|
||||||
|
setEditing(undefined);
|
||||||
|
methods.reset({ name: "" });
|
||||||
|
setError(undefined);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("bank.cancel")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button variant="default" onClick={() => setOpened(false)}>
|
||||||
|
{t("bank.close")}
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
</Stack>
|
||||||
|
</fieldset>
|
||||||
|
</form>
|
||||||
|
</FormProvider>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { CategoryManager };
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
function useBankFormFocus() {
|
||||||
|
const [trigger] = useState(() => document.activeElement);
|
||||||
|
useEffect(
|
||||||
|
() => () => {
|
||||||
|
queueMicrotask(() => {
|
||||||
|
if (trigger instanceof HTMLElement && trigger.isConnected)
|
||||||
|
trigger.focus();
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[trigger],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { useBankFormFocus };
|
||||||
@@ -1,6 +1,16 @@
|
|||||||
import { apiQueryClient, useAuthenticatedQuery } from "@/shared/api";
|
import {
|
||||||
|
apiQueryClient,
|
||||||
|
type paths,
|
||||||
|
useAuthenticatedQuery,
|
||||||
|
} from "@/shared/api";
|
||||||
|
|
||||||
type BondPeriod = "month" | "halfYear" | "year" | "all";
|
type BondPeriod = NonNullable<
|
||||||
|
NonNullable<
|
||||||
|
paths["/api/v1/bonds/{uid}/candles"]["get"]["parameters"]["query"]
|
||||||
|
>["period"]
|
||||||
|
>;
|
||||||
|
|
||||||
|
const BOND_STALE_TIME_MS = 30_000;
|
||||||
|
|
||||||
function useBondSearch(query: string) {
|
function useBondSearch(query: string) {
|
||||||
return useAuthenticatedQuery({
|
return useAuthenticatedQuery({
|
||||||
@@ -8,7 +18,7 @@ function useBondSearch(query: string) {
|
|||||||
params: { query: { query } },
|
params: { query: { query } },
|
||||||
}),
|
}),
|
||||||
enabled: query.length >= 2,
|
enabled: query.length >= 2,
|
||||||
staleTime: 30_000,
|
staleTime: BOND_STALE_TIME_MS,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function bondQueryOptions(uid: string) {
|
function bondQueryOptions(uid: string) {
|
||||||
@@ -16,7 +26,7 @@ function bondQueryOptions(uid: string) {
|
|||||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}", {
|
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}", {
|
||||||
params: { path: { uid } },
|
params: { path: { uid } },
|
||||||
}),
|
}),
|
||||||
staleTime: 30_000,
|
staleTime: BOND_STALE_TIME_MS,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,7 +45,7 @@ function useBond(identifier: string) {
|
|||||||
params: { path: { ticker: identifier } },
|
params: { path: { ticker: identifier } },
|
||||||
}),
|
}),
|
||||||
enabled: Boolean(identifier) && !isUid,
|
enabled: Boolean(identifier) && !isUid,
|
||||||
staleTime: 30_000,
|
staleTime: BOND_STALE_TIME_MS,
|
||||||
});
|
});
|
||||||
return isUid ? byUid : byTicker;
|
return isUid ? byUid : byTicker;
|
||||||
}
|
}
|
||||||
@@ -45,7 +55,7 @@ function useBondMetrics(uid: string) {
|
|||||||
params: { path: { uid } },
|
params: { path: { uid } },
|
||||||
}),
|
}),
|
||||||
enabled: Boolean(uid),
|
enabled: Boolean(uid),
|
||||||
staleTime: 30_000,
|
staleTime: BOND_STALE_TIME_MS,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function useBondQuote(uid: string) {
|
function useBondQuote(uid: string) {
|
||||||
@@ -54,7 +64,7 @@ function useBondQuote(uid: string) {
|
|||||||
params: { path: { uid } },
|
params: { path: { uid } },
|
||||||
}),
|
}),
|
||||||
enabled: Boolean(uid),
|
enabled: Boolean(uid),
|
||||||
staleTime: 30_000,
|
staleTime: BOND_STALE_TIME_MS,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function useBondCandles(uid: string, period: BondPeriod) {
|
function useBondCandles(uid: string, period: BondPeriod) {
|
||||||
@@ -63,7 +73,7 @@ function useBondCandles(uid: string, period: BondPeriod) {
|
|||||||
params: { path: { uid }, query: { period } },
|
params: { path: { uid }, query: { period } },
|
||||||
}),
|
}),
|
||||||
enabled: Boolean(uid),
|
enabled: Boolean(uid),
|
||||||
staleTime: 30_000,
|
staleTime: BOND_STALE_TIME_MS,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function useBondPosition(uid: string) {
|
function useBondPosition(uid: string) {
|
||||||
@@ -72,7 +82,7 @@ function useBondPosition(uid: string) {
|
|||||||
params: { path: { uid } },
|
params: { path: { uid } },
|
||||||
}),
|
}),
|
||||||
enabled: Boolean(uid),
|
enabled: Boolean(uid),
|
||||||
staleTime: 30_000,
|
staleTime: BOND_STALE_TIME_MS,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function useBondCoupons(uid: string) {
|
function useBondCoupons(uid: string) {
|
||||||
@@ -81,7 +91,7 @@ function useBondCoupons(uid: string) {
|
|||||||
params: { path: { uid } },
|
params: { path: { uid } },
|
||||||
}),
|
}),
|
||||||
enabled: Boolean(uid),
|
enabled: Boolean(uid),
|
||||||
staleTime: 30_000,
|
staleTime: BOND_STALE_TIME_MS,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ function formatShare(
|
|||||||
if (!numerator || !denominator) return null;
|
if (!numerator || !denominator) return null;
|
||||||
const total = Number(denominator.value);
|
const total = Number(denominator.value);
|
||||||
if (!Number.isFinite(total) || total <= 0) return null;
|
if (!Number.isFinite(total) || total <= 0) return null;
|
||||||
|
// biome-ignore lint/style/noMagicNumbers: obvious conversion of a ratio to percent.
|
||||||
const percent = (Number(numerator.value) / total) * 100;
|
const percent = (Number(numerator.value) / total) * 100;
|
||||||
if (!Number.isFinite(percent)) return null;
|
if (!Number.isFinite(percent)) return null;
|
||||||
const rounded = new Intl.NumberFormat("ru-RU", {
|
const rounded = new Intl.NumberFormat("ru-RU", {
|
||||||
|
|||||||
@@ -1,10 +1,17 @@
|
|||||||
import {
|
import {
|
||||||
apiQueryClient,
|
apiQueryClient,
|
||||||
|
type paths,
|
||||||
useAuthenticatedQueries,
|
useAuthenticatedQueries,
|
||||||
useAuthenticatedQuery,
|
useAuthenticatedQuery,
|
||||||
} from "@/shared/api";
|
} from "@/shared/api";
|
||||||
|
|
||||||
type StockPeriod = "month" | "halfYear" | "year" | "all";
|
type StockPeriod = NonNullable<
|
||||||
|
NonNullable<
|
||||||
|
paths["/api/v1/stocks/{uid}/candles"]["get"]["parameters"]["query"]
|
||||||
|
>["period"]
|
||||||
|
>;
|
||||||
|
|
||||||
|
const STOCK_STALE_TIME_MS = 30_000;
|
||||||
|
|
||||||
function useStockSearch(query: string) {
|
function useStockSearch(query: string) {
|
||||||
return useAuthenticatedQuery({
|
return useAuthenticatedQuery({
|
||||||
@@ -12,7 +19,7 @@ function useStockSearch(query: string) {
|
|||||||
params: { query: { query } },
|
params: { query: { query } },
|
||||||
}),
|
}),
|
||||||
enabled: query.length >= 2,
|
enabled: query.length >= 2,
|
||||||
staleTime: 30_000,
|
staleTime: STOCK_STALE_TIME_MS,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function stockQueryOptions(uid: string) {
|
function stockQueryOptions(uid: string) {
|
||||||
@@ -20,7 +27,7 @@ function stockQueryOptions(uid: string) {
|
|||||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}", {
|
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}", {
|
||||||
params: { path: { uid } },
|
params: { path: { uid } },
|
||||||
}),
|
}),
|
||||||
staleTime: 30_000,
|
staleTime: STOCK_STALE_TIME_MS,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,7 +54,7 @@ function useStock(identifier: string) {
|
|||||||
params: { path: { ticker: identifier } },
|
params: { path: { ticker: identifier } },
|
||||||
}),
|
}),
|
||||||
enabled: Boolean(identifier) && !isUid,
|
enabled: Boolean(identifier) && !isUid,
|
||||||
staleTime: 30_000,
|
staleTime: STOCK_STALE_TIME_MS,
|
||||||
});
|
});
|
||||||
return isUid ? byUid : byTicker;
|
return isUid ? byUid : byTicker;
|
||||||
}
|
}
|
||||||
@@ -57,7 +64,7 @@ function useStockQuote(uid: string) {
|
|||||||
params: { path: { uid } },
|
params: { path: { uid } },
|
||||||
}),
|
}),
|
||||||
enabled: Boolean(uid),
|
enabled: Boolean(uid),
|
||||||
staleTime: 30_000,
|
staleTime: STOCK_STALE_TIME_MS,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function useStockCandles(uid: string, period: StockPeriod) {
|
function useStockCandles(uid: string, period: StockPeriod) {
|
||||||
@@ -66,7 +73,7 @@ function useStockCandles(uid: string, period: StockPeriod) {
|
|||||||
params: { path: { uid }, query: { period } },
|
params: { path: { uid }, query: { period } },
|
||||||
}),
|
}),
|
||||||
enabled: Boolean(uid),
|
enabled: Boolean(uid),
|
||||||
staleTime: 30_000,
|
staleTime: STOCK_STALE_TIME_MS,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function useStockPosition(uid: string) {
|
function useStockPosition(uid: string) {
|
||||||
@@ -75,7 +82,7 @@ function useStockPosition(uid: string) {
|
|||||||
params: { path: { uid } },
|
params: { path: { uid } },
|
||||||
}),
|
}),
|
||||||
enabled: Boolean(uid),
|
enabled: Boolean(uid),
|
||||||
staleTime: 30_000,
|
staleTime: STOCK_STALE_TIME_MS,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function useStockCompany(uid: string) {
|
function useStockCompany(uid: string) {
|
||||||
@@ -84,7 +91,7 @@ function useStockCompany(uid: string) {
|
|||||||
params: { path: { uid } },
|
params: { path: { uid } },
|
||||||
}),
|
}),
|
||||||
enabled: Boolean(uid),
|
enabled: Boolean(uid),
|
||||||
staleTime: 30_000,
|
staleTime: STOCK_STALE_TIME_MS,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function useStockDividends(uid: string) {
|
function useStockDividends(uid: string) {
|
||||||
@@ -93,7 +100,7 @@ function useStockDividends(uid: string) {
|
|||||||
params: { path: { uid } },
|
params: { path: { uid } },
|
||||||
}),
|
}),
|
||||||
enabled: Boolean(uid),
|
enabled: Boolean(uid),
|
||||||
staleTime: 30_000,
|
staleTime: STOCK_STALE_TIME_MS,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ import { createTestQueryClient } from "@/test/query";
|
|||||||
import { server } from "@/test/server";
|
import { server } from "@/test/server";
|
||||||
import { AuthProvider, useAuth } from "./auth";
|
import { AuthProvider, useAuth } from "./auth";
|
||||||
|
|
||||||
|
const bankCardsKey = apiQueryClient.queryOptions("get", "/api/v1/bank-cards", {
|
||||||
|
params: { query: { includeArchived: "false" } },
|
||||||
|
}).queryKey;
|
||||||
|
|
||||||
describe("AuthProvider", () => {
|
describe("AuthProvider", () => {
|
||||||
it("authorizes requests after restoring the initial session", async () => {
|
it("authorizes requests after restoring the initial session", async () => {
|
||||||
let authorization: string | null = null;
|
let authorization: string | null = null;
|
||||||
@@ -54,6 +58,7 @@ describe("AuthProvider", () => {
|
|||||||
server.use(http.post("*/api/v1/auth/refresh", () => HttpResponse.error()));
|
server.use(http.post("*/api/v1/auth/refresh", () => HttpResponse.error()));
|
||||||
const queryClient = createTestQueryClient();
|
const queryClient = createTestQueryClient();
|
||||||
queryClient.setQueryData(["cached-query"], { value: "stale" });
|
queryClient.setQueryData(["cached-query"], { value: "stale" });
|
||||||
|
queryClient.setQueryData(bankCardsKey, [{ id: "bank-card-1" }]);
|
||||||
const wrapper: FC<PropsWithChildren> = (props) => {
|
const wrapper: FC<PropsWithChildren> = (props) => {
|
||||||
const { children } = props;
|
const { children } = props;
|
||||||
|
|
||||||
@@ -70,6 +75,7 @@ describe("AuthProvider", () => {
|
|||||||
expect(result.current.user).toBeNull();
|
expect(result.current.user).toBeNull();
|
||||||
expect(result.current.accessToken).toBeNull();
|
expect(result.current.accessToken).toBeNull();
|
||||||
expect(queryClient.getQueryData(["cached-query"])).toBeUndefined();
|
expect(queryClient.getQueryData(["cached-query"])).toBeUndefined();
|
||||||
|
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("keeps the original protected 401 when serialized refresh has a transport error", async () => {
|
it("keeps the original protected 401 when serialized refresh has a transport error", async () => {
|
||||||
@@ -90,6 +96,7 @@ describe("AuthProvider", () => {
|
|||||||
);
|
);
|
||||||
const queryClient = createTestQueryClient();
|
const queryClient = createTestQueryClient();
|
||||||
queryClient.setQueryData(["cached-query"], { value: "stale" });
|
queryClient.setQueryData(["cached-query"], { value: "stale" });
|
||||||
|
queryClient.setQueryData(bankCardsKey, [{ id: "bank-card-1" }]);
|
||||||
const wrapper: FC<PropsWithChildren> = (props) => {
|
const wrapper: FC<PropsWithChildren> = (props) => {
|
||||||
const { children } = props;
|
const { children } = props;
|
||||||
|
|
||||||
@@ -110,6 +117,7 @@ describe("AuthProvider", () => {
|
|||||||
await waitFor(() => expect(result.current.user).toBeNull());
|
await waitFor(() => expect(result.current.user).toBeNull());
|
||||||
expect(result.current.accessToken).toBeNull();
|
expect(result.current.accessToken).toBeNull();
|
||||||
expect(queryClient.getQueryData(["cached-query"])).toBeUndefined();
|
expect(queryClient.getQueryData(["cached-query"])).toBeUndefined();
|
||||||
|
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("clears connection status and financial cache independently on logout", async () => {
|
it("clears connection status and financial cache independently on logout", async () => {
|
||||||
@@ -136,6 +144,7 @@ describe("AuthProvider", () => {
|
|||||||
connectedAt: "2026-08-14T00:00:00Z",
|
connectedAt: "2026-08-14T00:00:00Z",
|
||||||
});
|
});
|
||||||
queryClient.setQueryData(portfolioKey, { source: "current-connection" });
|
queryClient.setQueryData(portfolioKey, { source: "current-connection" });
|
||||||
|
queryClient.setQueryData(bankCardsKey, [{ id: "bank-card-1" }]);
|
||||||
const wrapper: FC<PropsWithChildren> = (props) => {
|
const wrapper: FC<PropsWithChildren> = (props) => {
|
||||||
const { children } = props;
|
const { children } = props;
|
||||||
return (
|
return (
|
||||||
@@ -147,11 +156,15 @@ describe("AuthProvider", () => {
|
|||||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||||
await waitFor(() => expect(result.current.accessToken).toBe("test-token"));
|
await waitFor(() => expect(result.current.accessToken).toBe("test-token"));
|
||||||
|
|
||||||
|
expect(queryClient.getQueryData(bankCardsKey)).toEqual([
|
||||||
|
{ id: "bank-card-1" },
|
||||||
|
]);
|
||||||
await act(() => result.current.logout());
|
await act(() => result.current.logout());
|
||||||
|
|
||||||
expect(result.current.user).toBeNull();
|
expect(result.current.user).toBeNull();
|
||||||
expect(result.current.accessToken).toBeNull();
|
expect(result.current.accessToken).toBeNull();
|
||||||
expect(queryClient.getQueryData(statusKey)).toBeUndefined();
|
expect(queryClient.getQueryData(statusKey)).toBeUndefined();
|
||||||
expect(queryClient.getQueryData(portfolioKey)).toBeUndefined();
|
expect(queryClient.getQueryData(portfolioKey)).toBeUndefined();
|
||||||
|
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { validationMessage } from "@/shared/i18n";
|
import { validationMessage } from "@/shared/i18n";
|
||||||
|
|
||||||
|
const ASCII_SPACE = 32;
|
||||||
|
const ASCII_DELETE = 127;
|
||||||
|
const MAX_EMAIL_LENGTH = 254;
|
||||||
|
const MIN_PASSWORD_BYTES = 12;
|
||||||
|
const MAX_PASSWORD_BYTES = 72;
|
||||||
|
|
||||||
function isEmailCharacterInvalid(character: string): boolean {
|
function isEmailCharacterInvalid(character: string): boolean {
|
||||||
return (
|
return (
|
||||||
/\s/.test(character) ||
|
/\s/.test(character) ||
|
||||||
character.charCodeAt(0) < 32 ||
|
character.charCodeAt(0) < ASCII_SPACE ||
|
||||||
character.charCodeAt(0) === 127
|
character.charCodeAt(0) === ASCII_DELETE
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -13,21 +19,21 @@ const email = z
|
|||||||
.string()
|
.string()
|
||||||
.trim()
|
.trim()
|
||||||
.toLowerCase()
|
.toLowerCase()
|
||||||
.max(254)
|
.max(MAX_EMAIL_LENGTH)
|
||||||
.refine(
|
.refine(
|
||||||
(value) =>
|
(value) =>
|
||||||
value.split("@").length === 2 &&
|
value.split("@").length === 2 &&
|
||||||
value.split("@").every(Boolean) &&
|
value.split("@").every(Boolean) &&
|
||||||
!value.split("").some(isEmailCharacterInvalid),
|
!value.split("").some(isEmailCharacterInvalid),
|
||||||
validationMessage("auth.validation.invalidEmail"),
|
{ error: validationMessage("auth.validation.invalidEmail") },
|
||||||
);
|
);
|
||||||
const password = z
|
const password = z
|
||||||
.string()
|
.string()
|
||||||
.refine(
|
.refine(
|
||||||
(value) =>
|
(value) =>
|
||||||
new TextEncoder().encode(value).length >= 12 &&
|
new TextEncoder().encode(value).length >= MIN_PASSWORD_BYTES &&
|
||||||
new TextEncoder().encode(value).length <= 72,
|
new TextEncoder().encode(value).length <= MAX_PASSWORD_BYTES,
|
||||||
validationMessage("auth.validation.invalidPasswordLength"),
|
{ error: validationMessage("auth.validation.invalidPasswordLength") },
|
||||||
);
|
);
|
||||||
|
|
||||||
const loginSchema = z.object({
|
const loginSchema = z.object({
|
||||||
@@ -37,10 +43,10 @@ const loginSchema = z.object({
|
|||||||
});
|
});
|
||||||
const registerSchema = loginSchema.refine(
|
const registerSchema = loginSchema.refine(
|
||||||
(value) => value.password === value.passwordConfirmation,
|
(value) => value.password === value.passwordConfirmation,
|
||||||
(value) => ({
|
{
|
||||||
path: ["passwordConfirmation"],
|
path: ["passwordConfirmation"],
|
||||||
...validationMessage("auth.validation.passwordsDoNotMatch")(value),
|
error: validationMessage("auth.validation.passwordsDoNotMatch"),
|
||||||
}),
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
type AuthFormValues = z.input<typeof loginSchema>;
|
type AuthFormValues = z.input<typeof loginSchema>;
|
||||||
|
|||||||
@@ -14,6 +14,9 @@ import { LoadingSkeleton } from "@/shared/ui";
|
|||||||
import type { SectionState } from "../model/section";
|
import type { SectionState } from "../model/section";
|
||||||
import classes from "./InstrumentDetails.module.css";
|
import classes from "./InstrumentDetails.module.css";
|
||||||
|
|
||||||
|
const CHART_SKELETON_HEIGHT_PX = 280;
|
||||||
|
const SECTION_SKELETON_HEIGHT_PX = 65;
|
||||||
|
|
||||||
type InstrumentSectionProps = PropsWithChildren<{
|
type InstrumentSectionProps = PropsWithChildren<{
|
||||||
title: string;
|
title: string;
|
||||||
state: SectionState;
|
state: SectionState;
|
||||||
@@ -59,7 +62,13 @@ const InstrumentSection: FC<InstrumentSectionProps> = (props) => {
|
|||||||
label={t("stock.loadingSection", { section: props.title })}
|
label={t("stock.loadingSection", { section: props.title })}
|
||||||
>
|
>
|
||||||
<Stack>
|
<Stack>
|
||||||
<Skeleton h={props.large ? 280 : 65} />
|
<Skeleton
|
||||||
|
h={
|
||||||
|
props.large
|
||||||
|
? CHART_SKELETON_HEIGHT_PX
|
||||||
|
: SECTION_SKELETON_HEIGHT_PX
|
||||||
|
}
|
||||||
|
/>
|
||||||
<Skeleton h={14} w="60%" />
|
<Skeleton h={14} w="60%" />
|
||||||
</Stack>
|
</Stack>
|
||||||
</LoadingSkeleton>
|
</LoadingSkeleton>
|
||||||
|
|||||||
@@ -32,6 +32,13 @@ const bondQueryKey = apiQueryClient.queryOptions(
|
|||||||
"/api/v1/bonds/{uid}/position",
|
"/api/v1/bonds/{uid}/position",
|
||||||
{ params: { path: { uid: "e6123145-9665-43e0-8413-cd61b8aa9b13" } } },
|
{ params: { path: { uid: "e6123145-9665-43e0-8413-cd61b8aa9b13" } } },
|
||||||
).queryKey;
|
).queryKey;
|
||||||
|
const bankCardsQueryKey = apiQueryClient.queryOptions(
|
||||||
|
"get",
|
||||||
|
"/api/v1/bank-cards",
|
||||||
|
{
|
||||||
|
params: { query: { includeArchived: "false" } },
|
||||||
|
},
|
||||||
|
).queryKey;
|
||||||
const unrelatedQueryKey = apiQueryClient.queryOptions(
|
const unrelatedQueryKey = apiQueryClient.queryOptions(
|
||||||
"get",
|
"get",
|
||||||
"/api/v1/auth/me",
|
"/api/v1/auth/me",
|
||||||
@@ -66,6 +73,7 @@ function seededClient() {
|
|||||||
client.setQueryData(stockQueryKey, { source: "previous-connection" });
|
client.setQueryData(stockQueryKey, { source: "previous-connection" });
|
||||||
client.setQueryData(bondQueryKey, { source: "previous-connection" });
|
client.setQueryData(bondQueryKey, { source: "previous-connection" });
|
||||||
client.setQueryData(unrelatedQueryKey, { id: "user-1" });
|
client.setQueryData(unrelatedQueryKey, { id: "user-1" });
|
||||||
|
client.setQueryData(bankCardsQueryKey, [{ id: "bank-card-1" }]);
|
||||||
return client;
|
return client;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,6 +94,10 @@ describe("TbankConnectionSection", () => {
|
|||||||
).toBeInTheDocument(),
|
).toBeInTheDocument(),
|
||||||
);
|
);
|
||||||
expect(client.getQueryData(brokerageAccountsQueryKey)).toBeUndefined();
|
expect(client.getQueryData(brokerageAccountsQueryKey)).toBeUndefined();
|
||||||
|
expect(client.getQueryData(bankCardsQueryKey)).toEqual([
|
||||||
|
{ id: "bank-card-1" },
|
||||||
|
]);
|
||||||
|
expect(client.getQueryState(bankCardsQueryKey)?.isInvalidated).toBe(false);
|
||||||
expect(client.getQueryData(portfolioQueryKey)).toBeUndefined();
|
expect(client.getQueryData(portfolioQueryKey)).toBeUndefined();
|
||||||
expect(client.getQueryData(stockQueryKey)).toBeUndefined();
|
expect(client.getQueryData(stockQueryKey)).toBeUndefined();
|
||||||
expect(client.getQueryData(bondQueryKey)).toBeUndefined();
|
expect(client.getQueryData(bondQueryKey)).toBeUndefined();
|
||||||
@@ -114,6 +126,10 @@ describe("TbankConnectionSection", () => {
|
|||||||
expect(client.getQueryData(portfolioQueryKey)).toBeUndefined(),
|
expect(client.getQueryData(portfolioQueryKey)).toBeUndefined(),
|
||||||
);
|
);
|
||||||
expect(client.getQueryData(brokerageAccountsQueryKey)).toBeUndefined();
|
expect(client.getQueryData(brokerageAccountsQueryKey)).toBeUndefined();
|
||||||
|
expect(client.getQueryData(bankCardsQueryKey)).toEqual([
|
||||||
|
{ id: "bank-card-1" },
|
||||||
|
]);
|
||||||
|
expect(client.getQueryState(bankCardsQueryKey)?.isInvalidated).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("commits disconnected status and resets financial queries after deleting", async () => {
|
it("commits disconnected status and resets financial queries after deleting", async () => {
|
||||||
@@ -139,6 +155,10 @@ describe("TbankConnectionSection", () => {
|
|||||||
).toBeInTheDocument(),
|
).toBeInTheDocument(),
|
||||||
);
|
);
|
||||||
expect(client.getQueryData(brokerageAccountsQueryKey)).toBeUndefined();
|
expect(client.getQueryData(brokerageAccountsQueryKey)).toBeUndefined();
|
||||||
|
expect(client.getQueryData(bankCardsQueryKey)).toEqual([
|
||||||
|
{ id: "bank-card-1" },
|
||||||
|
]);
|
||||||
|
expect(client.getQueryState(bankCardsQueryKey)?.isInvalidated).toBe(false);
|
||||||
expect(client.getQueryData(portfolioQueryKey)).toBeUndefined();
|
expect(client.getQueryData(portfolioQueryKey)).toBeUndefined();
|
||||||
expect(client.getQueryData(stockQueryKey)).toBeUndefined();
|
expect(client.getQueryData(stockQueryKey)).toBeUndefined();
|
||||||
expect(client.getQueryData(bondQueryKey)).toBeUndefined();
|
expect(client.getQueryData(bondQueryKey)).toBeUndefined();
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ describe("Upcoming event date filters", () => {
|
|||||||
);
|
);
|
||||||
render(
|
render(
|
||||||
<QueryClientProvider client={createTestQueryClient()}>
|
<QueryClientProvider client={createTestQueryClient()}>
|
||||||
<MantineProvider>
|
<MantineProvider env="test">
|
||||||
<MemoryRouter
|
<MemoryRouter
|
||||||
initialEntries={[
|
initialEntries={[
|
||||||
`/accounts/${accountId}/events?from=2099-02-01&to=2099-02-28`,
|
`/accounts/${accountId}/events?from=2099-02-01&to=2099-02-28`,
|
||||||
@@ -72,31 +72,37 @@ describe("Upcoming event date filters", () => {
|
|||||||
</MantineProvider>
|
</MantineProvider>
|
||||||
</QueryClientProvider>,
|
</QueryClientProvider>,
|
||||||
);
|
);
|
||||||
const from = await screen.findByLabelText("С");
|
const from = await screen.findByLabelText("Период");
|
||||||
const to = screen.getByLabelText("По");
|
expect(from).toHaveTextContent("01.02.2099 – 28.02.2099");
|
||||||
expect(from).toHaveValue("01.02.2099");
|
|
||||||
expect(to).toHaveValue("28.02.2099");
|
|
||||||
expect(screen.getByRole("button", { name: "Применить" })).toBeDisabled();
|
expect(screen.getByRole("button", { name: "Применить" })).toBeDisabled();
|
||||||
expect(searches).toEqual(["?from=2099-02-01&to=2099-02-28"]);
|
expect(searches).toEqual(["?from=2099-02-01&to=2099-02-28"]);
|
||||||
fireEvent.change(from, { target: { value: "10.02.2099" } });
|
fireEvent.click(from);
|
||||||
fireEvent.blur(from);
|
fireEvent.click(
|
||||||
|
await screen.findByRole("button", { name: /10 February 2099/i }),
|
||||||
|
);
|
||||||
|
fireEvent.click(
|
||||||
|
await screen.findByRole("button", { name: /28 February 2099/i }),
|
||||||
|
);
|
||||||
expect(searches).toHaveLength(1);
|
expect(searches).toHaveLength(1);
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Применить" }));
|
fireEvent.click(screen.getByRole("button", { name: "Применить" }));
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(searches.at(-1)).toBe("?from=2099-02-10&to=2099-02-28"),
|
expect(searches.at(-1)).toBe("?from=2099-02-10&to=2099-02-28"),
|
||||||
);
|
);
|
||||||
expect(await screen.findByLabelText("С")).toHaveValue("10.02.2099");
|
expect(await screen.findByLabelText("Период")).toHaveTextContent(
|
||||||
|
"10.02.2099 – 28.02.2099",
|
||||||
|
);
|
||||||
fireEvent.click(screen.getByRole("button", { name: "History back" }));
|
fireEvent.click(screen.getByRole("button", { name: "History back" }));
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(screen.getByLabelText("С")).toHaveValue("01.02.2099"),
|
expect(screen.getByLabelText("Период")).toHaveTextContent(
|
||||||
|
"01.02.2099 – 28.02.2099",
|
||||||
|
),
|
||||||
);
|
);
|
||||||
expect(screen.getByLabelText("URL")).toHaveTextContent(
|
expect(screen.getByLabelText("URL")).toHaveTextContent(
|
||||||
"?from=2099-02-01&to=2099-02-28",
|
"?from=2099-02-01&to=2099-02-28",
|
||||||
);
|
);
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Сбросить" }));
|
fireEvent.click(screen.getByRole("button", { name: "Сбросить" }));
|
||||||
await waitFor(() => expect(searches.at(-1)).toBe(""));
|
await waitFor(() => expect(searches.at(-1)).toBe(""));
|
||||||
expect(await screen.findByLabelText("С")).toHaveValue("");
|
expect(await screen.findByLabelText("Период")).toHaveTextContent("");
|
||||||
expect(screen.getByLabelText("По")).toHaveValue("");
|
|
||||||
expect(screen.getByRole("button", { name: "Применить" })).toBeDisabled();
|
expect(screen.getByRole("button", { name: "Применить" })).toBeDisabled();
|
||||||
expect(
|
expect(
|
||||||
screen.getByText("За выбранный период событий не найдено"),
|
screen.getByText("За выбранный период событий не найдено"),
|
||||||
|
|||||||
@@ -7,22 +7,13 @@ import {
|
|||||||
Text,
|
Text,
|
||||||
Title,
|
Title,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
import { DateInput } from "@mantine/dates";
|
import { DatePickerInput } from "@mantine/dates";
|
||||||
import dayjs from "dayjs";
|
|
||||||
import customParseFormat from "dayjs/plugin/customParseFormat";
|
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { BrokerageEventCard } from "@/entities/brokerage-event";
|
import { BrokerageEventCard } from "@/entities/brokerage-event";
|
||||||
import type { AccountEventsPageViewModel } from "../AccountEventsPage.vm";
|
import type { AccountEventsPageViewModel } from "../AccountEventsPage.vm";
|
||||||
import { AccountEventsPageEmpty } from "./AccountEventsPageEmpty.view";
|
import { AccountEventsPageEmpty } from "./AccountEventsPageEmpty.view";
|
||||||
|
|
||||||
dayjs.extend(customParseFormat);
|
|
||||||
|
|
||||||
const parseDate = (value: string) => {
|
|
||||||
const date = dayjs(value, "DD.MM.YYYY", true);
|
|
||||||
return date.isValid() ? date.format("YYYY-MM-DD") : null;
|
|
||||||
};
|
|
||||||
|
|
||||||
type AccountEventsPageLoadedProps = Extract<
|
type AccountEventsPageLoadedProps = Extract<
|
||||||
AccountEventsPageViewModel,
|
AccountEventsPageViewModel,
|
||||||
{ state: "loaded" }
|
{ state: "loaded" }
|
||||||
@@ -46,25 +37,22 @@ const AccountEventsPageLoaded: FC<AccountEventsPageLoadedProps> = (props) => {
|
|||||||
) : null}
|
) : null}
|
||||||
<Text c="dimmed">{t("events.hint")}</Text>
|
<Text c="dimmed">{t("events.hint")}</Text>
|
||||||
<Group align="end">
|
<Group align="end">
|
||||||
<DateInput
|
<DatePickerInput
|
||||||
label={t("ledger.from")}
|
type="range"
|
||||||
value={props.draftFrom}
|
allowSingleDateInRange
|
||||||
onChange={props.onDraftFromChange}
|
clearable
|
||||||
maxDate={props.draftTo ?? undefined}
|
clearButtonProps={{ "aria-label": t("ledger.clearPeriod") }}
|
||||||
|
label={t("ledger.period")}
|
||||||
|
value={[props.draftFrom, props.draftTo]}
|
||||||
|
onChange={([from, to]) => {
|
||||||
|
props.onDraftFromChange(from);
|
||||||
|
props.onDraftToChange(to);
|
||||||
|
}}
|
||||||
valueFormat="DD.MM.YYYY"
|
valueFormat="DD.MM.YYYY"
|
||||||
dateParser={parseDate}
|
popoverProps={{
|
||||||
allowDeselect
|
returnFocus: true,
|
||||||
popoverProps={{ middlewares: { shift: { crossAxis: true } } }}
|
middlewares: { shift: { crossAxis: true } },
|
||||||
/>
|
}}
|
||||||
<DateInput
|
|
||||||
label={t("ledger.to")}
|
|
||||||
value={props.draftTo}
|
|
||||||
onChange={props.onDraftToChange}
|
|
||||||
minDate={props.draftFrom ?? undefined}
|
|
||||||
valueFormat="DD.MM.YYYY"
|
|
||||||
dateParser={parseDate}
|
|
||||||
allowDeselect
|
|
||||||
popoverProps={{ middlewares: { shift: { crossAxis: true } } }}
|
|
||||||
/>
|
/>
|
||||||
</Group>
|
</Group>
|
||||||
<Group>
|
<Group>
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import type { FC } from "react";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
import { LoadingSkeleton } from "@/shared/ui";
|
||||||
|
|
||||||
|
const skeletonRowIds = ["first", "second", "third", "fourth"];
|
||||||
|
|
||||||
const AccountEventsPageLoading: FC = () => {
|
const AccountEventsPageLoading: FC = () => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
@@ -17,8 +19,8 @@ const AccountEventsPageLoading: FC = () => {
|
|||||||
<Skeleton height={36} width={116} />
|
<Skeleton height={36} width={116} />
|
||||||
<Skeleton height={36} width={108} />
|
<Skeleton height={36} width={108} />
|
||||||
</Group>
|
</Group>
|
||||||
{[0, 1, 2, 3].map((index) => (
|
{skeletonRowIds.map((id) => (
|
||||||
<Skeleton key={index} height={82} radius="md" />
|
<Skeleton key={id} height={82} radius="md" />
|
||||||
))}
|
))}
|
||||||
</LoadingSkeleton>
|
</LoadingSkeleton>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
.fields {
|
.fields {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
grid-template-columns: minmax(0, 1fr);
|
||||||
gap: var(--mantine-spacing-sm);
|
gap: var(--mantine-spacing-sm);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -523,12 +523,10 @@ const LocationProbe: FC = () => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
function inputDate(label: string, value: string) {
|
function selectPeriod() {
|
||||||
const field = screen.getByLabelText(label);
|
fireEvent.click(screen.getByLabelText("Период"));
|
||||||
fireEvent.focus(field);
|
fireEvent.click(screen.getByRole("button", { name: /^2 августа 2026$/i }));
|
||||||
fireEvent.input(field, { target: { value } });
|
fireEvent.click(screen.getByRole("button", { name: /^27 августа 2026$/i }));
|
||||||
fireEvent.blur(field);
|
|
||||||
return field;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function respondWithRequestedPeriod(requests: string[]) {
|
function respondWithRequestedPeriod(requests: string[]) {
|
||||||
@@ -557,9 +555,10 @@ describe("income period and snapshot boundary", () => {
|
|||||||
const requests: string[] = [];
|
const requests: string[] = [];
|
||||||
respondWithRequestedPeriod(requests);
|
respondWithRequestedPeriod(requests);
|
||||||
renderPage();
|
renderPage();
|
||||||
expect(await screen.findByLabelText("С")).toHaveValue("01.08.2026");
|
expect(await screen.findByLabelText("Период")).toHaveTextContent(
|
||||||
expect(screen.getByLabelText("По")).toHaveValue("27.08.2026");
|
"01.08.2026 – 27.08.2026",
|
||||||
inputDate("С", "02.08.2026");
|
);
|
||||||
|
selectPeriod();
|
||||||
expect(requests).toHaveLength(1);
|
expect(requests).toHaveLength(1);
|
||||||
expect(
|
expect(
|
||||||
screen.queryByText("2026-08-01 — 2026-08-27"),
|
screen.queryByText("2026-08-01 — 2026-08-27"),
|
||||||
@@ -573,66 +572,37 @@ describe("income period and snapshot boundary", () => {
|
|||||||
.closest("form") as HTMLFormElement,
|
.closest("form") as HTMLFormElement,
|
||||||
);
|
);
|
||||||
await waitFor(() => expect(requests).toHaveLength(2));
|
await waitFor(() => expect(requests).toHaveLength(2));
|
||||||
expect(await screen.findByLabelText("С")).toHaveValue("02.08.2026");
|
expect(await screen.findByLabelText("Период")).toHaveTextContent(
|
||||||
|
"02.08.2026 – 27.08.2026",
|
||||||
|
);
|
||||||
expect(screen.getByTestId("location")).toHaveTextContent(
|
expect(screen.getByTestId("location")).toHaveTextContent(
|
||||||
"from=2026-08-02&to=2026-08-27",
|
"from=2026-08-02&to=2026-08-27",
|
||||||
);
|
);
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Back" }));
|
fireEvent.click(screen.getByRole("button", { name: "Back" }));
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(screen.getByLabelText("С")).toHaveValue("01.08.2026"),
|
expect(screen.getByLabelText("Период")).toHaveTextContent(
|
||||||
|
"01.08.2026 – 27.08.2026",
|
||||||
|
),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it.each([
|
it("rejects an incomplete range without replacing the URL and allows a single day", async () => {
|
||||||
["С", "", "Введите существующую дату"],
|
|
||||||
["С", "31.02.2026", "Введите существующую дату"],
|
|
||||||
["По", "29.02.2026", "Введите существующую дату"],
|
|
||||||
["По", "2026-08-02", "Введите существующую дату"],
|
|
||||||
["С", "01.01.2099", "Дата не может быть позже"],
|
|
||||||
["По", "01.01.2099", "Дата не может быть позже"],
|
|
||||||
["По", "31.07.2026", "Укажите корректный период"],
|
|
||||||
])(
|
|
||||||
"rejects visible %s=%s without replacing data or URL",
|
|
||||||
async (label, value, error) => {
|
|
||||||
const requests: string[] = [];
|
const requests: string[] = [];
|
||||||
respondWithRequestedPeriod(requests);
|
respondWithRequestedPeriod(requests);
|
||||||
renderPage();
|
renderPage();
|
||||||
await screen.findByLabelText("С");
|
const period = await screen.findByLabelText("Период");
|
||||||
const field = inputDate(label, value);
|
fireEvent.click(period);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /^2 августа 2026$/i }));
|
||||||
|
fireEvent.keyDown(period, { key: "Escape" });
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Применить" }));
|
fireEvent.click(screen.getByRole("button", { name: "Применить" }));
|
||||||
expect(await screen.findByText(new RegExp(error))).toBeInTheDocument();
|
expect(await screen.findByText(/Введите существующую дату/)).toBeVisible();
|
||||||
expect(field).toHaveValue(value);
|
|
||||||
expect(field).toHaveAttribute("aria-invalid", "true");
|
|
||||||
await waitFor(() => expect(field).toHaveFocus());
|
|
||||||
expect(requests).toHaveLength(1);
|
expect(requests).toHaveLength(1);
|
||||||
expect(screen.getByTestId("location")).toHaveTextContent(
|
if (period.getAttribute("aria-expanded") !== "true")
|
||||||
"from=2026-08-01&to=2026-08-27",
|
fireEvent.click(period);
|
||||||
);
|
fireEvent.click(screen.getByRole("button", { name: /^2 августа 2026$/i }));
|
||||||
expect(
|
fireEvent.click(screen.getByRole("button", { name: "Применить" }));
|
||||||
screen.queryByText("2026-08-01 — 2026-08-27"),
|
|
||||||
).not.toBeInTheDocument();
|
|
||||||
expect(screen.getByRole("region", { name: "Выплаты" })).toBeVisible();
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
it("replaces invalid raw text with a calendar choice and closes the calendar with Escape", async () => {
|
|
||||||
respondWithRequestedPeriod([]);
|
|
||||||
renderPage();
|
|
||||||
const from = await screen.findByLabelText("С");
|
|
||||||
act(() => from.focus());
|
|
||||||
fireEvent.input(from, { target: { value: "invalid" } });
|
|
||||||
// The selected month stays available even when the visible draft is invalid.
|
|
||||||
const day = await screen.findByRole("button", {
|
|
||||||
name: /^2 августа 2026$/i,
|
|
||||||
});
|
|
||||||
fireEvent.click(day);
|
|
||||||
expect(from).toHaveValue("02.08.2026");
|
|
||||||
act(() => from.focus());
|
|
||||||
fireEvent.keyDown(from, { key: "Escape" });
|
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(
|
expect(requests.at(-1)).toBe("?from=2026-08-02&to=2026-08-02"),
|
||||||
screen.queryByRole("button", { name: /^2 августа 2026$/i }),
|
|
||||||
).not.toBeInTheDocument(),
|
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -642,19 +612,23 @@ describe("income period and snapshot boundary", () => {
|
|||||||
const requests: string[] = [];
|
const requests: string[] = [];
|
||||||
respondWithRequestedPeriod(requests);
|
respondWithRequestedPeriod(requests);
|
||||||
renderPage("");
|
renderPage("");
|
||||||
expect(await screen.findByLabelText("С")).toHaveValue("01.09.2026");
|
expect(await screen.findByLabelText("Период")).toHaveTextContent(
|
||||||
expect(screen.getByLabelText("По")).toHaveValue("01.09.2026");
|
"01.09.2026 – 01.09.2026",
|
||||||
inputDate("С", "wrong");
|
);
|
||||||
|
fireEvent.click(screen.getByLabelText("Период"));
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /^1 сентября 2026$/i }));
|
||||||
|
fireEvent.keyDown(screen.getByLabelText("Период"), { key: "Escape" });
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Применить" }));
|
fireEvent.click(screen.getByRole("button", { name: "Применить" }));
|
||||||
await screen.findByText(/Введите существующую дату/);
|
await screen.findByText(/Введите существующую дату/);
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Сбросить" }));
|
fireEvent.click(screen.getByRole("button", { name: "Сбросить" }));
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(screen.getByLabelText("С")).toHaveValue("01.09.2026"),
|
expect(screen.getByLabelText("Период")).toHaveTextContent(
|
||||||
|
"01.09.2026 – 01.09.2026",
|
||||||
|
),
|
||||||
);
|
);
|
||||||
expect(
|
expect(
|
||||||
screen.queryByText(/Введите существующую дату/),
|
screen.queryByText(/Введите существующую дату/),
|
||||||
).not.toBeInTheDocument();
|
).not.toBeInTheDocument();
|
||||||
expect(screen.getByLabelText("По")).toHaveValue("01.09.2026");
|
|
||||||
expect(screen.getByTestId("location")).toHaveTextContent(
|
expect(screen.getByTestId("location")).toHaveTextContent(
|
||||||
"from=2026-09-01&to=2026-09-01",
|
"from=2026-09-01&to=2026-09-01",
|
||||||
);
|
);
|
||||||
@@ -664,8 +638,8 @@ describe("income period and snapshot boundary", () => {
|
|||||||
it("keeps valid data and draft during refetch, warns on failure and retries", async () => {
|
it("keeps valid data and draft during refetch, warns on failure and retries", async () => {
|
||||||
respondWithRequestedPeriod([]);
|
respondWithRequestedPeriod([]);
|
||||||
const { queryClient } = renderPage();
|
const { queryClient } = renderPage();
|
||||||
await screen.findByLabelText("С");
|
await screen.findByLabelText("Период");
|
||||||
inputDate("С", "02.08.2026");
|
selectPeriod();
|
||||||
let release!: () => void;
|
let release!: () => void;
|
||||||
const pending = new Promise<void>((resolve) => {
|
const pending = new Promise<void>((resolve) => {
|
||||||
release = resolve;
|
release = resolve;
|
||||||
@@ -686,7 +660,9 @@ describe("income period and snapshot boundary", () => {
|
|||||||
await screen.findByRole("status", { name: "Обновляем пассивный доход" }),
|
await screen.findByRole("status", { name: "Обновляем пассивный доход" }),
|
||||||
).toBeInTheDocument();
|
).toBeInTheDocument();
|
||||||
expect(screen.getByRole("region", { name: "Выплаты" })).toBeVisible();
|
expect(screen.getByRole("region", { name: "Выплаты" })).toBeVisible();
|
||||||
expect(screen.getByLabelText("С")).toHaveValue("02.08.2026");
|
expect(screen.getByLabelText("Период")).toHaveTextContent(
|
||||||
|
"02.08.2026 – 27.08.2026",
|
||||||
|
);
|
||||||
release();
|
release();
|
||||||
expect(
|
expect(
|
||||||
await screen.findByText(/Показан последний загруженный результат/),
|
await screen.findByText(/Показан последний загруженный результат/),
|
||||||
@@ -699,13 +675,15 @@ describe("income period and snapshot boundary", () => {
|
|||||||
screen.queryByText(/Показан последний загруженный результат/),
|
screen.queryByText(/Показан последний загруженный результат/),
|
||||||
).not.toBeInTheDocument(),
|
).not.toBeInTheDocument(),
|
||||||
);
|
);
|
||||||
expect(screen.getByLabelText("С")).toHaveValue("02.08.2026");
|
expect(screen.getByLabelText("Период")).toHaveTextContent(
|
||||||
|
"02.08.2026 – 27.08.2026",
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("shows busy skeleton for a new uncached period without relabeling the previous result", async () => {
|
it("shows busy skeleton for a new uncached period without relabeling the previous result", async () => {
|
||||||
respondWithRequestedPeriod([]);
|
respondWithRequestedPeriod([]);
|
||||||
renderPage();
|
renderPage();
|
||||||
await screen.findByLabelText("С");
|
await screen.findByLabelText("Период");
|
||||||
let release!: () => void;
|
let release!: () => void;
|
||||||
const pending = new Promise<void>((resolve) => {
|
const pending = new Promise<void>((resolve) => {
|
||||||
release = resolve;
|
release = resolve;
|
||||||
@@ -722,7 +700,7 @@ describe("income period and snapshot boundary", () => {
|
|||||||
},
|
},
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
inputDate("С", "02.08.2026");
|
selectPeriod();
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Применить" }));
|
fireEvent.click(screen.getByRole("button", { name: "Применить" }));
|
||||||
expect(
|
expect(
|
||||||
await screen.findByRole("status", { name: "Загрузка" }),
|
await screen.findByRole("status", { name: "Загрузка" }),
|
||||||
@@ -734,7 +712,9 @@ describe("income period and snapshot boundary", () => {
|
|||||||
screen.queryByText("2026-08-02 — 2026-08-27"),
|
screen.queryByText("2026-08-02 — 2026-08-27"),
|
||||||
).not.toBeInTheDocument();
|
).not.toBeInTheDocument();
|
||||||
release();
|
release();
|
||||||
expect(await screen.findByLabelText("С")).toHaveValue("02.08.2026");
|
expect(await screen.findByLabelText("Период")).toHaveTextContent(
|
||||||
|
"02.08.2026 – 27.08.2026",
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("shows one flat payment card per entry in server order without currency or instrument groups", () => {
|
it("shows one flat payment card per entry in server order without currency or instrument groups", () => {
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import { type IncomeAnalytics, useIncomeAnalytics } from "@/entities/income";
|
|||||||
import { validationMessage } from "@/shared/i18n";
|
import { validationMessage } from "@/shared/i18n";
|
||||||
import { formatDate } from "@/shared/lib";
|
import { formatDate } from "@/shared/lib";
|
||||||
|
|
||||||
|
const ISO_MONTH_LENGTH = 7;
|
||||||
|
|
||||||
type IncomePeriod = { from: string; to: string };
|
type IncomePeriod = { from: string; to: string };
|
||||||
type IncomeForm = IncomePeriod;
|
type IncomeForm = IncomePeriod;
|
||||||
|
|
||||||
@@ -42,14 +44,16 @@ type AccountIncomePageViewModel =
|
|||||||
const datePattern = /^\d{4}-\d{2}-\d{2}$/;
|
const datePattern = /^\d{4}-\d{2}-\d{2}$/;
|
||||||
const draftDate = z
|
const draftDate = z
|
||||||
.string()
|
.string()
|
||||||
|
.refine((value) => parseDraftDate(value) !== null, {
|
||||||
|
error: validationMessage("income.validation.date"),
|
||||||
|
})
|
||||||
.refine(
|
.refine(
|
||||||
(value) => parseDraftDate(value) !== null,
|
(value) => {
|
||||||
validationMessage("income.validation.date"),
|
|
||||||
)
|
|
||||||
.refine((value) => {
|
|
||||||
const date = parseDraftDate(value);
|
const date = parseDraftDate(value);
|
||||||
return !date || date <= moscowDate(new Date());
|
return !date || date <= moscowDate(new Date());
|
||||||
}, validationMessage("income.validation.future"));
|
},
|
||||||
|
{ error: validationMessage("income.validation.future") },
|
||||||
|
);
|
||||||
const incomeFormSchema = z.object({ from: draftDate, to: draftDate }).refine(
|
const incomeFormSchema = z.object({ from: draftDate, to: draftDate }).refine(
|
||||||
({ from, to }) => {
|
({ from, to }) => {
|
||||||
const start = parseDraftDate(from);
|
const start = parseDraftDate(from);
|
||||||
@@ -99,7 +103,7 @@ const useAccountIncomePageViewModel = (
|
|||||||
const onReset = () => {
|
const onReset = () => {
|
||||||
const next = defaultPeriod();
|
const next = defaultPeriod();
|
||||||
form.reset(draftPeriod(next));
|
form.reset(draftPeriod(next));
|
||||||
// DateInput retains raw text while its calendar is open; reset that UI state too.
|
// Reset the open calendar along with the form.
|
||||||
setFormRevision((revision) => revision + 1);
|
setFormRevision((revision) => revision + 1);
|
||||||
setSearchParams(next, { replace: true });
|
setSearchParams(next, { replace: true });
|
||||||
};
|
};
|
||||||
@@ -143,7 +147,7 @@ function draftPeriod(period: IncomePeriod): IncomeForm {
|
|||||||
|
|
||||||
function defaultPeriod(): IncomePeriod {
|
function defaultPeriod(): IncomePeriod {
|
||||||
const today = moscowDate(new Date());
|
const today = moscowDate(new Date());
|
||||||
return { from: `${today.slice(0, 7)}-01`, to: today };
|
return { from: `${today.slice(0, ISO_MONTH_LENGTH)}-01`, to: today };
|
||||||
}
|
}
|
||||||
|
|
||||||
function validPeriod(period: IncomePeriod): period is IncomePeriod {
|
function validPeriod(period: IncomePeriod): period is IncomePeriod {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Button, Paper, Stack, Text } from "@mantine/core";
|
import { Button, Paper, Stack, Text } from "@mantine/core";
|
||||||
import { DateInput } from "@mantine/dates";
|
import { DatePickerInput } from "@mantine/dates";
|
||||||
import type { FC, FormEventHandler } from "react";
|
import type { FC, FormEventHandler } from "react";
|
||||||
import { Controller, useFormContext, useWatch } from "react-hook-form";
|
import { useController, useFormContext, useWatch } from "react-hook-form";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import classes from "../AccountIncomePage.module.css";
|
import classes from "../AccountIncomePage.module.css";
|
||||||
import {
|
import {
|
||||||
@@ -22,6 +22,8 @@ const IncomePeriodForm: FC<IncomePeriodFormProps> = (props) => {
|
|||||||
control,
|
control,
|
||||||
formState: { isSubmitting },
|
formState: { isSubmitting },
|
||||||
} = useFormContext<IncomeForm>();
|
} = useFormContext<IncomeForm>();
|
||||||
|
const fromField = useController({ control, name: "from" });
|
||||||
|
const toField = useController({ control, name: "to" });
|
||||||
const [from, to] = useWatch({ control, name: ["from", "to"] });
|
const [from, to] = useWatch({ control, name: ["from", "to"] });
|
||||||
const today = moscowDate(new Date());
|
const today = moscowDate(new Date());
|
||||||
const start = parseDraftDate(from);
|
const start = parseDraftDate(from);
|
||||||
@@ -37,39 +39,34 @@ const IncomePeriodForm: FC<IncomePeriodFormProps> = (props) => {
|
|||||||
<Stack gap="sm">
|
<Stack gap="sm">
|
||||||
<Text fw={700}>{t("income.period")}</Text>
|
<Text fw={700}>{t("income.period")}</Text>
|
||||||
<div className={classes.fields}>
|
<div className={classes.fields}>
|
||||||
{(["from", "to"] as const).map((name) => (
|
<DatePickerInput
|
||||||
<Controller
|
type="range"
|
||||||
key={name}
|
allowSingleDateInRange
|
||||||
name={name}
|
clearable
|
||||||
control={control}
|
clearButtonProps={{ "aria-label": t("ledger.clearPeriod") }}
|
||||||
render={({ field, fieldState }) => (
|
ref={fromField.field.ref}
|
||||||
<DateInput
|
label={t("income.period")}
|
||||||
ref={field.ref}
|
|
||||||
label={t(`income.${name}`)}
|
|
||||||
placeholder={t("income.datePlaceholder")}
|
|
||||||
valueFormat="DD.MM.YYYY"
|
valueFormat="DD.MM.YYYY"
|
||||||
value={parseDraftDate(field.value)}
|
value={[start, end]}
|
||||||
dateParser={parseDraftDate}
|
onChange={([from, to]) => {
|
||||||
fixOnBlur={false}
|
fromField.field.onChange(from ? formatDraftDate(from) : "");
|
||||||
popoverProps={{ middlewares: { shift: { crossAxis: true } } }}
|
toField.field.onChange(to ? formatDraftDate(to) : "");
|
||||||
onInput={(event) => field.onChange(event.currentTarget.value)}
|
|
||||||
onChange={(value) =>
|
|
||||||
field.onChange(value ? formatDraftDate(value) : "")
|
|
||||||
}
|
|
||||||
onBlur={(event) => {
|
|
||||||
field.onChange(event.currentTarget.value);
|
|
||||||
field.onBlur();
|
|
||||||
}}
|
}}
|
||||||
minDate={
|
onBlur={() => {
|
||||||
name === "to" && start && start <= today ? start : undefined
|
fromField.field.onBlur();
|
||||||
|
toField.field.onBlur();
|
||||||
|
}}
|
||||||
|
maxDate={today}
|
||||||
|
error={
|
||||||
|
fromField.fieldState.error?.message ??
|
||||||
|
toField.fieldState.error?.message
|
||||||
}
|
}
|
||||||
maxDate={name === "from" && end && end <= today ? end : today}
|
|
||||||
error={fieldState.error?.message}
|
|
||||||
disabled={isSubmitting}
|
disabled={isSubmitting}
|
||||||
|
popoverProps={{
|
||||||
|
returnFocus: true,
|
||||||
|
middlewares: { shift: { crossAxis: true } },
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
<div className={classes.actions}>
|
<div className={classes.actions}>
|
||||||
<Button type="submit" loading={isSubmitting}>
|
<Button type="submit" loading={isSubmitting}>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import {
|
|||||||
Stack,
|
Stack,
|
||||||
Title,
|
Title,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
import { DateInput } from "@mantine/dates";
|
import { DatePickerInput } from "@mantine/dates";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import {
|
||||||
@@ -25,21 +25,6 @@ type AccountOperationsPageLoadedProps = Extract<
|
|||||||
|
|
||||||
const operationCategorySet = new Set<string>(operationCategories);
|
const operationCategorySet = new Set<string>(operationCategories);
|
||||||
|
|
||||||
function toDateValue(value: string | null): Date | null {
|
|
||||||
if (!value) return null;
|
|
||||||
const [year, month, day] = value.split("-").map(Number);
|
|
||||||
return new Date(year, month - 1, day);
|
|
||||||
}
|
|
||||||
|
|
||||||
function fromDateValue(value: Date | string | null): string | null {
|
|
||||||
if (!value) return null;
|
|
||||||
if (typeof value === "string") return value;
|
|
||||||
const year = value.getFullYear();
|
|
||||||
const month = String(value.getMonth() + 1).padStart(2, "0");
|
|
||||||
const day = String(value.getDate()).padStart(2, "0");
|
|
||||||
return `${year}-${month}-${day}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function fromMultiSelectValue(value: string[]) {
|
function fromMultiSelectValue(value: string[]) {
|
||||||
return value.filter((item): item is OperationCategory =>
|
return value.filter((item): item is OperationCategory =>
|
||||||
operationCategorySet.has(item),
|
operationCategorySet.has(item),
|
||||||
@@ -87,19 +72,22 @@ const AccountOperationsPageLoaded: FC<AccountOperationsPageLoadedProps> = (
|
|||||||
</Alert>
|
</Alert>
|
||||||
) : null}
|
) : null}
|
||||||
<Group align="end">
|
<Group align="end">
|
||||||
<DateInput
|
<DatePickerInput
|
||||||
label={t("ledger.from")}
|
type="range"
|
||||||
value={toDateValue(draftFrom)}
|
allowSingleDateInRange
|
||||||
onChange={(value) => onDraftFromChange(fromDateValue(value))}
|
clearable
|
||||||
maxDate={toDateValue(draftTo) ?? undefined}
|
clearButtonProps={{ "aria-label": t("ledger.clearPeriod") }}
|
||||||
valueFormat="DD.MM.YYYY"
|
label={t("ledger.period")}
|
||||||
/>
|
value={[draftFrom, draftTo]}
|
||||||
<DateInput
|
onChange={([from, to]) => {
|
||||||
label={t("ledger.to")}
|
onDraftFromChange(from);
|
||||||
value={toDateValue(draftTo)}
|
onDraftToChange(to);
|
||||||
onChange={(value) => onDraftToChange(fromDateValue(value))}
|
}}
|
||||||
minDate={toDateValue(draftFrom) ?? undefined}
|
|
||||||
valueFormat="DD.MM.YYYY"
|
valueFormat="DD.MM.YYYY"
|
||||||
|
popoverProps={{
|
||||||
|
returnFocus: true,
|
||||||
|
middlewares: { shift: { crossAxis: true } },
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</Group>
|
</Group>
|
||||||
<MultiSelect
|
<MultiSelect
|
||||||
@@ -111,6 +99,7 @@ const AccountOperationsPageLoaded: FC<AccountOperationsPageLoadedProps> = (
|
|||||||
onDraftCategoriesChange(fromMultiSelectValue(value))
|
onDraftCategoriesChange(fromMultiSelectValue(value))
|
||||||
}
|
}
|
||||||
clearable
|
clearable
|
||||||
|
clearButtonProps={{ "aria-label": t("ledger.clearPeriod") }}
|
||||||
/>
|
/>
|
||||||
<Group>
|
<Group>
|
||||||
<Button onClick={onApply} disabled={!canApply}>
|
<Button onClick={onApply} disabled={!canApply}>
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import type { FC } from "react";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
import { LoadingSkeleton } from "@/shared/ui";
|
||||||
|
|
||||||
|
const skeletonRowIds = ["first", "second", "third", "fourth"];
|
||||||
|
|
||||||
const AccountOperationsPageLoading: FC = () => {
|
const AccountOperationsPageLoading: FC = () => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
@@ -19,8 +21,8 @@ const AccountOperationsPageLoading: FC = () => {
|
|||||||
<Skeleton height={36} width={110} radius="sm" />
|
<Skeleton height={36} width={110} radius="sm" />
|
||||||
</Group>
|
</Group>
|
||||||
<Stack gap="xs">
|
<Stack gap="xs">
|
||||||
{[0, 1, 2, 3].map((index) => (
|
{skeletonRowIds.map((id) => (
|
||||||
<Skeleton key={index} height={64} radius="md" />
|
<Skeleton key={id} height={64} radius="md" />
|
||||||
))}
|
))}
|
||||||
</Stack>
|
</Stack>
|
||||||
</LoadingSkeleton>
|
</LoadingSkeleton>
|
||||||
|
|||||||
@@ -123,11 +123,13 @@ function emptyProps() {
|
|||||||
describe("AccountPage states", () => {
|
describe("AccountPage states", () => {
|
||||||
it.each(
|
it.each(
|
||||||
["account-1", "all"].flatMap((accountId) =>
|
["account-1", "all"].flatMap((accountId) =>
|
||||||
["STOCK", "BOND"].map((type) => ({ accountId, type })),
|
["STOCK", "BOND"].flatMap((type) =>
|
||||||
|
[true, false].map((hasMetadata) => ({ accountId, type, hasMetadata })),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
)(
|
)(
|
||||||
"links name and logo to the exact issue in $accountId for $type",
|
"keeps portfolio metadata authoritative and links the exact issue in $accountId for $type (metadata: $hasMetadata)",
|
||||||
async ({ accountId, type }) => {
|
async ({ accountId, type, hasMetadata }) => {
|
||||||
const collection = type === "STOCK" ? "stocks" : "bonds";
|
const collection = type === "STOCK" ? "stocks" : "bonds";
|
||||||
const slug = type === "STOCK" ? "SBERP" : "SU26238RMFS4";
|
const slug = type === "STOCK" ? "SBERP" : "SU26238RMFS4";
|
||||||
const uid = "c190ff1f-1447-4227-b543-316332699ca5";
|
const uid = "c190ff1f-1447-4227-b543-316332699ca5";
|
||||||
@@ -136,8 +138,9 @@ describe("AccountPage states", () => {
|
|||||||
...portfolio.positions[0],
|
...portfolio.positions[0],
|
||||||
type,
|
type,
|
||||||
instrumentUid: uid,
|
instrumentUid: uid,
|
||||||
ticker: slug,
|
ticker: hasMetadata ? slug : null,
|
||||||
displayName: "Сбербанк привилегированные",
|
displayName: hasMetadata ? "Сбербанк привилегированные" : "FIGI-2",
|
||||||
|
logoName: hasMetadata ? "vtoraya.png" : null,
|
||||||
};
|
};
|
||||||
server.use(
|
server.use(
|
||||||
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
|
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
|
||||||
@@ -154,7 +157,14 @@ describe("AccountPage states", () => {
|
|||||||
),
|
),
|
||||||
http.get(`*/api/v1/${collection}/:uid`, () => {
|
http.get(`*/api/v1/${collection}/:uid`, () => {
|
||||||
requests();
|
requests();
|
||||||
return HttpResponse.json({ instrumentUid: uid, slug });
|
return HttpResponse.json({
|
||||||
|
instrumentUid: uid,
|
||||||
|
slug,
|
||||||
|
name: "Название из карточки инструмента",
|
||||||
|
ticker: "OTHER-TICKER",
|
||||||
|
isin: "OTHER-ISIN",
|
||||||
|
logoName: "other.png",
|
||||||
|
});
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
configureTestAuth();
|
configureTestAuth();
|
||||||
@@ -171,6 +181,19 @@ describe("AccountPage states", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
expect(requests).toHaveBeenCalledTimes(type === "STOCK" ? 1 : 0);
|
expect(requests).toHaveBeenCalledTimes(type === "STOCK" ? 1 : 0);
|
||||||
|
expect(
|
||||||
|
screen.queryByText("Название из карточки инструмента"),
|
||||||
|
).not.toBeInTheDocument();
|
||||||
|
expect(
|
||||||
|
screen.queryByText(/OTHER-TICKER|OTHER-ISIN/),
|
||||||
|
).not.toBeInTheDocument();
|
||||||
|
const logo = screen.queryByRole("img", { name: position.displayName });
|
||||||
|
if (hasMetadata)
|
||||||
|
expect(logo).toHaveAttribute(
|
||||||
|
"src",
|
||||||
|
"https://invest-brands.cdn-tinkoff.ru/vtorayax160.png",
|
||||||
|
);
|
||||||
|
else expect(logo).not.toBeInTheDocument();
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ import { useStocks } from "@/entities/stock";
|
|||||||
import { apiErrorCode } from "@/shared/api";
|
import { apiErrorCode } from "@/shared/api";
|
||||||
import { formatMoney, instrumentLogoUrl } from "@/shared/lib";
|
import { formatMoney, instrumentLogoUrl } from "@/shared/lib";
|
||||||
|
|
||||||
|
const RECENT_EVENTS_LIMIT = 5;
|
||||||
|
|
||||||
type PositionSectionKind = "stocks" | "bonds" | "other";
|
type PositionSectionKind = "stocks" | "bonds" | "other";
|
||||||
type AccountPageReturnTone = "positive" | "negative";
|
type AccountPageReturnTone = "positive" | "negative";
|
||||||
|
|
||||||
@@ -176,7 +178,7 @@ function toRecentEvents(
|
|||||||
const to = `/accounts/${accountId}/events`;
|
const to = `/accounts/${accountId}/events`;
|
||||||
if (events.isLoading) return { state: "loading", to };
|
if (events.isLoading) return { state: "loading", to };
|
||||||
if (events.isError) return { state: "error", to };
|
if (events.isError) return { state: "error", to };
|
||||||
const items = events.data?.events.slice(0, 5) ?? [];
|
const items = events.data?.events.slice(0, RECENT_EVENTS_LIMIT) ?? [];
|
||||||
if (!items.length) return { state: "empty", to };
|
if (!items.length) return { state: "empty", to };
|
||||||
return { state: "loaded", to, items };
|
return { state: "loaded", to, items };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import type { Portfolio } from "@/entities/portfolio";
|
|||||||
import { formatMoney } from "@/shared/lib";
|
import { formatMoney } from "@/shared/lib";
|
||||||
import { PortfolioStructureView } from "./PortfolioStructure.view";
|
import { PortfolioStructureView } from "./PortfolioStructure.view";
|
||||||
|
|
||||||
|
const MIN_VISIBLE_SHARE_PERCENT = 0.01;
|
||||||
|
|
||||||
// A cached snapshot or an older running server can predate this response field.
|
// A cached snapshot or an older running server can predate this response field.
|
||||||
type PortfolioStructureProps = { structure?: Portfolio["structure"] | null };
|
type PortfolioStructureProps = { structure?: Portfolio["structure"] | null };
|
||||||
|
|
||||||
@@ -45,7 +47,7 @@ const PortfolioStructure: FC<PortfolioStructureProps> = (props) => {
|
|||||||
share:
|
share:
|
||||||
percentage === null
|
percentage === null
|
||||||
? t("portfolio.structure.shareUnavailable")
|
? t("portfolio.structure.shareUnavailable")
|
||||||
: percentage > 0 && percentage < 0.01
|
: percentage > 0 && percentage < MIN_VISIBLE_SHARE_PERCENT
|
||||||
? t("portfolio.structure.smallShare")
|
? t("portfolio.structure.smallShare")
|
||||||
: `${new Intl.NumberFormat("ru-RU", { maximumFractionDigits: 2 }).format(percentage)} %`,
|
: `${new Intl.NumberFormat("ru-RU", { maximumFractionDigits: 2 }).format(percentage)} %`,
|
||||||
value: percentage ?? 0,
|
value: percentage ?? 0,
|
||||||
|
|||||||
@@ -4,10 +4,12 @@ import { useBondSearch } from "@/entities/bond";
|
|||||||
import { apiErrorCode } from "@/shared/api";
|
import { apiErrorCode } from "@/shared/api";
|
||||||
import { instrumentLogoUrl } from "@/shared/lib";
|
import { instrumentLogoUrl } from "@/shared/lib";
|
||||||
|
|
||||||
|
const SEARCH_DEBOUNCE_MS = 300;
|
||||||
|
|
||||||
function useBondsPageVm() {
|
function useBondsPageVm() {
|
||||||
const [params, setParams] = useSearchParams();
|
const [params, setParams] = useSearchParams();
|
||||||
const query = params.get("q") ?? "";
|
const query = params.get("q") ?? "";
|
||||||
const [debounced] = useDebouncedValue(query.trim(), 300);
|
const [debounced] = useDebouncedValue(query.trim(), SEARCH_DEBOUNCE_MS);
|
||||||
const result = useBondSearch(debounced);
|
const result = useBondSearch(debounced);
|
||||||
const waiting = query.trim() !== debounced;
|
const waiting = query.trim() !== debounced;
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
export { CardPage } from "./ui/CardPage";
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
.card {
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 28rem;
|
||||||
|
}
|
||||||
|
.cardActions {
|
||||||
|
position: absolute;
|
||||||
|
top: 4.5rem;
|
||||||
|
right: clamp(1.1rem, 3vw, 1.6rem);
|
||||||
|
padding: 4px;
|
||||||
|
border: 1px solid var(--mantine-color-gray-3);
|
||||||
|
border-radius: var(--mantine-radius-lg);
|
||||||
|
background: var(--mantine-color-white);
|
||||||
|
box-shadow: 0 3px 12px #0000001a;
|
||||||
|
}
|
||||||
|
@media (hover: hover) and (pointer: fine) {
|
||||||
|
.cardActions {
|
||||||
|
opacity: 0;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
.card:hover .cardActions,
|
||||||
|
.card:focus-within .cardActions {
|
||||||
|
opacity: 1;
|
||||||
|
pointer-events: auto;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.wrap {
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.operation {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.operation p {
|
||||||
|
white-space: normal;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.operation > div > div {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
@media (min-width: 36em) {
|
||||||
|
.operation > div:first-child {
|
||||||
|
grid-template-columns: auto minmax(0, 1fr) minmax(0, 40%);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.operations[data-pending] {
|
||||||
|
opacity: 0.55;
|
||||||
|
}
|
||||||
|
@media (pointer: coarse) {
|
||||||
|
.cardActions button {
|
||||||
|
min-width: 36px;
|
||||||
|
min-height: 36px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (prefers-reduced-motion: no-preference) {
|
||||||
|
.cardActions {
|
||||||
|
transition: opacity 180ms ease;
|
||||||
|
}
|
||||||
|
.page button {
|
||||||
|
transition:
|
||||||
|
background-color 180ms ease,
|
||||||
|
color 180ms ease;
|
||||||
|
}
|
||||||
|
.operations {
|
||||||
|
animation: operations-appear 200ms ease-out;
|
||||||
|
transition: opacity 150ms ease;
|
||||||
|
}
|
||||||
|
@keyframes operations-appear {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(4px);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,349 @@
|
|||||||
|
import { MantineProvider } from "@mantine/core";
|
||||||
|
import { QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
fireEvent,
|
||||||
|
render,
|
||||||
|
screen,
|
||||||
|
waitFor,
|
||||||
|
within,
|
||||||
|
} from "@testing-library/react";
|
||||||
|
import { HttpResponse, http } from "msw";
|
||||||
|
import { MemoryRouter, Route, Routes } from "react-router";
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { configureAuthClient } from "@/shared/api";
|
||||||
|
import { createTestQueryClient } from "@/test/query";
|
||||||
|
import { server } from "@/test/server";
|
||||||
|
import { CardPage } from "./CardPage";
|
||||||
|
|
||||||
|
const money = (value: string) => ({ currency: "RUB", value });
|
||||||
|
const card = {
|
||||||
|
id: "a",
|
||||||
|
name: "Повседневная",
|
||||||
|
bankName: null,
|
||||||
|
lastFour: null,
|
||||||
|
balance: money("10000"),
|
||||||
|
openingBalance: money("10000"),
|
||||||
|
openingDate: "2026-01-01",
|
||||||
|
archivedAt: null,
|
||||||
|
version: 1,
|
||||||
|
};
|
||||||
|
const operation = {
|
||||||
|
id: "transfer",
|
||||||
|
kind: "transfer",
|
||||||
|
cardId: "a",
|
||||||
|
cardName: "Повседневная",
|
||||||
|
targetCardId: "b",
|
||||||
|
targetCardName: "Запасная",
|
||||||
|
categoryId: null,
|
||||||
|
categoryName: null,
|
||||||
|
originalExpenseId: null,
|
||||||
|
amount: money("50.01"),
|
||||||
|
availableRefund: null,
|
||||||
|
date: "2026-08-03",
|
||||||
|
description: null,
|
||||||
|
version: 1,
|
||||||
|
createdAt: "2026-08-03T00:00:00Z",
|
||||||
|
};
|
||||||
|
function setup(
|
||||||
|
options: {
|
||||||
|
missing?: boolean;
|
||||||
|
summaryError?: boolean;
|
||||||
|
cardsError?: boolean;
|
||||||
|
} = {},
|
||||||
|
) {
|
||||||
|
configureAuthClient({
|
||||||
|
accessToken: () => "test",
|
||||||
|
refresh: async () => false,
|
||||||
|
clear: () => {},
|
||||||
|
});
|
||||||
|
const requests: string[] = [];
|
||||||
|
const summaryRequests: string[] = [];
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/a", () =>
|
||||||
|
options.missing
|
||||||
|
? HttpResponse.json({ code: "BANK_NOT_FOUND" }, { status: 404 })
|
||||||
|
: HttpResponse.json(card),
|
||||||
|
),
|
||||||
|
http.get("*/api/v1/bank-cards", () =>
|
||||||
|
options.cardsError
|
||||||
|
? HttpResponse.error()
|
||||||
|
: HttpResponse.json([card, { ...card, id: "b", name: "Запасная" }]),
|
||||||
|
),
|
||||||
|
http.get("*/api/v1/bank-cards/a/operations", ({ request }) => {
|
||||||
|
requests.push(new URL(request.url).search);
|
||||||
|
return HttpResponse.json({
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
...operation,
|
||||||
|
id: `operation-${new URL(request.url).searchParams.get("page")}`,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
page: Number(new URL(request.url).searchParams.get("page")),
|
||||||
|
total: 30,
|
||||||
|
hasNext: Number(new URL(request.url).searchParams.get("page")) < 3,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
http.get("*/api/v1/bank-cards/summary", ({ request }) => {
|
||||||
|
summaryRequests.push(new URL(request.url).search);
|
||||||
|
return options.summaryError
|
||||||
|
? HttpResponse.error()
|
||||||
|
: HttpResponse.json({
|
||||||
|
month: "2026-08",
|
||||||
|
cardId: "a",
|
||||||
|
expenses: money("0"),
|
||||||
|
refunds: money("50"),
|
||||||
|
net: money("-50"),
|
||||||
|
categories: [],
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const client = createTestQueryClient();
|
||||||
|
render(
|
||||||
|
<QueryClientProvider client={client}>
|
||||||
|
<MantineProvider env="test">
|
||||||
|
<MemoryRouter initialEntries={["/cards/a?month=2026-08"]}>
|
||||||
|
<Routes>
|
||||||
|
<Route path="/cards/:cardId" element={<CardPage />} />
|
||||||
|
</Routes>
|
||||||
|
</MemoryRouter>
|
||||||
|
</MantineProvider>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
);
|
||||||
|
return { requests, summaryRequests, client };
|
||||||
|
}
|
||||||
|
describe("CardPage", () => {
|
||||||
|
it("shares date range with history, pages the journal and keeps current balance", async () => {
|
||||||
|
const { requests, summaryRequests } = setup();
|
||||||
|
await screen.findByRole("heading", { name: "Повседневная" });
|
||||||
|
expect(
|
||||||
|
await screen.findByText("Перевод на «Запасная»"),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("03.08.2026")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("−50,01 ₽")).toBeInTheDocument();
|
||||||
|
expect(await screen.findByText("-50,00 ₽")).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole("button", { name: "Назад" })).toBeDisabled();
|
||||||
|
expect(requests.every((value) => value.includes("limit=10"))).toBe(true);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Далее" }));
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(requests.some((v) => v.includes("page=2"))).toBe(true),
|
||||||
|
);
|
||||||
|
const lastPage = await screen.findByRole("button", { name: "Страница 3" });
|
||||||
|
await waitFor(() => expect(lastPage).toBeEnabled());
|
||||||
|
fireEvent.click(lastPage);
|
||||||
|
await waitFor(() => expect(requests.at(-1)).toContain("page=3"));
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByRole("button", { name: "Далее" })).toBeDisabled(),
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
screen.getByRole("button", { name: "Страница 3" }),
|
||||||
|
).toHaveTextContent("3");
|
||||||
|
fireEvent.click(screen.getByLabelText("Период"));
|
||||||
|
fireEvent.click(
|
||||||
|
await screen.findByRole("button", { name: "10 August 2026" }),
|
||||||
|
);
|
||||||
|
fireEvent.click(
|
||||||
|
await screen.findByRole("button", { name: "20 August 2026" }),
|
||||||
|
);
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(
|
||||||
|
requests.some(
|
||||||
|
(v) =>
|
||||||
|
v.includes("from=2026-08-10") &&
|
||||||
|
v.includes("to=2026-08-20") &&
|
||||||
|
v.includes("page=1"),
|
||||||
|
),
|
||||||
|
).toBe(true),
|
||||||
|
);
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(summaryRequests.at(-1)).toContain("from=2026-08-10&to=2026-08-20"),
|
||||||
|
);
|
||||||
|
expect(screen.getByRole("link", { name: "Карта" })).toHaveAttribute(
|
||||||
|
"href",
|
||||||
|
"/cards/b?from=2026-08-10&to=2026-08-20",
|
||||||
|
);
|
||||||
|
expect(screen.getByText(/10\s000 ₽/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
it("keeps the journal in place while the next page loads", async () => {
|
||||||
|
const scroll = vi.spyOn(window, "scrollBy").mockImplementation(() => {});
|
||||||
|
setup();
|
||||||
|
await screen.findByText("Перевод на «Запасная»");
|
||||||
|
const navigation = screen.getByRole("navigation", {
|
||||||
|
name: "Страницы операций",
|
||||||
|
});
|
||||||
|
const measure = vi
|
||||||
|
.spyOn(navigation, "getBoundingClientRect")
|
||||||
|
.mockReturnValue({ top: 600 } as DOMRect);
|
||||||
|
let release = () => {};
|
||||||
|
const pending = new Promise<void>((resolve) => {
|
||||||
|
release = resolve;
|
||||||
|
});
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/a/operations", async () => {
|
||||||
|
await pending;
|
||||||
|
return HttpResponse.json({
|
||||||
|
items: [{ ...operation, id: "next", description: "Новая страница" }],
|
||||||
|
page: 2,
|
||||||
|
total: 30,
|
||||||
|
hasNext: true,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Далее" }));
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByRole("button", { name: "Далее" })).toBeDisabled(),
|
||||||
|
);
|
||||||
|
expect(screen.getByText("Перевод на «Запасная»")).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole("button", { name: "Изменить" })).toBeDisabled();
|
||||||
|
expect(
|
||||||
|
screen.queryByLabelText("Загрузка операций"),
|
||||||
|
).not.toBeInTheDocument();
|
||||||
|
expect(scroll).not.toHaveBeenCalled();
|
||||||
|
measure.mockReturnValue({ top: 200 } as DOMRect);
|
||||||
|
release();
|
||||||
|
await screen.findByText(/Новая страница/);
|
||||||
|
const list = screen.getByText(/Новая страница/).closest("[aria-busy]");
|
||||||
|
expect(list?.parentElement?.style.minHeight).toBe("");
|
||||||
|
expect(scroll).toHaveBeenCalledExactlyOnceWith({
|
||||||
|
top: -400,
|
||||||
|
behavior: "instant",
|
||||||
|
});
|
||||||
|
measure.mockRestore();
|
||||||
|
scroll.mockRestore();
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByRole("button", { name: "Далее" })).toBeEnabled(),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
it("changes page size, resets the page and shows all monthly operations", async () => {
|
||||||
|
const { requests } = setup();
|
||||||
|
await screen.findByText("Перевод на «Запасная»");
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Страница 3" }));
|
||||||
|
await waitFor(() => expect(requests.at(-1)).toContain("page=3"));
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByRole("button", { name: "Страница 1" })).toBeEnabled(),
|
||||||
|
);
|
||||||
|
fireEvent.click(
|
||||||
|
screen.getByRole("combobox", { name: "Операций на странице" }),
|
||||||
|
);
|
||||||
|
fireEvent.click(await screen.findByRole("option", { name: "20" }));
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(requests.at(-1)).toContain("limit=20");
|
||||||
|
expect(requests.at(-1)).toContain("page=1");
|
||||||
|
});
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByRole("button", { name: "Страница 1" })).toBeEnabled(),
|
||||||
|
);
|
||||||
|
fireEvent.click(
|
||||||
|
screen.getByRole("combobox", { name: "Операций на странице" }),
|
||||||
|
);
|
||||||
|
fireEvent.click(await screen.findByRole("option", { name: "Все" }));
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(
|
||||||
|
screen.queryByRole("navigation", { name: "Страницы операций" }),
|
||||||
|
).not.toBeInTheDocument(),
|
||||||
|
);
|
||||||
|
await waitFor(() => expect(requests.at(-1)).toContain("limit=100"));
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getAllByText("Перевод на «Запасная»")).toHaveLength(3),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
it("keeps card and journal when summary fails", async () => {
|
||||||
|
setup({ summaryError: true });
|
||||||
|
await screen.findByRole("heading", { name: "Повседневная" });
|
||||||
|
await screen.findByRole("alert");
|
||||||
|
expect(
|
||||||
|
await screen.findByText("Перевод на «Запасная»"),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText("0 ₽")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
it("keeps cached card and history after refetch failure", async () => {
|
||||||
|
const { client } = setup();
|
||||||
|
await screen.findByText("Перевод на «Запасная»");
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/a", () => HttpResponse.error()),
|
||||||
|
http.get("*/api/v1/bank-cards/a/operations", () => HttpResponse.error()),
|
||||||
|
);
|
||||||
|
await client.invalidateQueries();
|
||||||
|
await screen.findAllByRole("alert");
|
||||||
|
expect(
|
||||||
|
screen.getByRole("heading", { name: "Повседневная" }),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Перевод на «Запасная»")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
it("handles inaccessible card neutrally", async () => {
|
||||||
|
setup({ missing: true });
|
||||||
|
await screen.findByRole("heading", { name: "Карта не найдена" });
|
||||||
|
expect(screen.getByRole("link", { name: "К картам" })).toHaveAttribute(
|
||||||
|
"href",
|
||||||
|
"/cards",
|
||||||
|
);
|
||||||
|
expect(screen.queryByText(/10\s000 ₽/)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
it("archives without deleting history and restores financial actions", async () => {
|
||||||
|
setup();
|
||||||
|
await screen.findByText("Перевод на «Запасная»");
|
||||||
|
let current = card;
|
||||||
|
const bodies: unknown[] = [];
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/a", () => HttpResponse.json(current)),
|
||||||
|
http.get("*/api/v1/bank-cards", () =>
|
||||||
|
HttpResponse.json([current, { ...card, id: "b", name: "Запасная" }]),
|
||||||
|
),
|
||||||
|
http.patch("*/api/v1/bank-cards/a", async ({ request }) => {
|
||||||
|
const body = (await request.json()) as {
|
||||||
|
version: number;
|
||||||
|
archived: boolean;
|
||||||
|
};
|
||||||
|
bodies.push(body);
|
||||||
|
current = {
|
||||||
|
...current,
|
||||||
|
version: current.version + 1,
|
||||||
|
archivedAt: body.archived ? "2026-09-01" : null,
|
||||||
|
} as typeof card;
|
||||||
|
return HttpResponse.json(current);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Убрать в архив" }));
|
||||||
|
await screen.findByRole("button", { name: "Вернуть из архива" });
|
||||||
|
expect(
|
||||||
|
screen.getByRole("button", { name: "Добавить операцию" }),
|
||||||
|
).toBeDisabled();
|
||||||
|
expect(screen.getByRole("button", { name: "Изменить" })).toBeDisabled();
|
||||||
|
expect(screen.getByText("Перевод на «Запасная»")).toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Вернуть из архива" }));
|
||||||
|
await screen.findByRole("button", { name: "Убрать в архив" });
|
||||||
|
expect(
|
||||||
|
screen.getByRole("button", { name: "Добавить операцию" }),
|
||||||
|
).toBeEnabled();
|
||||||
|
expect(bodies).toEqual([
|
||||||
|
{ version: 1, archived: true },
|
||||||
|
{ version: 2, archived: false },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
it("recovers the prerequisite card list while preserving the visible balance and journal", async () => {
|
||||||
|
setup({ cardsError: true });
|
||||||
|
await screen.findByText("Перевод на «Запасная»");
|
||||||
|
expect(await screen.findByRole("alert")).toHaveTextContent(
|
||||||
|
"Не удалось загрузить данные карт.",
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
screen.getByRole("button", { name: "Добавить операцию" }),
|
||||||
|
).toBeDisabled();
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards", () =>
|
||||||
|
HttpResponse.json([card, { ...card, id: "b", name: "Запасная" }]),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
fireEvent.click(
|
||||||
|
within(screen.getByRole("alert")).getByRole("button", {
|
||||||
|
name: "Повторить",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(
|
||||||
|
screen.getByRole("button", { name: "Добавить операцию" }),
|
||||||
|
).toBeEnabled(),
|
||||||
|
);
|
||||||
|
expect(screen.getByText("Перевод на «Запасная»")).toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import type { FC } from "react";
|
||||||
|
import { BankCardForm } from "@/entities/bank-card";
|
||||||
|
import { CardPageView } from "./CardPage.view";
|
||||||
|
import { useCardPageVm } from "./CardPage.vm";
|
||||||
|
import { DeleteOperation } from "./DeleteOperation";
|
||||||
|
import { OperationForm } from "./OperationForm";
|
||||||
|
|
||||||
|
const CardPage: FC = () => {
|
||||||
|
const vm = useCardPageVm();
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<CardPageView vm={vm} />
|
||||||
|
{vm.editingCard && vm.card.data && (
|
||||||
|
<BankCardForm
|
||||||
|
card={vm.card.data}
|
||||||
|
onClose={() => vm.setEditingCard(false)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{vm.operation && vm.card.data && vm.cards.data && (
|
||||||
|
<OperationForm
|
||||||
|
card={vm.card.data}
|
||||||
|
cards={vm.cards.data}
|
||||||
|
operation={vm.operation === "new" ? undefined : vm.operation}
|
||||||
|
onClose={() => vm.setOperation(null)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{vm.deleting && (
|
||||||
|
<DeleteOperation
|
||||||
|
operation={vm.deleting}
|
||||||
|
onClose={() => vm.setDeleting(null)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { CardPage };
|
||||||
@@ -0,0 +1,385 @@
|
|||||||
|
import {
|
||||||
|
ActionIcon,
|
||||||
|
Anchor,
|
||||||
|
Button,
|
||||||
|
Group,
|
||||||
|
Pagination,
|
||||||
|
Select,
|
||||||
|
Skeleton,
|
||||||
|
Stack,
|
||||||
|
Text,
|
||||||
|
Title,
|
||||||
|
} from "@mantine/core";
|
||||||
|
import { type FC, useLayoutEffect, useRef } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { Link } from "react-router";
|
||||||
|
import {
|
||||||
|
BankCardFace,
|
||||||
|
BankFeedback,
|
||||||
|
BankOperationIcon,
|
||||||
|
BankPeriodPicker,
|
||||||
|
BankSummaryView,
|
||||||
|
} from "@/entities/bank-card";
|
||||||
|
import { EntryCard, LoadingSkeleton, StateView } from "@/shared/ui";
|
||||||
|
import classes from "./CardPage.module.css";
|
||||||
|
import type { CardPageVm } from "./CardPage.vm";
|
||||||
|
|
||||||
|
type CardPageViewProps = { vm: CardPageVm };
|
||||||
|
const CardPageView: FC<CardPageViewProps> = (props) => {
|
||||||
|
const { vm } = props;
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const card = vm.card.data;
|
||||||
|
const paginationRef = useRef<HTMLDivElement>(null);
|
||||||
|
const pendingPage = useRef<{
|
||||||
|
scope: string;
|
||||||
|
page: number;
|
||||||
|
top: number;
|
||||||
|
} | null>(null);
|
||||||
|
const scope = `${card?.id}-${vm.period.from}-${vm.period.to}-${vm.pageSize}`;
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const pending = pendingPage.current;
|
||||||
|
if (!pending) return;
|
||||||
|
if (pending.scope !== scope || vm.history.isError) {
|
||||||
|
pendingPage.current = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (vm.history.isPlaceholderData || vm.history.data?.page !== pending.page)
|
||||||
|
return;
|
||||||
|
const pagination = paginationRef.current;
|
||||||
|
if (pagination) {
|
||||||
|
const delta = pagination.getBoundingClientRect().top - pending.top;
|
||||||
|
if (delta) window.scrollBy({ top: delta, behavior: "instant" });
|
||||||
|
}
|
||||||
|
pendingPage.current = null;
|
||||||
|
}, [
|
||||||
|
scope,
|
||||||
|
vm.history.data,
|
||||||
|
vm.history.isPlaceholderData,
|
||||||
|
vm.history.isError,
|
||||||
|
]);
|
||||||
|
if (!card) {
|
||||||
|
if (vm.card.isLoading)
|
||||||
|
return (
|
||||||
|
<LoadingSkeleton label={t("bank.loading")}>
|
||||||
|
<Stack>
|
||||||
|
<Skeleton h={130} />
|
||||||
|
<Skeleton h={160} />
|
||||||
|
<Skeleton h={90} />
|
||||||
|
<Skeleton h={90} />
|
||||||
|
</Stack>
|
||||||
|
</LoadingSkeleton>
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<StateView
|
||||||
|
error
|
||||||
|
title={t(vm.notFound ? "bank.notFound" : "bank.error")}
|
||||||
|
text={t("bank.back")}
|
||||||
|
action={
|
||||||
|
<Group>
|
||||||
|
<Button component={Link} to="/cards">
|
||||||
|
{t("bank.back")}
|
||||||
|
</Button>
|
||||||
|
{!vm.notFound && (
|
||||||
|
<Button onClick={() => void vm.card.refetch()}>
|
||||||
|
{t("bank.retry")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</Group>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<Stack gap="lg" className={classes.page}>
|
||||||
|
<Stack>
|
||||||
|
<Title order={1} className={classes.wrap}>
|
||||||
|
{card.name}
|
||||||
|
</Title>
|
||||||
|
<div className={classes.card}>
|
||||||
|
<BankCardFace card={card} />
|
||||||
|
<Group gap={4} wrap="nowrap" className={classes.cardActions}>
|
||||||
|
<ActionIcon
|
||||||
|
variant="subtle"
|
||||||
|
size="md"
|
||||||
|
radius="md"
|
||||||
|
aria-label={t("bank.editCard")}
|
||||||
|
title={t("bank.editCard")}
|
||||||
|
onClick={() => vm.setEditingCard(true)}
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
width="18"
|
||||||
|
height="18"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="1.5"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path d="m16 3 5 5-12 12-6 1 1-6L16 3Z M13 6l5 5" />
|
||||||
|
</svg>
|
||||||
|
</ActionIcon>
|
||||||
|
<ActionIcon
|
||||||
|
variant="subtle"
|
||||||
|
size="md"
|
||||||
|
radius="md"
|
||||||
|
color="red"
|
||||||
|
aria-label={t(card.archivedAt ? "bank.restore" : "bank.archive")}
|
||||||
|
title={t(card.archivedAt ? "bank.restore" : "bank.archive")}
|
||||||
|
loading={vm.archivePending}
|
||||||
|
onClick={() => void vm.toggleArchive()}
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
width="18"
|
||||||
|
height="18"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="1.5"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
d={
|
||||||
|
card.archivedAt
|
||||||
|
? "M3 3h18v4H3z M5 7v14h14V7 M12 17V10m-3 3 3-3 3 3"
|
||||||
|
: "M3 6h18 M9 6V3h6v3 M5 6l1 15h12l1-15 M10 10v7 M14 10v7"
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</ActionIcon>
|
||||||
|
</Group>
|
||||||
|
</div>
|
||||||
|
{vm.archiveError ? (
|
||||||
|
<BankFeedback
|
||||||
|
error={vm.archiveError}
|
||||||
|
retry={() => void vm.card.refetch()}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
{card.archivedAt && <Text>{t("bank.archiveHint")}</Text>}
|
||||||
|
</Stack>
|
||||||
|
{vm.card.isError && (
|
||||||
|
<Group role="alert">
|
||||||
|
<Text>{t("bank.refreshError")}</Text>
|
||||||
|
<Button onClick={() => void vm.card.refetch()}>
|
||||||
|
{t("bank.retry")}
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
)}
|
||||||
|
{vm.card.isFetching && <Text role="status">{t("bank.refreshing")}</Text>}
|
||||||
|
{vm.cards.isError && (
|
||||||
|
<BankFeedback
|
||||||
|
loadingError
|
||||||
|
error={vm.cards.error}
|
||||||
|
cached={Boolean(vm.cards.data)}
|
||||||
|
retry={() => void vm.cards.refetch()}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<BankPeriodPicker period={vm.period} onChange={vm.setPeriod} />
|
||||||
|
<BankSummaryView
|
||||||
|
data={vm.summary.data}
|
||||||
|
loading={vm.summary.isLoading}
|
||||||
|
fetching={vm.summary.isFetching}
|
||||||
|
error={vm.summary.isError}
|
||||||
|
retry={() => void vm.summary.refetch()}
|
||||||
|
/>
|
||||||
|
<Group justify="space-between" align="end">
|
||||||
|
<Group gap="xs">
|
||||||
|
<Title order={2}>{t("bank.operations")}</Title>
|
||||||
|
<ActionIcon
|
||||||
|
variant="subtle"
|
||||||
|
size="lg"
|
||||||
|
aria-label={t("bank.addOperation")}
|
||||||
|
title={t("bank.addOperation")}
|
||||||
|
disabled={Boolean(card.archivedAt) || !vm.cards.data}
|
||||||
|
onClick={() => vm.setOperation("new")}
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
width="20"
|
||||||
|
height="20"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="1.5"
|
||||||
|
strokeLinecap="round"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path d="M12 5v14 M5 12h14" />
|
||||||
|
</svg>
|
||||||
|
</ActionIcon>
|
||||||
|
</Group>
|
||||||
|
<Select
|
||||||
|
label={t("bank.pageSize")}
|
||||||
|
value={vm.pageSize}
|
||||||
|
onChange={vm.setPageSize}
|
||||||
|
allowDeselect={false}
|
||||||
|
w={180}
|
||||||
|
data={[
|
||||||
|
"5",
|
||||||
|
"10",
|
||||||
|
"20",
|
||||||
|
"50",
|
||||||
|
"100",
|
||||||
|
{ value: "all", label: t("bank.allOperations") },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Group>
|
||||||
|
<Stack
|
||||||
|
key={`${vm.period.from}-${vm.period.to}-${vm.pageSize}-${vm.history.data?.page ?? "loading"}`}
|
||||||
|
gap="lg"
|
||||||
|
className={classes.operations}
|
||||||
|
aria-busy={vm.history.isFetching}
|
||||||
|
data-pending={vm.history.isPlaceholderData || undefined}
|
||||||
|
>
|
||||||
|
{vm.rows ? (
|
||||||
|
vm.rows.length ? (
|
||||||
|
vm.rows.map((row) => (
|
||||||
|
<section
|
||||||
|
key={row.item.id}
|
||||||
|
className={classes.operation}
|
||||||
|
aria-label={`${row.title} ${row.item.date}`}
|
||||||
|
>
|
||||||
|
<EntryCard
|
||||||
|
title={row.title}
|
||||||
|
metadata={row.metadata}
|
||||||
|
color={row.color}
|
||||||
|
initial={row.title[0]}
|
||||||
|
icon={
|
||||||
|
<BankOperationIcon
|
||||||
|
kind={row.item.kind}
|
||||||
|
categoryName={row.item.categoryName}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
value={row.value}
|
||||||
|
valueLabel={t(`bank.kinds.${row.item.kind}`)}
|
||||||
|
tone={row.tone}
|
||||||
|
details={
|
||||||
|
row.otherCard ? (
|
||||||
|
<Anchor
|
||||||
|
component={Link}
|
||||||
|
to={`/cards/${row.otherCard}?from=${vm.period.from}&to=${vm.period.to}`}
|
||||||
|
>
|
||||||
|
{t("bank.card")}
|
||||||
|
</Anchor>
|
||||||
|
) : null
|
||||||
|
}
|
||||||
|
actions={
|
||||||
|
<Group gap={4} wrap="nowrap">
|
||||||
|
<ActionIcon
|
||||||
|
variant="subtle"
|
||||||
|
disabled={
|
||||||
|
vm.history.isPlaceholderData ||
|
||||||
|
!row.editable ||
|
||||||
|
Boolean(card.archivedAt)
|
||||||
|
}
|
||||||
|
size="sm"
|
||||||
|
aria-label={t("bank.edit")}
|
||||||
|
title={t("bank.edit")}
|
||||||
|
onClick={() => vm.setOperation(row.item)}
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
width="18"
|
||||||
|
height="18"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="1.5"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path d="m16 3 5 5-12 12-6 1 1-6L16 3Z M13 6l5 5" />
|
||||||
|
</svg>
|
||||||
|
</ActionIcon>
|
||||||
|
<ActionIcon
|
||||||
|
variant="subtle"
|
||||||
|
color="red"
|
||||||
|
disabled={
|
||||||
|
vm.history.isPlaceholderData ||
|
||||||
|
!row.editable ||
|
||||||
|
Boolean(card.archivedAt)
|
||||||
|
}
|
||||||
|
size="sm"
|
||||||
|
aria-label={t("bank.delete")}
|
||||||
|
title={t("bank.delete")}
|
||||||
|
onClick={() => vm.setDeleting(row.item)}
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
width="18"
|
||||||
|
height="18"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="1.5"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path d="M3 6h18 M9 6V3h6v3 M5 6l1 15h12l1-15 M10 10v7 M14 10v7" />
|
||||||
|
</svg>
|
||||||
|
</ActionIcon>
|
||||||
|
</Group>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</section>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<Text>{t("bank.noOperations")}</Text>
|
||||||
|
)
|
||||||
|
) : vm.history.isLoading ? (
|
||||||
|
<LoadingSkeleton label={t("bank.loadingHistory")}>
|
||||||
|
<Stack>
|
||||||
|
<Skeleton h={90} />
|
||||||
|
<Skeleton h={90} />
|
||||||
|
</Stack>
|
||||||
|
</LoadingSkeleton>
|
||||||
|
) : null}
|
||||||
|
</Stack>
|
||||||
|
{vm.history.isError && (
|
||||||
|
<Group role="alert">
|
||||||
|
<Text>{t(vm.rows ? "bank.refreshError" : "bank.error")}</Text>
|
||||||
|
<Button onClick={() => void vm.history.refetch()}>
|
||||||
|
{t("bank.retry")}
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
)}
|
||||||
|
{vm.history.data && vm.pageSize !== "all" && (
|
||||||
|
<Group
|
||||||
|
component="nav"
|
||||||
|
ref={paginationRef}
|
||||||
|
aria-label={t("bank.pagination")}
|
||||||
|
justify="center"
|
||||||
|
py="sm"
|
||||||
|
>
|
||||||
|
<Pagination
|
||||||
|
total={vm.totalPages}
|
||||||
|
value={vm.page}
|
||||||
|
onChange={(page) => {
|
||||||
|
if (paginationRef.current)
|
||||||
|
pendingPage.current = {
|
||||||
|
scope,
|
||||||
|
page,
|
||||||
|
top: paginationRef.current.getBoundingClientRect().top,
|
||||||
|
};
|
||||||
|
vm.setPage(page);
|
||||||
|
}}
|
||||||
|
disabled={vm.history.isFetching}
|
||||||
|
siblings={0}
|
||||||
|
getItemProps={(page) => ({
|
||||||
|
"aria-label": t("bank.page", { page }),
|
||||||
|
})}
|
||||||
|
getControlProps={(control) => ({
|
||||||
|
"aria-label": t(
|
||||||
|
control === "previous" ? "bank.previous" : "bank.next",
|
||||||
|
),
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
</Group>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { CardPageView };
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useParams, useSearchParams } from "react-router";
|
||||||
|
import {
|
||||||
|
type BankOperation,
|
||||||
|
bankPeriod,
|
||||||
|
useBankCard,
|
||||||
|
useBankCards,
|
||||||
|
useBankMutations,
|
||||||
|
useBankOperations,
|
||||||
|
useBankSummary,
|
||||||
|
} from "@/entities/bank-card";
|
||||||
|
import { apiErrorCode } from "@/shared/api";
|
||||||
|
import { formatDate, formatMoney } from "@/shared/lib";
|
||||||
|
|
||||||
|
const PAGE_SIZES = ["5", "10", "20", "50", "100", "all"];
|
||||||
|
|
||||||
|
function useCardPageVm() {
|
||||||
|
const { cardId } = useParams();
|
||||||
|
const [params, setParams] = useSearchParams();
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const period = bankPeriod(params);
|
||||||
|
const requestedSize = params.get("limit") ?? "10";
|
||||||
|
const pageSize = PAGE_SIZES.includes(requestedSize) ? requestedSize : "10";
|
||||||
|
const rawPage = Number(params.get("page") ?? 1);
|
||||||
|
const page =
|
||||||
|
pageSize !== "all" && Number.isSafeInteger(rawPage) && rawPage > 0
|
||||||
|
? rawPage
|
||||||
|
: 1;
|
||||||
|
const card = useBankCard(cardId);
|
||||||
|
const { updateCard } = useBankMutations();
|
||||||
|
const [archiveError, setArchiveError] = useState<unknown>();
|
||||||
|
const cards = useBankCards(true);
|
||||||
|
const history = useBankOperations(cardId, {
|
||||||
|
...period,
|
||||||
|
page,
|
||||||
|
limit: pageSize === "all" ? "all" : Number(pageSize),
|
||||||
|
});
|
||||||
|
const summary = useBankSummary(period, cardId);
|
||||||
|
const [editingCard, setEditingCard] = useState(false);
|
||||||
|
const [operation, setOperation] = useState<BankOperation | "new" | null>(
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
const [deleting, setDeleting] = useState<BankOperation | null>(null);
|
||||||
|
const rows = history.data?.items.map((item) => {
|
||||||
|
const outgoing =
|
||||||
|
item.kind === "expense" ||
|
||||||
|
(item.kind === "transfer" && item.cardId === cardId);
|
||||||
|
return {
|
||||||
|
item,
|
||||||
|
color: outgoing ? "red" : "green",
|
||||||
|
title:
|
||||||
|
item.kind === "transfer"
|
||||||
|
? t(outgoing ? "bank.transferTo" : "bank.transferFrom", {
|
||||||
|
name: outgoing ? item.targetCardName : item.cardName,
|
||||||
|
})
|
||||||
|
: t(`bank.kinds.${item.kind}`),
|
||||||
|
metadata: [formatDate(item.date), item.categoryName, item.description]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(" · "),
|
||||||
|
value: `${outgoing ? "−" : "+"}${formatMoney(item.amount)}`,
|
||||||
|
tone: outgoing ? ("negative" as const) : ("positive" as const),
|
||||||
|
otherCard:
|
||||||
|
item.kind === "transfer"
|
||||||
|
? outgoing
|
||||||
|
? item.targetCardId
|
||||||
|
: item.cardId
|
||||||
|
: null,
|
||||||
|
editable:
|
||||||
|
Boolean(cards.data) &&
|
||||||
|
!cards.data?.some(
|
||||||
|
(c) =>
|
||||||
|
(c.id === item.cardId || c.id === item.targetCardId) &&
|
||||||
|
c.archivedAt,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
card,
|
||||||
|
cards,
|
||||||
|
archiveError,
|
||||||
|
archivePending: updateCard.isPending,
|
||||||
|
toggleArchive: async () => {
|
||||||
|
if (!card.data) return;
|
||||||
|
setArchiveError(undefined);
|
||||||
|
try {
|
||||||
|
await updateCard.mutateAsync({
|
||||||
|
id: card.data.id,
|
||||||
|
body: { version: card.data.version, archived: !card.data.archivedAt },
|
||||||
|
});
|
||||||
|
} catch (failure) {
|
||||||
|
setArchiveError(failure);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
history,
|
||||||
|
summary,
|
||||||
|
period,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
totalPages:
|
||||||
|
pageSize === "all"
|
||||||
|
? 1
|
||||||
|
: Math.max(1, Math.ceil((history.data?.total ?? 0) / Number(pageSize))),
|
||||||
|
rows,
|
||||||
|
editingCard,
|
||||||
|
setEditingCard,
|
||||||
|
operation,
|
||||||
|
setOperation,
|
||||||
|
deleting,
|
||||||
|
setDeleting,
|
||||||
|
notFound: apiErrorCode(card.error) === "BANK_NOT_FOUND",
|
||||||
|
setPeriod: (value: [string | null, string | null]) => {
|
||||||
|
if (value[0] && value[1])
|
||||||
|
setParams({ from: value[0], to: value[1], limit: pageSize });
|
||||||
|
},
|
||||||
|
setPageSize: (value: string | null) => {
|
||||||
|
if (value && PAGE_SIZES.includes(value))
|
||||||
|
setParams({ ...period, limit: value });
|
||||||
|
},
|
||||||
|
setPage: (value: number) =>
|
||||||
|
setParams({ ...period, page: String(value), limit: pageSize }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
type CardPageVm = ReturnType<typeof useCardPageVm>;
|
||||||
|
|
||||||
|
export { type CardPageVm, useCardPageVm };
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import { MantineProvider } from "@mantine/core";
|
||||||
|
import { QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||||
|
import { HttpResponse, http } from "msw";
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import type { BankOperation } from "@/entities/bank-card";
|
||||||
|
import { configureAuthClient } from "@/shared/api";
|
||||||
|
import { createTestQueryClient } from "@/test/query";
|
||||||
|
import { server } from "@/test/server";
|
||||||
|
import { DeleteOperation } from "./DeleteOperation";
|
||||||
|
|
||||||
|
const transfer: BankOperation = {
|
||||||
|
id: "transfer",
|
||||||
|
kind: "transfer",
|
||||||
|
cardId: "a",
|
||||||
|
cardName: "Основная",
|
||||||
|
targetCardId: "b",
|
||||||
|
targetCardName: "Запасная",
|
||||||
|
categoryId: null,
|
||||||
|
categoryName: null,
|
||||||
|
originalExpenseId: null,
|
||||||
|
amount: { currency: "RUB", value: "100" },
|
||||||
|
availableRefund: null,
|
||||||
|
date: "2026-08-01",
|
||||||
|
description: null,
|
||||||
|
version: 1,
|
||||||
|
createdAt: "2026-08-01T00:00:00Z",
|
||||||
|
};
|
||||||
|
describe("DeleteOperation", () => {
|
||||||
|
it("names both sides and requires a deliberate fresh version after conflict", async () => {
|
||||||
|
configureAuthClient({
|
||||||
|
accessToken: () => "test",
|
||||||
|
refresh: async () => false,
|
||||||
|
clear: () => {},
|
||||||
|
});
|
||||||
|
const versions: string[] = [];
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/operations/transfer", () =>
|
||||||
|
HttpResponse.json({ ...transfer, version: 2 }),
|
||||||
|
),
|
||||||
|
http.delete("*/api/v1/bank-cards/operations/transfer", ({ request }) => {
|
||||||
|
const version = new URL(request.url).searchParams.get("version") ?? "";
|
||||||
|
versions.push(version);
|
||||||
|
return version === "1"
|
||||||
|
? HttpResponse.json(
|
||||||
|
{ code: "BANK_VERSION_CONFLICT" },
|
||||||
|
{ status: 409 },
|
||||||
|
)
|
||||||
|
: new HttpResponse(null, { status: 204 });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const close = vi.fn();
|
||||||
|
render(
|
||||||
|
<QueryClientProvider client={createTestQueryClient()}>
|
||||||
|
<MantineProvider env="test">
|
||||||
|
<DeleteOperation operation={transfer} onClose={close} />
|
||||||
|
</MantineProvider>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
);
|
||||||
|
expect(screen.getByText(/«Основная» → «Запасная»/)).toHaveTextContent(
|
||||||
|
"Обе стороны перевода будут удалены.",
|
||||||
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Удалить" }));
|
||||||
|
await screen.findByText(/Запись уже изменена/);
|
||||||
|
expect(close).not.toHaveBeenCalled();
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Перечитать запись" }));
|
||||||
|
fireEvent.click(
|
||||||
|
await screen.findByRole("button", {
|
||||||
|
name: "Использовать актуальную версию 2",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Удалить" }));
|
||||||
|
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||||
|
expect(versions).toEqual(["1", "2"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import { Button, Group, Modal, Stack, Text } from "@mantine/core";
|
||||||
|
import { type FC, useState } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import {
|
||||||
|
BankFeedback,
|
||||||
|
type BankOperation,
|
||||||
|
useBankFormFocus,
|
||||||
|
useBankMutations,
|
||||||
|
useBankOperation,
|
||||||
|
} from "@/entities/bank-card";
|
||||||
|
import { formatDate, formatMoney } from "@/shared/lib";
|
||||||
|
|
||||||
|
type DeleteOperationProps = { operation: BankOperation; onClose: () => void };
|
||||||
|
const DeleteOperation: FC<DeleteOperationProps> = (props) => {
|
||||||
|
useBankFormFocus();
|
||||||
|
const [opened, setOpened] = useState(true);
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [record, setRecord] = useState(props.operation);
|
||||||
|
const [latest, setLatest] = useState<BankOperation>();
|
||||||
|
const [error, setError] = useState<unknown>();
|
||||||
|
const query = useBankOperation(record.id);
|
||||||
|
const { deleteOperation } = useBankMutations();
|
||||||
|
const pending =
|
||||||
|
!opened ||
|
||||||
|
deleteOperation.isPending ||
|
||||||
|
(query.isFetching && Boolean(error));
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
opened={opened}
|
||||||
|
onExitTransitionEnd={props.onClose}
|
||||||
|
onClose={() => !pending && setOpened(false)}
|
||||||
|
title={t("bank.deleteTitle")}
|
||||||
|
closeOnEscape={!pending}
|
||||||
|
closeOnClickOutside={!pending}
|
||||||
|
closeButtonProps={{ "aria-label": t("bank.close"), disabled: pending }}
|
||||||
|
>
|
||||||
|
<Stack>
|
||||||
|
<Text>
|
||||||
|
{record.kind === "transfer"
|
||||||
|
? t("bank.deleteTransfer", {
|
||||||
|
amount: formatMoney(record.amount),
|
||||||
|
source: record.cardName,
|
||||||
|
target: record.targetCardName,
|
||||||
|
})
|
||||||
|
: t("bank.deleteHint", {
|
||||||
|
kind: t(`bank.kinds.${record.kind}`),
|
||||||
|
amount: formatMoney(record.amount),
|
||||||
|
card: record.cardName,
|
||||||
|
})}
|
||||||
|
</Text>
|
||||||
|
{error ? (
|
||||||
|
<>
|
||||||
|
<BankFeedback error={error} />
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
disabled={pending}
|
||||||
|
onClick={async () => {
|
||||||
|
const result = await query.refetch();
|
||||||
|
if (result.data && !result.error) setLatest(result.data);
|
||||||
|
else setError(result.error);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("bank.reloadRecord")}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
{latest && (
|
||||||
|
<>
|
||||||
|
<Text>
|
||||||
|
{t("bank.versionHint", {
|
||||||
|
details: `${formatDate(latest.date)} · ${formatMoney(latest.amount)} · ${latest.description ?? ""}`,
|
||||||
|
})}
|
||||||
|
</Text>
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
disabled={pending}
|
||||||
|
onClick={() => {
|
||||||
|
setRecord(latest);
|
||||||
|
setLatest(undefined);
|
||||||
|
setError(undefined);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("bank.adoptVersion", { version: latest.version })}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<Group>
|
||||||
|
<Button
|
||||||
|
color="red"
|
||||||
|
loading={pending}
|
||||||
|
onClick={async () => {
|
||||||
|
setError(undefined);
|
||||||
|
try {
|
||||||
|
await deleteOperation.mutateAsync({
|
||||||
|
id: record.id,
|
||||||
|
version: record.version,
|
||||||
|
});
|
||||||
|
setOpened(false);
|
||||||
|
} catch (failure) {
|
||||||
|
setError(failure);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("bank.delete")}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
disabled={pending}
|
||||||
|
onClick={() => setOpened(false)}
|
||||||
|
>
|
||||||
|
{t("bank.cancel")}
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
</Stack>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { DeleteOperation };
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
.fieldset {
|
||||||
|
border: 0;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,465 @@
|
|||||||
|
import { MantineProvider } from "@mantine/core";
|
||||||
|
import { QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
fireEvent,
|
||||||
|
render,
|
||||||
|
screen,
|
||||||
|
waitFor,
|
||||||
|
within,
|
||||||
|
} from "@testing-library/react";
|
||||||
|
import { HttpResponse, http } from "msw";
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import type { BankCard, BankOperation } from "@/entities/bank-card";
|
||||||
|
import { configureAuthClient } from "@/shared/api";
|
||||||
|
import { createTestQueryClient } from "@/test/query";
|
||||||
|
import { server } from "@/test/server";
|
||||||
|
import { OperationForm } from "./OperationForm";
|
||||||
|
|
||||||
|
const money = (value: string) => ({ currency: "RUB", value });
|
||||||
|
const card: BankCard = {
|
||||||
|
id: "a",
|
||||||
|
name: "Повседневная",
|
||||||
|
bankName: null,
|
||||||
|
lastFour: null,
|
||||||
|
paymentSystem: null,
|
||||||
|
balance: money("0"),
|
||||||
|
openingBalance: money("0"),
|
||||||
|
openingDate: "2026-01-01",
|
||||||
|
archivedAt: null,
|
||||||
|
version: 1,
|
||||||
|
};
|
||||||
|
function setup(operation?: BankOperation) {
|
||||||
|
configureAuthClient({
|
||||||
|
accessToken: () => "test",
|
||||||
|
refresh: async () => false,
|
||||||
|
clear: () => {},
|
||||||
|
});
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/categories", () =>
|
||||||
|
HttpResponse.json([
|
||||||
|
{ id: "default", name: "Остальное", isDefault: true, version: 2 },
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const close = vi.fn();
|
||||||
|
render(
|
||||||
|
<QueryClientProvider client={createTestQueryClient()}>
|
||||||
|
<MantineProvider env="test">
|
||||||
|
<OperationForm
|
||||||
|
operation={operation}
|
||||||
|
card={card}
|
||||||
|
cards={[
|
||||||
|
card,
|
||||||
|
{ ...card, id: "b", name: "Запасная", openingDate: "2026-08-01" },
|
||||||
|
{
|
||||||
|
...card,
|
||||||
|
id: "archived",
|
||||||
|
name: "Архивная",
|
||||||
|
archivedAt: "2026-01-02",
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
onClose={close}
|
||||||
|
/>
|
||||||
|
</MantineProvider>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
);
|
||||||
|
return close;
|
||||||
|
}
|
||||||
|
async function select(label: string, value: string | RegExp) {
|
||||||
|
fireEvent.click(screen.getByRole("combobox", { name: new RegExp(label) }));
|
||||||
|
fireEvent.click(await screen.findByRole("option", { name: value }));
|
||||||
|
}
|
||||||
|
describe("OperationForm", () => {
|
||||||
|
it("uses renamed default category and exact maximum positive money despite zero balance", async () => {
|
||||||
|
const close = setup();
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByRole("combobox", { name: /Категория/ })).toHaveValue(
|
||||||
|
"Остальное",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
fireEvent.change(screen.getByLabelText(/Дата операции/), {
|
||||||
|
target: { value: "07.08.2026" },
|
||||||
|
});
|
||||||
|
fireEvent.blur(screen.getByLabelText(/Дата операции/));
|
||||||
|
expect(screen.getByLabelText(/Дата операции/)).toHaveValue("07.08.2026");
|
||||||
|
let body: unknown;
|
||||||
|
server.use(
|
||||||
|
http.post("*/api/v1/bank-cards/operations", async ({ request }) => {
|
||||||
|
body = await request.json();
|
||||||
|
return HttpResponse.json({}, { status: 201 });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
fireEvent.change(screen.getByLabelText(/Сумма/), {
|
||||||
|
target: { value: "92233720368547758,07" },
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||||
|
expect(body).toMatchObject({
|
||||||
|
categoryId: "default",
|
||||||
|
date: "2026-08-07",
|
||||||
|
amount: money("92233720368547758.07"),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it("checks both transfer opening dates, excludes archive and reuses intent after a lost response", async () => {
|
||||||
|
setup();
|
||||||
|
await select("Вид операции", "Перевод");
|
||||||
|
await select("Карта-получатель", "Запасная");
|
||||||
|
fireEvent.change(screen.getByLabelText(/Сумма/), {
|
||||||
|
target: { value: "0" },
|
||||||
|
});
|
||||||
|
fireEvent.change(screen.getByLabelText(/Дата операции/), {
|
||||||
|
target: { value: "31.07.2026" },
|
||||||
|
});
|
||||||
|
const bodies: unknown[] = [];
|
||||||
|
server.use(
|
||||||
|
http.post("*/api/v1/bank-cards/operations", async ({ request }) => {
|
||||||
|
bodies.push(await request.json());
|
||||||
|
return bodies.length === 1
|
||||||
|
? HttpResponse.error()
|
||||||
|
: HttpResponse.json({}, { status: 201 });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
expect(
|
||||||
|
await screen.findByText("Сумма операции должна быть больше нуля."),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/Дата не может быть раньше/)).toBeInTheDocument();
|
||||||
|
expect(bodies).toHaveLength(0);
|
||||||
|
fireEvent.change(screen.getByLabelText(/Сумма/), {
|
||||||
|
target: { value: "150,01" },
|
||||||
|
});
|
||||||
|
fireEvent.change(screen.getByLabelText(/Дата операции/), {
|
||||||
|
target: { value: "02.08.2026" },
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
await screen.findByText(/Не удалось подтвердить сохранение/);
|
||||||
|
expect(screen.getByLabelText(/Сумма/)).toHaveValue("150,01");
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
await waitFor(() => expect(bodies).toHaveLength(2));
|
||||||
|
expect(bodies[0]).toEqual(bodies[1]);
|
||||||
|
expect(bodies[0]).toMatchObject({
|
||||||
|
kind: "transfer",
|
||||||
|
cardId: "a",
|
||||||
|
targetCardId: "b",
|
||||||
|
amount: money("150.01"),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it("topup omits categories and preserves entered description", async () => {
|
||||||
|
setup();
|
||||||
|
await select("Вид операции", "Пополнение");
|
||||||
|
expect(
|
||||||
|
screen.queryByRole("combobox", { name: /Категория/ }),
|
||||||
|
).not.toBeInTheDocument();
|
||||||
|
let body: unknown;
|
||||||
|
server.use(
|
||||||
|
http.post("*/api/v1/bank-cards/operations", async ({ request }) => {
|
||||||
|
body = await request.json();
|
||||||
|
return HttpResponse.json({}, { status: 201 });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
fireEvent.change(screen.getByLabelText(/Сумма/), {
|
||||||
|
target: { value: "0.10" },
|
||||||
|
});
|
||||||
|
fireEvent.change(screen.getByLabelText(/Описание/), {
|
||||||
|
target: { value: "Внесение" },
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
await waitFor(() => expect(body).toBeDefined());
|
||||||
|
expect(body).toMatchObject({
|
||||||
|
kind: "topup",
|
||||||
|
amount: money("0.10"),
|
||||||
|
description: "Внесение",
|
||||||
|
});
|
||||||
|
expect(body).not.toHaveProperty("categoryId");
|
||||||
|
});
|
||||||
|
it("finds a previous-month purchase across pages, checks remaining refund and retains the complete-refund intent", async () => {
|
||||||
|
const purchase: BankOperation = {
|
||||||
|
id: "purchase",
|
||||||
|
kind: "expense",
|
||||||
|
cardId: "a",
|
||||||
|
cardName: card.name,
|
||||||
|
targetCardId: null,
|
||||||
|
targetCardName: null,
|
||||||
|
categoryId: "default",
|
||||||
|
categoryName: "Остальное",
|
||||||
|
originalExpenseId: null,
|
||||||
|
amount: money("500"),
|
||||||
|
availableRefund: money("500"),
|
||||||
|
date: "2026-07-01",
|
||||||
|
description: "Прошлая покупка",
|
||||||
|
version: 1,
|
||||||
|
createdAt: "2026-07-01T00:00:00Z",
|
||||||
|
};
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/a/expenses", ({ request }) => {
|
||||||
|
return HttpResponse.json({
|
||||||
|
items:
|
||||||
|
new URL(request.url).searchParams.get("page") === "2"
|
||||||
|
? [purchase]
|
||||||
|
: [],
|
||||||
|
page: 1,
|
||||||
|
total: 1,
|
||||||
|
hasNext: new URL(request.url).searchParams.get("page") !== "2",
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
http.get("*/api/v1/bank-cards/operations/purchase", () =>
|
||||||
|
HttpResponse.json(purchase),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const close = setup();
|
||||||
|
await select("Вид операции", "Возврат");
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByRole("button", { name: "Далее" })).toBeEnabled(),
|
||||||
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Далее" }));
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByRole("button", { name: "Назад" })).toBeEnabled(),
|
||||||
|
);
|
||||||
|
await select("Исходная покупка", /Прошлая покупка/);
|
||||||
|
await screen.findByText("Доступно к возврату: 500 ₽");
|
||||||
|
fireEvent.change(screen.getByLabelText(/Сумма/), {
|
||||||
|
target: { value: "500.01" },
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
await screen.findByText("Сумма превышает доступный возврат.");
|
||||||
|
const bodies: unknown[] = [];
|
||||||
|
server.use(
|
||||||
|
http.post("*/api/v1/bank-cards/operations", async ({ request }) => {
|
||||||
|
bodies.push(await request.json());
|
||||||
|
purchase.availableRefund = money("0");
|
||||||
|
return bodies.length === 1
|
||||||
|
? HttpResponse.error()
|
||||||
|
: HttpResponse.json({}, { status: 201 });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
fireEvent.change(screen.getByLabelText(/Сумма/), {
|
||||||
|
target: { value: "500" },
|
||||||
|
});
|
||||||
|
fireEvent.change(screen.getByLabelText(/Дата операции/), {
|
||||||
|
target: { value: "01.08.2026" },
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
await screen.findByText(/Не удалось подтвердить сохранение/);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Перечитать запись" }));
|
||||||
|
await screen.findByText("Доступно к возврату: 0 ₽");
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||||
|
expect(bodies[0]).toEqual(bodies[1]);
|
||||||
|
expect(bodies[0]).toMatchObject({
|
||||||
|
kind: "refund",
|
||||||
|
originalExpenseId: "purchase",
|
||||||
|
date: "2026-08-01",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it("edits a full refund with its own amount excluded from the limit and immutable purchase", async () => {
|
||||||
|
const refund: BankOperation = {
|
||||||
|
id: "refund",
|
||||||
|
kind: "refund",
|
||||||
|
cardId: "a",
|
||||||
|
cardName: card.name,
|
||||||
|
targetCardId: null,
|
||||||
|
targetCardName: null,
|
||||||
|
categoryId: "default",
|
||||||
|
categoryName: "Остальное",
|
||||||
|
originalExpenseId: "purchase",
|
||||||
|
amount: money("500"),
|
||||||
|
availableRefund: money("500"),
|
||||||
|
date: "2026-08-01",
|
||||||
|
description: "",
|
||||||
|
version: 2,
|
||||||
|
createdAt: "2026-08-01T00:00:00Z",
|
||||||
|
};
|
||||||
|
const purchase = {
|
||||||
|
...refund,
|
||||||
|
id: "purchase",
|
||||||
|
kind: "expense",
|
||||||
|
date: "2026-07-01",
|
||||||
|
availableRefund: money("0"),
|
||||||
|
};
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/a/expenses", () =>
|
||||||
|
HttpResponse.json({
|
||||||
|
items: [purchase],
|
||||||
|
page: 1,
|
||||||
|
total: 1,
|
||||||
|
hasNext: false,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
http.get("*/api/v1/bank-cards/operations/purchase", () =>
|
||||||
|
HttpResponse.json(purchase),
|
||||||
|
),
|
||||||
|
http.get("*/api/v1/bank-cards/operations/refund", () =>
|
||||||
|
HttpResponse.json(refund),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const close = setup(refund);
|
||||||
|
await screen.findByText("Доступно к возврату: 500 ₽");
|
||||||
|
expect(
|
||||||
|
screen.getByRole("combobox", { name: /Исходная покупка/ }),
|
||||||
|
).toBeDisabled();
|
||||||
|
expect(
|
||||||
|
screen.getByRole("combobox", { name: /Вид операции/ }),
|
||||||
|
).toBeDisabled();
|
||||||
|
fireEvent.change(screen.getByLabelText(/Описание/), {
|
||||||
|
target: { value: "Полностью возвращено" },
|
||||||
|
});
|
||||||
|
let body: unknown;
|
||||||
|
server.use(
|
||||||
|
http.patch(
|
||||||
|
"*/api/v1/bank-cards/operations/refund",
|
||||||
|
async ({ request }) => {
|
||||||
|
body = await request.json();
|
||||||
|
return HttpResponse.json(refund);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByRole("button", { name: "Сохранить" })).toBeEnabled(),
|
||||||
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||||
|
expect(body).toMatchObject({
|
||||||
|
version: 2,
|
||||||
|
amount: money("500"),
|
||||||
|
originalExpenseId: "purchase",
|
||||||
|
description: "Полностью возвращено",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps edit draft and stale version until explicit adoption after conflict", async () => {
|
||||||
|
const operation: BankOperation = {
|
||||||
|
id: "expense",
|
||||||
|
kind: "expense",
|
||||||
|
cardId: "a",
|
||||||
|
cardName: card.name,
|
||||||
|
targetCardId: null,
|
||||||
|
targetCardName: null,
|
||||||
|
categoryId: "default",
|
||||||
|
categoryName: "Остальное",
|
||||||
|
originalExpenseId: null,
|
||||||
|
amount: money("100"),
|
||||||
|
availableRefund: money("100"),
|
||||||
|
date: "2026-08-01",
|
||||||
|
description: "Первое",
|
||||||
|
version: 1,
|
||||||
|
createdAt: "2026-08-01T00:00:00Z",
|
||||||
|
};
|
||||||
|
let readVersion = 1;
|
||||||
|
const bodies: Record<string, unknown>[] = [];
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/operations/expense", () =>
|
||||||
|
HttpResponse.json({
|
||||||
|
...operation,
|
||||||
|
version: readVersion,
|
||||||
|
description: readVersion === 1 ? "Первое" : "Другое исправление",
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
http.patch(
|
||||||
|
"*/api/v1/bank-cards/operations/expense",
|
||||||
|
async ({ request }) => {
|
||||||
|
const body = (await request.json()) as Record<string, unknown>;
|
||||||
|
bodies.push(body);
|
||||||
|
readVersion = 2;
|
||||||
|
return body.version === 1
|
||||||
|
? HttpResponse.json(
|
||||||
|
{ code: "BANK_VERSION_CONFLICT" },
|
||||||
|
{ status: 409 },
|
||||||
|
)
|
||||||
|
: HttpResponse.json({ ...operation, ...body });
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const close = setup(operation);
|
||||||
|
fireEvent.change(screen.getByLabelText(/Описание/), {
|
||||||
|
target: { value: "Мой черновик" },
|
||||||
|
});
|
||||||
|
fireEvent.change(screen.getByLabelText(/Сумма/), {
|
||||||
|
target: { value: "150" },
|
||||||
|
});
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByRole("button", { name: "Сохранить" })).toBeEnabled(),
|
||||||
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
await screen.findByText(/Запись уже изменена/);
|
||||||
|
expect(screen.getByLabelText(/Описание/)).toHaveValue("Мой черновик");
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Перечитать запись" }));
|
||||||
|
await screen.findByRole("button", {
|
||||||
|
name: "Использовать актуальную версию 2",
|
||||||
|
});
|
||||||
|
expect(screen.getByLabelText(/Сумма/)).toHaveValue("150");
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
await waitFor(() => expect(bodies).toHaveLength(2));
|
||||||
|
expect(bodies[1].version).toBe(1);
|
||||||
|
fireEvent.click(
|
||||||
|
screen.getByRole("button", { name: "Использовать актуальную версию 2" }),
|
||||||
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||||
|
expect(bodies[2]).toMatchObject({
|
||||||
|
version: 2,
|
||||||
|
description: "Мой черновик",
|
||||||
|
amount: money("150"),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it("creates a category inside expense without losing operation fields", async () => {
|
||||||
|
setup();
|
||||||
|
fireEvent.change(screen.getByLabelText(/Сумма/), {
|
||||||
|
target: { value: "001.20" },
|
||||||
|
});
|
||||||
|
fireEvent.change(screen.getByLabelText(/Описание/), {
|
||||||
|
target: { value: "Черновик расхода" },
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Добавить категорию" }));
|
||||||
|
const dialog = screen.getByRole("dialog", { name: "Категории" });
|
||||||
|
fireEvent.change(within(dialog).getByLabelText(/Название категории/), {
|
||||||
|
target: { value: " кафе " },
|
||||||
|
});
|
||||||
|
let created = false;
|
||||||
|
server.use(
|
||||||
|
http.post("*/api/v1/bank-cards/categories", () => {
|
||||||
|
created = true;
|
||||||
|
return HttpResponse.json(
|
||||||
|
{ id: "new", name: "кафе", version: 1, isDefault: false },
|
||||||
|
{ status: 201 },
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
http.get("*/api/v1/bank-cards/categories", () =>
|
||||||
|
HttpResponse.json([
|
||||||
|
{ id: "default", name: "Остальное", isDefault: true, version: 2 },
|
||||||
|
...(created
|
||||||
|
? [{ id: "new", name: "кафе", isDefault: false, version: 1 }]
|
||||||
|
: []),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
fireEvent.click(
|
||||||
|
within(dialog).getByRole("button", { name: "Добавить категорию" }),
|
||||||
|
);
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(
|
||||||
|
screen.queryByRole("dialog", { name: "Категории" }),
|
||||||
|
).not.toBeInTheDocument(),
|
||||||
|
);
|
||||||
|
expect(screen.getByLabelText(/Сумма/)).toHaveValue("001.20");
|
||||||
|
expect(screen.getByLabelText(/Описание/)).toHaveValue("Черновик расхода");
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByRole("combobox", { name: /Категория/ })).toHaveValue(
|
||||||
|
"кафе",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
let body: unknown;
|
||||||
|
server.use(
|
||||||
|
http.post("*/api/v1/bank-cards/operations", async ({ request }) => {
|
||||||
|
body = await request.json();
|
||||||
|
return HttpResponse.json({}, { status: 201 });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
|
await waitFor(() => expect(body).toBeDefined());
|
||||||
|
expect(body).toMatchObject({
|
||||||
|
categoryId: "new",
|
||||||
|
description: "Черновик расхода",
|
||||||
|
amount: money("1.20"),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,424 @@
|
|||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { Button, Group, Modal, Stack, Text } from "@mantine/core";
|
||||||
|
import { type FC, useState } from "react";
|
||||||
|
import { FormProvider, useForm } from "react-hook-form";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { z } from "zod";
|
||||||
|
import {
|
||||||
|
type BankCard,
|
||||||
|
BankFeedback,
|
||||||
|
type BankOperation,
|
||||||
|
bankDateSchema,
|
||||||
|
bankMoneyValue,
|
||||||
|
bankToday,
|
||||||
|
CategoryManager,
|
||||||
|
moneyCents,
|
||||||
|
positiveMoneySchema,
|
||||||
|
useBankCategories,
|
||||||
|
useBankExpenses,
|
||||||
|
useBankFormFocus,
|
||||||
|
useBankMutations,
|
||||||
|
useBankOperation,
|
||||||
|
} from "@/entities/bank-card";
|
||||||
|
import { validationMessage } from "@/shared/i18n";
|
||||||
|
import { formatDate, formatMoney } from "@/shared/lib";
|
||||||
|
import classes from "./OperationForm.module.css";
|
||||||
|
import type { OperationValues } from "./OperationForm.types";
|
||||||
|
import { OperationFields, RefundFields } from "./OperationForm.view";
|
||||||
|
|
||||||
|
const MAX_DESCRIPTION_LENGTH = 500;
|
||||||
|
|
||||||
|
const operationSchema = z.object({
|
||||||
|
kind: z.enum(["expense", "topup", "transfer", "refund"]),
|
||||||
|
cardId: z.string(),
|
||||||
|
targetCardId: z.string(),
|
||||||
|
categoryId: z.string(),
|
||||||
|
originalExpenseId: z.string(),
|
||||||
|
amount: positiveMoneySchema,
|
||||||
|
date: bankDateSchema,
|
||||||
|
description: z
|
||||||
|
.string()
|
||||||
|
.max(
|
||||||
|
MAX_DESCRIPTION_LENGTH,
|
||||||
|
validationMessage("bank.validation.description")(undefined),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
type OperationFormProps = {
|
||||||
|
card: BankCard;
|
||||||
|
cards: BankCard[];
|
||||||
|
operation?: BankOperation;
|
||||||
|
onClose: () => void;
|
||||||
|
};
|
||||||
|
const OperationForm: FC<OperationFormProps> = (props) => {
|
||||||
|
useBankFormFocus();
|
||||||
|
const [opened, setOpened] = useState(true);
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [categoriesOpen, setCategoriesOpen] = useState(false);
|
||||||
|
const [version, setVersion] = useState(props.operation?.version ?? 1);
|
||||||
|
const [latest, setLatest] = useState<BankOperation>();
|
||||||
|
const [sourcePage, setSourcePage] = useState(1);
|
||||||
|
const [sourceId, setSourceId] = useState(
|
||||||
|
props.operation?.originalExpenseId ?? "",
|
||||||
|
);
|
||||||
|
const sourceQuery = useBankOperation(sourceId || undefined);
|
||||||
|
const currentQuery = useBankOperation(props.operation?.id);
|
||||||
|
const [refundLimit, setRefundLimit] = useState(
|
||||||
|
props.operation?.availableRefund,
|
||||||
|
);
|
||||||
|
const [intent] = useState(() => crypto.randomUUID());
|
||||||
|
const [submittedValues, setSubmittedValues] = useState<OperationValues>();
|
||||||
|
const [error, setError] = useState<unknown>();
|
||||||
|
const categories = useBankCategories();
|
||||||
|
const mutation = useBankMutations();
|
||||||
|
const methods = useForm<OperationValues>({
|
||||||
|
resolver: zodResolver(
|
||||||
|
operationSchema.superRefine((values, ctx) => {
|
||||||
|
// Repeated intent reaches server idempotency even after its source changed.
|
||||||
|
if (
|
||||||
|
submittedValues &&
|
||||||
|
JSON.stringify(values) === JSON.stringify(submittedValues)
|
||||||
|
)
|
||||||
|
return;
|
||||||
|
const source = props.cards.find((c) => c.id === values.cardId);
|
||||||
|
const target = props.cards.find((c) => c.id === values.targetCardId);
|
||||||
|
if (!source || source.archivedAt)
|
||||||
|
ctx.addIssue({
|
||||||
|
code: "custom",
|
||||||
|
path: ["cardId"],
|
||||||
|
...validationMessage("bank.validation.required")(undefined),
|
||||||
|
});
|
||||||
|
if (
|
||||||
|
values.kind === "transfer" &&
|
||||||
|
(!target || target.archivedAt || target.id === values.cardId)
|
||||||
|
)
|
||||||
|
ctx.addIssue({
|
||||||
|
code: "custom",
|
||||||
|
path: ["targetCardId"],
|
||||||
|
...validationMessage("bank.validation.destination")(undefined),
|
||||||
|
});
|
||||||
|
if (
|
||||||
|
(source && values.date < source.openingDate) ||
|
||||||
|
(values.kind === "transfer" &&
|
||||||
|
target &&
|
||||||
|
values.date < target.openingDate)
|
||||||
|
)
|
||||||
|
ctx.addIssue({
|
||||||
|
code: "custom",
|
||||||
|
path: ["date"],
|
||||||
|
...validationMessage("bank.validation.start")(undefined),
|
||||||
|
});
|
||||||
|
if (values.kind === "refund") {
|
||||||
|
const expense = sourceQuery.data;
|
||||||
|
if (!expense || expense.cardId !== values.cardId)
|
||||||
|
ctx.addIssue({
|
||||||
|
code: "custom",
|
||||||
|
path: ["originalExpenseId"],
|
||||||
|
...validationMessage("bank.validation.required")(undefined),
|
||||||
|
});
|
||||||
|
if (expense && values.date < expense.date)
|
||||||
|
ctx.addIssue({
|
||||||
|
code: "custom",
|
||||||
|
path: ["date"],
|
||||||
|
...validationMessage("bank.validation.start")(undefined),
|
||||||
|
});
|
||||||
|
const limit = props.operation
|
||||||
|
? refundLimit
|
||||||
|
: expense?.availableRefund;
|
||||||
|
const amount = moneyCents(values.amount);
|
||||||
|
if (
|
||||||
|
limit &&
|
||||||
|
amount !== null &&
|
||||||
|
amount > (moneyCents(limit.value) ?? 0n)
|
||||||
|
)
|
||||||
|
ctx.addIssue({
|
||||||
|
code: "custom",
|
||||||
|
path: ["amount"],
|
||||||
|
...validationMessage("bank.validation.refund")(undefined),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
values.kind === "expense" &&
|
||||||
|
!categories.data?.some(
|
||||||
|
(c) =>
|
||||||
|
c.id ===
|
||||||
|
(values.categoryId ||
|
||||||
|
categories.data?.find((c) => c.isDefault)?.id),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
ctx.addIssue({
|
||||||
|
code: "custom",
|
||||||
|
path: ["categoryId"],
|
||||||
|
...validationMessage("bank.validation.required")(undefined),
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
defaultValues: {
|
||||||
|
kind: props.operation?.kind ?? "expense",
|
||||||
|
cardId: props.operation?.cardId ?? props.card.id,
|
||||||
|
targetCardId: props.operation?.targetCardId ?? "",
|
||||||
|
categoryId: props.operation?.categoryId ?? "",
|
||||||
|
originalExpenseId: props.operation?.originalExpenseId ?? "",
|
||||||
|
amount: props.operation?.amount.value ?? "",
|
||||||
|
date: props.operation?.date ?? bankToday(),
|
||||||
|
description: props.operation?.description ?? "",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const kind = methods.watch("kind");
|
||||||
|
const expenses = useBankExpenses(
|
||||||
|
kind === "refund" ? props.card.id : undefined,
|
||||||
|
{ page: sourcePage },
|
||||||
|
);
|
||||||
|
const source = methods.watch("cardId");
|
||||||
|
const pending = !opened || methods.formState.isSubmitting;
|
||||||
|
const options = props.cards
|
||||||
|
.filter((c) => !c.archivedAt)
|
||||||
|
.map((c) => ({ value: c.id, label: c.name }));
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Modal
|
||||||
|
opened={opened}
|
||||||
|
onExitTransitionEnd={props.onClose}
|
||||||
|
onClose={() => !pending && !categoriesOpen && setOpened(false)}
|
||||||
|
title={t(props.operation ? "bank.editOperation" : "bank.addOperation")}
|
||||||
|
closeOnEscape={!pending && !categoriesOpen}
|
||||||
|
closeOnClickOutside={!pending && !categoriesOpen}
|
||||||
|
closeButtonProps={{ "aria-label": t("bank.close"), disabled: pending }}
|
||||||
|
>
|
||||||
|
<FormProvider {...methods}>
|
||||||
|
<form
|
||||||
|
onSubmit={methods.handleSubmit(async (values) => {
|
||||||
|
setSubmittedValues(values);
|
||||||
|
setError(undefined);
|
||||||
|
try {
|
||||||
|
const body = {
|
||||||
|
kind: values.kind,
|
||||||
|
cardId: values.cardId,
|
||||||
|
...(values.kind === "transfer"
|
||||||
|
? { targetCardId: values.targetCardId }
|
||||||
|
: {}),
|
||||||
|
...(values.kind === "expense"
|
||||||
|
? {
|
||||||
|
categoryId:
|
||||||
|
values.categoryId ||
|
||||||
|
categories.data?.find((c) => c.isDefault)?.id,
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
...(values.kind === "refund"
|
||||||
|
? { originalExpenseId: values.originalExpenseId }
|
||||||
|
: {}),
|
||||||
|
amount: {
|
||||||
|
currency: "RUB" as const,
|
||||||
|
value: bankMoneyValue(values.amount),
|
||||||
|
},
|
||||||
|
date: values.date,
|
||||||
|
description: values.description,
|
||||||
|
};
|
||||||
|
if (props.operation)
|
||||||
|
await mutation.updateOperation.mutateAsync({
|
||||||
|
id: props.operation.id,
|
||||||
|
body: { ...body, version },
|
||||||
|
});
|
||||||
|
else
|
||||||
|
await mutation.createOperation.mutateAsync({
|
||||||
|
id: intent,
|
||||||
|
...body,
|
||||||
|
});
|
||||||
|
setOpened(false);
|
||||||
|
} catch (failure) {
|
||||||
|
setError(failure);
|
||||||
|
}
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
<fieldset disabled={pending} className={classes.fieldset}>
|
||||||
|
<Stack>
|
||||||
|
<OperationFields
|
||||||
|
refundCardId={props.card.id}
|
||||||
|
editing={Boolean(props.operation)}
|
||||||
|
kind={kind}
|
||||||
|
cards={options}
|
||||||
|
targets={options.filter((c) => c.value !== source)}
|
||||||
|
categories={
|
||||||
|
categories.data?.map((c) => ({
|
||||||
|
value: c.id,
|
||||||
|
label: c.name,
|
||||||
|
})) ?? []
|
||||||
|
}
|
||||||
|
defaultCategory={
|
||||||
|
categories.data?.find((c) => c.isDefault)?.id ?? ""
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{kind === "refund" && (
|
||||||
|
<>
|
||||||
|
<RefundFields
|
||||||
|
editing={Boolean(props.operation)}
|
||||||
|
expenses={
|
||||||
|
expenses.data?.items.map((item) => ({
|
||||||
|
value: item.id,
|
||||||
|
label: t("bank.expenseChoice", {
|
||||||
|
date: formatDate(item.date),
|
||||||
|
name: item.description || item.categoryName,
|
||||||
|
amount: formatMoney(item.amount),
|
||||||
|
available: formatMoney(item.availableRefund),
|
||||||
|
}),
|
||||||
|
})) ?? []
|
||||||
|
}
|
||||||
|
selected={
|
||||||
|
sourceQuery.data
|
||||||
|
? {
|
||||||
|
value: sourceQuery.data.id,
|
||||||
|
label: t("bank.expenseChoice", {
|
||||||
|
date: formatDate(sourceQuery.data.date),
|
||||||
|
name:
|
||||||
|
sourceQuery.data.description ||
|
||||||
|
sourceQuery.data.categoryName,
|
||||||
|
amount: formatMoney(sourceQuery.data.amount),
|
||||||
|
available: formatMoney(
|
||||||
|
sourceQuery.data.availableRefund,
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
onSelect={setSourceId}
|
||||||
|
limit={
|
||||||
|
props.operation
|
||||||
|
? refundLimit
|
||||||
|
: sourceQuery.data?.availableRefund
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{expenses.isLoading && (
|
||||||
|
<Text role="status">{t("bank.loadingHistory")}</Text>
|
||||||
|
)}
|
||||||
|
{expenses.data &&
|
||||||
|
!expenses.data.items.length &&
|
||||||
|
!props.operation && <Text>{t("bank.noPurchases")}</Text>}
|
||||||
|
{!props.operation && (
|
||||||
|
<Group>
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
disabled={sourcePage === 1 || expenses.isFetching}
|
||||||
|
onClick={() => setSourcePage(sourcePage - 1)}
|
||||||
|
>
|
||||||
|
{t("bank.previous")}
|
||||||
|
</Button>
|
||||||
|
<Text>{t("bank.page", { page: sourcePage })}</Text>
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
disabled={
|
||||||
|
!expenses.data?.hasNext || expenses.isFetching
|
||||||
|
}
|
||||||
|
onClick={() => setSourcePage(sourcePage + 1)}
|
||||||
|
>
|
||||||
|
{t("bank.next")}
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
)}
|
||||||
|
{expenses.isError && (
|
||||||
|
<BankFeedback
|
||||||
|
loadingError
|
||||||
|
error={expenses.error}
|
||||||
|
retry={() => void expenses.refetch()}
|
||||||
|
/>
|
||||||
|
)}{" "}
|
||||||
|
{sourceQuery.isError && (
|
||||||
|
<BankFeedback
|
||||||
|
loadingError
|
||||||
|
error={sourceQuery.error}
|
||||||
|
retry={() => void sourceQuery.refetch()}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{kind === "expense" && (
|
||||||
|
<Button
|
||||||
|
variant="subtle"
|
||||||
|
onClick={() => setCategoriesOpen(true)}
|
||||||
|
>
|
||||||
|
{t("bank.addCategory")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{categories.isError && (
|
||||||
|
<BankFeedback
|
||||||
|
loadingError
|
||||||
|
error={categories.error}
|
||||||
|
retry={() => void categories.refetch()}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{error ? (
|
||||||
|
<>
|
||||||
|
<BankFeedback error={error} />
|
||||||
|
{(props.operation || sourceId) && (
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
onClick={async () => {
|
||||||
|
const query = props.operation
|
||||||
|
? currentQuery
|
||||||
|
: sourceQuery;
|
||||||
|
const result = await query.refetch();
|
||||||
|
if (result.data && !result.error) {
|
||||||
|
if (props.operation) {
|
||||||
|
setLatest(result.data);
|
||||||
|
setRefundLimit(result.data.availableRefund);
|
||||||
|
} else setError(undefined);
|
||||||
|
} else setError(result.error);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("bank.reloadRecord")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
{latest && (
|
||||||
|
<>
|
||||||
|
<Text>
|
||||||
|
{t("bank.versionHint", {
|
||||||
|
details: `${formatDate(latest.date)} · ${formatMoney(latest.amount)} · ${latest.description ?? ""}`,
|
||||||
|
})}
|
||||||
|
</Text>
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
onClick={() => {
|
||||||
|
setVersion(latest.version);
|
||||||
|
setLatest(undefined);
|
||||||
|
setError(undefined);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("bank.adoptVersion", { version: latest.version })}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<Group>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
loading={pending}
|
||||||
|
disabled={
|
||||||
|
(kind === "expense" && !categories.data) ||
|
||||||
|
(kind === "refund" && !sourceQuery.data)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{t("bank.save")}
|
||||||
|
</Button>
|
||||||
|
<Button variant="default" onClick={() => setOpened(false)}>
|
||||||
|
{t("bank.cancel")}
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
</Stack>
|
||||||
|
</fieldset>
|
||||||
|
</form>
|
||||||
|
</FormProvider>
|
||||||
|
</Modal>
|
||||||
|
{categoriesOpen && (
|
||||||
|
<CategoryManager
|
||||||
|
onClose={() => setCategoriesOpen(false)}
|
||||||
|
onCreated={(id) => {
|
||||||
|
methods.setValue("categoryId", id);
|
||||||
|
setCategoriesOpen(false);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { OperationForm };
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import type { BankOperation } from "@/entities/bank-card";
|
||||||
|
|
||||||
|
type OperationValues = {
|
||||||
|
kind: BankOperation["kind"];
|
||||||
|
cardId: string;
|
||||||
|
targetCardId: string;
|
||||||
|
categoryId: string;
|
||||||
|
originalExpenseId: string;
|
||||||
|
amount: string;
|
||||||
|
date: string;
|
||||||
|
description: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type { OperationValues };
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
import { Select, Stack, Text, Textarea, TextInput } from "@mantine/core";
|
||||||
|
import { DateInput } from "@mantine/dates";
|
||||||
|
import type { FC } from "react";
|
||||||
|
import { Controller, useFormContext } from "react-hook-form";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import {
|
||||||
|
type BankOperation,
|
||||||
|
bankDateInputValue,
|
||||||
|
bankDateSchema,
|
||||||
|
bankToday,
|
||||||
|
} from "@/entities/bank-card";
|
||||||
|
import { formatMoney } from "@/shared/lib";
|
||||||
|
import type { OperationValues } from "./OperationForm.types";
|
||||||
|
|
||||||
|
type Choice = { value: string; label: string };
|
||||||
|
type OperationFieldsProps = {
|
||||||
|
editing: boolean;
|
||||||
|
refundCardId: string;
|
||||||
|
kind: OperationValues["kind"];
|
||||||
|
cards: Choice[];
|
||||||
|
targets: Choice[];
|
||||||
|
categories: Choice[];
|
||||||
|
defaultCategory: string;
|
||||||
|
};
|
||||||
|
const OperationFields: FC<OperationFieldsProps> = (props) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const {
|
||||||
|
control,
|
||||||
|
register,
|
||||||
|
setValue,
|
||||||
|
formState: { errors, isSubmitting },
|
||||||
|
} = useFormContext<OperationValues>();
|
||||||
|
return (
|
||||||
|
<Stack>
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name="kind"
|
||||||
|
render={({ field }) => (
|
||||||
|
<Select
|
||||||
|
label={t("bank.kind")}
|
||||||
|
required
|
||||||
|
data={(["expense", "topup", "transfer", "refund"] as const).map(
|
||||||
|
(value) => ({ value, label: t(`bank.kinds.${value}`) }),
|
||||||
|
)}
|
||||||
|
{...field}
|
||||||
|
disabled={isSubmitting || props.editing}
|
||||||
|
onChange={(value) => {
|
||||||
|
field.onChange(value ?? "expense");
|
||||||
|
if (value === "refund") setValue("cardId", props.refundCardId);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name="cardId"
|
||||||
|
render={({ field }) => (
|
||||||
|
<Select
|
||||||
|
label={t(
|
||||||
|
props.kind === "transfer" ? "bank.source" : "bank.operationCard",
|
||||||
|
)}
|
||||||
|
required
|
||||||
|
data={props.cards}
|
||||||
|
{...field}
|
||||||
|
disabled={isSubmitting || props.kind === "refund"}
|
||||||
|
error={errors.cardId?.message}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{props.kind === "transfer" && (
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name="targetCardId"
|
||||||
|
render={({ field }) => (
|
||||||
|
<Select
|
||||||
|
label={t("bank.destination")}
|
||||||
|
required
|
||||||
|
data={props.targets}
|
||||||
|
{...field}
|
||||||
|
disabled={isSubmitting}
|
||||||
|
error={errors.targetCardId?.message}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<TextInput
|
||||||
|
label={t("bank.amount")}
|
||||||
|
required
|
||||||
|
inputMode="decimal"
|
||||||
|
{...register("amount")}
|
||||||
|
error={errors.amount?.message}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name="date"
|
||||||
|
render={({ field }) => (
|
||||||
|
<DateInput
|
||||||
|
{...field}
|
||||||
|
label={t("bank.date")}
|
||||||
|
required
|
||||||
|
valueFormat="DD.MM.YYYY"
|
||||||
|
value={
|
||||||
|
bankDateSchema.safeParse(field.value).success ? field.value : null
|
||||||
|
}
|
||||||
|
dateParser={(value) =>
|
||||||
|
bankDateSchema.safeParse(bankDateInputValue(value)).success
|
||||||
|
? bankDateInputValue(value)
|
||||||
|
: null
|
||||||
|
}
|
||||||
|
fixOnBlur={false}
|
||||||
|
onInput={(event) =>
|
||||||
|
field.onChange(bankDateInputValue(event.currentTarget.value))
|
||||||
|
}
|
||||||
|
onChange={(value) => field.onChange(value ?? "")}
|
||||||
|
onBlur={(event) => {
|
||||||
|
field.onChange(bankDateInputValue(event.currentTarget.value));
|
||||||
|
field.onBlur();
|
||||||
|
}}
|
||||||
|
maxDate={bankToday()}
|
||||||
|
popoverProps={{
|
||||||
|
withinPortal: false,
|
||||||
|
middlewares: { shift: { crossAxis: true } },
|
||||||
|
}}
|
||||||
|
error={errors.date?.message}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{props.kind === "expense" && (
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name="categoryId"
|
||||||
|
render={({ field }) => (
|
||||||
|
<Select
|
||||||
|
label={t("bank.category")}
|
||||||
|
required
|
||||||
|
data={props.categories}
|
||||||
|
{...field}
|
||||||
|
value={field.value || props.defaultCategory}
|
||||||
|
disabled={isSubmitting}
|
||||||
|
error={errors.categoryId?.message}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<Textarea
|
||||||
|
label={t("bank.description")}
|
||||||
|
{...register("description")}
|
||||||
|
error={errors.description?.message}
|
||||||
|
/>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
type RefundFieldsProps = {
|
||||||
|
editing: boolean;
|
||||||
|
expenses: Choice[];
|
||||||
|
selected?: Choice;
|
||||||
|
onSelect: (id: string) => void;
|
||||||
|
limit: BankOperation["availableRefund"] | undefined;
|
||||||
|
};
|
||||||
|
const RefundFields: FC<RefundFieldsProps> = (props) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const {
|
||||||
|
control,
|
||||||
|
formState: { errors, isSubmitting },
|
||||||
|
} = useFormContext<OperationValues>();
|
||||||
|
return (
|
||||||
|
<Stack>
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name="originalExpenseId"
|
||||||
|
render={({ field }) => (
|
||||||
|
<Select
|
||||||
|
label={t("bank.expense")}
|
||||||
|
required
|
||||||
|
data={
|
||||||
|
props.selected &&
|
||||||
|
!props.expenses.some(
|
||||||
|
(item) => item.value === props.selected?.value,
|
||||||
|
)
|
||||||
|
? [props.selected, ...props.expenses]
|
||||||
|
: props.expenses
|
||||||
|
}
|
||||||
|
{...field}
|
||||||
|
onChange={(value) => {
|
||||||
|
field.onChange(value ?? "");
|
||||||
|
props.onSelect(value ?? "");
|
||||||
|
}}
|
||||||
|
disabled={isSubmitting || props.editing}
|
||||||
|
error={errors.originalExpenseId?.message}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{props.limit && (
|
||||||
|
<Text>
|
||||||
|
{t("bank.availableRefund", { amount: formatMoney(props.limit) })}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
{props.editing && <Text>{t("bank.purchaseImmutable")}</Text>}
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { OperationFields, RefundFields };
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export { CardsPage } from "./ui/CardsPage";
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
.card {
|
||||||
|
text-decoration: none;
|
||||||
|
color: inherit;
|
||||||
|
min-width: 0;
|
||||||
|
max-width: 28rem;
|
||||||
|
border-radius: 1.25rem;
|
||||||
|
background: transparent;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.card:focus-visible {
|
||||||
|
outline: 2px solid var(--mantine-primary-color-filled);
|
||||||
|
outline-offset: 3px;
|
||||||
|
}
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
import { MantineProvider } from "@mantine/core";
|
||||||
|
import { QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
fireEvent,
|
||||||
|
render,
|
||||||
|
screen,
|
||||||
|
waitFor,
|
||||||
|
within,
|
||||||
|
} from "@testing-library/react";
|
||||||
|
import { HttpResponse, http } from "msw";
|
||||||
|
import { MemoryRouter } from "react-router";
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { configureAuthClient } from "@/shared/api";
|
||||||
|
import { createTestQueryClient } from "@/test/query";
|
||||||
|
import { server } from "@/test/server";
|
||||||
|
import { CardsPage } from "./CardsPage";
|
||||||
|
|
||||||
|
const money = (value: string) => ({ currency: "RUB", value });
|
||||||
|
function renderCards(fail = false, categoryFail = false) {
|
||||||
|
configureAuthClient({
|
||||||
|
accessToken: () => "test",
|
||||||
|
refresh: async () => false,
|
||||||
|
clear: () => {},
|
||||||
|
});
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/categories", () =>
|
||||||
|
categoryFail ? HttpResponse.error() : HttpResponse.json([]),
|
||||||
|
),
|
||||||
|
http.get("*/api/v1/bank-cards", () =>
|
||||||
|
fail ? HttpResponse.error() : HttpResponse.json([]),
|
||||||
|
),
|
||||||
|
http.get("*/api/v1/bank-cards/summary", () =>
|
||||||
|
HttpResponse.json({
|
||||||
|
month: "2026-09",
|
||||||
|
cardId: null,
|
||||||
|
expenses: money("0"),
|
||||||
|
refunds: money("0"),
|
||||||
|
net: money("0"),
|
||||||
|
categories: [],
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return render(
|
||||||
|
<QueryClientProvider client={createTestQueryClient()}>
|
||||||
|
<MantineProvider env="test">
|
||||||
|
<MemoryRouter initialEntries={["/cards?month=2026-09"]}>
|
||||||
|
<CardsPage />
|
||||||
|
</MemoryRouter>
|
||||||
|
</MantineProvider>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
describe("CardsPage", () => {
|
||||||
|
it("preserves exact negative opening amount and the creation intent through unknown failure", async () => {
|
||||||
|
renderCards();
|
||||||
|
await screen.findByRole("heading", { name: "Добавьте первую карту" });
|
||||||
|
fireEvent.click(
|
||||||
|
screen.getAllByRole("button", { name: "Добавить карту" })[0],
|
||||||
|
);
|
||||||
|
const dialog = screen.getByRole("dialog");
|
||||||
|
const submitted: Record<string, unknown>[] = [];
|
||||||
|
let resolve: (() => void) | undefined;
|
||||||
|
server.use(
|
||||||
|
http.post("*/api/v1/bank-cards", async ({ request }) => {
|
||||||
|
submitted.push((await request.json()) as Record<string, unknown>);
|
||||||
|
if (submitted.length === 1) {
|
||||||
|
await new Promise<void>((r) => {
|
||||||
|
resolve = r;
|
||||||
|
});
|
||||||
|
return HttpResponse.error();
|
||||||
|
}
|
||||||
|
return HttpResponse.json({ id: submitted[0].id }, { status: 201 });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
fireEvent.change(within(dialog).getByLabelText(/Название карты/), {
|
||||||
|
target: { value: " Повседневная " },
|
||||||
|
});
|
||||||
|
fireEvent.change(within(dialog).getByLabelText(/Начальный остаток/), {
|
||||||
|
target: { value: "1,001" },
|
||||||
|
});
|
||||||
|
fireEvent.click(within(dialog).getByRole("button", { name: "Сохранить" }));
|
||||||
|
expect(
|
||||||
|
await screen.findByText(/Введите сумму в допустимом диапазоне/),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
expect(submitted).toHaveLength(0);
|
||||||
|
fireEvent.change(within(dialog).getByLabelText(/Начальный остаток/), {
|
||||||
|
target: { value: "-92233720368547758,08" },
|
||||||
|
});
|
||||||
|
fireEvent.change(within(dialog).getByLabelText(/Дата начала учёта/), {
|
||||||
|
target: { value: "2026-01-01" },
|
||||||
|
});
|
||||||
|
fireEvent.click(within(dialog).getByRole("button", { name: "Сохранить" }));
|
||||||
|
await waitFor(() => expect(submitted).toHaveLength(1));
|
||||||
|
expect(
|
||||||
|
within(dialog).getByRole("button", { name: "Отмена" }),
|
||||||
|
).toBeDisabled();
|
||||||
|
expect(
|
||||||
|
within(dialog).getByRole("button", { name: "Закрыть" }),
|
||||||
|
).toBeDisabled();
|
||||||
|
resolve?.();
|
||||||
|
await screen.findByText(/Не удалось подтвердить сохранение/);
|
||||||
|
expect(within(dialog).getByLabelText(/Начальный остаток/)).toHaveValue(
|
||||||
|
"-92233720368547758,08",
|
||||||
|
);
|
||||||
|
fireEvent.click(within(dialog).getByRole("button", { name: "Сохранить" }));
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),
|
||||||
|
);
|
||||||
|
expect(submitted[0]).toEqual(submitted[1]);
|
||||||
|
expect(submitted[0]).toMatchObject({
|
||||||
|
name: "Повседневная",
|
||||||
|
bankName: null,
|
||||||
|
lastFour: null,
|
||||||
|
openingBalance: money("-92233720368547758.08"),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it("uses archive only for card list and keeps all-card summary including negative net", async () => {
|
||||||
|
renderCards();
|
||||||
|
const requests: string[] = [];
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards", ({ request }) => {
|
||||||
|
requests.push(new URL(request.url).search);
|
||||||
|
return HttpResponse.json([
|
||||||
|
{
|
||||||
|
id: "demo",
|
||||||
|
name: "Запасная",
|
||||||
|
bankName: null,
|
||||||
|
lastFour: null,
|
||||||
|
balance: money("0"),
|
||||||
|
archivedAt: "2026-09-01",
|
||||||
|
version: 1,
|
||||||
|
openingBalance: money("0"),
|
||||||
|
openingDate: "2026-01-01",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
fireEvent.click(screen.getByLabelText("Показать архив"));
|
||||||
|
await screen.findByText("Запасная");
|
||||||
|
expect(requests).toContain("?includeArchived=true");
|
||||||
|
expect(screen.getByLabelText("Период")).toHaveTextContent(
|
||||||
|
"01.09.2026 – 30.09.2026",
|
||||||
|
);
|
||||||
|
expect(screen.getByRole("link", { name: /Запасная/ })).toHaveAttribute(
|
||||||
|
"href",
|
||||||
|
"/cards/demo?from=2026-09-01&to=2026-09-30",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
it("applies a completed custom period to the summary", async () => {
|
||||||
|
renderCards();
|
||||||
|
await screen.findByText("За этот период операций по расходам нет.");
|
||||||
|
await screen.findByRole("heading", { name: "Добавьте первую карту" });
|
||||||
|
const requests: string[] = [];
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/summary", ({ request }) => {
|
||||||
|
requests.push(new URL(request.url).search);
|
||||||
|
return HttpResponse.json({
|
||||||
|
cardId: null,
|
||||||
|
expenses: money("0"),
|
||||||
|
refunds: money("0"),
|
||||||
|
net: money("0"),
|
||||||
|
categories: [],
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
fireEvent.click(screen.getByLabelText("Период"));
|
||||||
|
fireEvent.click(
|
||||||
|
await screen.findByRole("button", { name: "10 September 2026" }),
|
||||||
|
);
|
||||||
|
expect(requests).toHaveLength(0);
|
||||||
|
|
||||||
|
fireEvent.click(
|
||||||
|
await screen.findByRole("button", { name: "20 September 2026" }),
|
||||||
|
);
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(requests.at(-1)).toBe("?from=2026-09-10&to=2026-09-20"),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
it("shows retry after failure instead of presenting an empty list", async () => {
|
||||||
|
renderCards(true);
|
||||||
|
// Mount starts asynchronously; this handler owns the request.
|
||||||
|
expect(await screen.findByRole("alert")).toHaveTextContent(
|
||||||
|
"Не удалось загрузить данные карт.",
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
screen.queryByRole("heading", { name: "Добавьте первую карту" }),
|
||||||
|
).not.toBeInTheDocument();
|
||||||
|
server.use(http.get("*/api/v1/bank-cards", () => HttpResponse.json([])));
|
||||||
|
fireEvent.click(
|
||||||
|
within(screen.getByRole("alert")).getByRole("button", {
|
||||||
|
name: "Повторить",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await screen.findByRole("heading", { name: "Добавьте первую карту" });
|
||||||
|
});
|
||||||
|
it("makes failed category loading recoverable without hiding successful cards data", async () => {
|
||||||
|
renderCards(false, true);
|
||||||
|
await screen.findByRole("heading", { name: "Добавьте первую карту" });
|
||||||
|
expect(await screen.findByRole("alert")).toHaveTextContent(
|
||||||
|
"Не удалось загрузить данные карт.",
|
||||||
|
);
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/bank-cards/categories", () =>
|
||||||
|
HttpResponse.json([
|
||||||
|
{ id: "default", name: "Другое", version: 1, isDefault: true },
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
fireEvent.click(
|
||||||
|
within(screen.getByRole("alert")).getByRole("button", {
|
||||||
|
name: "Повторить",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await screen.findByRole("button", { name: "Категории" });
|
||||||
|
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import type { FC } from "react";
|
||||||
|
import { BankCardForm, CategoryManager } from "@/entities/bank-card";
|
||||||
|
import { CardsPageView } from "./CardsPage.view";
|
||||||
|
import { useCardsPageVm } from "./CardsPage.vm";
|
||||||
|
|
||||||
|
const CardsPage: FC = () => {
|
||||||
|
const vm = useCardsPageVm();
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<CardsPageView vm={vm} />
|
||||||
|
{vm.adding && <BankCardForm onClose={() => vm.setAdding(false)} />}
|
||||||
|
{vm.managingCategories && (
|
||||||
|
<CategoryManager onClose={() => vm.setManagingCategories(false)} />
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { CardsPage };
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
import {
|
||||||
|
ActionIcon,
|
||||||
|
Button,
|
||||||
|
Group,
|
||||||
|
Paper,
|
||||||
|
SimpleGrid,
|
||||||
|
Skeleton,
|
||||||
|
Stack,
|
||||||
|
Switch,
|
||||||
|
Text,
|
||||||
|
Title,
|
||||||
|
} from "@mantine/core";
|
||||||
|
import type { FC } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { Link } from "react-router";
|
||||||
|
import {
|
||||||
|
BankCardFace,
|
||||||
|
BankFeedback,
|
||||||
|
BankPeriodPicker,
|
||||||
|
BankSummaryView,
|
||||||
|
} from "@/entities/bank-card";
|
||||||
|
import { LoadingSkeleton, StateView } from "@/shared/ui";
|
||||||
|
import classes from "./CardsPage.module.css";
|
||||||
|
import type { CardsPageVm } from "./CardsPage.vm";
|
||||||
|
|
||||||
|
type CardsPageViewProps = { vm: CardsPageVm };
|
||||||
|
const CardsPageView: FC<CardsPageViewProps> = (props) => {
|
||||||
|
const { vm } = props;
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<Stack gap="lg">
|
||||||
|
<Group gap="sm">
|
||||||
|
<Title order={1}>{t("bank.title")}</Title>
|
||||||
|
<ActionIcon
|
||||||
|
size="lg"
|
||||||
|
variant="light"
|
||||||
|
aria-label={t("bank.addCard")}
|
||||||
|
title={t("bank.addCard")}
|
||||||
|
onClick={() => vm.setAdding(true)}
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
width="20"
|
||||||
|
height="20"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
strokeLinecap="round"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path d="M12 5v14M5 12h14" />
|
||||||
|
</svg>
|
||||||
|
</ActionIcon>
|
||||||
|
</Group>
|
||||||
|
<Switch
|
||||||
|
label={t("bank.showArchive")}
|
||||||
|
checked={vm.archive}
|
||||||
|
onChange={(event) => vm.setArchive(event.currentTarget.checked)}
|
||||||
|
/>
|
||||||
|
{vm.items ? (
|
||||||
|
vm.items.length ? (
|
||||||
|
<SimpleGrid cols={{ base: 1, sm: 2 }}>
|
||||||
|
{vm.items.map((card) => (
|
||||||
|
<Paper
|
||||||
|
key={card.id}
|
||||||
|
component={Link}
|
||||||
|
to={card.to}
|
||||||
|
p={0}
|
||||||
|
className={classes.card}
|
||||||
|
>
|
||||||
|
<BankCardFace card={card} />
|
||||||
|
</Paper>
|
||||||
|
))}
|
||||||
|
</SimpleGrid>
|
||||||
|
) : (
|
||||||
|
<StateView
|
||||||
|
title={t("bank.empty")}
|
||||||
|
text={t(vm.archive ? "bank.emptyHint" : "bank.noActive")}
|
||||||
|
action={
|
||||||
|
<Button onClick={() => vm.setAdding(true)}>
|
||||||
|
{t("bank.addCard")}
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
) : vm.cards.isLoading ? (
|
||||||
|
<LoadingSkeleton label={t("bank.loading")}>
|
||||||
|
<SimpleGrid cols={{ base: 1, sm: 2 }}>
|
||||||
|
<Skeleton h={250} />
|
||||||
|
<Skeleton h={250} />
|
||||||
|
</SimpleGrid>
|
||||||
|
</LoadingSkeleton>
|
||||||
|
) : null}
|
||||||
|
{vm.cards.isError && (
|
||||||
|
<Group role="alert">
|
||||||
|
<Text>{t(vm.items ? "bank.refreshError" : "bank.error")}</Text>
|
||||||
|
<Button variant="default" onClick={() => void vm.cards.refetch()}>
|
||||||
|
{t("bank.retry")}
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
)}
|
||||||
|
{vm.cards.data && vm.cards.isFetching && (
|
||||||
|
<Text role="status">{t("bank.refreshing")}</Text>
|
||||||
|
)}
|
||||||
|
<Group align="flex-end" justify="space-between">
|
||||||
|
<BankPeriodPicker period={vm.period} onChange={vm.setPeriod} />
|
||||||
|
{Boolean(vm.categories.data?.length || vm.cards.data?.length) && (
|
||||||
|
<Button
|
||||||
|
variant="subtle"
|
||||||
|
color="gray"
|
||||||
|
onClick={() => vm.setManagingCategories(true)}
|
||||||
|
leftSection={
|
||||||
|
<svg
|
||||||
|
width="18"
|
||||||
|
height="18"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="1.7"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path d="M3 3h7v7H3zM14 3h7v7h-7zM3 14h7v7H3zM14 14h7v7h-7z" />
|
||||||
|
</svg>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{t("bank.categories")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</Group>
|
||||||
|
<BankSummaryView
|
||||||
|
all
|
||||||
|
data={vm.summary.data}
|
||||||
|
loading={vm.summary.isLoading}
|
||||||
|
error={vm.summary.isError}
|
||||||
|
fetching={vm.summary.isFetching}
|
||||||
|
retry={() => void vm.summary.refetch()}
|
||||||
|
/>
|
||||||
|
{vm.categories.isError && (
|
||||||
|
<BankFeedback
|
||||||
|
loadingError
|
||||||
|
error={vm.categories.error}
|
||||||
|
cached={Boolean(vm.categories.data)}
|
||||||
|
retry={() => void vm.categories.refetch()}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { CardsPageView };
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useSearchParams } from "react-router";
|
||||||
|
import {
|
||||||
|
bankPeriod,
|
||||||
|
useBankCards,
|
||||||
|
useBankCategories,
|
||||||
|
useBankSummary,
|
||||||
|
} from "@/entities/bank-card";
|
||||||
|
|
||||||
|
function useCardsPageVm() {
|
||||||
|
const [params, setParams] = useSearchParams();
|
||||||
|
const period = bankPeriod(params);
|
||||||
|
const [archive, setArchive] = useState(false);
|
||||||
|
const categories = useBankCategories();
|
||||||
|
const [managingCategories, setManagingCategories] = useState(false);
|
||||||
|
const [adding, setAdding] = useState(false);
|
||||||
|
const cards = useBankCards(archive);
|
||||||
|
const summary = useBankSummary(period);
|
||||||
|
return {
|
||||||
|
categories,
|
||||||
|
managingCategories,
|
||||||
|
setManagingCategories,
|
||||||
|
period,
|
||||||
|
archive,
|
||||||
|
setArchive,
|
||||||
|
adding,
|
||||||
|
setAdding,
|
||||||
|
cards,
|
||||||
|
summary,
|
||||||
|
setPeriod: (value: [string | null, string | null]) => {
|
||||||
|
if (value[0] && value[1]) setParams({ from: value[0], to: value[1] });
|
||||||
|
},
|
||||||
|
items: cards.data?.map((card) => ({
|
||||||
|
...card,
|
||||||
|
to: `/cards/${card.id}?${new URLSearchParams(period)}`,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
type CardsPageVm = ReturnType<typeof useCardsPageVm>;
|
||||||
|
|
||||||
|
export { type CardsPageVm, useCardsPageVm };
|
||||||
@@ -4,10 +4,12 @@ import { useStockSearch } from "@/entities/stock";
|
|||||||
import { apiErrorCode } from "@/shared/api";
|
import { apiErrorCode } from "@/shared/api";
|
||||||
import { instrumentLogoUrl } from "@/shared/lib";
|
import { instrumentLogoUrl } from "@/shared/lib";
|
||||||
|
|
||||||
|
const SEARCH_DEBOUNCE_MS = 300;
|
||||||
|
|
||||||
function useStocksPageVm() {
|
function useStocksPageVm() {
|
||||||
const [params, setParams] = useSearchParams();
|
const [params, setParams] = useSearchParams();
|
||||||
const query = params.get("q") ?? "";
|
const query = params.get("q") ?? "";
|
||||||
const [debounced] = useDebouncedValue(query.trim(), 300);
|
const [debounced] = useDebouncedValue(query.trim(), SEARCH_DEBOUNCE_MS);
|
||||||
const result = useStockSearch(debounced);
|
const result = useStockSearch(debounced);
|
||||||
const waiting = query.trim() !== debounced;
|
const waiting = query.trim() !== debounced;
|
||||||
return {
|
return {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user