20 Commits
Author SHA1 Message Date
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
130 changed files with 10925 additions and 4104 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, domain literals, magic values | [Код](conventions/frontend-ui.md#код-и-components) + [Domain literals](conventions/frontend-ui.md#domain-literals-and-magic-values) |
| query/mutation, shared/api, server state/cache, generated types, Bearer/refresh | [Data](conventions/frontend-data.md) |
| Тесты или behavior с testing risk | [Testing](conventions/frontend-testing.md) |
| Новый abstraction/dependency, refactor или неоднозначный scope | [Общий выбор реализации](../../AGENTS.md) |
| Request/response field, route/status/error shape, OpenAPI snapshot/generated type | [Источник HTTP-контракта](../../docs/architecture/http-api.md#источник-контракта) |
| Login/refresh/logout, token/cookie, auth ownership | Data + [security](../../backend/.ai/conventions/security-auth.md) + Testing |
| 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-owned contract → provided snapshot → [Источник HTTP-контракта](../../docs/architecture/http-api.md#источник-контракта) |
| Error codes/validation/error envelope | [docs: HTTP API](../../docs/architecture/http-api.md) |
| Auth/session, token storage и refresh | [Аутентификация](../../docs/domains/authentication/overview.md), [подключение брокера](../../docs/integrations/tbank.md) |
| Значение Money, cached snapshot, account/position/income | [docs: Domain](../../docs/glossary.md) |
| Mantine/theme/tokens и существующие stories | [Дизайн-система](../../docs/design/overview.md), [UI-каталог](../README.md#ui-каталог-storybook) |
| As-built behavior нужной feature | [docs: Features](../../docs/README.md#предметные-области) |
| Существующие 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.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.
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/design/overview.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 не доказывает
правильный выбор слоя.
-60
View File
@@ -1,60 +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-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 вручную не исправляется. Frontend-команды не читают соседний
backend checkout и не проверяют backend runtime OpenAPI; изменение wire
shape/status/route сохраняет
[границу HTTP-контракта](../../../docs/architecture/http-api.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/domains/authentication/overview.md).
Успешная connection mutation коммитит подтверждённый status и сбрасывает financial
GET subtree; ошибка mutation не меняет generation/cache. Это отдельная граница
от обычного фонового refetch: [connection policy](../../../docs/integrations/tbank.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 и проверки наблюдаемого
HTTP-поведения на стороне backend.
+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.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,5 +1,9 @@
# Frontend testing # Frontend testing
Перед нетривиальными тестами сформулируй
[общий Test Intent](engineering.md#test-intent); отдельный документ
не требуется. Trivial low-risk изменения обходятся без него.
## Выбор проверки ## Выбор проверки
Читай при изменении тестов, доступа, денежных расчётов, восстановления Читай при изменении тестов, доступа, денежных расчётов, восстановления
@@ -11,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).
@@ -30,7 +35,7 @@ MSW запускается только Vitest setup в `src/test/`, без brow
экземпляр и 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 запросов и мутаций для предсказуемого исхода; Тестовый клиент отключает retries запросов и мутаций для предсказуемого исхода;
это не меняет [политику обновления приложения](../../../docs/adr/007-react-query-fetch-policy.md). это не меняет [политику обновления приложения](data.md#auth-и-invalidation).
## Важные случаи ## Важные случаи
+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).
@@ -11,21 +11,31 @@ Mantine component и общую тему. Для выпадающего выбо
ограничения JSDOM решай в test setup, сохраняя production UI. ограничения JSDOM решай в test setup, сохраняя production UI.
Семантический HTML для структуры страницы остаётся уместным. Семантический HTML для структуры страницы остаётся уместным.
Icons ищи у существующего owner (например,
[BankOperationIcon](../../src/entities/bank-card/ui/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 нужен для проектной ответственности, а не ради нового имени Wrapper нужен для проектной ответственности, а не ради нового имени
для Button. Локальный CSS module принадлежит component; общий token вводи для для Button. Локальный CSS module принадлежит component; общий token вводи для
реально общей роли через [design system](../../../docs/design/overview.md). реально общей роли в [визуальной основе](#визуальная-основа).
| Состояние | Владелец | | Состояние | Владелец |
| --- | --- | | --- | --- |
| Ответ сервера / query lifecycle | TanStack Query, [data rules](frontend-data.md) | | Ответ сервера / query lifecycle | TanStack Query, [data rules](data.md) |
| Ввод и ошибки формы | React Hook Form + Zod, container/VM | | Ввод и ошибки формы | React Hook Form + Zod, container/VM |
| Параметр навигации, который должен переживать переход/ссылку | Router/URL | | Параметр навигации, который должен переживать переход/ссылку | Router/URL |
| Локальное открытие, focus, rendering fallback | React UI state | | Локальное открытие, focus, rendering fallback | React UI state |
| Значение, вычисляемое из уже доступных inputs | Вычисление при render/в VM, без копирования через effect в state | | Значение, вычисляемое из уже доступных inputs | Вычисление при render/в VM, без копирования через effect в state |
Effect нужен для синхронизации с внешней системой; действие пользователя State, который нужен в ссылке, back/forward или после navigation, хранится в URL
обрабатывай в handler. Не добавляй store, memoization или abstraction без текущей через existing router search params. Остальной UI state остаётся у ближайшего
потребности. Inspect ближайший component до создания нового pattern. owner. Shared client store нужен только нескольким consumers без подходящего
общего owner; наличие двух компонентов само по себе его не требует.
Hooks/effects/derived state — по [TypeScript/React](typescript-react.md#hooks-и-derived-state).
## Container, VM и view ## Container, VM и view
@@ -76,71 +86,12 @@ Button loading при mutation и компактный cached-snapshot progress
## Код и components ## Код и components
Style/type automation задают configs. Используй `import type`; `enum` и Types, props, hooks и memoization — в [TypeScript/React](typescript-react.md).
`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.
## Domain literals and magic values ## Domain literals and magic values
Finite business vocabulary must be modeled explicitly; incidental implementation Правило и generated API exception — в
literals stay inline. Это относится к error codes, statuses, operation/account/ [TypeScript/React](typescript-react.md#domain-literals-and-magic-values).
instrument/transaction types, permissions, roles, feature states и бизнес-режимам.
Перед новым определением найди existing owner/type/value. В branching и comparisons
используй символическое значение владельца; не повторяй raw domain literals.
Храни словарь у domain/module/entity с соблюдением границ слоёв, без глобальной
свалки `constants.ts`. Сохраняй принятый pattern; для нового project-owned словаря
без подходящего аналога используй `as const` с derived union:
```ts
const BankErrorCode = {
InvalidDate: "BANK_INVALID_DATE",
ImmutableOperation: "BANK_IMMUTABLE_OPERATION",
} as const;
type BankErrorCode = (typeof BankErrorCode)[keyof typeof BankErrorCode];
// Вместо code === "BANK_INVALID_DATE":
if (code === BankErrorCode.InvalidDate) { /* existing handling */ }
```
Значимые numeric policies (timeout, retry, page size, threshold, coefficient)
называй по смыслу и единицам: `REQUEST_TIMEOUT_MS`, `CACHE_TTL_SECONDS`,
`MAX_RETRY_COUNT`, `PAGE_SIZE`. Оставляй inline UI labels в принятом месте,
log messages, индексы, `index + 1`, `Math.max(value, 0)`, `page ?? 1`,
`percentage * 100` и очевидные локальные детали без semantic benefit.
При неясном owner/смысле оставь значение и укажи ограничение в review.
Не мигрируй корректные existing enum/union styles массово. Не добавляй ради
правила factories, registries, schemas, loaders, abstraction layers, dependencies,
custom lint/AST rules, generation/validation scripts или тесты существования
констант. Semantic review проверяет ownership, единое написание и неизменность
wire values; обычные behavior tests проверяют поведение.
Backend API vocabulary бери из generated OpenAPI types/client, runtime values —
когда генератор их предоставляет. Не создавай ручную копию backend enum/object.
Текущий `schema.d.ts` предоставляет только types: используй indexed-access type
из `paths`; typed literals в запросах/сравнениях допустимы при отсутствии
runtime values. `ProblemDetailsDto.code` сейчас `string`: не выдумывай закрытый
frontend error enum. Развитие API source — отдельное contract-решение.
Frontend `enum` по-прежнему запрещён локальным TS/style profile.
`noMagicNumbers` включён как error в Biome. Fixtures, tests и stories исключены
из этого правила; остальные проверки для них сохраняются. Используй имена
политик/единиц и existing values. Точечное подавление допустимо для очевидного
incidental значения с объяснением, например перевода доли в проценты; не подавляй
скрытые бизнес-лимиты. Semantic magic strings проверяются conventions/review: в
установленном Biome нет такого встроенного правила, новый инструмент не добавляем.
## Строки и валидация ## Строки и валидация
@@ -153,6 +104,35 @@ incidental значения с объяснением, например пере
## Проверка ## Проверка
Type/style: `npm run typecheck`, `npm run lint`. Для risk behavior/изменения тестов Type/style: `npm run typecheck`, `npm run lint`. Для risk behavior/изменения тестов
используй [Testing](frontend-testing.md). UI: keyboard, narrow viewport, используй [Testing](testing.md). UI: keyboard, narrow viewport,
loading/error/empty/loaded и recovery по применимости. [Storybook](../../README.md#ui-каталог-storybook) loading/error/empty/loaded и recovery по применимости. [Storybook](storybook.md) задаёт выбор stories и изоляцию каталога;
уже установлен; используй его как reference, но сверяй UI с задачей отдельно от build. сверяй 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
+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"
+10
View File
@@ -11,6 +11,8 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: https://github.com/actions/checkout@v4 - uses: https://github.com/actions/checkout@v4
with:
fetch-depth: 0
- name: Record checked revision - name: Record checked revision
run: git rev-parse HEAD run: git rev-parse HEAD
- uses: https://github.com/actions/setup-node@v4 - uses: https://github.com/actions/setup-node@v4
@@ -24,3 +26,11 @@ jobs:
env: env:
# OXC raw transfer allocates a ~6 GiB buffer; use the standard parser in CI. # OXC raw transfer allocates a ~6 GiB buffer; use the standard parser in CI.
KNIP_DISABLE_RAW_TRANSFER: '1' 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 -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 },
+2 -1
View File
@@ -1,12 +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 { 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,
+32 -31
View File
@@ -1,36 +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 используют предоставленный OpenAPI snapshot; frontend ## Источники
локально проверяет только соответствие generated types этому snapshot:
[Источник HTTP-контракта](../docs/architecture/http-api.md#источник-контракта).
Generated types редактируются через их source; T-Bank доступен только через backend.
Frontend dependencies используют exact versions. Pre-commit запускает staged
formatting и FSD checks; сообщения commits — Conventional Commits.
Если у задачи есть связанная issue этого репозитория, добавляй её номер
в конец заголовка: `ci: run full frontend verification #1`.
Без связанной issue номер необязателен: `chore(deps): update non-major dependencies`.
Формат Conventional Commits проверяет `commitlint.config.cjs`.
Code/style checks автоматические только в scope конфигурации. i18n, props, | Вопрос | Локальный источник |
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; неясное ожидание уточни до изменения |
Работа — в отдельной ветке от `develop`, затем PR в `develop`; в `main` напрямую | Versions/scripts/check scope | Manifest/lockfile, Biome/TypeScript/dependency configs |
не пушить. Release/hotfix и синхронизация веток — по [root README](../README.md#релизы-и-ветки).
Commits и заголовки PR — Conventional Commits; для спецификаций допустим `spec:`.
Перед подготовкой релиза прочитай root README; версии вручную не повышать.
+41
View File
@@ -1,5 +1,46 @@
# Changelog # Changelog
## [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) ## 0.1.0 (2026-09-14)
### Features ### Features
+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
+162 -15
View File
@@ -23,6 +23,54 @@ staged diff с полной редакцией секретов, затем за
Находка или отсутствие Gitleaks блокирует commit. Находка или отсутствие Gitleaks блокирует commit.
Проверка этого поведения: `node --test scripts/test-pre-commit.mjs`. Проверка этого поведения: `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
@@ -49,32 +97,131 @@ TypeScript остаётся на 5.9.3: `openapi-typescript@7.13.0` требуе
обновите `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 ## UI-каталог Storybook
После `nvm use --silent` выполните `npm run dev:catalog`; статическая сборка — После `nvm use --silent` выполните `npm run dev:catalog`; статическая сборка —
`npm run build:catalog`. Каталог использует общую тему приложения, вымышленные `npm run build:catalog`. Каталог использует общую тему приложения, вымышленные
данные и локальные действия без application API. Примеры не доказывают данные и локальные действия без application API. Примеры не доказывают
восстановление реального запроса. Визуальные роли описаны в восстановление реального запроса. Визуальные роли описаны в
[дизайн-системе](../docs/design/overview.md). [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](#ui-каталог-storybook) - [UI-каталог Storybook](#ui-каталог-storybook)
- [Обзор поставленной системы](../docs/overview.md)
- [Карта проектных фактов](../docs/README.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 — по явному запросу.
Версии и ветки: [процесс релиза](../README.md#релизы-и-ветки).
Knip исключает `conventional-changelog-conventionalcommits`: release-it загружает Knip исключает `conventional-changelog-conventionalcommits`: release-it загружает
preset по имени из `.release-it.json`. Версия preset закреплена напрямую. 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 остаются в приложении.
+3 -1
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",
@@ -38,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": {
+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 -2
View File
@@ -1,4 +1,17 @@
{ {
"project": ["src/**/*.{ts,tsx}", "!src/shared/api/generated/**"], "ignoreDependencies": ["conventional-changelog-conventionalcommits"],
"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}"]
}
}
} }
+4632 -2
View File
File diff suppressed because it is too large Load Diff
+23 -15
View File
@@ -1,33 +1,34 @@
{ {
"name": "wealth-ledger-frontend", "name": "wealth-ledger-frontend",
"private": true, "private": true,
"version": "0.1.0", "version": "0.3.0",
"type": "module", "type": "module",
"engines": { "engines": {
"node": "24.21.0" "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:preview": "release-it --dry-run --ci",
"release:prepare": "release-it --ci", "release:prepare": "release-it --ci",
"commitlint": "commitlint" "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"
@@ -39,6 +40,9 @@
"@mantine/dates": "9.6.1", "@mantine/dates": "9.6.1",
"@mantine/hooks": "9.6.1", "@mantine/hooks": "9.6.1",
"@tanstack/react-query": "5.102.8", "@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.4.2", "i18next": "26.4.2",
"motion": "13.2.0", "motion": "13.2.0",
@@ -82,10 +86,14 @@
"storybook": "10.6.0", "storybook": "10.6.0",
"typescript": "5.9.3", "typescript": "5.9.3",
"vite": "8.3.0", "vite": "8.3.0",
"vite-plugin-pwa": "1.3.0",
"vitest": "5.0.0" "vitest": "5.0.0"
}, },
"allowScripts": { "allowScripts": {
"esbuild@0.28.2": true, "esbuild@0.28.2": true,
"fsevents@2.3.3": 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"
}
}
@@ -4,8 +4,8 @@
gap: var(--mantine-spacing-sm); gap: var(--mantine-spacing-sm);
align-items: center; align-items: center;
padding: var(--mantine-spacing-md); padding: var(--mantine-spacing-md);
border-color: var(--mantine-color-gray-3); border-color: var(--wl-color-border);
background: var(--mantine-color-gray-0); background: var(--wl-color-subtle);
} }
.identity, .identity,
@@ -19,15 +19,15 @@
} }
.positive { .positive {
color: var(--mantine-color-green-6); color: var(--wl-color-positive);
} }
.negative { .negative {
color: var(--mantine-color-red-6); color: var(--wl-color-negative);
} }
.neutral { .neutral {
color: var(--mantine-color-dimmed); color: var(--mantine-color-gray-7);
} }
@media (max-width: 36em) { @media (max-width: 36em) {
+37
View File
@@ -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 = {};
+35
View File
@@ -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();
});
});
@@ -25,7 +25,7 @@ const EntryCard: FC<EntryCardProps> = (props) => {
style={ style={
props.color props.color
? { ? {
background: `color-mix(in srgb, var(--mantine-color-${props.color}-0) 45%, white)`, background: `color-mix(in srgb, var(--mantine-color-${props.color}-0) 45%, var(--wl-color-surface))`,
} }
: undefined : undefined
} }
@@ -1,4 +1,3 @@
export { AppShell } from "./AppShell";
export { EntryCard } from "./EntryCard"; export { EntryCard } from "./EntryCard";
export { LoadingSkeleton } from "./LoadingSkeleton"; export { LoadingSkeleton } from "./LoadingSkeleton";
export { StateView } from "./StateView"; export { StateView } from "./StateView";
@@ -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,3 +1,4 @@
import "./styles.css";
import { import {
type CSSVariablesResolver, type CSSVariablesResolver,
colorsTuple, colorsTuple,
@@ -8,7 +9,7 @@ import {
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;
+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

+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 });
}
});
+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
+1 -2
View File
@@ -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";
+1 -2
View File
@@ -1,6 +1,5 @@
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"; import { ProtectedDocumentTitle } from "./DocumentTitle";
const ProtectedLayout: FC = () => { const ProtectedLayout: FC = () => {
+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: {
@@ -2,7 +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 "../lib"; import { bindIconAnimation } from "@/shared/lib";
import classes from "./AppShell.module.css"; import classes from "./AppShell.module.css";
type AppShellProps = { type AppShellProps = {
+1
View File
@@ -1 +1,2 @@
export { AppBreadcrumbs } from "./AppBreadcrumbs"; export { AppBreadcrumbs } from "./AppBreadcrumbs";
export { AppShell } from "./AppShell";
+1
View File
@@ -18,6 +18,7 @@ export {
moneyCents, moneyCents,
positiveMoneySchema, positiveMoneySchema,
} from "./model/form-validation"; } from "./model/form-validation";
export { bankOperationKinds } from "./model/operation-kinds";
export { bankPeriod } from "./model/period"; export { bankPeriod } from "./model/period";
export { BankCardFace } from "./ui/BankCardFace"; export { BankCardFace } from "./ui/BankCardFace";
export { BankCardForm } from "./ui/BankCardForm"; export { BankCardForm } from "./ui/BankCardForm";
@@ -0,0 +1,10 @@
import type { BankOperation } from "../api/queries";
const bankOperationKinds = [
"expense",
"topup",
"transfer",
"refund",
] as const satisfies readonly BankOperation["kind"][];
export { bankOperationKinds };
@@ -1,6 +1,6 @@
import { Stack } from "@mantine/core"; import { Stack } from "@mantine/core";
import type { Meta, StoryObj } from "@storybook/react-vite"; import type { Meta, StoryObj } from "@storybook/react-vite";
import { EntryCard } from "@/shared/ui"; import { EntryCard } from "@wealthledger/ui";
import { BankOperationIcon } from "./BankOperationIcon"; import { BankOperationIcon } from "./BankOperationIcon";
const meta = { const meta = {
@@ -1,8 +1,8 @@
import { Button, Group, Skeleton, Stack, Text, Title } from "@mantine/core"; import { Button, Group, Skeleton, Stack, Text, Title } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { CSSProperties, FC } from "react"; import type { CSSProperties, FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { formatMoney } from "@/shared/lib"; import { formatMoney } from "@/shared/lib";
import { LoadingSkeleton } from "@/shared/ui";
import type { BankSummary } from "../api/queries"; import type { BankSummary } from "../api/queries";
import { BankOperationIcon } from "./BankOperationIcon"; import { BankOperationIcon } from "./BankOperationIcon";
import classes from "./BankSummary.module.css"; import classes from "./BankSummary.module.css";
@@ -1,4 +1,5 @@
import { Anchor, Group, Text } from "@mantine/core"; import { Anchor, Group, Text } from "@mantine/core";
import { EntryCard } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Link } from "react-router"; import { Link } from "react-router";
@@ -8,7 +9,6 @@ import {
formatSnapshotTime, formatSnapshotTime,
instrumentLogoUrl, instrumentLogoUrl,
} from "@/shared/lib"; } from "@/shared/lib";
import { EntryCard } from "@/shared/ui";
import type { BrokerageOperation } from "../api/useBrokerageOperations"; import type { BrokerageOperation } from "../api/useBrokerageOperations";
import { operationLabelKey, paymentPresentation } from "../model/display"; import { operationLabelKey, paymentPresentation } from "../model/display";
@@ -1,7 +1,7 @@
import { EntryCard } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { formatDate, formatMoney, instrumentLogoUrl } from "@/shared/lib"; import { formatDate, formatMoney, instrumentLogoUrl } from "@/shared/lib";
import { EntryCard } from "@/shared/ui";
import type { BrokerageEvent } from "../api/useBrokerageEvents"; import type { BrokerageEvent } from "../api/useBrokerageEvents";
type BrokerageEventCardProps = { event: BrokerageEvent }; type BrokerageEventCardProps = { event: BrokerageEvent };
@@ -1,8 +1,8 @@
import { Alert, Button, Skeleton, Stack, Text } from "@mantine/core"; import { Alert, Button, Skeleton, Stack, Text } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Link } from "react-router"; import { Link } from "react-router";
import { LoadingSkeleton } from "@/shared/ui";
import type { BrokerageEvent } from "../api/useBrokerageEvents"; import type { BrokerageEvent } from "../api/useBrokerageEvents";
import { BrokerageEventCard } from "./BrokerageEventCard"; import { BrokerageEventCard } from "./BrokerageEventCard";
+161 -1
View File
@@ -3,7 +3,7 @@ import { act, renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw"; import { HttpResponse, http } from "msw";
import type { FC, PropsWithChildren } from "react"; import type { FC, PropsWithChildren } from "react";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { apiClient, apiQueryClient } from "@/shared/api"; import { apiClient, apiQueryClient, useAuthenticatedQuery } from "@/shared/api";
import { createTestQueryClient } from "@/test/query"; import { createTestQueryClient } from "@/test/query";
import { server } from "@/test/server"; import { server } from "@/test/server";
import { AuthProvider, useAuth } from "./auth"; import { AuthProvider, useAuth } from "./auth";
@@ -167,4 +167,164 @@ describe("AuthProvider", () => {
expect(queryClient.getQueryData(portfolioKey)).toBeUndefined(); expect(queryClient.getQueryData(portfolioKey)).toBeUndefined();
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined(); expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
}); });
it.each([
[false, false],
[true, false],
[false, true],
[true, true],
])(
"serializes late refresh (failure=%s, login=%s)",
async (failure, loginAfterLogout) => {
let release!: () => void;
const pending = new Promise<void>((resolve) => {
release = resolve;
});
let calls = 0;
const order: string[] = [];
server.use(
http.post("*/api/v1/auth/refresh", async () => {
if (++calls > 1) {
order.push("refresh-start");
await pending;
order.push("refresh-cookie");
}
return failure && calls > 1
? HttpResponse.error()
: HttpResponse.json({
accessToken: "a",
user: { id: "a", email: "a@example.com" },
});
}),
http.post("*/api/v1/auth/logout", () => {
order.push("logout-cookie");
return new HttpResponse(null, { status: 204 });
}),
http.post("*/api/v1/auth/login", () => {
order.push("login-cookie");
return HttpResponse.json({
accessToken: "b",
user: { id: "b", email: "b@example.com" },
});
}),
http.get("*/api/v1/brokerage-accounts", () =>
HttpResponse.json({ code: "UNAUTHORIZED" }, { status: 401 }),
),
);
const queryClient = createTestQueryClient();
const wrapper: FC<PropsWithChildren> = ({ children }) => (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(result.current.ready).toBe(true));
const oldRequest = apiClient
.GET("/api/v1/brokerage-accounts")
.catch(() => null);
await waitFor(() => expect(order).toContain("refresh-start"));
let logout!: Promise<void>;
act(() => {
logout = result.current.logout();
});
await waitFor(() => expect(result.current.user).toBeNull());
let login!: Promise<void>;
act(() => {
login = loginAfterLogout
? result.current.login("b@example.com", "password")
: Promise.resolve();
});
await act(async () => {
release();
await Promise.all([oldRequest, logout, login]);
});
expect(result.current.user?.id ?? null).toBe(
loginAfterLogout ? "b" : null,
);
expect(order).toEqual([
"refresh-start",
"refresh-cookie",
"logout-cookie",
...(loginAfterLogout ? ["login-cookie"] : []),
]);
},
);
it("preserves same-user cache and removes inactive and pending data on refresh identity change", async () => {
let identity = "a";
server.use(
http.post("*/api/v1/auth/refresh", () =>
HttpResponse.json({
accessToken: identity,
user: { id: identity, email: `${identity}@example.com` },
}),
),
);
const queryClient = createTestQueryClient();
const wrapper: FC<PropsWithChildren> = ({ children }) => (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(result.current.ready).toBe(true));
queryClient.setQueryData(bankCardsKey, [{ id: "a-card" }]);
await act(() => result.current.refresh());
expect(queryClient.getQueryData(bankCardsKey)).toEqual([{ id: "a-card" }]);
let release!: (value: string) => void;
const pending = queryClient
.fetchQuery({
queryKey: ["pending-finance"],
queryFn: () =>
new Promise<string>((resolve) => {
release = resolve;
}),
})
.catch(() => null);
identity = "b";
await act(() => result.current.refresh());
release("a-data");
await pending;
expect(result.current.user?.id).toBe("b");
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
expect(queryClient.getQueryData(["pending-finance"])).toBeUndefined();
});
it("replaces an observed financial query when refresh changes identity", async () => {
let identity = "a";
server.use(
http.post("*/api/v1/auth/refresh", () =>
HttpResponse.json({
accessToken: identity,
user: { id: identity, email: `${identity}@example.com` },
}),
),
http.get("*/api/v1/bank-cards", () =>
HttpResponse.json([{ id: `${identity}-card` }]),
),
);
const queryClient = createTestQueryClient();
const wrapper: FC<PropsWithChildren> = (props) => (
<QueryClientProvider client={queryClient}>
<AuthProvider>{props.children}</AuthProvider>
</QueryClientProvider>
);
const { result } = renderHook(
() => ({
auth: useAuth(),
cards: useAuthenticatedQuery(
apiQueryClient.queryOptions("get", "/api/v1/bank-cards", {
params: { query: { includeArchived: "false" } },
}),
),
}),
{ wrapper },
);
await waitFor(() =>
expect(result.current.cards.data?.[0].id).toBe("a-card"),
);
identity = "b";
await act(() => result.current.auth.refresh());
await waitFor(() =>
expect(result.current.cards.data?.[0].id).toBe("b-card"),
);
});
}); });
+57 -32
View File
@@ -47,49 +47,70 @@ const AuthProvider: FC<PropsWithChildren> = (props) => {
const accessTokenRef = useRef<string | null>(null); const accessTokenRef = useRef<string | null>(null);
const [ready, setReady] = useState(false); const [ready, setReady] = useState(false);
const generation = useRef(0);
const userRef = useRef<User | null>(null);
const authQueue = useRef<Promise<unknown>>(Promise.resolve());
const refreshPromise = useRef<Promise<boolean> | null>(null); const refreshPromise = useRef<Promise<boolean> | null>(null);
const applyAuthentication = useCallback((authentication: Authentication) => { // Cookie-writing requests share ordering, including across tabs with Web Locks.
setUser(authentication.user); const serialize = useCallback(<T,>(run: () => Promise<T>): Promise<T> => {
setAccessToken(authentication.accessToken); const next = authQueue.current.then(async () =>
accessTokenRef.current = authentication.accessToken; "locks" in navigator
? navigator.locks.request("wealth-ledger-refresh", run)
: run(),
);
authQueue.current = next.catch(() => undefined);
return next;
}, []); }, []);
const applyAuthentication = useCallback(
(authentication: Authentication) => {
const changedIdentity =
userRef.current && userRef.current.id !== authentication.user.id;
accessTokenRef.current = authentication.accessToken;
if (changedIdentity) {
generation.current += 1;
queryClient.removeQueries({ type: "inactive" });
queryClient.getMutationCache().clear();
void queryClient.resetQueries();
}
userRef.current = authentication.user;
setUser(authentication.user);
setAccessToken(authentication.accessToken);
},
[queryClient],
);
const clearSession = useCallback(() => { const clearSession = useCallback(() => {
generation.current += 1;
userRef.current = null;
setUser(null); setUser(null);
setAccessToken(null); setAccessToken(null);
accessTokenRef.current = null; accessTokenRef.current = null;
queryClient.clear(); queryClient.clear();
}, [queryClient]); }, [queryClient]);
const refresh = useCallback(async (): Promise<boolean> => { const refresh = useCallback((): Promise<boolean> => {
if (refreshPromise.current) return refreshPromise.current; if (refreshPromise.current) return refreshPromise.current;
refreshPromise.current = (async () => { const started = generation.current;
const run = async () => { const pending = serialize(async () => {
try { if (started !== generation.current) return false;
const { data } = await apiClient.POST("/api/v1/auth/refresh"); try {
if (!data) { const { data } = await apiClient.POST("/api/v1/auth/refresh");
clearSession(); if (started !== generation.current) return false;
return false; if (!data) {
}
applyAuthentication(data as Authentication);
return true;
} catch {
clearSession(); clearSession();
return false; return false;
} }
}; applyAuthentication(data);
try { return true;
return "locks" in navigator
? navigator.locks.request("wealth-ledger-refresh", run)
: run();
} catch { } catch {
clearSession(); if (started === generation.current) clearSession();
return false; return false;
} }
})().finally(() => { }).finally(() => {
refreshPromise.current = null; if (refreshPromise.current === pending) refreshPromise.current = null;
}); });
return refreshPromise.current; refreshPromise.current = pending;
}, [applyAuthentication, clearSession]); return pending;
}, [applyAuthentication, clearSession, serialize]);
useEffect(() => { useEffect(() => {
void refresh().finally(() => setReady(true)); void refresh().finally(() => setReady(true));
@@ -100,21 +121,25 @@ const AuthProvider: FC<PropsWithChildren> = (props) => {
email: string, email: string,
password: string, password: string,
) { ) {
const authentication = await request(path, email, password); clearSession();
applyAuthentication(authentication); const started = generation.current;
await serialize(async () => {
const authentication = await request(path, email, password);
if (started === generation.current) applyAuthentication(authentication);
});
} }
async function logout() { async function logout() {
try { clearSession();
await serialize(async () => {
await apiClient.POST("/api/v1/auth/logout"); await apiClient.POST("/api/v1/auth/logout");
} finally { });
clearSession();
}
} }
useEffect(() => { useEffect(() => {
configureAuthClient({ configureAuthClient({
accessToken: () => accessTokenRef.current, accessToken: () => accessTokenRef.current,
generation: () => generation.current,
refresh, refresh,
clear: clearSession, clear: clearSession,
}); });
@@ -8,9 +8,9 @@ import {
Text, Text,
Title, Title,
} from "@mantine/core"; } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC, PropsWithChildren, ReactNode } from "react"; import type { FC, PropsWithChildren, ReactNode } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { LoadingSkeleton } from "@/shared/ui";
import type { SectionState } from "../model/section"; import type { SectionState } from "../model/section";
import classes from "./InstrumentDetails.module.css"; import classes from "./InstrumentDetails.module.css";
@@ -1,7 +1,7 @@
import { Alert, Button, Skeleton } from "@mantine/core"; import { Alert, Button, Skeleton } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { LoadingSkeleton } from "@/shared/ui";
type TbankConnectionErrorProps = { type TbankConnectionErrorProps = {
retry: () => void; retry: () => void;
+1
View File
@@ -3,6 +3,7 @@ import { createRoot } from "react-dom/client";
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 "./shared/i18n"; import "./shared/i18n";
import { App } from "./app"; import { App } from "./app";
@@ -1,6 +1,6 @@
import { StateView } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { StateView } from "@/shared/ui";
const AccountEventsPageEmpty: FC = () => { const AccountEventsPageEmpty: FC = () => {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -1,7 +1,7 @@
import { Button } from "@mantine/core"; import { Button } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { StateView } from "@/shared/ui";
type AccountEventsPageErrorProps = { retry: () => void }; type AccountEventsPageErrorProps = { retry: () => void };
@@ -1,7 +1,7 @@
import { Group, Skeleton } from "@mantine/core"; import { Group, Skeleton } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { LoadingSkeleton } from "@/shared/ui";
const skeletonRowIds = ["first", "second", "third", "fourth"]; const skeletonRowIds = ["first", "second", "third", "fourth"];
+46
View File
@@ -0,0 +1,46 @@
type IncomePeriod = { from: string; to: string };
type IncomeForm = IncomePeriod;
const datePattern = /^\d{4}-\d{2}-\d{2}$/;
function formatDraftDate(value: string): string {
const [year, month, day] = value.split("-");
return `${day}.${month}.${year}`;
}
function parseDraftDate(value: string): string | null {
if (!/^\d{2}\.\d{2}\.\d{4}$/.test(value)) return null;
const [day, month, year] = value.split(".");
const date = `${year}-${month}-${day}`;
return isDate(date) ? date : null;
}
function isDate(value: string): boolean {
if (!datePattern.test(value)) return false;
const parsed = new Date(`${value}T00:00:00Z`);
return (
Number.isFinite(parsed.valueOf()) &&
parsed.toISOString().slice(0, 10) === value
);
}
function moscowDate(value: Date): string {
const parts = new Intl.DateTimeFormat("en-CA", {
timeZone: "Europe/Moscow",
year: "numeric",
month: "2-digit",
day: "2-digit",
}).formatToParts(value);
const part = (type: string) =>
parts.find((item) => item.type === type)?.value;
return `${part("year")}-${part("month")}-${part("day")}`;
}
export {
formatDraftDate,
type IncomeForm,
type IncomePeriod,
isDate,
moscowDate,
parseDraftDate,
};
@@ -23,8 +23,9 @@ import type { IncomeAnalytics } from "@/entities/income";
import { configureAuthClient } from "@/shared/api"; import { configureAuthClient } from "@/shared/api";
import { createQueryWrapper } from "@/test/query"; import { createQueryWrapper } from "@/test/query";
import { server } from "@/test/server"; import { server } from "@/test/server";
import { isDate } from "../model/period";
import { AccountIncomePage } from "./AccountIncomePage"; import { AccountIncomePage } from "./AccountIncomePage";
import { isDate, toIncomeDisplayModel } from "./AccountIncomePage.vm"; import { toIncomeDisplayModel } from "./AccountIncomePage.vm";
import { IncomePayments } from "./components/IncomePayments.view"; import { IncomePayments } from "./components/IncomePayments.view";
const analytics = { const analytics = {
@@ -6,12 +6,17 @@ import { z } from "zod";
import { type IncomeAnalytics, useIncomeAnalytics } from "@/entities/income"; import { type IncomeAnalytics, useIncomeAnalytics } from "@/entities/income";
import { validationMessage } from "@/shared/i18n"; import { validationMessage } from "@/shared/i18n";
import { formatDate } from "@/shared/lib"; import { formatDate } from "@/shared/lib";
import {
formatDraftDate,
type IncomeForm,
type IncomePeriod,
isDate,
moscowDate,
parseDraftDate,
} from "../model/period";
const ISO_MONTH_LENGTH = 7; const ISO_MONTH_LENGTH = 7;
type IncomePeriod = { from: string; to: string };
type IncomeForm = IncomePeriod;
type IncomeDisplayModel = { type IncomeDisplayModel = {
entries: { key: string; operation: IncomeAnalytics["entries"][number] }[]; entries: { key: string; operation: IncomeAnalytics["entries"][number] }[];
comparison: { comparison: {
@@ -41,7 +46,6 @@ type AccountIncomePageViewModel =
onSubmit: (values: IncomeForm) => void; onSubmit: (values: IncomeForm) => void;
}; };
const datePattern = /^\d{4}-\d{2}-\d{2}$/;
const draftDate = z const draftDate = z
.string() .string()
.refine((value) => parseDraftDate(value) !== null, { .refine((value) => parseDraftDate(value) !== null, {
@@ -129,18 +133,6 @@ const useAccountIncomePageViewModel = (
}; };
}; };
function formatDraftDate(value: string): string {
const [year, month, day] = value.split("-");
return `${day}.${month}.${year}`;
}
function parseDraftDate(value: string): string | null {
if (!/^\d{2}\.\d{2}\.\d{4}$/.test(value)) return null;
const [day, month, year] = value.split(".");
const date = `${year}-${month}-${day}`;
return isDate(date) ? date : null;
}
function draftPeriod(period: IncomePeriod): IncomeForm { function draftPeriod(period: IncomePeriod): IncomeForm {
return { from: formatDraftDate(period.from), to: formatDraftDate(period.to) }; return { from: formatDraftDate(period.from), to: formatDraftDate(period.to) };
} }
@@ -163,15 +155,6 @@ function validPeriod(period: IncomePeriod): period is IncomePeriod {
); );
} }
function isDate(value: string): boolean {
if (!datePattern.test(value)) return false;
const parsed = new Date(`${value}T00:00:00Z`);
return (
Number.isFinite(parsed.valueOf()) &&
parsed.toISOString().slice(0, 10) === value
);
}
function toIncomeDisplayModel( function toIncomeDisplayModel(
analytics: IncomeAnalytics, analytics: IncomeAnalytics,
): IncomeDisplayModel | null { ): IncomeDisplayModel | null {
@@ -276,26 +259,9 @@ function formatIncomeChange(
}).format(ratio); }).format(ratio);
} }
function moscowDate(value: Date): string {
const parts = new Intl.DateTimeFormat("en-CA", {
timeZone: "Europe/Moscow",
year: "numeric",
month: "2-digit",
day: "2-digit",
}).formatToParts(value);
const part = (type: string) =>
parts.find((item) => item.type === type)?.value;
return `${part("year")}-${part("month")}-${part("day")}`;
}
export { export {
type AccountIncomePageViewModel, type AccountIncomePageViewModel,
formatDraftDate,
type IncomeDisplayModel, type IncomeDisplayModel,
type IncomeForm,
isDate,
moscowDate,
parseDraftDate,
toIncomeDisplayModel, toIncomeDisplayModel,
useAccountIncomePageViewModel, useAccountIncomePageViewModel,
}; };
@@ -1,7 +1,7 @@
import { Button } from "@mantine/core"; import { Button } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { StateView } from "@/shared/ui";
import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm"; import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
type ErrorProps = Extract<AccountIncomePageViewModel, { state: "error" }>; type ErrorProps = Extract<AccountIncomePageViewModel, { state: "error" }>;
@@ -7,10 +7,10 @@ import {
Text, Text,
Title, Title,
} from "@mantine/core"; } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { FormProvider } from "react-hook-form"; import { FormProvider } from "react-hook-form";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { StateView } from "@/shared/ui";
import classes from "../AccountIncomePage.module.css"; import classes from "../AccountIncomePage.module.css";
import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm"; import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
import { IncomeComparisons } from "./IncomeComparisons.view"; import { IncomeComparisons } from "./IncomeComparisons.view";
@@ -1,7 +1,7 @@
import { Paper, Skeleton, Stack } from "@mantine/core"; import { Paper, Skeleton, Stack } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { LoadingSkeleton } from "@/shared/ui";
import classes from "../AccountIncomePage.module.css"; import classes from "../AccountIncomePage.module.css";
const AccountIncomePageLoading: FC = () => { const AccountIncomePageLoading: FC = () => {
@@ -0,0 +1,58 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import type { FC } from "react";
import { FormProvider, useForm, useFormState } from "react-hook-form";
import type { IncomeForm } from "../../model/period";
import { IncomePeriodForm } from "./IncomePeriodForm.view";
const period = { from: "01.08.2026", to: "27.08.2026" };
const errors = {
to: { type: "manual", message: "Синтетическая ошибка периода" },
};
type PeriodExampleProps = { invalid?: boolean };
const PeriodExample: FC<PeriodExampleProps> = (props) => {
const methods = useForm<IncomeForm>({
defaultValues: period,
errors: props.invalid ? errors : undefined,
});
const { isSubmitSuccessful } = useFormState({ control: methods.control });
const submitted = isSubmitSuccessful ? methods.getValues() : null;
return (
<FormProvider {...methods}>
<IncomePeriodForm
onSubmit={methods.handleSubmit(() => undefined)}
onReset={() => {
methods.reset(period);
}}
/>
<output aria-live="polite">
{submitted
? `Применено: ${submitted.from} – ${submitted.to}`
: "Период не применён"}
</output>
</FormProvider>
);
};
const meta = {
title: "Product/IncomePeriodForm",
component: PeriodExample,
tags: ["autodocs"],
parameters: {
docs: {
description: {
component:
"Изолированная форма с синтетическим периодом. Submit показывает значения локально; reset возвращает fixture. Ошибка задана явно: query, URL и production validation остаются у page VM, API и router providers не используются.",
},
},
},
render: () => <PeriodExample />,
} satisfies Meta<typeof PeriodExample>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Default: Story = {};
export const ValidationError: Story = {
render: () => <PeriodExample invalid />,
};
@@ -3,13 +3,13 @@ import { DatePickerInput } from "@mantine/dates";
import type { FC, FormEventHandler } from "react"; import type { FC, FormEventHandler } from "react";
import { useController, useFormContext, useWatch } from "react-hook-form"; import { useController, useFormContext, useWatch } from "react-hook-form";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import classes from "../AccountIncomePage.module.css";
import { import {
formatDraftDate, formatDraftDate,
type IncomeForm, type IncomeForm,
moscowDate, moscowDate,
parseDraftDate, parseDraftDate,
} from "../AccountIncomePage.vm"; } from "../../model/period";
import classes from "../AccountIncomePage.module.css";
type IncomePeriodFormProps = { type IncomePeriodFormProps = {
onSubmit: FormEventHandler<HTMLFormElement>; onSubmit: FormEventHandler<HTMLFormElement>;
@@ -1,7 +1,7 @@
import { Button } from "@mantine/core"; import { Button } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { StateView } from "@/shared/ui";
import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm"; import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm";
type AccountOperationsPageErrorProps = Extract< type AccountOperationsPageErrorProps = Extract<
@@ -8,6 +8,7 @@ import {
Title, Title,
} from "@mantine/core"; } from "@mantine/core";
import { DatePickerInput } from "@mantine/dates"; import { DatePickerInput } from "@mantine/dates";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { import {
@@ -15,7 +16,6 @@ import {
type OperationCategory, type OperationCategory,
operationCategories, operationCategories,
} from "@/entities/broker-operation"; } from "@/entities/broker-operation";
import { StateView } from "@/shared/ui";
import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm"; import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm";
type AccountOperationsPageLoadedProps = Extract< type AccountOperationsPageLoadedProps = Extract<
@@ -1,7 +1,7 @@
import { Group, Skeleton, Stack } from "@mantine/core"; import { Group, Skeleton, Stack } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { LoadingSkeleton } from "@/shared/ui";
const skeletonRowIds = ["first", "second", "third", "fourth"]; const skeletonRowIds = ["first", "second", "third", "fourth"];
+2 -2
View File
@@ -63,11 +63,11 @@
} }
.positive { .positive {
color: var(--mantine-color-green-6); color: var(--wl-color-positive);
} }
.negative { .negative {
color: var(--mantine-color-red-6); color: var(--wl-color-negative);
} }
.expandedCard { .expandedCard {
@@ -1,9 +1,9 @@
import { Stack } from "@mantine/core"; import { Stack } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import type { BrokerageAccount } from "@/entities/brokerage-account"; import type { BrokerageAccount } from "@/entities/brokerage-account";
import { BrokerageEventsPreview } from "@/entities/brokerage-event"; import { BrokerageEventsPreview } from "@/entities/brokerage-event";
import { StateView } from "@/shared/ui";
import type { import type {
AccountPageIncomeSummary, AccountPageIncomeSummary,
AccountPageRecentEvents, AccountPageRecentEvents,
@@ -1,8 +1,8 @@
import { Button } from "@mantine/core"; import { Button } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Link } from "react-router"; import { Link } from "react-router";
import { StateView } from "@/shared/ui";
type AccountPageErrorProps = { code?: string; retry: () => void }; type AccountPageErrorProps = { code?: string; retry: () => void };
@@ -1,7 +1,7 @@
import { Paper, SimpleGrid, Skeleton } from "@mantine/core"; import { Paper, SimpleGrid, Skeleton } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { LoadingSkeleton } from "@/shared/ui";
import classes from "../AccountPage.module.css"; import classes from "../AccountPage.module.css";
const AccountPageLoading: FC = () => { const AccountPageLoading: FC = () => {
@@ -1,10 +1,10 @@
import { Button, Paper, Stack, Text } from "@mantine/core"; import { Button, Paper, Stack, Text } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Link } from "react-router"; import { Link } from "react-router";
import type { IncomeSummary as IncomeSummaryData } from "@/entities/income"; import type { IncomeSummary as IncomeSummaryData } from "@/entities/income";
import { formatMoney } from "@/shared/lib"; import { formatMoney } from "@/shared/lib";
import { StateView } from "@/shared/ui";
type IncomeSummaryProps = type IncomeSummaryProps =
| { state: "loading"; to: string } | { state: "loading"; to: string }
@@ -1,9 +1,9 @@
import { Alert, Button, Skeleton, Stack, Text } from "@mantine/core"; import { Alert, Button, Skeleton, Stack, Text } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Link } from "react-router"; import { Link } from "react-router";
import { LedgerEntryRow } from "@/entities/broker-operation"; import { LedgerEntryRow } from "@/entities/broker-operation";
import { LoadingSkeleton } from "@/shared/ui";
import type { AccountPageRecentOperations } from "../AccountPage.vm"; import type { AccountPageRecentOperations } from "../AccountPage.vm";
type RecentOperationsProps = { type RecentOperationsProps = {
@@ -1,7 +1,7 @@
import { Stack } from "@mantine/core"; import { Stack } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { StateView } from "@/shared/ui";
import { import {
AccountsRefreshState, AccountsRefreshState,
type AccountsRefreshStateProps, type AccountsRefreshStateProps,

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