Compare commits

..
53 Commits
Author SHA1 Message Date
ksv741 b34c1c860a chore(release): 0.4.0
Frontend image / publish (push) Successful in 6m44s
Conventional commits / commits (pull_request) Successful in 27s
Frontend security / security (pull_request) Successful in 10s
Frontend verify / verify (pull_request) Successful in 5m46s
Frontend security / security (push) Successful in 10s
Frontend verify / verify (push) Successful in 6m57s
2026-09-26 22:10:01 +03:00
ksv741 a005e8b13b chore: synchronize develop before release
Conventional commits / commits (pull_request) Successful in 27s
Frontend security / security (pull_request) Successful in 10s
Frontend verify / verify (pull_request) Successful in 6m6s
Frontend security / security (push) Successful in 10s
Frontend verify / verify (push) Successful in 7m5s
2026-09-26 21:30:58 +03:00
ksv741 4e5f564fa1 feat: show persisted investment data and sync state
Consume the provided resource-envelope API snapshot. Preserve financial snapshots during
refresh, observe synchronization without importing, and fence late responses across
account and connection changes.
2026-09-26 21:22:49 +03:00
codex-bot cd09ec698c refactor: colocate frontend component files (#35)
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Successful in 6m53s
2026-09-23 08:49:01 +03:00
ksv741 b987fd8e78 refactor: colocate frontend component files
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Successful in 5m10s
Conventional commits / commits (pull_request) Successful in 25s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 5m10s
2026-09-23 08:34:58 +03:00
ksv741 85fcfe3d07 refactor: establish local frontend workspace boundaries
Conventional commits / commits (pull_request) Successful in 24s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 5m18s
Frontend security / security (push) Successful in 10s
Frontend verify / verify (push) Successful in 6m45s
OpenSpec change: evolve-frontend-stack
2026-09-22 22:11:02 +03:00
ksv741 c86be7bf73 fix(ui): improve financial text contrast
TD-010: use readable semantic text colors on financial surfaces while preserving signs
and state meanings.
2026-09-21 21:10:10 +03:00
ksv741 6a87379813 fix(ci): resume verification of immutable release images
TD-009: retry verification of an existing digest without republishing. Paired backend
workflow fix: 82eccc3.
2026-09-21 21:09:53 +03:00
ksv741 db184c8cae fix(api): update validation and conflict response contract
TD-003 and TD-005: explicitly deliver OpenAPI and generated types from backend commit 1667991.
2026-09-21 21:09:41 +03:00
ksv741 a209d71589 fix(auth): isolate session races and financial caches
TD-001 and TD-002: serialize cookie writes, ignore stale responses and reset financial
queries on identity changes. Backend cookie lifecycle regression: ec5780d.
2026-09-21 21:09:23 +03:00
ksv741 3c99debe88 chore(release): 0.3.0
Frontend image / publish (push) Successful in 5m45s
Conventional commits / commits (pull_request) Successful in 27s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 4m42s
Frontend security / security (push) Successful in 10s
Frontend verify / verify (push) Successful in 6m17s
2026-09-20 20:09:11 +03:00
ksv741 bb30935f73 feat: add installable PWA #30
Conventional commits / commits (pull_request) Successful in 30s
Frontend security / security (pull_request) Successful in 1m7s
Frontend verify / verify (pull_request) Successful in 4m48s
Frontend security / security (push) Successful in 11s
Frontend verify / verify (push) Successful in 6m17s
2026-09-20 19:55:53 +03:00
ksv741 f486ae4fb2 chore(release): 0.2.3
Frontend image / publish (push) Successful in 4m51s
Conventional commits / commits (pull_request) Successful in 21s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 3m56s
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Successful in 5m27s
2026-09-19 16:25:12 +03:00
ksv741 9171b9f5c8 fix: correct Nexus routing and SonarQube host 2026-09-19 16:24:07 +03:00
ksv741 d68ec3b15b chore(release): 0.2.2
Frontend image / publish (push) Failing after 3m59s
Conventional commits / commits (pull_request) Successful in 20s
Frontend security / security (pull_request) Successful in 10s
Frontend verify / verify (pull_request) Successful in 4m5s
Frontend security / security (push) Successful in 10s
Frontend verify / verify (push) Failing after 4m26s
2026-09-19 15:04:33 +03:00
ksv741 bac95ebb39 fix: update Nexus registry host
Conventional commits / commits (pull_request) Successful in 21s
Frontend security / security (pull_request) Successful in 8s
Frontend verify / verify (pull_request) Successful in 4m11s
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Failing after 4m7s
2026-09-19 14:51:25 +03:00
ksv741 8183b66e2f chore(release): 0.2.1
Conventional commits / commits (pull_request) Successful in 20s
Frontend security / security (pull_request) Successful in 8s
Frontend verify / verify (pull_request) Successful in 3m36s
Frontend image / publish (push) Failing after 3m56s
Frontend security / security (push) Successful in 8s
Frontend verify / verify (push) Failing after 4m13s
2026-09-18 08:12:21 +03:00
ksv741 1ad578fb37 docs: use shared Nexus account #21
Frontend security / security (pull_request) Successful in 53s
Frontend verify / verify (pull_request) Successful in 3m52s
Conventional commits / commits (pull_request) Successful in 20s
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Failing after 7m49s
2026-09-17 20:53:03 +03:00
ksv741 999b8590ec ci: publish frontend images to Nexus #21
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Successful in 3m57s
Conventional commits / commits (pull_request) Failing after 19s
Frontend security / security (pull_request) Successful in 32s
Frontend verify / verify (pull_request) Successful in 3m54s
2026-09-17 20:41:12 +03:00
ksv741 3f19b3643f ci: add frontend SonarQube analysis #19
Conventional commits / commits (pull_request) Successful in 22s
Frontend security / security (pull_request) Successful in 16s
Frontend verify / verify (pull_request) Successful in 3m59s
Frontend security / security (push) Successful in 18s
Frontend verify / verify (push) Successful in 9m45s
2026-09-16 20:08:51 +03:00
ksv741 97f1ad3e89 chore(release): 0.2.0
Frontend image / publish (push) Successful in 5m19s
Conventional commits / commits (pull_request) Successful in 22s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 4m7s
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Successful in 4m11s
2026-09-16 11:35:44 +03:00
ksv741 e31ab35a5a feat: add frontend container delivery
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 3m55s
Conventional commits / commits (pull_request) Successful in 21s
Frontend security / security (push) Successful in 8s
Frontend verify / verify (push) Successful in 3m50s
2026-09-16 09:41:38 +03:00
ksv741 d9ada27621 docs: make frontend instructions self-contained
Frontend security / security (pull_request) Successful in 8s
Frontend verify / verify (pull_request) Successful in 3m55s
Conventional commits / commits (pull_request) Successful in 20s
Frontend security / security (push) Successful in 8s
Frontend verify / verify (push) Successful in 3m49s
2026-09-15 20:45:37 +03:00
ksv741 9f7e342333 docs: simplify conventions layout
Frontend security / security (pull_request) Successful in 8s
Frontend verify / verify (pull_request) Successful in 3m53s
Conventional commits / commits (pull_request) Successful in 19s
Frontend security / security (push) Successful in 8s
Frontend verify / verify (push) Successful in 3m53s
2026-09-15 05:58:31 +03:00
ksv741 718365cd5a docs: refine frontend conventions and routing
Frontend security / security (push) Successful in 8s
Frontend verify / verify (push) Successful in 3m56s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 3m41s
Conventional commits / commits (pull_request) Successful in 19s
2026-09-15 05:42:14 +03:00
ksv741 0244acf429 chore(release): 0.1.0
Conventional commits / commits (pull_request) Successful in 22s
Frontend security / security (pull_request) Successful in 10s
Frontend verify / verify (pull_request) Successful in 4m31s
Frontend security / security (push) Successful in 10s
Frontend verify / verify (push) Successful in 4m34s
2026-09-14 07:04:41 +03:00
ksv741 53b18c6e86 chore: configure releases and develop workflow 2026-09-14 07:02:45 +03:00
ksv741 dc3434c371 docs: update system documentation references
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Successful in 4m14s
2026-09-14 05:51:41 +03:00
ksv741 3be6e61b8f chore: secure hooks and update dependencies #4 #9
Frontend security / security (push) Successful in 11s
Frontend verify / verify (push) Successful in 4m35s
2026-09-13 19:36:15 +03:00
ksv741 7a89356f87 docs: align OpenAPI workflow guidance #3
Frontend verify / verify (push) Successful in 4m31s
2026-09-13 19:08:13 +03:00
renovate-bot 0c6bac8b90 chore(deps): update non-major dependencies
Frontend verify / verify (push) Successful in 4m29s
2026-09-13 15:37:11 +00:00
ksv741 82b904393d chore: make issue references optional and use chore for dependency updates #5
Frontend verify / verify (push) Successful in 4m56s
2026-09-13 18:30:04 +03:00
ksv741 4b97395385 ci: configure Renovate dependency updates #5
Frontend verify / verify (push) Successful in 6m22s
2026-09-13 18:13:10 +03:00
renovate-bot bb6623275c Add renovate.json
Frontend verify / verify (push) Failing after 43s
2026-09-13 14:02:36 +00:00
ksv741 942ed3d453 test: allow UI scenarios more time in CI #1
Frontend verify / verify (push) Successful in 4m54s
2026-09-13 16:31:02 +03:00
ksv741 2f26e4fe0d ci: disable memory-heavy Knip raw transfer #1
Frontend verify / verify (push) Failing after 3m44s
2026-09-13 16:22:17 +03:00
ksv741 22e331e2ff ci: run full frontend verification #1
Frontend verify / verify (push) Failing after 3m48s
2026-09-13 16:15:54 +03:00
ksv741 ccff422f36 ci: run Biome on branch pushes in Gitea
Biome / biome (push) Successful in 37s
2026-09-13 15:56:00 +03:00
ksv741 117e74cdfc chore: upgrade Node to 24 LTS 2026-09-13 15:05:37 +03:00
ksv741 53c852b437 refactor: enforce semantic values and numeric lint rules 2026-09-13 14:37:25 +03:00
ksv741 24d332e063 feat: replace paired date inputs with range pickers 2026-09-12 22:41:40 +03:00
ksv741 aba4cf1ce8 feat(cards): refine controls and modal transitions 2026-09-12 22:34:27 +03:00
ksv741 cf21a5bd17 feat(card): refine header and inline actions 2026-09-12 22:07:29 +03:00
ksv741 9bb385b9f0 feat(cards): filter operations by date range 2026-09-12 21:52:13 +03:00
ksv741 8e58c016d2 feat(ui): animate navigation and operation icons 2026-09-12 21:31:57 +03:00
ksv741 d3ac8c242d feat: improve bank card expenses summary 2026-09-12 20:54:57 +03:00
ksv741 9a65687d38 feat: improve card operations pagination and scroll behavior 2026-09-12 20:31:44 +03:00
ksv741 ae06f6e6e0 chore: save pending changes 2026-09-12 19:59:10 +03:00
ksv741 6b310db0b8 feat: polish bank operation cards and dates 2026-09-12 19:56:12 +03:00
ksv741 dedfec10d1 feat(cards): show operation icons on hover 2026-09-12 19:29:11 +03:00
ksv741 ff4e88edbe feat: add manual bank card screens
Add cards, operations, refunds, categories and monthly summaries with Mantine date controls.

Derive banking types from runtime OpenAPI. Cover recovery and session isolation.
2026-09-12 18:34:41 +03:00
ksv741 427ca23a43 test: keep portfolio metadata authoritative in cards 2026-09-12 15:38:04 +03:00
ksv741 a42f104bed docs: update routes to system documentation 2026-09-12 14:45:43 +03:00
324 changed files with 29481 additions and 6421 deletions
-23
View File
@@ -1,23 +0,0 @@
# Frontend router
Читай строки, которые активирует задача, затронутый путь **или** обнаруженная
граница. Объединяй совпадения; якорь разрешает чтение только нужного раздела.
Не загружай все conventions из-за одного frontend-файла.
| Решение / сигнал | Читать до решения |
| --- | --- |
| Создать/перенести 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) |
| Только продуктовая строка или Zod message | [Строки](conventions/frontend-ui.md#строки-и-валидация) |
| Только TS declaration/import/export | [Код](conventions/frontend-ui.md#код-и-components) |
| query/mutation, shared/api, server state/cache, generated types, Bearer/refresh | [Data](conventions/frontend-data.md) |
| Тесты или behavior с testing risk | [Testing](conventions/frontend-testing.md) |
| Новый abstraction/dependency, refactor или неоднозначный scope | [Общий выбор реализации](../../docs/development/engineering-governance.md#выбор-реализации) |
| Request/response field, route/status/error shape, OpenAPI snapshot/generated type | [Общий contract workflow](../../docs/development/runtime-openapi-verification.md) |
| Login/refresh/logout, token/cookie, auth ownership | Data + [security](../../backend/.ai/conventions/security-auth.md) + Testing |
| Storybook/theme/tokens/shared UI | UI + точные [источники](SOURCES.md) дизайн-системы/каталога |
UI-only props/presentation требуют UI, без API/structure/testing при отсутствии
их triggers. Показ query state не означает изменение data fetching.
Изменение тестов активирует Testing и без production diff. Нужные project facts
выбирай через SOURCES. Повтори routing при новой границе и по итоговому diff.
-18
View File
@@ -1,18 +0,0 @@
# Источники frontend
| Что нужно установить | Владелец |
| --- | --- |
| Какое implementation-решение принять | [CONVENTIONS](CONVENTIONS.md) |
| HTTP wire contract и направление генерации | Backend runtime OpenAPI → [snapshot/types workflow](../../docs/development/runtime-openapi-verification.md) |
| Error codes/validation/error envelope | [docs: HTTP API](../../docs/AI_INDEX.md#http-api) |
| Auth/session, token storage и refresh | [docs: Security](../../docs/AI_INDEX.md#security) |
| Значение Money, cached snapshot, account/position/income | [docs: Domain](../../docs/AI_INDEX.md#domain) |
| Mantine/theme/tokens и существующие stories | [docs: UI](../../docs/AI_INDEX.md#ui) |
| As-built behavior нужной feature | [docs: Features](../../docs/AI_INDEX.md#features) |
| Существующие behavioral requirements, если нужны по задаче | [specs index](../../specs/AI_INDEX.md) |
| Действующие versions/scripts/check scope | package.json, lockfile, Biome/TS/dependency configs |
Открывай точный source только по возникшему вопросу. Code examples показывают
pattern, но не переопределяют контракт. Specs не являются editable OpenAPI;
SDD-процедура для обычной работы не нужна. При конфликте источников сначала
установи факты, не меняй generated types или security policy по догадке.
+90
View File
@@ -0,0 +1,90 @@
# Frontend architecture
## Устройство и data flow
React + TypeScript + Vite SPA. Router задаёт navigation; providers в `app`
подключают auth, TanStack Query, i18n и Mantine. Vite использует React Compiler;
Vitest — отдельную JSDOM конфигурацию. Точные versions/scripts — в
[package.json](../package.json), реализация — source of truth.
```text
app → pages → features → entities → shared
page container → page VM → entity/feature query → shared/api → backend /api/v1
↓
props → state/section views
```
Server state и lifecycle запроса принадлежат TanStack Query; VM собирает данные
для view. Transport — `openapi-fetch`/`openapi-react-query`, типизированные из
предоставленного snapshot через `openapi-typescript`. Backend владеет wire
contract; frontend не читает его checkout для генерации и не вызывает T-Bank.
[Data convention](conventions/data.md) задаёт auth/cache границы.
## Выбор владельца
Сначала найди владельца поведения и ближайший пример. Расширяй existing slice,
если ответственность остаётся связной. Размер файла или возможный будущий reuse
не создают новую архитектурную границу.
| Ответственность | Размещение |
| --- | --- |
| Bootstrap, глобальные providers, routes | `app` |
| Композиция маршрута и поведение, нужное только этому экрану | `pages/<page>` |
| Самостоятельная пользовательская возможность с собственным смыслом | `features/<capability>` |
| Представление/поведение бизнес-сущности | `entities/<entity>` |
| Переиспользуемый код без WealthLedger domain meaning | `shared` |
Локальный FSD profile: `app → pages → features → entities → shared`, без `widgets`.
Крупный уникальный блок остаётся в своей page. Form, mutation или click handler
сами по себе не требуют feature. Два callers не делают domain helper generic shared.
Slice именуется по ответственности, а не `helpers`, `hooks` или `types`.
**Безопасный путь:** при сомнении оставь код у ближайшего допустимого owner.
Извлекай его, когда появилась самостоятельная ответственность или реальный reuse.
Не вводи новый layer и не обходи public API, чтобы устранить неудобный import.
## Imports и public API
Cross-slice consumer использует `@/` и `index.ts` владельца, например
`@/entities/portfolio`. Alias Vite и TypeScript согласован. Другой slice не
импортирует внутренний файл напрямую. Slices `pages`, `features`, `entities` не зависят от соседнего slice своего слоя;
композиция принадлежит вышележащему owner. Existing меж-slice исключения
не являются разрешением добавлять новые.
Направление зависимостей, public imports и запрет соседних slices в
`pages`, `features`, `entities` проверяет `npm run deps`. Внутренние imports
одного slice и связи shared segments этот запрет не ограничивает.
Knip проверяет использование exports, а не смысл placement.
## UI foundation
Private workspace `packages/tokens` экспортирует переносимый source design tokens
как `@wealthledger/tokens/tokens.json`. Private workspace `packages/ui`
адаптирует доверенный JSON к Mantine без runtime schema. App и Storybook читают
`@wealthledger/ui/theme` и явно подключают `@wealthledger/ui/styles.css` после
Mantine CSS. Потребители используют public exports пакетов напрямую. Storybook показывает synthetic presentation states,
не использует application API. RTL/MSW проверяют поведение приложения отдельно.
Route-aware AppShell и его navigation styles принадлежат `app/ui`;
`ProtectedLayout` использует public API этого владельца. При изменении foundation прочитай
[UI](conventions/ui.md#визуальная-основа) и [Storybook](conventions/storybook.md).
Статичные Add/Edit/Delete и публичный `IconProps` принадлежат private
`packages/icons`; package не зависит от UI, domain или motion.
`BankOperationIcon` и mappings остаются у entity. Card/Cards используют package
Add/Edit/Delete; restore/category SVG остаются локальными.
## Примеры
- Общая busy-область: существующий [LoadingSkeleton](../packages/ui/src/LoadingSkeleton/LoadingSkeleton.tsx), а не domain widget в shared.
- Account-income state views: [страница](../src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.tsx) и её `components/`; новый page-local filter остаётся здесь. Комплекты файлов группируются по [UI convention](conventions/ui.md#размещение-файлов-компонента).
- Portfolio query: [entity public API](../src/entities/portfolio/index.ts); новая UI-сводка с бизнес-смыслом не становится shared только из-за нескольких экранов.
## Проверка
После placement/import change: `npm run deps`, `npm run typecheck`, `npm run knip`;
после собственного behavior — применимые tests. Финальный gate указан в AGENTS.
Graph `src` и `packages` проверяет текущий dependency-cruiser; зависимости
из packages в код приложения `src` запрещены. Generated `packages/*/dist`
не анализируется как исходник; все package sources остаются в graph. Review отдельно проверяет смысл
owner: разрешённый dependency graph не доказывает правильный выбор слоя.
+85
View File
@@ -0,0 +1,85 @@
# Frontend data
## Выбор owner
Server state принадлежит TanStack Query, form state — React Hook Form, локальное
UI — React state. Не копируй успешный query result в useState/context для второго
кэша. Domain-specific queries, keys и policies принадлежат вызывающему slice;
общий transport — `shared/api`. Page VM выбирает inputs и собирает presentation data.
Используй `apiClient`/`apiQueryClient` из shared public API. Прямой fetch в
pages/features/entities и прямой T-Bank call запрещены. Сначала найди
существующий query того же endpoint; расширяй его owner, не создавай второй key
или глобальную query policy для одной страницы.
## Типы и contract
Backend-owned OpenAPI contract поступает во frontend как предоставленный
актуальный snapshot; generated `schema.d.ts` производен от него. Тип
request/response бери из generated `paths`, например:
```ts
type User = paths["/api/v1/auth/me"]["get"]["responses"][200]["content"]["application/json"];
```
Domain/UI type допустим, когда он отличается по смыслу, а не копирует transport DTO.
Generated TS вручную не исправляется. Не добавляй параллельный fetch/axios
client, runtime schema, hash/checksum registry или дополнительный drift checker
без отдельной текущей потребности; existing OpenAPI flow уже владеет генерацией. Frontend-команды не читают соседний
backend checkout и не проверяют backend runtime OpenAPI; изменение wire
shape/status/route сохраняет
публичный контракт предоставленного snapshot.
Одна UI-модель не требует менять API. `openapi:generate` работает offline от snapshot;
`openapi:check` генерирует во временный каталог и сравнивает, не меняя tracked files.
## Auth и invalidation
Bearer header принадлежит shared authenticated fetch; query/mutation не задают
Authorization. Auth endpoints исключены из Bearer/retry middleware. Refresh
координируется single-flight; после `401` с `UNAUTHORIZED` возможен один retry.
Не добавляй собственный refresh/retry loop в caller.
Protected queries используют existing session-aware boundary; logout очищает
session-scoped cache. Access token хранится только в памяти, refresh передаётся
httpOnly cookie с `credentials: include`. Не сохраняй tokens в localStorage,
URL, логах или fixtures. Logout очищает локальную session/cache и при ошибке
сети; до окончания auth bootstrap показывай neutral state. Перед auth change
прочитай shared client, session owner и их tests.
Успешная connection mutation коммитит подтверждённый status и сбрасывает financial
GET subtree; ошибка mutation не меняет generation/cache. Это отдельная граница
от обычного фонового refetch. Даже повторное сохранение того же token начинает
новую generation; поздний ответ прежней generation не попадает в новый кэш.
Mutations используют существующий generated client и query-key owner;
после успеха обновляй/invalidируй только связанные данные. Optimistic update
нужен конкретному UX и обязан иметь rollback/error behavior.
Default focus refetch выключен; freshness и retry задаются существующими
query options у entity/feature owner. После `staleTime` повторное открытие
экрана может запустить background refetch; focus сам по себе его не запускает.
При обычном refetch сохраняй Client Cached Snapshot, при session/connection
смене не показывай данные прежнего владельца. UI presentation — в UI convention.
## Errors
Извлекай code через existing `apiErrorCode` из shared/api. Backend Problem
Details code задаёт machine behavior; user-facing текст принадлежит i18n.
Network/unknown error получает безопасное локальное сообщение и retry,
не raw exception text. Input/domain failure сохраняет ввод и показывает
ошибку у ответственного form/section owner; не маскируй её успешным результатом.
Если одна группа API codes требует одинакового recovery в нескольких views,
сведи классификацию у ближайшего общего owner. Не размножай magic comparisons
и не объявляй закрытый frontend error enum: generated `code` пока `string`.
Неизвестный новый code должен сохранять fallback. Рефакторинг существующих
разных recovery paths требует behavior proof, а не общей обработки всех ошибок.
## Примеры и проверка
[usePortfolio](../../src/entities/portfolio/api/usePortfolio.ts) — entity query;
[shared client](../../src/shared/api/client.ts) — transport/auth boundary.
Изменяя header/retry/invalidation, проверяй наблюдаемое поведение через MSW и
[Testing](testing.md); не обращайся к реальному T-Bank.
`npm run openapi:check`, `npm run typecheck` и targeted tests проверяют разные
части решения. Для поведения API-клиента используй сценарии MSW на публичной
HTTP-границе; реализация сервера не является входом frontend-проверок.
+76
View File
@@ -0,0 +1,76 @@
# Работа в репозитории
## Граница и порядок работы
Репозиторий сам содержит инструкции, исходники, конфигурацию и входы своих
проверок. Сборка, CI и обязательный маршрут чтения работают без соседних
checkout. Внешний API задаётся предоставленным публичным контрактом;
исходники или инструкции его реализации не являются зависимостью разработки.
При нехватке требования сообщи, какое решение не определено, до его реализации.
Начни с результата и affected areas. До edits проследи flow/invariants, найди
owner и 1–3 примера. Код показывает механизм; случайный аналог не меняет контракт.
Работай напрямую; OpenSpec/SDD lifecycle — только по явному запросу.
Перед Node-командами активируй местную `.nvmrc`: `nvm use --silent`.
Сохраняй чужие staged/unstaged/untracked изменения и read-only архивы.
## Change scope
Сначала расширь существующего владельца. Иначе используй standard library,
платформу или установленную dependency; небольшая новая реализация допустима
при собственной ответственности. Не создавай helper/interface/wrapper ради
возможного reuse. Общее имя не означает общую бизнес-ответственность.
Сохраняй validation, authorization, atomicity, accessibility и migration safety.
После diff выполни Boy Scout review: проверь новое дублирование, owner, callers,
небольшие связанные legacy issues и соответствие local conventions. Исправляй
непосредственно связанные low-risk проблемы; широкий cleanup — отдельная задача.
## Domain values
Finite business vocabulary принадлежит одному domain/module/entity owner.
Переиспользуй его symbols; для нового словаря без аналога — `as const` + union.
Сохраняй wire values; generated/external enums не переписывай вручную.
Numeric policy называй по смыслу и единицам. Индексы, `Math.max(value, 0)` и
обычные labels не выноси в constants без semantic benefit.
Локальный TypeScript/lint профиль определяет дополнительные ограничения.
## Dependencies
Проверь аналоги и direct dependencies в местном manifest до добавления пакета.
Новая dependency оправдана текущей потребностью и меньшей общей сложностью;
оцени compatibility, runtime/bundle и maintenance/security. Импортируемый пакет
объявляется напрямую; транзитивная установка не является контрактом.
Сохраняй exact versions и lockfile; воспроизводимая установка — `npm ci`.
Peer-конфликт решай совместимыми версиями без `--force`/`--legacy-peer-deps`.
Используй существующий analyzer; не добавляй второй для той же проверки.
## Test Intent
Перед нетривиальным тестом кратко определи наблюдаемый исход, regression risk,
значимые edge/error/concurrency cases и самую дешёвую надёжную boundary.
Отдельный artifact не нужен. Проверяй результат, а не private call order,
декларации, тривиальные wrappers или поведение framework.
При bug сначала воспроизведи исход. Mock race не доказывает DB atomicity.
Уровни и runnable commands выбирай по местной testing convention.
## Проверки и завершение
Code/dependency change: `npm ci`, полный `npm run verify` и дополнительные
risk checks из местной testing convention. Targeted tests ускоряют итерацию,
но не заменяют финальный gate. `lint:fix`/format — edits, не proof.
Markdown-only: проверь новые/изменённые тексты, локальные ссылки/якоря, маршруты
чтения и `git diff --check`; application build ради текста не нужен.
Повтори routing по staged/unstaged/new files. Запиши краткие команды, результаты
и ограничения. Зелёный lint не заменяет semantic/security review.
## Git и релизы
Работа — в `codex/<task>` от актуального `develop`, затем PR в `develop`.
Сохраняй чужие изменения; перед commit просмотри staged paths и diff.
Commits и PR titles — Conventional Commits; допустим `spec:`. Каждый commit
содержит одну связанную задачу. При связанной issue добавь её номер в конец
заголовка (`fix: … #12`); без issue номер не нужен. Root другого checkout
не управляет этим repo.
Прямой push в `main`, force-push и перенос опубликованных тегов не входят в
обычную работу. Перед release/hotfix прочитай местный README, раздел «Релизы».
-56
View File
@@ -1,56 +0,0 @@
# Frontend architecture
## Выбор владельца
Сначала найди владельца поведения и ближайший пример. Расширяй existing slice,
если ответственность остаётся связной. Размер файла или возможный будущий reuse
не создают новую архитектурную границу.
| Ответственность | Размещение |
| --- | --- |
| Bootstrap, глобальные providers, routes | `app` |
| Композиция маршрута и поведение, нужное только этому экрану | `pages/<page>` |
| Самостоятельная пользовательская возможность с собственным смыслом | `features/<capability>` |
| Представление/поведение бизнес-сущности | `entities/<entity>` |
| Переиспользуемый код без WealthLedger domain meaning | `shared` |
Локальный FSD profile: `app → pages → features → entities → shared`, без `widgets`.
Крупный уникальный блок остаётся в своей page. Form, mutation или click handler
сами по себе не требуют feature. Два callers не делают domain helper generic shared.
Slice именуется по ответственности, а не `helpers`, `hooks` или `types`.
**Безопасный путь:** при сомнении оставь код у ближайшего допустимого owner.
Извлекай его, когда появилась самостоятельная ответственность или реальный reuse.
Не вводи новый layer и не обходи public API, чтобы устранить неудобный import.
## Imports и public API
Cross-slice consumer использует `@/` и `index.ts` владельца, например
`@/entities/portfolio`. Alias Vite и TypeScript согласован. Другой slice не
импортирует внутренний файл напрямую. Направление зависимостей проверяет
`npm run deps`; Knip проверяет использование exports, а не смысл placement.
## UI foundation
Общий visual foundation принадлежит `shared/theme`. `tokens.json` — переносимый
WealthLedger v1 source; `theme.ts` адаптирует доверенный JSON в Mantine без runtime
schema. App и Storybook используют public API `shared/theme/index.ts`: theme,
designTokens, color roles, CSSVariablesResolver и base styles. Внешний consumer
читает JSON напрямую. Mantine defaults и локальные domain styles остаются у владельцев.
`shared/ui` содержит StateView/LoadingSkeleton. Existing route-aware AppShell также
лежит в shared/ui, но не является общим catalog primitive; его расположение не
служит основанием переносить новую domain/navigation логику в shared.
Изменяя foundation, прочитай [design system](../../../docs/development/design-system.md).
## Примеры
- Общая busy-область: существующий [LoadingSkeleton](../../src/shared/ui/LoadingSkeleton.tsx), а не domain widget в shared.
- Account-income state views: [страница](../../src/pages/account-income/ui/AccountIncomePage.tsx) и её flat `components/*.view.tsx`; новый page-local filter остаётся здесь.
- Portfolio query: [entity public API](../../src/entities/portfolio/index.ts); новая UI-сводка с бизнес-смыслом не становится shared только из-за нескольких экранов.
## Проверка
После placement/import change: `npm run deps`, `npm run typecheck`, `npm run knip`;
после собственного behavior — применимые tests. Финальный gate указан в AGENTS.
Review отдельно проверяет смысл owner: разрешённый dependency graph не доказывает
правильный выбор слоя.
-56
View File
@@ -1,56 +0,0 @@
# Frontend data
## Выбор owner
Server state принадлежит TanStack Query, form state — React Hook Form, локальное
UI — React state. Не копируй успешный query result в useState/context для второго
кэша. Domain-specific queries, keys и policies принадлежат вызывающему slice;
общий transport — `shared/api`. Page VM выбирает inputs и собирает presentation data.
Используй `apiClient`/`apiQueryClient` из shared public API. Прямой fetch в
pages/features/entities и прямой T-Bank call запрещены. Сначала найди
существующий query того же endpoint; расширяй его owner, не создавай второй key
или глобальную query policy для одной страницы.
## Типы и contract
Backend runtime OpenAPI — source; committed frontend snapshot и generated
`schema.d.ts` производны. Тип request/response бери из generated `paths`, например:
```ts
type User = paths["/api/v1/auth/me"]["get"]["responses"][200]["content"]["application/json"];
```
Domain/UI type допустим, когда он отличается по смыслу, а не копирует transport DTO.
Generated TS вручную не исправляется. Изменение wire shape/status/route проходит
[общий contract workflow](../../../docs/development/runtime-openapi-verification.md).
Одна UI-модель не требует менять API. `openapi:generate` работает offline от snapshot;
`openapi:check` генерирует во временный каталог и сравнивает, не меняя tracked files.
## Auth и invalidation
Bearer header принадлежит shared authenticated fetch; query/mutation не задают
Authorization. Auth endpoints исключены из Bearer/retry middleware. Refresh
координируется single-flight; после `401` с `UNAUTHORIZED` возможен один retry.
Не добавляй собственный refresh/retry loop в caller.
Protected queries используют existing session-aware boundary; logout очищает
session-scoped cache. При auth/token change читай [security](../../../backend/.ai/conventions/security-auth.md)
и [authentication](../../../docs/features/authentication.md).
Успешная connection mutation коммитит подтверждённый status и сбрасывает financial
GET subtree; ошибка mutation не меняет generation/cache. Это отдельная граница
от обычного фонового refetch: [connection policy](../../../docs/features/tbank-connection.md#граница-финансового-кэша).
Default focus refetch выключен; freshness и retry определяются существующей
[query policy](../../../docs/adr/007-react-query-fetch-policy.md) и feature source.
При обычном refetch сохраняй Client Cached Snapshot, при session/connection
смене не показывай данные прежнего владельца. UI presentation — в UI convention.
## Примеры и проверка
[usePortfolio](../../src/entities/portfolio/api/usePortfolio.ts) — entity query;
[shared client](../../src/shared/api/client.ts) — transport/auth boundary.
Изменяя header/retry/invalidation, проверяй наблюдаемое поведение через MSW и
[Testing](frontend-testing.md); не обращайся к реальному T-Bank.
`npm run openapi:check`, `npm run typecheck` и targeted tests проверяют разные
части решения. Для API semantics нужны также exact docs и contract gate.
-107
View File
@@ -1,107 +0,0 @@
# Frontend UI
## Выбор компонента и state
Сначала переиспользуй подходящий component проекта; иначе используй готовый
Mantine component и общую тему. Для выпадающего выбора используй `Select` или
`MultiSelect`, а не браузерный `<select>` / `NativeSelect` по умолчанию.
Нативный control или собственная реализация допустимы, когда готовые components
не покрывают конкретное продуктовое требование или доступность; укажи причину
в результате работы. Краткость кода и удобство тестирования не являются причиной:
ограничения JSDOM решай в test setup, сохраняя production UI.
Семантический HTML для структуры страницы остаётся уместным.
Wrapper нужен для проектной ответственности, а не ради нового имени
для Button. Локальный CSS module принадлежит component; общий token вводи для
реально общей роли через [design system](../../../docs/development/design-system.md).
| Состояние | Владелец |
| --- | --- |
| Ответ сервера / query lifecycle | TanStack Query, [data rules](frontend-data.md) |
| Ввод и ошибки формы | React Hook Form + Zod, container/VM |
| Параметр навигации, который должен переживать переход/ссылку | Router/URL |
| Локальное открытие, focus, rendering fallback | React UI state |
| Значение, вычисляемое из уже доступных inputs | Вычисление при render/в VM, без копирования через effect в state |
Effect нужен для синхронизации с внешней системой; действие пользователя
обрабатывай в handler. Не добавляй store, memoization или abstraction без текущей
потребности. Inspect ближайший component до создания нового pattern.
## Container, VM и view
Для data-driven finance page container вызывает один page VM и выбирает
Loading/Error/Empty/Loaded view. VM владеет data/auth/route inputs, state selection,
retry callbacks, domain grouping и derived presentation data. View получает props.
| Файл | Ответственность |
| --- | --- |
| `Component.tsx` | Container или публичный component |
| `Component.vm.ts` | Page VM, данные и действия |
| `Component.view.tsx` | Presentation |
| `Component.types.ts` | Переиспользуемые props/local types, когда отдельный owner полезен |
| `Component.module.css` | Локальные стили |
Во view нет data/auth/router/navigation/VM hooks и вычислений по domain collection.
Допустимы `useTranslation`, form-context hooks, UI-only state (например failed
image fallback) и formatter одного переданного значения. Группировка/доли
коллекции готовятся в VM. Перенос fetch во view ради меньшего container нарушает границу.
Отдельный state/section с самостоятельной responsibility выноси в flat
`components/*.view.tsx`. Небольшой tightly-coupled renderer оставляй рядом.
Не создавай folder/barrel/test/CSS для каждого view и не дроби по line count.
Пример: [AccountIncomePage](../../src/pages/account-income/ui/AccountIncomePage.tsx)
и [его VM](../../src/pages/account-income/ui/AccountIncomePage.vm.ts).
## Формы
Используй `react-hook-form`, `zodResolver`, `FormProvider`. Container/VM создаёт
form state, view получает `onSubmit`/`disabled`, fields используют `useFormContext`.
Во время submit блокируй все действия формы. Zod errors показывай у поля;
network error — отдельным Alert с сохранением ввода. Невалидная форма не отправляет request.
## Состояния и recovery
Без успешных данных выбирай loading → error → empty → loaded. При наличии query
данных сохраняй их во время refetch и его ошибки: progress, локальное предупреждение,
retry. Это Client Cached Snapshot, отдельный от server stale/fallback.
Known API errors принадлежат local view; непойманные route errors — route-keyed
ErrorBoundary. Сброс query cache после смены session/connection задают data rules.
Initial loading использует page-owned structural skeleton по semantic regions,
не одиночный spinner/StateView. Partial loading принадлежит section. Busy-область
доступна assistive technology, shapes декоративны, без данных, интерактивности
и focus. Route fallback сохраняет shell; до auth ready — neutral shell skeleton.
Button loading при mutation и компактный cached-snapshot progress остаются
контекстными indicators. Проверяй keyboard access к actions и безопасный retry.
## Код и components
Style/type automation задают configs. Используй `import type`; `enum` и
`namespace` в frontend не применяются. Named components — const-valued; Biome
проверяет declarations, no-default-export и exports-last в своём scope.
Обязательный review: `FC<Props>` и named props рядом/в types-файле; без inline
props typing и destructuring в параметрах. Принимай `props`, destructure в body.
Только children — `FC<PropsWithChildren>`; дополнительные props — named type
на основе `PropsWithChildren<{ ... }>`. Без props — `FC`.
Своди обычные exports к читаемому нижнему named block; barrel делает прямой
re-export без промежуточного import.
CSF `*.stories.tsx` сохраняют default meta и прямые story exports для indexer.
Vite/Vitest configs и `.storybook/main.ts`/`preview.tsx` имеют только
конфигурационное default-export exception. Scope исключений принадлежит biome.json.
## Строки и валидация
Продуктовый текст хранится в `src/shared/i18n/locales/ru.ts`, читается через
`useTranslation()`. В Zod используй `validationMessage(key)` из i18n/zod, без
пользовательских literal messages. Это mandatory semantic review: общего запрета
непереведённых JSX-строк в Biome/TypeScript нет. Synthetic story fixtures и
описания историй допустимы; они не заменяют продуктовую локализацию.
## Проверка
Type/style: `npm run typecheck`, `npm run lint`. Для risk behavior/изменения тестов
используй [Testing](frontend-testing.md). UI: keyboard, narrow viewport,
loading/error/empty/loaded и recovery по применимости. [Storybook](../../../docs/development/ui-catalog.md)
уже установлен; используй его как reference, но сверяй UI с задачей отдельно от build.
+36
View File
@@ -0,0 +1,36 @@
# Storybook
Единый каталог включает stories приложения и `packages/*/src`; общие
StateView/LoadingSkeleton и их stories принадлежат `packages/ui`.
## Когда нужна story
- Shared UI/theme: показывай принятые visual roles и переиспользуемое поведение.
- Domain/page presentation: добавляй story, когда независимый visual state
нужен для разработки/review или является устойчивым UI pattern.
- Выбирай значимые состояния: default, loading, disabled, error, empty,
длинный контент и смысловые variants по применимости. Не строй декартово
произведение props и story для каждого trivial wrapper/helper.
- Fetch/auth/router container и VM проверяй application tests; story получает
synthetic props presentation component. Каталог не нужен каждому файлу.
## Изоляция и interaction
Используй CSF, `Meta`/`StoryObj`, `satisfies Meta`, локальные fixtures и actions.
Общие Mantine/theme/i18n/Dates providers уже есть в
[preview](../../.storybook/preview.tsx); не создавай второй theme source.
Stories не достигают application API, auth, VM и query providers даже транзитивно;
границу проверяет `deps:storybook`. Не добавляй MSW worker ради каталога.
`play` через `storybook/test` нужен, когда interaction иллюстрирует собственный
контракт: keyboard activation, доступность действия, local callback. Не повторяй
RTL suite и не тестируй внутренности Mantine. Существующий
[Button](../../src/shared/ui/Button.stories.tsx) показывает themed control
без production wrapper; [LoadingSkeleton](../../packages/ui/src/LoadingSkeleton/LoadingSkeleton.stories.tsx)
— значимые busy states.
`npm run typecheck`, `npm run deps:storybook`, `npm run build:catalog` проверяют
типы, изоляцию и сборку. Build не выполняет `play` как CI interaction suite;
для проверки interaction открой story в браузере, для regression используй
существующий [Testing](testing.md). Визуальное соответствие задаче,
keyboard и узкий viewport проверяются отдельно от успешной сборки.
@@ -1,8 +1,13 @@
# Frontend testing # Frontend testing
Перед нетривиальными тестами сформулируй
[общий Test Intent](engineering.md#test-intent); отдельный документ
не требуется. Trivial low-risk изменения обходятся без него.
## Выбор проверки ## Выбор проверки
Читай при изменении тестов или behavior с [testing risk](../../../docs/development/engineering-governance.md#risk-based-testing). Читай при изменении тестов, доступа, денежных расчётов, восстановления
интерфейса или исправлении подтверждённой регрессии.
Выбирай boundary по наблюдаемому исходу, а не внутреннему helper/component state. Выбирай boundary по наблюдаемому исходу, а не внутреннему helper/component state.
| Изменение | Дешёвая надёжная проверка | | Изменение | Дешёвая надёжная проверка |
@@ -10,6 +15,7 @@
| Чистое domain преобразование/денежный расчёт | Unit case с граничными значениями | | Чистое domain преобразование/денежный расчёт | Unit case с граничными значениями |
| Форма, route access, recovery, UI-state selection | RTL component/route test через видимое поведение | | Форма, route access, recovery, UI-state selection | RTL component/route test через видимое поведение |
| Headers, refresh/retry, query invalidation | MSW на transport boundary | | Headers, refresh/retry, query invalidation | MSW на transport boundary |
| Критический browser flow, который JSDOM не доказывает | Browser/e2e proof существующими доступными средствами; отдельный frontend e2e runner пока не принят |
| Только declarative props/Storybook fixture | Type/build + semantic/visual review; unit test без собственной логики не нужен | | Только declarative props/Storybook fixture | Type/build + semantic/visual review; unit test без собственной логики не нужен |
Tests colocated с source (`*.test.tsx` для UI, существующий `*.test.ts` для pure code). Tests colocated с source (`*.test.tsx` для UI, существующий `*.test.ts` для pure code).
@@ -28,6 +34,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 запросов и мутаций для предсказуемого исхода;
это не меняет [политику обновления приложения](data.md#auth-и-invalidation).
## Важные случаи ## Важные случаи
@@ -37,7 +45,7 @@ Finance: loading/error/empty/loaded, cached snapshot при refetch failure, ret
отсутствие старых данных после session/connection switch. ErrorBoundary: test-only отсутствие старых данных после session/connection switch. ErrorBoundary: test-only
throwing route, безопасная ссылка и reset после navigation. throwing route, безопасная ссылка и reset после navigation.
Примеры: [AuthForm test](../../src/features/auth/ui/AuthForm.test.tsx), Примеры: [AuthForm test](../../src/features/auth/ui/AuthForm/AuthForm.test.tsx),
[client test](../../src/shared/api/client.test.ts), [client test](../../src/shared/api/client.test.ts),
[usePortfolio test](../../src/entities/portfolio/api/usePortfolio.test.tsx). [usePortfolio test](../../src/entities/portfolio/api/usePortfolio.test.tsx).
Не копируй fixtures/сценарии целиком, если задача затрагивает один исход. Не копируй fixtures/сценарии целиком, если задача затрагивает один исход.
+53
View File
@@ -0,0 +1,53 @@
# TypeScript и React
## Types и components
- Сохраняй strict TS profile и `import type`. Для недоверенного значения используй
`unknown` с narrowing; `any` не заменяет DTO/validation. Локальное исключение
на нетипизированной boundary должно быть узким и объяснённым.
- `enum` и `namespace` не используются: frontend имеет `erasableSyntaxOnly`.
Для состояния с разными payload выбирай discriminated union; не добавляй
необязательные поля, допускающие невозможные комбинации.
- Named components — const-valued `FC<Props>`; named props находятся рядом или
в types-файле. Принимай `props`, destructure в body, без inline props typing.
Только children — `FC<PropsWithChildren>`; дополнительные props — named type
на основе `PropsWithChildren<{ … }>`; без props — `FC`.
- Обычные exports — нижний named block; barrel делает прямой re-export.
CSF сохраняет default meta и прямые story exports; configuration exceptions
заданы в [Biome](../../biome.json). Не распространяй их на application code.
## Hooks и derived state
Hooks вызываются без условий и ранних выходов перед ними; custom hook нужен
связному поведению, а не новому имени над одним вызовом. Derived value вычисляй
при render/в VM. Пользовательское действие обрабатывай handler; `useEffect`
оставляй синхронизации с внешней системой с корректным cleanup/dependencies.
`useMemo`, `useCallback`, `memo` нужны измеренной стоимости или конкретному
контракту стабильной identity; не добавляй их ко всем значениям/handlers.
React Compiler включён в Vite, но не доказывает выигрыш и не заменяет effect
correctness. Не удаляй существующую memoization без понимания её consumers.
Container/VM/view и state owners — в [UI](ui.md).
## Domain literals and magic values
Общее правило ownership и символических значений —
[Domain values](engineering.md#domain-values).
Backend vocabulary бери из generated `paths`, не создавай ручную копию enum.
Текущий `schema.d.ts` содержит только types: typed wire literals допустимы,
когда generator не предоставляет runtime values.
`ProblemDetailsDto.code` сейчас `string`. Не объявляй закрытый frontend error
enum и не превращай неизвестный code в известный через cast. Повторяющуюся
обработку своди у ответственного owner; [errors](data.md#errors).
`noMagicNumbers` в Biome — error; fixtures/tests/stories исключены только
из этого правила. Policy получает имя и единицы; подавление допустимо для
incidental value с объяснением. Обычный UI-текст не превращай в constant:
его owner — [i18n](ui.md#строки-и-валидация).
Semantic magic strings и props profile требуют review.
## Проверка
`npm run typecheck` и `npm run lint`; behavior проверяй по
[Testing](testing.md), placement — по [FSD](../architecture.md).
+161
View File
@@ -0,0 +1,161 @@
# Frontend UI
## Выбор компонента и state
Сначала переиспользуй подходящий component проекта; иначе используй готовый
Mantine component и общую тему. Для выпадающего выбора используй `Select` или
`MultiSelect`, а не браузерный `<select>` / `NativeSelect` по умолчанию.
Нативный control или собственная реализация допустимы, когда готовые components
не покрывают конкретное продуктовое требование или доступность; укажи причину
в результате работы. Краткость кода и удобство тестирования не являются причиной:
ограничения JSDOM решай в test setup, сохраняя production UI.
Семантический HTML для структуры страницы остаётся уместным.
Icons ищи у существующего owner (например,
[BankOperationIcon](../../src/entities/bank-card/ui/BankOperationIcon/BankOperationIcon.tsx));
статичные Add/Edit/Delete доступны в `@wealthledger/icons`. Их SVG декоративны
по умолчанию; имя action принадлежит кнопке. Standalone meaningful icon получает
`aria-hidden={false}`, `role="img"` и доступное имя. Category/kind mappings
и анимации остаются в entity. Не добавляй пакет ради одного символа. Business/domain
components живут у feature/entity/page, даже при повторном использовании.
Wrapper нужен для проектной ответственности, а не ради нового имени
для Button. Локальный CSS module принадлежит component; общий token вводи для
реально общей роли в [визуальной основе](#визуальная-основа).
| Состояние | Владелец |
| --- | --- |
| Ответ сервера / query lifecycle | TanStack Query, [data rules](data.md) |
| Ввод и ошибки формы | React Hook Form + Zod, container/VM |
| Параметр навигации, который должен переживать переход/ссылку | Router/URL |
| Локальное открытие, focus, rendering fallback | React UI state |
| Значение, вычисляемое из уже доступных inputs | Вычисление при render/в VM, без копирования через effect в state |
State, который нужен в ссылке, back/forward или после navigation, хранится в URL
через existing router search params. Остальной UI state остаётся у ближайшего
owner. Shared client store нужен только нескольким consumers без подходящего
общего owner; наличие двух компонентов само по себе его не требует.
Hooks/effects/derived state — по [TypeScript/React](typescript-react.md#hooks-и-derived-state).
## Container, VM и view
Для data-driven finance page container вызывает один page VM и выбирает
Loading/Error/Empty/Loaded view. VM владеет data/auth/route inputs, state selection,
retry callbacks, domain grouping и derived presentation data. View получает props.
| Файл | Ответственность |
| --- | --- |
| `Component.tsx` | Container или публичный component |
| `Component.vm.ts` | Page VM, данные и действия |
| `Component.view.tsx` | Presentation |
| `Component.types.ts` | Переиспользуемые props/local types, когда отдельный owner полезен |
| `Component.module.css` | Локальные стили |
Во view нет data/auth/router/navigation/VM hooks и вычислений по domain collection.
Допустимы `useTranslation`, form-context hooks, UI-only state (например failed
image fallback) и formatter одного переданного значения. Группировка/доли
коллекции готовятся в VM. Перенос fetch во view ради меньшего container нарушает границу.
Отдельный state/section с самостоятельной responsibility выноси в
`components/` своего component. Небольшой tightly-coupled renderer оставляй
рядом; размер файла сам по себе не требует разделения.
Пример: [AccountIncomePage](../../src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.tsx)
и [его VM](../../src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.vm.ts).
## Размещение файлов компонента
Правило действует в `src` и `packages`: компонент с сопутствующими файлами
(view, VM, types, CSS, tests, stories) размещай в папке `Component/`.
Сохраняй полные имена файлов: `Component.tsx`, `Component.view.tsx`,
`Component.test.tsx`. Создавай только нужные файлы; одиночный компонент
оставляй непосредственно в `ui`, `components` или source-каталоге пакета.
Внутренние части принадлежат папке родителя; для набора state/section views
используй её `components/`. Внутри него действует то же правило: отдельная
папка объединяет комплект файлов, одиночный view остаётся файлом.
Стили и хуки нескольких соседних компонентов остаются у ближайшего общего
владельца; не копируй их и не прячь внутрь одного потребителя.
Папка компонента не создаёт новую FSD-границу. Публичные exports остаются в
существующем `index.ts` slice/segment или entry пакета; внутри используй
прямые относительные imports без дополнительных barrels на каждый компонент.
При переносе обновляй imports, ссылки документации и проверки, зависящие от пути.
Пример: [BankCardForm](../../src/entities/bank-card/ui/BankCardForm/BankCardForm.tsx)
лежит рядом со своим view, тестом и story; общий `BankForms.module.css`
остаётся в `bank-card/ui`.
## Формы
Используй `react-hook-form`, `zodResolver`, `FormProvider`. Container/VM создаёт
form state, view получает `onSubmit`/`disabled`, fields используют `useFormContext`.
Во время submit блокируй все действия формы. Zod errors показывай у поля;
network error — отдельным Alert с сохранением ввода. Невалидная форма не отправляет request.
## Состояния и recovery
Без успешных данных выбирай loading → error → empty → loaded. При наличии query
данных сохраняй их во время refetch и его ошибки: progress, локальное предупреждение,
retry. Это Client Cached Snapshot, отдельный от server stale/fallback.
Known API errors принадлежат local view; непойманные route errors — route-keyed
ErrorBoundary. Сброс query cache после смены session/connection задают data rules.
Initial loading использует page-owned structural skeleton по semantic regions,
не одиночный spinner/StateView. Partial loading принадлежит section. Busy-область
доступна assistive technology, shapes декоративны, без данных, интерактивности
и focus. Route fallback сохраняет shell; до auth ready — neutral shell skeleton.
Button loading при mutation и компактный cached-snapshot progress остаются
контекстными indicators. Проверяй keyboard access к actions и безопасный retry.
## Код и components
Types, props, hooks и memoization — в [TypeScript/React](typescript-react.md).
## Domain literals and magic values
Правило и generated API exception — в
[TypeScript/React](typescript-react.md#domain-literals-and-magic-values).
## Строки и валидация
Продуктовый текст хранится в `src/shared/i18n/locales/ru.ts`, читается через
`useTranslation()`. В Zod используй `validationMessage(key)` из i18n/zod, без
пользовательских literal messages. Это mandatory semantic review: общего запрета
непереведённых JSX-строк в Biome/TypeScript нет. Synthetic story fixtures и
описания историй допустимы; они не заменяют продуктовую локализацию.
## Проверка
Type/style: `npm run typecheck`, `npm run lint`. Для risk behavior/изменения тестов
используй [Testing](testing.md). UI: keyboard, narrow viewport,
loading/error/empty/loaded и recovery по применимости. [Storybook](storybook.md) задаёт выбор stories и изоляцию каталога;
сверяй UI с задачей отдельно от build.
## Визуальная основа
Private workspace `packages/tokens` владеет переносимыми значениями
`tokens.json`; `packages/ui/src/theme.ts` читает export пакета
`@wealthledger/tokens/tokens.json` и адаптирует его к Mantine. Используй
`@wealthledger/ui/theme` и его semantic roles; runtime подключает
`@wealthledger/ui/styles.css` после Mantine CSS. Providers остаются у runtime.
Палитра page/component следует этим semantic roles. Поддерживается светлая схема.
Цвет дополняет подпись или знак; проверяй контраст конкретной пары text/background.
Warning не используй для мелкого текста на белом. Деньги сохраняют валюту, знак
и различие между нулём и неизвестной суммой. Общие состояния демонстрирует
Storybook; presentation stories используют synthetic data без application API.
EntryCard, StateView и LoadingSkeleton принадлежат `packages/ui`; публичный import —
`@wealthledger/ui`. Переводы, retry и формы skeleton остаются у callers.
Compatibility re-exports удалены; callers используют public export пакета.
## Modal animation
BankCardForm, OperationForm, DeleteOperation и CategoryManager монтируют Modal
с `opened=true`: Mantine Transition начинает в состоянии `entered`.
CSS `modal-appear`/`modal-backdrop-appear` в `packages/ui/src/styles.css`
обеспечивает появление при mount (220ms, только no-preference). Mantine theme
владеет exit transition (180ms), overlay blur и completion callback;
`onExitTransitionEnd` позволяет дождаться закрытия перед unmount и вернуть фокус.
Удаление CSS без изменения mount lifecycle убирает вступительную анимацию.
TbankConnection Modal использует toggle `opened`; вывод о разделении фаз
банковских форм на этот сценарий автоматически не распространяется.
+42
View File
@@ -0,0 +1,42 @@
**
!package.json
!package-lock.json
!.nvmrc
!index.html
!tsconfig*.json
!vite.config.ts
!.storybook/
!.storybook/**
!src/
!src/**
!public/
!public/**
!docker/
!docker/**
!packages/
!packages/tokens/
!packages/tokens/package.json
!packages/tokens/tokens.json
!packages/ui/
!packages/ui/package.json
!packages/ui/vite.config.ts
!packages/ui/tsconfig.json
!packages/ui/src/
!packages/ui/src/theme.ts
!packages/ui/src/styles.css
!packages/ui/src/index.ts
!packages/ui/src/StateView.tsx
!packages/ui/src/LoadingSkeleton.tsx
!packages/ui/src/EntryCard.tsx
!packages/ui/src/EntryCard.module.css
!packages/icons/
!packages/icons/package.json
!packages/icons/tsconfig.json
!packages/icons/vite.config.ts
!packages/icons/src/
!packages/icons/src/index.ts
!packages/icons/src/types.ts
!packages/icons/src/svg/
!packages/icons/src/svg/AddIcon.tsx
!packages/icons/src/svg/EditIcon.tsx
!packages/icons/src/svg/DeleteIcon.tsx
+26
View File
@@ -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"
+63
View File
@@ -0,0 +1,63 @@
name: Frontend image
on:
push:
tags: ['v*']
concurrency:
group: frontend-image-publication
cancel-in-progress: false
jobs:
publish:
runs-on: ubuntu-latest
env:
IMAGE: nexus.personal.ksv741.ru/docker-hosted/wealthledger/frontend
RELEASE_TAG: ${{ gitea.ref_name }}
REVISION: ${{ gitea.sha }}
DOCKER_CONFIG: ${{ runner.temp }}/wealthledger-frontend-docker
steps:
- uses: https://github.com/actions/checkout@v4
- uses: https://github.com/actions/setup-node@v4
with:
node-version-file: .nvmrc
- name: Validate release version
run: |
node --input-type=commonjs -e 'const p = require("./package.json"); const l = require("./package-lock.json"); if (!/^v\d+\.\d+\.\d+$/.test(process.env.RELEASE_TAG) || process.env.RELEASE_TAG !== `v${p.version}` || l.version !== p.version || l.packages[""].version !== p.version) process.exit(1)'
test "$(git rev-parse HEAD)" = "$REVISION"
docker version
docker buildx version
- run: npm ci
env:
HUSKY: '0'
- run: npm run verify
env:
KNIP_DISABLE_RAW_TRANSFER: '1'
- name: Login with dedicated Nexus writer
env:
REGISTRY_USERNAME: ${{ secrets.NEXUS_USERNAME }}
REGISTRY_TOKEN: ${{ secrets.NEXUS_PASSWORD }}
run: |
test -n "$REGISTRY_USERNAME" && test -n "$REGISTRY_TOKEN"
install -d -m 700 "$DOCKER_CONFIG"
printf '%s' "$REGISTRY_TOKEN" | docker login nexus.personal.ksv741.ru --username "$REGISTRY_USERNAME" --password-stdin
- name: Publish immutable release tag
run: |
VERSION="${RELEASE_TAG#v}"
if docker manifest inspect "$IMAGE:$VERSION" >/dev/null 2>manifest-error.log; then
DIGEST="$(docker buildx imagetools inspect "$IMAGE:$VERSION" --format '{{.Manifest.Digest}}')"
else
if ! grep -Eq 'manifest unknown|no such manifest' manifest-error.log; then
echo 'Cannot prove tag absence; refusing publication'; exit 1
fi
docker buildx build --target production --build-arg VERSION="$VERSION" --build-arg REVISION="$REVISION" --tag "$IMAGE:$VERSION" --metadata-file image-metadata.json --push .
DIGEST="$(node --input-type=commonjs -p 'require("./image-metadata.json")["containerimage.digest"]')"
fi
docker pull "$IMAGE@$DIGEST"
test "$(docker image inspect "$IMAGE@$DIGEST" --format '{{index .Config.Labels "org.opencontainers.image.revision"}}')" = "$REVISION"
test "$(docker image inspect "$IMAGE@$DIGEST" --format '{{index .Config.Labels "org.opencontainers.image.version"}}')" = "$VERSION"
docker run --rm --entrypoint sh "$IMAGE@$DIGEST" -c 'test -s /usr/share/nginx/html/index.html && nginx -t && nginx && wget -q -O /dev/null http://127.0.0.1:8080/'
printf 'Frontend image: %s@%s\n' "$IMAGE" "$DIGEST"
- name: Remove registry session
if: always()
run: rm -rf "$DOCKER_CONFIG"
+33
View File
@@ -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
+36
View File
@@ -0,0 +1,36 @@
name: Frontend verify
on:
push:
branches:
- '**'
pull_request:
jobs:
verify:
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
- 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'
- name: Analyze develop with SonarQube
if: gitea.event_name == 'push' && gitea.ref == 'refs/heads/develop'
# v2.3.0: Docker-based scanner for the SonarQube 9.9 server.
uses: https://github.com/SonarSource/sonarqube-scan-action@aecaf43ae57e412bd97d70ef9ce6076e672fe0a9
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
with:
args: -Dsonar.qualitygate.wait=true
+1
View File
@@ -12,6 +12,7 @@ dist
storybook-static storybook-static
dist-ssr dist-ssr
coverage coverage
.scannerwork
*.local *.local
# Local runtime configuration # Local runtime configuration
+1
View File
@@ -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
+1 -1
View File
@@ -1 +1 @@
22 24.21.0
+106
View File
@@ -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"
}
}
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ module.exports = {
severity: "error", severity: "error",
from: { path: "\\.stories\\.tsx$|^\\.storybook/preview\\.tsx$" }, from: { path: "\\.stories\\.tsx$|^\\.storybook/preview\\.tsx$" },
to: { to: {
path: "^src/(shared/api|features/auth|app/routes|app/ui)/|^src/(entities|features)/[^/]+/api/|\\.vm\\.ts$|^src/pages/[^/]+/ui/[^/]+Page\\.tsx$|node_modules/(@tanstack/react-query|openapi-fetch|openapi-react-query)/", path: "^src/(shared/api|features/auth|app/routes|app/ui)/|^src/(entities|features)/[^/]+/api/|\\.vm\\.ts$|^src/pages/[^/]+/ui/.*Page\\.tsx$|node_modules/(@tanstack/react-query|openapi-fetch|openapi-react-query)/",
reachable: true, reachable: true,
}, },
}, },
+1 -1
View File
@@ -1,7 +1,7 @@
import type { StorybookConfig } from "@storybook/react-vite"; import type { StorybookConfig } from "@storybook/react-vite";
const config: StorybookConfig = { const config: StorybookConfig = {
stories: ["../src/**/*.stories.tsx"], stories: ["../src/**/*.stories.tsx", "../packages/*/src/**/*.stories.tsx"],
addons: ["@storybook/addon-docs"], addons: ["@storybook/addon-docs"],
framework: "@storybook/react-vite", framework: "@storybook/react-vite",
core: { disableTelemetry: true }, core: { disableTelemetry: true },
+6 -2
View File
@@ -1,11 +1,13 @@
import "@mantine/core/styles.css"; import "@mantine/core/styles.css";
import "@mantine/charts/styles.css"; import "@mantine/charts/styles.css";
import "@mantine/dates/styles.css"; import "@mantine/dates/styles.css";
import "@wealthledger/ui/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 "@wealthledger/ui/theme";
const colorSchemeManager = { const colorSchemeManager = {
get: () => "light" as const, get: () => "light" as const,
@@ -33,7 +35,9 @@ const preview: Preview = {
forceColorScheme="light" forceColorScheme="light"
colorSchemeManager={colorSchemeManager} colorSchemeManager={colorSchemeManager}
> >
<Story /> <DatesProvider settings={{ locale: "ru" }}>
<Story />
</DatesProvider>
</MantineProvider> </MantineProvider>
), ),
], ],
+32 -19
View File
@@ -1,24 +1,37 @@
# Frontend # Frontend router
React/Vite-клиент; общие правила работы — в root `AGENTS.md`. Репозиторий самостоятельный: обязательные инструкции и проверки используют
До frontend-решения прочитай [router](.ai/CONVENTIONS.md) и только его файлы и предоставленные публичные контракты. Перед работой прочитай
[sources](.ai/SOURCES.md), затем только применимые документы/разделы. [порядок работы](.ai/conventions/engineering.md#граница-и-порядок-работы), затем
объединяй triggers задачи и путей; читай активированные темы до решения.
## Проверка | Решение / сигнал | Читать |
| --- | --- |
| Устройство/data flow, component/module/slice, owner/FSD, cross-slice imports | [Architecture](.ai/architecture.md) |
| TS types/props/imports/exports, hooks/effects, derived state, memoization, domain literals | [TypeScript/React](.ai/conventions/typescript-react.md) |
| UI/Mantine, form, container/VM/view, state owner, loading/error/recovery | [UI](.ai/conventions/ui.md) |
| Только продуктовая строка / Zod message | [Строки](.ai/conventions/ui.md#строки-и-валидация) |
| Query/mutation, server cache, shared/api, generated types | [Data](.ai/conventions/data.md) |
| API/network/application errors, codes и сообщения | [Errors](.ai/conventions/data.md#errors) |
| Login/refresh/logout, token/cookie, session ownership | [Data/auth](.ai/conventions/data.md#auth-и-invalidation) + [Testing](.ai/conventions/testing.md) |
| Request/response field, route/status/error shape, OpenAPI | [Data/contract](.ai/conventions/data.md#типы-и-contract) |
| Tests или behavior с regression risk | [Testing](.ai/conventions/testing.md) |
| Storybook/stories/play, theme/tokens/shared UI | [Storybook](.ai/conventions/storybook.md), UI; design facts — в разделе Источники |
| Helper/dependency/новый pattern, refactor/scope | [Change scope](.ai/conventions/engineering.md#change-scope), для пакета — [Dependencies](.ai/conventions/engineering.md#dependencies) |
| Выбор gate, tooling, завершение | [Проверки](.ai/conventions/engineering.md#проверки-и-завершение) |
Перед Node-командами: `nvm use --silent` по `.nvmrc`. Показ query state не означает изменение fetching. Изменение тестов активирует
После lockfile install `npm ci` полный gate — `npm run verify`. Testing и без production diff. Перед завершением повтори routing по новым и
Он проверяет OpenAPI drift, TypeScript, Biome, Vitest/coverage, Knip, изменённым файлам. Для Git/release прочитай
dependency boundaries и сборки приложения/Storybook без backend. [Git и релизы](.ai/conventions/engineering.md#git-и-релизы).
Точные scripts принадлежат `package.json`; targeted checks — у выбранного convention.
HTTP contract changes дополнительно проходят общий ## Источники
[contract workflow](../docs/development/runtime-openapi-verification.md).
Generated types редактируются через их source; T-Bank доступен только через backend.
Frontend dependencies используют exact versions. Pre-commit запускает staged
formatting и FSD checks; сообщения commits — Conventional Commits.
Code/style checks автоматические только в scope конфигурации. i18n, props, | Вопрос | Локальный источник |
semantic placement и выбор полезных тестов обязательны при review. | --- | --- |
Storybook уже доступен как reference; ожидаемый UI и его состояния определяет | HTTP request/response/errors | [OpenAPI snapshot](src/shared/api/spec/openapi.json), generated types и [Data](.ai/conventions/data.md) |
задача, а визуальное соответствие проверяется отдельно от сборки. | Auth/session/refresh/cache | [Data](.ai/conventions/data.md#auth-и-invalidation), source и colocated tests владельца |
| Money, account/position/income | Entity types, API snapshot, formatters и tests соответствующего slice |
| Theme/tokens, UI-каталог | [UI](.ai/conventions/ui.md), [Storybook](README.md#ui-каталог-storybook) |
| Поведение области | Source и tests её page/entity/feature; неясное ожидание уточни до изменения |
| Versions/scripts/check scope | Manifest/lockfile, Biome/TypeScript/dependency configs |
+177
View File
@@ -0,0 +1,177 @@
# Changelog
## [0.4.0](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.3.0...v0.4.0) (2026-09-26)
### Features
* show persisted investment data and sync state ([4e5f564](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/4e5f564fa1d583013fb3e7febdb3baa9737446b4))
### Bug Fixes
* **api:** update validation and conflict response contract ([db184c8](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/db184c8caec01609e8a3df3b16097ce634e5eff0))
* **auth:** isolate session races and financial caches ([a209d71](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/a209d715892862bb6d48084df0c84a10b8d56bf1))
* **ci:** resume verification of immutable release images ([6a87379](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/6a87379813ba1d4002779b23b2a65446b4d10258))
* **ui:** improve financial text contrast ([c86be7b](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/c86be7bf73d0141e0606d259ada6453c0d8e3dec))
### Refactoring
* colocate frontend component files ([b987fd8](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/b987fd8e780963dfe1dde0c714232697a52e0475))
* establish local frontend workspace boundaries ([85fcfe3](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/85fcfe3d073f80e759dafb14281c9462c1d7410d))
## [0.3.0](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.2.3...v0.3.0) (2026-09-20)
### Features
* add installable PWA [#30](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/30) ([bb30935](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/bb30935f73bfcbb77c10663cf6c683d8f0caca85))
## [0.2.3](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.2.2...v0.2.3) (2026-09-19)
### Bug Fixes
* correct Nexus routing and SonarQube host ([9171b9f](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/9171b9f5c8e0b694a2310e5a200fa2f8d3f28a61))
## [0.2.2](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.2.1...v0.2.2) (2026-09-19)
### Bug Fixes
* update Nexus registry host ([bac95eb](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/bac95ebb392febb667a9fc2f1fa4f06fa110d685))
## [0.2.1](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.2.0...v0.2.1) (2026-09-18)
### Documentation
* use shared Nexus account [#21](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/21) ([1ad578f](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/1ad578fb37b8dd6161dc362541d9c0cd0b008b75))
### CI
* add frontend SonarQube analysis [#19](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/19) ([3f19b36](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/3f19b3643f88e36d10e7c374262351f61947ed47))
* publish frontend images to Nexus [#21](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/21) ([999b859](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/999b8590ecd0a551da628c349d005ebb9b318883))
## [0.2.0](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.1.0...v0.2.0) (2026-09-16)
### Features
* add frontend container delivery ([e31ab35](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/e31ab35a5ac51b7dbd1509e35c4ce8e9f8fd4e92))
### Documentation
* make frontend instructions self-contained ([d9ada27](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/d9ada2762169b3347a0dc4b7e7ce6c7cd207af76))
* refine frontend conventions and routing ([718365c](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/718365cd5ab51e7c696c777b71095f7ee41b471d))
* simplify conventions layout ([9f7e342](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/9f7e342333b80bfacfd5bc394a2dcd0613d33ff3))
## 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))
+34
View File
@@ -0,0 +1,34 @@
FROM node:24.21.0-bookworm-slim AS dependencies
WORKDIR /app
ENV HUSKY=0
COPY package.json package-lock.json ./
COPY packages/tokens/package.json ./packages/tokens/
COPY packages/ui/package.json ./packages/ui/
COPY packages/icons/package.json ./packages/icons/
RUN npm ci
FROM dependencies AS development
COPY . .
RUN npm run build:packages
ENV VITE_API_BASE_URL="" API_PROXY_TARGET=http://backend:3000
EXPOSE 8080
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "8080", "--strictPort"]
FROM dependencies AS build
COPY . .
ENV VITE_API_BASE_URL=""
RUN npm run build
FROM nginx:1.28.0-alpine AS production
ARG VERSION
ARG REVISION
LABEL org.opencontainers.image.version=$VERSION \
org.opencontainers.image.revision=$REVISION
COPY docker/nginx.conf /etc/nginx/nginx.conf
COPY --from=build /app/dist /usr/share/nginx/html
USER nginx
EXPOSE 8080
ENTRYPOINT ["nginx"]
CMD ["-g", "daemon off;"]
HEALTHCHECK --interval=10s --timeout=3s --start-period=10s --retries=6 \
CMD wget -q -O /dev/null http://127.0.0.1:8080/ || exit 1
+192 -17
View File
@@ -5,7 +5,7 @@ backend; прямые вызовы T-Bank из frontend не допускают
## Быстрый старт ## Быстрый старт
Требуется Node 22 (`.nvmrc`). Создайте `.env` из примера и установите Требуется Node 24 (`.nvmrc`). Создайте `.env` из примера и установите
зависимости строго из lockfile: зависимости строго из lockfile:
```bash ```bash
@@ -17,6 +17,60 @@ 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`.
## Контейнерный image
`Dockerfile` имеет targets `development` (Vite HMR и proxy `/api/` во внутренний backend)
и `production` (nginx на 8080, SPA fallback и same-origin API proxy). Node соответствует `.nvmrc`.
Build context ограничен `.dockerignore`; `.env`, local DB и host node_modules
не попадают в image. Изменение `packages/tokens` или `packages/ui` требует rebuild development
image, если локальный запуск использует bind-mount только `src`/`public`.
```bash
docker build --target development -t wealthledger-frontend:development .
docker build --target production -t wealthledger-frontend:production .
```
Gitea `image.yml` запускается на защищённом release tag `vX.Y.Z`, проверяет
package/lock version и canonical gates. Runner `ubuntu-latest` должен иметь
Docker/buildx. Образы хранятся в Nexus:
`nexus.personal.ksv741.ru/docker-hosted/wealthledger/frontend`. Пользователь `wealthledger-ci`
задаётся Actions secrets `NEXUS_USERNAME`/`NEXUS_PASSWORD`; эта же учётная
запись используется сервером для загрузки образов. Docker endpoint и token realm должны использовать
HTTPS; в `docker-hosted` включается запрет redeploy. Прежние Gitea secrets
сохраняются на время перехода и не передаются в Nexus.
Публикуются semver tags, без `latest`; существующие release tags не перезаписываются. Production выбирает опубликованный version tag.
Compose topology принадлежит workspace, эксплуатационная последовательность —
[документация](https://git.personal.ksv741.ru/WealthLedger/docs),
страница `architecture/deployment.md`.
Проверка публикации требует настроенного registry/runner; локальный build
не доказывает package permissions.
## Установка как приложение (PWA)
Production-сборка поддерживает установку WealthLedger в отдельное окно через
`vite-plugin-pwa`. Нужен HTTPS или localhost. В Chrome/Edge выберите «Установить
WealthLedger» в меню браузера или значок установки в адресной строке; на iPhone
и iPad — Safari → «Поделиться» → «На экран Домой». Доступность установки зависит
от браузера и ОС.
Service worker кеширует только статическую оболочку, включая страницы SPA.
Вход, финансовые данные и сохранение изменений требуют сети: API, токены и
ответы API не сохраняются в Cache Storage. Это не автономный финансовый
клиент. Новая версия загружается в фоне и применяется после закрытия всех
вкладок и окон WealthLedger и повторного открытия; открытые формы автоматически
не перезагружаются.
Локальная проверка: `nvm use --silent`, `npm run build`, `npm run preview`.
В DevTools → Application проверьте Manifest, Service Workers и Cache Storage.
В режиме `npm run dev` и в Storybook service worker не включается.
## Проверка ## Проверка
```bash ```bash
@@ -27,26 +81,147 @@ 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`.
## SonarQube
Проект `wealthledger-frontend` использует настройки из
`sonar-project.properties`. Анализируются исходники `src`; тесты учитываются
отдельно, а Storybook fixtures, test helpers, generated API types и OpenAPI
snapshot исключены. `npm run test:coverage` (также входит в `npm run verify`)
создаёт `coverage/lcov.info` для импорта покрытия.
Для первого анализа установите SonarScanner CLI, совместимый с версией сервера,
и выполните из корня frontend:
```bash
nvm use --silent
npm ci
npm run test:coverage
# SONAR_TOKEN передайте через окружение; не сохраняйте токен в репозитории.
sonar-scanner
```
В Gitea откройте frontend → Settings → Actions → Secrets и добавьте
`SONAR_TOKEN` с токеном анализа проекта. Переименовывать основную ветку в
SonarQube не требуется; `sonar.branch.name` не задаётся.
Используется Community Edition 9.9.8: CI отправляет только
push в `develop`, после успешного `verify`, и ожидает результат Quality Gate.
PR и остальные ветки проходят обычные проверки без отправки в SonarQube.
Отрицательный Quality Gate или ошибка scanner завершает `verify` с ошибкой.
Runner должен поддерживать Docker actions и иметь HTTPS-доступ к
`https://sonarqube.personal.ksv741.ru`, GitHub и Docker Hub. Docker action
SonarSource закреплён на commit версии 2.3.0; scanner запускается отдельно от
Node 24, используемого для сборки. `tsconfig.sonar.json` содержит совместимые
со старым анализатором TS настройки; приложение проверяется штатным TypeScript
5.9 через `npm run verify`. После обновления сервера пересмотрите scanner и
возможность использовать основной tsconfig. Успешный локальный `verify` не
доказывает доступность сервера и успешность анализа в CI.
## UI-каталог Storybook
После `nvm use --silent` выполните `npm run dev:catalog`; статическая сборка —
`npm run build:catalog`. Каталог использует общую тему приложения, вымышленные
данные и локальные действия без application API. Примеры не доказывают
восстановление реального запроса. Визуальные роли описаны в
[UI convention](.ai/conventions/ui.md#визуальная-основа).
## Документация ## Документация
- [Router conventions](.ai/CONVENTIONS.md) и [источники](.ai/SOURCES.md) - [AGENTS: правила и источники](AGENTS.md)
- [Выбор owner/FSD](.ai/conventions/frontend-architecture.md) - [Выбор owner/FSD](.ai/architecture.md)
- [UI, state, формы и компоненты](.ai/conventions/frontend-ui.md) - [UI, state, формы и компоненты](.ai/conventions/ui.md)
- [Data/API/cache](.ai/conventions/frontend-data.md) - [Data/API/cache](.ai/conventions/data.md)
- [Testing](.ai/conventions/frontend-testing.md) - [Testing](.ai/conventions/testing.md)
- [Поставленный UI-каталог Storybook](../docs/development/ui-catalog.md) - [UI-каталог Storybook](#ui-каталог-storybook)
- [Обзор поставленной системы](../docs/architecture/system-overview.md)
- [Engineering governance и risk-based testing](../docs/development/engineering-governance.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 Checkout frontend содержит все входы сборки и проверок. Публичная схема API
backend командой `npm run test:openapi-contract`. поступает как отдельный artifact; команды frontend используют только её
Разработка идёт напрямую по задаче пользователя. Каждый affected repo проходит локальную копию и не обращаются к исходникам или CI сервера. Доставка новой
свой verify; при изменении wire contract дополнительно выполняется contract check. схемы — явное обновление snapshot с review и `npm run openapi:generate`.
Обязательного OpenSpec/SDD lifecycle нет. Runtime URL API задаётся окружением, а не расположением другого репозитория.
Разработка идёт напрямую по задаче пользователя; OpenSpec/SDD — по явному запросу.
Knip исключает `conventional-changelog-conventionalcommits`: release-it загружает
preset по имени из `.release-it.json`. Версия preset закреплена напрямую.
## Релизы
Репозиторий выпускается независимо. `develop` — интеграция, `main` — принятые
релизы. Работа: `codex/<task>` от актуального `develop`, PR в `develop`.
Обычные PR допускают squash; release и обратная синхронизация сохраняют историю.
Commits и PR titles — Conventional Commits, включая `spec:`. Версии вручную не повышай.
1. Получи `main`, `develop` и теги: `git fetch origin --tags`. Убедись, что
`develop` содержит последний релиз. Создай `release/<name>` от проверенного
`develop`; `nvm use --silent`, `npm ci`. Hotfix начинается от `main` в
`release/hotfix-<name>` и проходит тот же процесс.
2. На чистой ветке выполни `npm run release:preview`, просмотри версию/changelog,
затем `npm run release:prepare`. Команда создаёт `chore(release): X.Y.Z`,
обновляет manifest/lockfile/CHANGELOG; тег и push не выполняет. Не обходи
guards ветки, чистого дерева, отсутствующих тегов или уже подготовленной версии.
3. Проверь diff и штатные gates этого репозитория. Отправь только release-ветку,
открой PR в `main` с заголовком `chore(release): X.Y.Z`. После зелёных
`verify`, `security`, `commits` выполни fast-forward-only merge. Если `main`
изменился, согласуй историю и повтори проверки кандидата.
4. Получи удалённый `main`, сравни его HEAD с проверенным release SHA и версией
manifest/lockfile. Создай аннотированный `vX.Y.Z` именно на этом SHA:
`git tag -a vX.Y.Z <release-sha> -m "Release X.Y.Z"`, затем отправь только
`git push origin refs/tags/vX.Y.Z`. Не запускай release-it повторно на `main`.
5. Верни release-коммит через PR `main → develop` без squash/rebase; проверь,
что `develop` содержит тег. Опубликованные теги не перемещай. При сбое после
merge создай отсутствующий тег без нового bump; до merge исправь и проверь
существующий кандидат без повторного повышения версии.
`feat:` повышает minor, `fix:`/`perf:` и прочие разрешённые типы — patch;
`!`/`BREAKING CHANGE:` — major, включая версии до 1.0. `chore(release):`
исключён из рекомендации и changelog. Конфигурация — `.release-it.json`.
В Gitea для `main`/`develop` должны быть запрещены прямой/force push и обход
администратором, обязательны `verify`, `security`, `commits`; теги `v*` защищены.
Workflow сам не включает эти настройки. Отдельное review approval для одного
владельца не требуется. Npm publishing, deploy и Gitea Releases не включены.
## Локальные пакеты
`packages/tokens` — private npm workspace с единственным export
`@wealthledger/tokens/tokens.json`. `packages/ui` экспортирует собранные
`@wealthledger/ui/theme` (JS + declarations) и `@wealthledger/ui/styles.css`.
Корневой export `@wealthledger/ui` содержит EntryCard, StateView и LoadingSkeleton;
Потребители импортируют компоненты напрямую из `@wealthledger/ui`.
CSS явно подключается после Mantine; providers остаются в приложении/Storybook.
Тема доступна через `@wealthledger/ui/theme`; compatibility re-exports удалены.
JSON не требует сборки. `npm ci` связывает workspaces, а существующие команды
разработки, проверок и сборки сначала выполняют `npm run build:packages`.
Library build использует отдельный Vite config без app plugins и TypeScript
для declarations. После изменения package sources перезапустите `npm run dev`
или `npm run dev:catalog`; отдельный watch-процесс пока не нужен.
Начальная версия manifest взята из приложения; отдельный release-процесс
и публикация не настроены.
Private `@wealthledger/icons` экспортирует `AddIcon`, `EditIcon`, `DeleteIcon`
и type `IconProps`. Единственный source рисунка — TSX в `packages/icons/src/svg`;
поставка содержит ESM/declarations, без raw SVG, CSS, Mantine и motion.
React — peer/external. Размер `size` по умолчанию 24, `strokeWidth` — 1.5;
цвет наследуется через `currentColor`, SVG props можно передать явно.
В action используйте декоративный `<AddIcon size={20} strokeWidth={2} />`,
доступное имя задавайте кнопке. Standalone пример:
`<EditIcon aria-hidden={false} role="img" aria-label="Редактирование" />`.
Поддерживается также стандартный `aria-labelledby`; подпись выбирает caller.
Card/Cards используют пакетные Add/Edit/Delete с прежними размерами/strokeWidth.
Restore/category SVG и предметный BankOperationIcon остаются в приложении.
+20 -2
View File
@@ -7,6 +7,7 @@
"includes": [ "includes": [
"**", "**",
"!dist", "!dist",
"!packages/*/dist",
"!storybook-static", "!storybook-static",
"!src/shared/api/generated", "!src/shared/api/generated",
"!src/shared/api/spec", "!src/shared/api/spec",
@@ -27,7 +28,8 @@
}, },
"style": { "style": {
"noDefaultExport": "error", "noDefaultExport": "error",
"useExportsLast": "error" "useExportsLast": "error",
"noMagicNumbers": "error"
} }
} }
}, },
@@ -37,7 +39,8 @@
"vite.config.ts", "vite.config.ts",
"vitest.config.ts", "vitest.config.ts",
".storybook/main.ts", ".storybook/main.ts",
".storybook/preview.tsx" ".storybook/preview.tsx",
"packages/*/vite.config.ts"
], ],
"linter": { "linter": {
"rules": { "rules": {
@@ -57,6 +60,21 @@
} }
} }
} }
},
{
"includes": [
"**/*.test.ts",
"**/*.test.tsx",
"**/*.stories.tsx",
"src/test/**"
],
"linter": {
"rules": {
"style": {
"noMagicNumbers": "off"
}
}
}
} }
] ]
} }
+23 -1
View File
@@ -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",
],
],
},
};
+13
View File
@@ -1,5 +1,11 @@
module.exports = { module.exports = {
forbidden: [ forbidden: [
{
name: "packages-must-not-depend-on-app",
severity: "error",
from: { path: "^packages/" },
to: { path: "^src/" },
},
{ {
name: "no-circular", name: "no-circular",
severity: "error", severity: "error",
@@ -17,6 +23,12 @@ module.exports = {
pathNot: "^src/$1/$2/", pathNot: "^src/$1/$2/",
}, },
}, },
{
name: "no-same-layer-cross-slice-imports",
severity: "error",
from: { path: "^src/(pages|features|entities)/([^/]+)/" },
to: { path: "^src/$1/", pathNot: "^src/$1/$2/" },
},
{ {
name: "shared-must-not-depend-on-layers", name: "shared-must-not-depend-on-layers",
severity: "error", severity: "error",
@@ -43,6 +55,7 @@ module.exports = {
}, },
], ],
options: { options: {
exclude: "^packages/[^/]+/dist/",
doNotFollow: { path: "node_modules" }, doNotFollow: { path: "node_modules" },
tsConfig: { fileName: "tsconfig.app.json" }, tsConfig: { fileName: "tsconfig.app.json" },
tsPreCompilationDeps: true, tsPreCompilationDeps: true,
+43
View File
@@ -0,0 +1,43 @@
worker_processes auto;
pid /tmp/nginx.pid;
error_log /dev/stderr warn;
events { worker_connections 1024; }
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Do not log query strings, cookies, authorization or bodies.
log_format safe '$request_method $uri $status';
access_log /dev/stdout safe;
client_body_temp_path /tmp/client_temp;
proxy_temp_path /tmp/proxy_temp;
fastcgi_temp_path /tmp/fastcgi_temp;
uwsgi_temp_path /tmp/uwsgi_temp;
scgi_temp_path /tmp/scgi_temp;
map $http_x_forwarded_proto $forwarded_proto {
default $http_x_forwarded_proto;
'' $scheme;
}
server {
listen 8080;
server_name _;
root /usr/share/nginx/html;
resolver 127.0.0.11 valid=5s ipv6=off;
location /api/ {
set $backend http://backend:3000;
proxy_pass $backend$request_uri;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Host $http_host;
proxy_set_header X-Forwarded-Proto $forwarded_proto;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Request-ID $http_x_request_id;
}
location /assets/ {
try_files $uri =404;
add_header Cache-Control "public, max-age=31536000, immutable";
}
location / {
try_files $uri $uri/ /index.html;
add_header Cache-Control "no-cache" always;
}
}
}
+3 -1
View File
@@ -1,8 +1,10 @@
<!doctype html> <!doctype html>
<html lang="en"> <html lang="ru">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<meta name="theme-color" content="#ffffff" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WealthLedger</title> <title>WealthLedger</title>
</head> </head>
+15 -1
View File
@@ -1,3 +1,17 @@
{ {
"project": ["src/**/*.{ts,tsx}", "!src/shared/api/generated/**"] "ignoreDependencies": ["conventional-changelog-conventionalcommits"],
"workspaces": {
".": {
"project": ["src/**/*.{ts,tsx}", "!src/shared/api/generated/**"]
},
"packages/tokens": {
"entry": ["tokens.json"]
},
"packages/ui": {
"project": ["src/**/*.{ts,tsx}"]
},
"packages/icons": {
"project": ["src/**/*.{ts,tsx}"]
}
}
} }
+7832 -1066
View File
File diff suppressed because it is too large Load Diff
+62 -44
View File
@@ -1,81 +1,99 @@
{ {
"name": "wealth-ledger-frontend", "name": "wealth-ledger-frontend",
"private": true, "private": true,
"version": "0.0.0", "version": "0.4.0",
"type": "module", "type": "module",
"engines": { "engines": {
"node": "22.x" "node": "24.21.0"
}, },
"scripts": { "scripts": {
"dev": "vite", "dev": "npm run build:packages && vite",
"dev:catalog": "storybook dev -p 6006 --no-open --disable-telemetry", "dev:catalog": "npm run build:packages && storybook dev -p 6006 --no-open --disable-telemetry",
"build:catalog": "storybook build --output-dir storybook-static --disable-telemetry", "build:catalog": "npm run build:packages && storybook build --output-dir storybook-static --disable-telemetry",
"preview:catalog": "vite preview --outDir storybook-static", "preview:catalog": "vite preview --outDir storybook-static",
"typecheck": "tsc -b --noEmit", "typecheck": "npm run build:packages && tsc -b --noEmit",
"build": "tsc -b && vite build", "build": "npm run build:packages && tsc -b && vite build",
"lint": "biome check .", "lint": "biome check .",
"test": "vitest", "test": "npm run build:packages && vitest",
"test:run": "vitest run", "test:run": "npm run build:packages && vitest run",
"test:coverage": "vitest run --coverage", "test:coverage": "npm run build:packages && vitest run --coverage",
"openapi:generate": "openapi-typescript src/shared/api/spec/openapi.json -o src/shared/api/generated/schema.d.ts", "openapi:generate": "openapi-typescript src/shared/api/spec/openapi.json -o src/shared/api/generated/schema.d.ts",
"openapi:check": "node scripts/check-openapi.mjs", "openapi:check": "node scripts/check-openapi.mjs",
"knip": "knip", "knip": "npm run build:packages && knip",
"deps": "depcruise src --config dependency-cruiser.cjs --output-type err-long", "deps": "npm run build:packages && depcruise src packages --config dependency-cruiser.cjs --output-type err-long",
"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 build:packages && 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": "npm run build:packages && depcruise src packages .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",
"build:packages": "npm run build --workspaces --if-present"
}, },
"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",
"@wealthledger/icons": "file:packages/icons",
"@wealthledger/tokens": "file:packages/tokens",
"@wealthledger/ui": "file:packages/ui",
"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" "vite-plugin-pwa": "1.3.0",
} "vitest": "5.0.0"
},
"allowScripts": {
"esbuild@0.28.2": true,
"fsevents@2.3.3": true
},
"workspaces": [
"packages/*"
]
} }
+30
View File
@@ -0,0 +1,30 @@
{
"name": "@wealthledger/icons",
"version": "0.3.0",
"private": true,
"type": "module",
"files": [
"dist"
],
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"sideEffects": false,
"scripts": {
"build": "vite build && tsc -p tsconfig.json"
},
"peerDependencies": {
"react": "19.3.0"
},
"devDependencies": {
"@storybook/react-vite": "10.6.0",
"@testing-library/react": "16.3.3",
"@types/react": "19.3.0",
"typescript": "5.9.3",
"vite": "8.3.0",
"vitest": "5.0.0"
}
}
+45
View File
@@ -0,0 +1,45 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { AddIcon, DeleteIcon, EditIcon } from "./index";
const meta = {
title: "Design System/Icons",
component: AddIcon,
tags: ["autodocs"],
parameters: {
docs: {
description: {
component:
"Статичные SVG: size по умолчанию 24, strokeWidth 1.5, цвет currentColor. В кнопке иконка декоративная, имя принадлежит действию. Для самостоятельного изображения задайте aria-hidden={false}, role=img и aria-label либо aria-labelledby. Геометрия взята из Card/Cards; подписи и действия остаются у приложения.",
},
},
},
} satisfies Meta<typeof AddIcon>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Decorative: Story = {
render: () => (
<div style={{ display: "flex", gap: 16, color: "#2563eb" }}>
<button type="button" aria-label="Добавить пример">
<AddIcon size={20} strokeWidth={2} />
</button>
<button type="button" aria-label="Изменить пример">
<EditIcon size={18} />
</button>
<button type="button" aria-label="Удалить пример">
<DeleteIcon size={18} />
</button>
</div>
),
};
export const Meaningful: Story = {
render: () => (
<div style={{ display: "flex", gap: 16, color: "#2563eb" }}>
<AddIcon aria-hidden={false} role="img" aria-label="Добавление" />
<EditIcon aria-hidden={false} role="img" aria-label="Редактирование" />
<DeleteIcon aria-hidden={false} role="img" aria-label="Удаление" />
</div>
),
};
+34
View File
@@ -0,0 +1,34 @@
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { AddIcon, DeleteIcon, EditIcon } from "./index";
describe("icon accessibility", () => {
it.each([AddIcon, EditIcon, DeleteIcon])(
"keeps decoration hidden and exposes explicitly named images: %s",
(Icon) => {
const { rerender } = render(
<button type="button" aria-label="Действие">
<Icon />
</button>,
);
expect(screen.queryByRole("img")).not.toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Действие" }).querySelector("svg"),
).toHaveAttribute("focusable", "false");
rerender(
<Icon
aria-hidden={false}
role="img"
aria-label="Пример"
size={18}
strokeWidth={2}
/>,
);
const icon = screen.getByRole("img", { name: "Пример" });
expect(icon).toHaveAttribute("width", "18");
expect(icon).toHaveAttribute("height", "18");
expect(icon).toHaveAttribute("stroke-width", "2");
expect(icon).toHaveAttribute("stroke", "currentColor");
},
);
});
+4
View File
@@ -0,0 +1,4 @@
export { AddIcon } from "./svg/AddIcon";
export { DeleteIcon } from "./svg/DeleteIcon";
export { EditIcon } from "./svg/EditIcon";
export type { IconProps } from "./types";
+24
View File
@@ -0,0 +1,24 @@
import type { FC } from "react";
import type { IconProps } from "../types";
const AddIcon: FC<IconProps> = (props) => {
const { size = "24", ...svgProps } = props;
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
aria-hidden="true"
focusable="false"
{...svgProps}
>
<path d="M12 5v14 M5 12h14" />
</svg>
);
};
export { AddIcon };
+25
View File
@@ -0,0 +1,25 @@
import type { FC } from "react";
import type { IconProps } from "../types";
const DeleteIcon: FC<IconProps> = (props) => {
const { size = "24", ...svgProps } = props;
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
{...svgProps}
>
<path d="M3 6h18 M9 6V3h6v3 M5 6l1 15h12l1-15 M10 10v7 M14 10v7" />
</svg>
);
};
export { DeleteIcon };
+25
View File
@@ -0,0 +1,25 @@
import type { FC } from "react";
import type { IconProps } from "../types";
const EditIcon: FC<IconProps> = (props) => {
const { size = "24", ...svgProps } = props;
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
{...svgProps}
>
<path d="m16 3 5 5-12 12-6 1 1-6L16 3Z M13 6l5 5" />
</svg>
);
};
export { EditIcon };
+10
View File
@@ -0,0 +1,10 @@
import type { ComponentPropsWithoutRef } from "react";
type IconProps = Omit<
ComponentPropsWithoutRef<"svg">,
"children" | "dangerouslySetInnerHTML"
> & {
size?: number | string;
};
export type { IconProps };
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2023",
"lib": ["ES2023", "DOM"],
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"skipLibCheck": true,
"verbatimModuleSyntax": true,
"declaration": true,
"emitDeclarationOnly": true,
"rootDir": "src",
"outDir": "dist",
"jsx": "react-jsx"
},
"include": ["src/index.ts"]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from "vite";
export default defineConfig({
build: {
lib: { entry: "src/index.ts", formats: ["es"], fileName: "index" },
rolldownOptions: { external: /^react(\/|$)/ },
},
});
+12
View File
@@ -0,0 +1,12 @@
{
"name": "@wealthledger/tokens",
"version": "0.3.0",
"private": true,
"type": "module",
"files": [
"tokens.json"
],
"exports": {
"./tokens.json": "./tokens.json"
}
}
@@ -53,7 +53,7 @@
"#40c057", "#40c057",
"#37b24d", "#37b24d",
"#2f9e44", "#2f9e44",
"#2b8a3e" "#237032"
], ],
"red": [ "red": [
"#fff5f5", "#fff5f5",
@@ -151,12 +151,12 @@
}, },
"positive": { "positive": {
"color": "green", "color": "green",
"shade": 6, "shade": 9,
"description": "Положительный результат; дополните знаком и текстом" "description": "Положительный результат; дополните знаком и текстом"
}, },
"negative": { "negative": {
"color": "red", "color": "red",
"shade": 6, "shade": 9,
"description": "Ошибка / отрицательный результат; дополните текстом" "description": "Ошибка / отрицательный результат; дополните текстом"
}, },
"warning": { "warning": {
+44
View File
@@ -0,0 +1,44 @@
{
"name": "@wealthledger/ui",
"version": "0.3.0",
"private": true,
"type": "module",
"files": [
"dist"
],
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
"./theme": {
"types": "./dist/theme.d.ts",
"import": "./dist/theme.js"
},
"./styles.css": "./dist/styles.css"
},
"sideEffects": [
"**/*.css"
],
"scripts": {
"build": "vite build && tsc -p tsconfig.json"
},
"dependencies": {
"@wealthledger/tokens": "0.3.0"
},
"peerDependencies": {
"@mantine/core": "9.6.1",
"@mantine/hooks": "9.6.1",
"react": "19.3.0",
"react-dom": "19.3.0"
},
"devDependencies": {
"@storybook/react-vite": "10.6.0",
"@testing-library/react": "16.3.3",
"@types/react": "19.3.0",
"storybook": "10.6.0",
"typescript": "5.9.3",
"vite": "8.3.0",
"vitest": "5.0.0"
}
}
@@ -0,0 +1,95 @@
.row {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
gap: var(--mantine-spacing-sm);
align-items: center;
padding: var(--mantine-spacing-md);
border-color: var(--wl-color-border);
background: var(--wl-color-subtle);
}
.identity,
.value {
min-width: 0;
}
.value {
text-align: right;
white-space: nowrap;
}
.positive {
color: var(--wl-color-positive);
}
.negative {
color: var(--wl-color-negative);
}
.neutral {
color: var(--mantine-color-gray-7);
}
@media (max-width: 36em) {
.row {
grid-template-columns: auto minmax(0, 1fr);
}
.value {
grid-column: 2;
text-align: left;
}
}
.valueFooter {
display: grid;
align-items: center;
justify-items: end;
min-height: 28px;
}
.valueLabel,
.actions {
grid-area: 1 / 1;
transition: opacity 180ms ease;
}
.valueLabel {
opacity: 0;
}
.actions {
display: flex;
}
@media (hover: hover) and (pointer: fine) {
.valueLabel {
opacity: 1;
}
.actions {
opacity: 0;
pointer-events: none;
}
.row:hover .actions,
.row:focus-within .actions {
opacity: 1;
pointer-events: auto;
}
.row:hover .valueLabel,
.row:focus-within .valueLabel {
opacity: 0;
}
}
@media (max-width: 36em) {
.valueFooter {
justify-items: start;
}
}
@media (pointer: coarse) {
.actions button {
min-width: 36px;
min-height: 36px;
}
}
@media (prefers-reduced-motion: reduce) {
.valueLabel,
.actions {
transition: none;
}
}
@@ -0,0 +1,37 @@
import { Button } from "@mantine/core";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { fn } from "storybook/test";
import { EntryCard } from "./EntryCard";
const meta = {
title: "Design System/Components/EntryCard",
component: EntryCard,
tags: ["autodocs"],
args: {
title:
"Учебная запись с очень длинным названием для проверки узкого экрана",
metadata: "22.09.2026 · Синтетические данные",
initial: "У",
imageSrc: "data:image/png;base64,invalid",
value: "−1 250,00 ₽",
valueLabel: "Тестовое значение",
tone: "negative",
actions: (
<Button size="compact-sm" onClick={fn()}>
Открыть пример
</Button>
),
},
parameters: {
docs: {
description: {
component:
"Готовые строки и slots без финансовых вычислений. Невалидное локальное изображение показывает fallback; действие доступно с клавиатуры и на узком экране. Данные вымышлены.",
},
},
},
} satisfies Meta<typeof EntryCard>;
export default meta;
type Story = StoryObj<typeof meta>;
export const LongContentAndFallback: Story = {};
@@ -0,0 +1,35 @@
import { MantineProvider } from "@mantine/core";
import { fireEvent, render, screen } from "@testing-library/react";
import { assert, describe, expect, it } from "vitest";
import { EntryCard } from "./EntryCard";
describe("EntryCard", () => {
it("keeps the fallback after an image fails", () => {
const props = {
title: "Пример",
metadata: "Описание",
initial: "У",
value: "—",
valueLabel: "Неизвестно",
tone: "neutral" as const,
imageSrc: "data:image/png;base64,invalid",
};
const { container, rerender } = render(
<MantineProvider>
<EntryCard {...props} />
</MantineProvider>,
);
// Decorative image has no accessible name; trigger its actual failure event.
const image = container.querySelector("img");
assert(image);
fireEvent.error(image);
rerender(
<MantineProvider>
<EntryCard {...props} title="Обновлённый пример" />
</MantineProvider>,
);
expect(container.querySelector("img")).toBeNull();
expect(screen.getByText("У")).toBeInTheDocument();
expect(screen.getByText("Обновлённый пример")).toBeInTheDocument();
});
});
@@ -6,7 +6,10 @@ type EntryCardProps = {
title: string; title: string;
metadata: string; metadata: string;
details?: ReactNode; details?: ReactNode;
actions?: ReactNode;
initial: string; initial: string;
icon?: ReactNode;
color?: string;
imageSrc?: string | null; imageSrc?: string | null;
value: string; value: string;
valueLabel: string; valueLabel: string;
@@ -16,7 +19,17 @@ type EntryCardProps = {
const EntryCard: FC<EntryCardProps> = (props) => { const EntryCard: FC<EntryCardProps> = (props) => {
const [imageFailed, setImageFailed] = useState(false); const [imageFailed, setImageFailed] = useState(false);
return ( return (
<Paper className={classes.row} withBorder> <Paper
className={classes.row}
withBorder
style={
props.color
? {
background: `color-mix(in srgb, var(--mantine-color-${props.color}-0) 45%, var(--wl-color-surface))`,
}
: undefined
}
>
<Avatar <Avatar
alt="" alt=""
aria-hidden="true" aria-hidden="true"
@@ -25,7 +38,7 @@ const EntryCard: FC<EntryCardProps> = (props) => {
src={imageFailed ? null : props.imageSrc} src={imageFailed ? null : props.imageSrc}
onError={() => setImageFailed(true)} onError={() => setImageFailed(true)}
> >
{props.initial} {props.icon ?? props.initial}
</Avatar> </Avatar>
<Stack className={classes.identity} gap={2}> <Stack className={classes.identity} gap={2}>
<Text fw={700} lineClamp={1}> <Text fw={700} lineClamp={1}>
@@ -40,9 +53,17 @@ const EntryCard: FC<EntryCardProps> = (props) => {
<Text className={classes[props.tone]} fw={700}> <Text className={classes[props.tone]} fw={700}>
{props.value} {props.value}
</Text> </Text>
<Text className={classes[props.tone]} size="sm"> <div className={props.actions ? classes.valueFooter : undefined}>
{props.valueLabel} <Text
</Text> className={`${classes[props.tone]} ${props.actions ? classes.valueLabel : ""}`}
size="sm"
>
{props.valueLabel}
</Text>
{props.actions && (
<div className={classes.actions}>{props.actions}</div>
)}
</div>
</Stack> </Stack>
</Paper> </Paper>
); );
@@ -1,7 +1,7 @@
import { MantineProvider } from "@mantine/core"; import { MantineProvider } from "@mantine/core";
import { render, screen } from "@testing-library/react"; import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { LoadingSkeleton } from "./LoadingSkeleton"; import { LoadingSkeleton } from "../LoadingSkeleton/LoadingSkeleton";
import { StateView } from "./StateView"; import { StateView } from "./StateView";
describe("StateView", () => { describe("StateView", () => {
+3
View File
@@ -0,0 +1,3 @@
export { EntryCard } from "./EntryCard/EntryCard";
export { LoadingSkeleton } from "./LoadingSkeleton/LoadingSkeleton";
export { StateView } from "./StateView/StateView";
+39
View File
@@ -0,0 +1,39 @@
* {
box-sizing: border-box;
}
body {
margin: 0;
background: var(--wl-color-canvas);
color: var(--wl-color-text);
}
a {
color: inherit;
text-decoration: none;
}
@media (prefers-reduced-motion: no-preference) {
.mantine-Modal-content {
animation: modal-appear 220ms ease-out;
}
.mantine-Modal-overlay {
animation: modal-backdrop-appear 220ms ease-out;
}
}
@keyframes modal-appear {
from {
opacity: 0;
transform: translateY(8px) scale(0.98);
}
to {
opacity: 1;
transform: translateY(0) scale(1);
}
}
@keyframes modal-backdrop-appear {
from {
opacity: 0;
}
}
@@ -1,7 +1,7 @@
import { DEFAULT_THEME, mergeMantineTheme } from "@mantine/core"; import { DEFAULT_THEME, mergeMantineTheme } from "@mantine/core";
import source from "@wealthledger/tokens/tokens.json";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { colorRoles, cssVariablesResolver, theme } from "./theme"; import { colorRoles, cssVariablesResolver, theme } from "./theme";
import source from "./tokens.json";
describe("design theme adapter", () => { describe("design theme adapter", () => {
it("preserves scale-aware sizes, unscaled breakpoints and shadow layers", () => { it("preserves scale-aware sizes, unscaled breakpoints and shadow layers", () => {
@@ -1,13 +1,15 @@
import "./styles.css";
import { import {
type CSSVariablesResolver, type CSSVariablesResolver,
colorsTuple, colorsTuple,
createTheme, createTheme,
getThemeColor, getThemeColor,
type MantinePrimaryShade, type MantinePrimaryShade,
Modal,
rem, rem,
rgba, rgba,
} from "@mantine/core"; } from "@mantine/core";
import designTokens from "./tokens.json"; import designTokens from "@wealthledger/tokens/tokens.json";
const { color, typography, spacing, radius, shadows, breakpoints } = const { color, typography, spacing, radius, shadows, breakpoints } =
designTokens; designTokens;
@@ -21,6 +23,20 @@ const colorRoles = mapValues(color.roles, (role) =>
); );
const theme = createTheme({ const theme = createTheme({
respectReducedMotion: true,
components: {
Modal: Modal.extend({
defaultProps: {
overlayProps: { blur: 3 },
transitionProps: {
transition: "fade-down",
duration: 220,
exitDuration: 180,
timingFunction: "ease-out",
},
},
}),
},
primaryColor: color.roles.primary.color, primaryColor: color.roles.primary.color,
primaryShade: color.primaryShade as MantinePrimaryShade, primaryShade: color.primaryShade as MantinePrimaryShade,
defaultRadius: radius.default, defaultRadius: radius.default,
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2023",
"lib": ["ES2023", "DOM"],
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"strict": true,
"skipLibCheck": true,
"verbatimModuleSyntax": true,
"declaration": true,
"emitDeclarationOnly": true,
"rootDir": "src",
"outDir": "dist",
"jsx": "react-jsx",
"types": ["vite/client"]
},
"include": ["src/index.ts", "src/theme.ts"]
}
+14
View File
@@ -0,0 +1,14 @@
import { defineConfig } from "vite";
export default defineConfig({
build: {
lib: {
entry: { index: "src/index.ts", theme: "src/theme.ts" },
formats: ["es"],
cssFileName: "styles",
},
rolldownOptions: {
external: /^(react(?:-dom)?|@mantine\/[^/]+|@wealthledger\/tokens)(\/|$)/,
},
},
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

+19
View File
@@ -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"]
}
+75
View File
@@ -0,0 +1,75 @@
const { test } = require("node:test");
const assert = require("node:assert/strict");
const {
mkdtempSync,
readFileSync,
writeFileSync,
chmodSync,
rmSync,
} = require("node:fs");
const { tmpdir } = require("node:os");
const { join, resolve } = require("node:path");
const EXECUTABLE_MODE = 0o755;
const { spawnSync } = require("node:child_process");
test("immutable publication resumes exact digest checks after post-push failure", () => {
const directory = mkdtempSync(join(tmpdir(), "wl-image-retry-"));
const workflow = readFileSync(
resolve(__dirname, "../.gitea/workflows/image.yml"),
"utf8",
);
const block = workflow
.split(" - name: Publish immutable release tag\n run: |\n")[1]
.split(" - name:")[0]
.replace(/^ {10}/gm, "");
const double = `#!${process.execPath}
const fs = require('node:fs');
const args = process.argv.slice(2).join(' ');
fs.appendFileSync('calls', args + '\\n');
if (args.startsWith('manifest inspect')) {
if (!fs.existsSync('published')) { console.error('manifest unknown'); process.exit(1); }
} else if (args.startsWith('buildx imagetools inspect')) {
console.log('sha256:exact');
} else if (args.startsWith('buildx build')) {
fs.writeFileSync('published', 'yes');
fs.writeFileSync('image-metadata.json', JSON.stringify({'containerimage.digest': 'sha256:exact'}));
} else if (args.startsWith('pull')) {
if (!fs.existsSync('pull-failed')) { fs.writeFileSync('pull-failed', 'yes'); process.exit(1); }
} else if (args.startsWith('image inspect')) {
console.log(args.includes('image.version') ? '1.2.3' : process.env.BAD_REVISION ? 'other' : 'commit');
} else if (args.startsWith('run') && process.env.BAD_SMOKE) process.exit(1);
`;
try {
for (const name of ["docker", "npm"]) {
writeFileSync(join(directory, name), double);
chmodSync(join(directory, name), EXECUTABLE_MODE);
}
const run = (extra = {}) =>
spawnSync("/bin/sh", ["-ec", block], {
cwd: directory,
encoding: "utf8",
env: {
...process.env,
PATH: `${directory}:${process.env.PATH}`,
IMAGE: "synthetic/image",
RELEASE_TAG: "v1.2.3",
REVISION: "commit",
...extra,
},
});
assert.notEqual(run().status, 0);
const retry = run();
assert.equal(retry.status, 0, retry.stdout + retry.stderr);
assert.notEqual(run({ BAD_REVISION: "1" }).status, 0);
assert.notEqual(run({ BAD_SMOKE: "1" }).status, 0);
const calls = readFileSync(join(directory, "calls"), "utf8");
assert.equal(
calls.split("\n").filter((line) => line.startsWith("buildx build"))
.length,
1,
);
assert.ok(calls.includes("synthetic/image@sha256:exact"));
} finally {
rmSync(directory, { recursive: true, force: true });
}
});
+25
View File
@@ -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.",
);
+61
View File
@@ -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 });
}
});
+12
View File
@@ -0,0 +1,12 @@
sonar.projectKey=wealthledger-frontend
sonar.projectName=WealthLedger frontend
sonar.host.url=https://sonarqube.personal.ksv741.ru
sonar.sourceEncoding=UTF-8
sonar.sources=src
sonar.tests=src
sonar.test.inclusions=src/**/*.test.ts,src/**/*.test.tsx
sonar.exclusions=src/**/*.test.ts,src/**/*.test.tsx,src/**/*.stories.tsx,src/test/**,src/shared/api/generated/**,src/shared/api/spec/**
sonar.javascript.lcov.reportPaths=coverage/lcov.info
# SonarQube 9.9 embeds an older TypeScript analyzer than the application compiler.
sonar.typescript.tsconfigPaths=tsconfig.sonar.json
@@ -16,6 +16,7 @@ import type { IncomeAnalytics } from "@/entities/income";
import type { Portfolio } from "@/entities/portfolio"; import type { Portfolio } from "@/entities/portfolio";
import { AuthProvider } from "@/features/auth"; import { AuthProvider } from "@/features/auth";
import { createTestQueryClient } from "@/test/query"; import { createTestQueryClient } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server"; import { server } from "@/test/server";
import { AppRoutes } from "./AppRoutes"; import { AppRoutes } from "./AppRoutes";
@@ -132,50 +133,56 @@ beforeEach(() => {
), ),
http.get("*/api/v1/brokerage-accounts", () => http.get("*/api/v1/brokerage-accounts", () =>
HttpResponse.json( HttpResponse.json(
accounts.map((account) => ({ resource(
...account, accounts.map((account) => ({
type: "BROKERAGE", ...account,
openedOn: null, type: "BROKERAGE",
portfolioSummary: null, openedOn: null,
})), portfolioSummary: null,
})),
),
), ),
), ),
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () => http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
HttpResponse.json(portfolio), HttpResponse.json(resource(portfolio)),
), ),
http.get( http.get(
"*/api/v1/brokerage-accounts/:accountId/operations", "*/api/v1/brokerage-accounts/:accountId/operations",
({ params }) => ({ params }) =>
HttpResponse.json({ HttpResponse.json(
accountId: params.accountId, resource({
items, accountId: params.accountId,
hasNext: false, items,
nextCursor: null, hasNext: false,
observedAt: receipt.occurredAt, nextCursor: null,
}), observedAt: receipt.occurredAt,
}),
),
), ),
http.get("*/api/v1/brokerage-accounts/:accountId/income-analytics", () => http.get("*/api/v1/brokerage-accounts/:accountId/income-analytics", () =>
HttpResponse.json(analytics), HttpResponse.json(resource(analytics)),
), ),
http.get("*/api/v1/brokerage-accounts/:accountId/events", () => http.get("*/api/v1/brokerage-accounts/:accountId/events", () =>
HttpResponse.json({ HttpResponse.json(
accountId: "all", resource({
calculatedAt: receipt.occurredAt, accountId: "all",
incomeTotalsByCurrency: [], calculatedAt: receipt.occurredAt,
events: accounts.map((account) => ({ incomeTotalsByCurrency: [],
account, events: accounts.map((account) => ({
type: "coupon", account,
date: "2026-09-15", type: "coupon",
dateKind: "event", date: "2026-09-15",
figi: null, dateKind: "event",
instrumentUid: null, figi: null,
ticker: "BOND", instrumentUid: null,
displayName: "Облигация", ticker: "BOND",
isin: null, displayName: "Облигация",
logoName: null, isin: null,
projectedAmount: { currency: "RUB", value: "2" }, logoName: null,
})), projectedAmount: { currency: "RUB", value: "2" },
}), })),
}),
),
), ),
); );
}); });
@@ -224,20 +231,22 @@ describe("All accounts routes", () => {
({ request, params }) => { ({ request, params }) => {
const url = new URL(request.url); const url = new URL(request.url);
requests.push(url); requests.push(url);
return HttpResponse.json({ return HttpResponse.json(
accountId: params.accountId, resource({
items: [ accountId: params.accountId,
{ items: [
...receipt, {
description: url.searchParams.has("cursor") ...receipt,
? "Вторая страница" description: url.searchParams.has("cursor")
: "Первая страница", ? "Вторая страница"
}, : "Первая страница",
], },
hasNext: !url.searchParams.has("cursor"), ],
nextCursor: url.searchParams.has("cursor") ? null : "next", hasNext: !url.searchParams.has("cursor"),
observedAt: receipt.occurredAt, nextCursor: url.searchParams.has("cursor") ? null : "next",
}); observedAt: receipt.occurredAt,
}),
);
}, },
), ),
); );
@@ -274,13 +283,15 @@ describe("All accounts routes", () => {
{ code: "INVALID_OPERATIONS_CURSOR" }, { code: "INVALID_OPERATIONS_CURSOR" },
{ status: 400 }, { status: 400 },
) )
: HttpResponse.json({ : HttpResponse.json(
accountId: "all", resource({
items, accountId: "all",
hasNext: true, items,
nextCursor: "expired", hasNext: true,
observedAt: receipt.occurredAt, nextCursor: "expired",
}), observedAt: receipt.occurredAt,
}),
),
), ),
); );
renderPage("/accounts/all/operations?from=2026-08-01&to=2026-08-31"); renderPage("/accounts/all/operations?from=2026-08-01&to=2026-08-31");
@@ -1,12 +1,11 @@
import { MantineProvider } from "@mantine/core"; import { MantineProvider } from "@mantine/core";
import { QueryClientProvider } from "@tanstack/react-query"; import { QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { cssVariablesResolver, theme } from "@wealthledger/ui/theme";
import { HttpResponse, http } from "msw"; import { HttpResponse, http } from "msw";
import { MemoryRouter } from "react-router"; import { MemoryRouter } from "react-router";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { AuthProvider } from "@/features/auth"; import { AuthProvider } from "@/features/auth";
import { cssVariablesResolver, theme } from "@/shared/theme";
import { createTestQueryClient } from "@/test/query"; import { createTestQueryClient } from "@/test/query";
import { server } from "@/test/server"; import { server } from "@/test/server";
import { AppRoutes } from "./AppRoutes"; import { AppRoutes } from "./AppRoutes";
@@ -37,6 +36,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 +94,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", () =>
@@ -1,9 +1,17 @@
import type { FC } from "react"; import type { FC } from "react";
import { lazy } from "react"; import { lazy } from "react";
import { Navigate, Route, Routes } from "react-router"; 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 };
@@ -57,7 +65,7 @@ const SettingsPage = lazy(async () => {
return { default: SettingsPage }; return { default: SettingsPage };
}); });
const ProtectedLayout = lazy(async () => { const ProtectedLayout = lazy(async () => {
const { ProtectedLayout } = await import("./ProtectedLayout"); const { ProtectedLayout } = await import("../ProtectedLayout");
return { default: ProtectedLayout }; return { default: ProtectedLayout };
}); });
@@ -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={
@@ -12,6 +12,7 @@ import { MemoryRouter, useNavigate } from "react-router";
import { beforeEach, describe, expect, it } from "vitest"; import { beforeEach, describe, expect, it } from "vitest";
import { AuthProvider } from "@/features/auth"; import { AuthProvider } from "@/features/auth";
import { createTestQueryClient } from "@/test/query"; import { createTestQueryClient } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server"; import { server } from "@/test/server";
import { ProtectedDocumentTitle } from "./DocumentTitle"; import { ProtectedDocumentTitle } from "./DocumentTitle";
@@ -62,7 +63,7 @@ describe("document titles", () => {
server.use( server.use(
http.get("*/api/v1/brokerage-accounts", async () => { http.get("*/api/v1/brokerage-accounts", async () => {
await accountsReady; await accountsReady;
return HttpResponse.json([{ id: "a", name: "ИИС" }]); return HttpResponse.json(resource([{ id: "a", name: "ИИС" }]));
}), }),
); );
renderTitle("/accounts/a/income?from=2026-01-01&to=2026-08-31"); renderTitle("/accounts/a/income?from=2026-01-01&to=2026-08-31");
@@ -85,7 +86,7 @@ describe("document titles", () => {
async (kind, id, fallback, name) => { async (kind, id, fallback, name) => {
server.use( server.use(
http.get(`*/api/v1/${kind}/by-ticker/:ticker`, () => http.get(`*/api/v1/${kind}/by-ticker/:ticker`, () =>
HttpResponse.json({ name }), HttpResponse.json(resource({ name })),
), ),
); );
renderTitle(`/${kind}/${id}`); renderTitle(`/${kind}/${id}`);
@@ -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,13 +83,15 @@ const ProtectedDocumentTitle: FC = () => {
return ( return (
<DocumentTitle <DocumentTitle
title={t( title={t(
bonds cards
? "navigation.bonds" ? "navigation.cards"
: stocks : bonds
? "navigation.stocks" ? "navigation.bonds"
: settings : stocks
? "navigation.settings" ? "navigation.stocks"
: "navigation.accounts", : settings
? "navigation.settings"
: "navigation.accounts",
)} )}
/> />
); );
+2 -3
View File
@@ -1,7 +1,6 @@
import type { FC } from "react"; import type { FC } from "react";
import { AppBreadcrumbs } from "@/app/ui"; import { AppBreadcrumbs, AppShell } from "@/app/ui";
import { AppShell } from "@/shared/ui"; import { ProtectedDocumentTitle } from "./DocumentTitle/DocumentTitle";
import { ProtectedDocumentTitle } from "./DocumentTitle";
const ProtectedLayout: FC = () => { const ProtectedLayout: FC = () => {
return ( return (
+9 -1
View File
@@ -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 };
+6 -1
View File
@@ -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>
+2 -2
View File
@@ -1,2 +1,2 @@
export { AppRoutes } from "./AppRoutes"; export { AppRoutes } from "./AppRoutes/AppRoutes";
export { RouteErrorBoundary } from "./RouteErrorBoundary"; export { RouteErrorBoundary } from "./RouteErrorBoundary/RouteErrorBoundary";
+1 -1
View File
@@ -1,11 +1,11 @@
import { MantineProvider } from "@mantine/core"; import { MantineProvider } from "@mantine/core";
import { DatesProvider } from "@mantine/dates"; import { DatesProvider } from "@mantine/dates";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { cssVariablesResolver, theme } from "@wealthledger/ui/theme";
import type { FC } from "react"; import type { FC } from "react";
import { BrowserRouter } from "react-router"; import { BrowserRouter } from "react-router";
import { AppRoutes, RouteErrorBoundary } from "@/app/routes"; import { AppRoutes, RouteErrorBoundary } from "@/app/routes";
import { AuthProvider } from "@/features/auth"; import { AuthProvider } from "@/features/auth";
import { cssVariablesResolver, theme } from "@/shared/theme";
const queryClient = new QueryClient({ const queryClient = new QueryClient({
defaultOptions: { defaultOptions: {
@@ -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 };
+258
View File
@@ -0,0 +1,258 @@
.content {
max-width: 1120px;
margin-inline: auto;
}
.header {
align-items: center;
display: flex;
padding: 0 var(--mantine-spacing-md);
}
.bottomNav {
display: none;
}
.navIcon {
display: inline-flex;
flex-shrink: 0;
}
.portfolioIcon {
color: var(--mantine-color-blue-7);
}
.cardsIcon {
color: var(--mantine-color-grape-7);
& svg {
overflow: visible;
}
}
.rubles {
pointer-events: none;
color: var(--mantine-color-green-8);
stroke: currentColor;
& path {
opacity: 0;
--flight-x: -7px;
--flight-rotation: -20deg;
--flight-delay: 0ms;
}
& path:nth-child(2) {
--flight-x: 0px;
--flight-rotation: 8deg;
--flight-delay: 120ms;
}
& path:nth-child(3) {
--flight-x: 7px;
--flight-rotation: 24deg;
--flight-delay: 240ms;
}
}
.stocksIcon {
color: var(--mantine-color-green-8);
}
.bondsIcon {
color: var(--mantine-color-orange-8);
}
.settingsIcon {
color: var(--mantine-color-gray-7);
}
.portfolioRuble {
stroke: var(--mantine-color-green-8);
opacity: 0;
}
.stockArrow {
transform-origin: 21px 5px;
}
.topSlider,
.bottomSlider {
fill: var(--mantine-color-body);
}
@media (prefers-reduced-motion: no-preference) {
.navLink {
transition: background-color 180ms ease-in-out;
}
.drawStroke,
.couponLines path {
stroke-dasharray: 1;
}
.topSlider {
--slider-offset: 3px;
--slider-delay: 0ms;
}
.bottomSlider {
--slider-offset: -3px;
--slider-delay: 160ms;
}
.couponLines path:nth-child(2) {
--line-delay: 140ms;
}
.couponLines path:nth-child(3) {
--line-delay: 280ms;
}
svg[data-icon-animating] {
.rubles path {
animation: ruble-fly 800ms ease-out var(--flight-delay) both;
}
.portfolioHandle {
animation: handle-lift 1200ms ease-in-out;
}
.portfolioLid {
animation: lid-open 1200ms ease-in-out;
}
.portfolioRuble {
animation: portfolio-ruble-reveal 1200ms ease-in-out;
}
.stockArrow {
animation: arrow-pop 300ms ease-out 400ms both;
}
.couponLines path {
animation: stroke-draw 300ms ease-out var(--line-delay, 0ms) both;
}
.drawStroke {
animation: stroke-draw 450ms ease-out;
}
:is(.topSlider, .bottomSlider) {
animation: slider-slide 650ms ease-in-out var(--slider-delay) both;
}
}
}
@keyframes ruble-fly {
0% {
opacity: 0;
transform: translate(0, 4px);
}
20%,
50% {
opacity: 1;
}
100% {
opacity: 0;
transform: translate(var(--flight-x), -10px) rotate(var(--flight-rotation));
}
}
@keyframes handle-lift {
0%,
100% {
transform: translateY(0);
}
20% {
transform: translateY(-3px);
}
40%,
75% {
transform: translateY(-3px);
}
}
@keyframes lid-open {
0%,
15%,
100% {
transform: translateY(0);
}
40%,
75% {
transform: translateY(-3px);
}
}
@keyframes portfolio-ruble-reveal {
0%,
25%,
100% {
opacity: 0;
transform: translateY(2px);
}
40%,
75% {
opacity: 1;
transform: translateY(0);
}
}
@keyframes arrow-pop {
0% {
opacity: 0;
transform: scale(0.7);
}
60% {
opacity: 1;
transform: scale(1.2);
}
100% {
opacity: 1;
transform: scale(1);
}
}
@keyframes stroke-draw {
0% {
stroke-dashoffset: 1;
}
100% {
stroke-dashoffset: 0;
}
}
@keyframes slider-slide {
0%,
100% {
transform: translateX(0);
}
50% {
transform: translateX(var(--slider-offset));
}
}
@media (max-width: 47.99375em) {
.bottomNav {
background: var(--mantine-color-white);
border-top: 1px solid var(--mantine-color-gray-3);
bottom: 0;
display: flex;
justify-content: space-around;
left: 0;
padding: var(--mantine-spacing-xs) 2px;
gap: 2px;
font-size: 11px;
& a {
min-width: 0;
padding: 8px 2px;
text-align: center;
}
position: fixed;
right: 0;
z-index: 200;
}
.active {
color: var(--mantine-primary-color-filled);
font-weight: 600;
}
.main {
padding-bottom: 5rem;
}
}
@@ -2,6 +2,7 @@ import { AppShell as MantineAppShell, NavLink, Text } from "@mantine/core";
import type { FC, ReactNode } from "react"; import type { FC, ReactNode } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Outlet, NavLink as RouterNavLink, useLocation } from "react-router"; import { Outlet, NavLink as RouterNavLink, useLocation } from "react-router";
import { bindIconAnimation } from "@/shared/lib";
import classes from "./AppShell.module.css"; import classes from "./AppShell.module.css";
type AppShellProps = { type AppShellProps = {
@@ -18,47 +19,75 @@ const AppShell: FC<AppShellProps> = (props) => {
label: t("navigation.accounts"), label: t("navigation.accounts"),
iconClassName: classes.portfolioIcon, iconClassName: classes.portfolioIcon,
icon: ( icon: (
<path d="M8 6V4h8v2M3 10h18M9 10v3h6v-3M5 6h14a2 2 0 0 1 2 2v11H3V8a2 2 0 0 1 2-2Z" /> <>
<path d="M3 10v9h18v-9" />
<path className={classes.portfolioHandle} d="M8 6V4h8v2" />
<path
className={classes.portfolioLid}
d="M3 10V8a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v2H3Zm6 0v3h6v-3"
/>
<path
className={classes.portfolioRuble}
d="M10 18v-7h3a2 2 0 0 1 0 4H9m0 1.5h4"
/>
</>
),
},
{
to: "/cards",
label: t("navigation.cards"),
iconClassName: classes.cardsIcon,
icon: (
<>
<path d="M3 5h18v14H3V5Zm0 4h18M6 15h4" />
<g className={classes.rubles}>
<path d="M10 12V4h3a2 2 0 0 1 0 4H9m0 2h4" />
<path d="M10 12V4h3a2 2 0 0 1 0 4H9m0 2h4" />
<path d="M10 12V4h3a2 2 0 0 1 0 4H9m0 2h4" />
</g>
</>
), ),
}, },
{ {
to: "/stocks", to: "/stocks",
label: t("navigation.stocks"), label: t("navigation.stocks"),
iconClassName: classes.stocksIcon,
icon: ( icon: (
<> <>
<path d="M3 3v18h18" /> <path d="M3 3v18h18" />
<path <path
className={classes.drawStroke} className={classes.drawStroke}
pathLength={1} pathLength={1}
d="M7 14l5-5 4 3 5-7M16 5h5v5" d="M7 14l5-5 4 3 5-7"
/> />
<path className={classes.stockArrow} d="M16 5h5v5" />
</> </>
), ),
}, },
{ {
to: "/bonds", to: "/bonds",
label: t("navigation.bonds"), label: t("navigation.bonds"),
iconClassName: classes.bondsIcon,
icon: ( icon: (
<> <>
<path d="M6 3h12v18l-3-2-3 2-3-2-3 2V3Z" /> <path d="M6 3h12v18l-3-2-3 2-3-2-3 2V3Z" />
<path <g className={classes.couponLines}>
className={classes.drawStroke} <path pathLength={1} d="M9 7h6" />
pathLength={1} <path pathLength={1} d="M9 11h6" />
d="M9 7h6M9 11h6M9 15h3" <path pathLength={1} d="M9 15h3" />
/> </g>
</> </>
), ),
}, },
{ {
to: "/settings", to: "/settings",
label: t("navigation.settings"), label: t("navigation.settings"),
iconClassName: classes.settingsIcon,
icon: ( icon: (
<> <>
<path className={classes.topSlider} d="M4 7h9m4 0h3M13 4v6h4V4h-4Z" /> <path d="M4 7h16M4 17h16" />
<path <path className={classes.topSlider} d="M10 4v6h4V4h-4Z" />
className={classes.bottomSlider} <path className={classes.bottomSlider} d="M10 14v6h4v-6h-4Z" />
d="M4 17h3m4 0h9M7 14v6h4v-6H7Z"
/>
</> </>
), ),
}, },
@@ -86,6 +115,7 @@ const AppShell: FC<AppShellProps> = (props) => {
className={`${classes.navIcon} ${item.iconClassName ?? ""}`} className={`${classes.navIcon} ${item.iconClassName ?? ""}`}
> >
<svg <svg
ref={bindIconAnimation}
width={20} width={20}
height={20} height={20}
viewBox="0 0 24 24" viewBox="0 0 24 24"
+2 -1
View File
@@ -1 +1,2 @@
export { AppBreadcrumbs } from "./AppBreadcrumbs"; export { AppBreadcrumbs } from "./AppBreadcrumbs/AppBreadcrumbs";
export { AppShell } from "./AppShell/AppShell";
+424
View File
@@ -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);
});
});
+111
View File
@@ -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 };
+194
View File
@@ -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);
});

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