Compare commits
7
Commits
dc3434c371
...
v0.2.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
97f1ad3e89 | ||
|
|
e31ab35a5a | ||
|
|
d9ada27621 | ||
|
|
9f7e342333 | ||
|
|
718365cd5a | ||
|
|
0244acf429 | ||
|
|
53b18c6e86 |
@@ -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.
|
||||
@@ -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 по догадке.
|
||||
@@ -0,0 +1,81 @@
|
||||
# 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 частично проверяет
|
||||
`npm run deps`; Knip проверяет использование exports, а не смысл placement.
|
||||
|
||||
## UI foundation
|
||||
|
||||
`shared/theme/tokens.json` — переносимый source design tokens; `theme.ts`
|
||||
адаптирует доверенный JSON к Mantine без runtime schema. App и Storybook читают
|
||||
public API `shared/theme`. Storybook показывает synthetic presentation states,
|
||||
не использует application API. RTL/MSW проверяют поведение приложения отдельно.
|
||||
|
||||
Existing route-aware AppShell расположен в shared/ui; это legacy placement,
|
||||
а не образец нового shared primitive. При изменении foundation прочитай
|
||||
[UI](conventions/ui.md#визуальная-основа) и [Storybook](conventions/storybook.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.
|
||||
Existing dependency config не запрещает все same-layer imports: их и смысл
|
||||
owner проверяет review. Не объявляй Steiger установленным; graph проверяет
|
||||
текущий dependency-cruiser. Review отдельно проверяет смысл owner: разрешённый dependency graph не доказывает
|
||||
правильный выбор слоя.
|
||||
@@ -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-проверок.
|
||||
@@ -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, раздел «Релизы».
|
||||
@@ -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 не доказывает
|
||||
правильный выбор слоя.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,33 @@
|
||||
# Storybook
|
||||
|
||||
## Когда нужна 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](../../src/shared/ui/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
|
||||
|
||||
Перед нетривиальными тестами сформулируй
|
||||
[общий Test Intent](engineering.md#test-intent); отдельный документ
|
||||
не требуется. Trivial low-risk изменения обходятся без него.
|
||||
|
||||
## Выбор проверки
|
||||
|
||||
Читай при изменении тестов, доступа, денежных расчётов, восстановления
|
||||
@@ -11,6 +15,7 @@
|
||||
| Чистое domain преобразование/денежный расчёт | Unit case с граничными значениями |
|
||||
| Форма, route access, recovery, UI-state selection | RTL component/route test через видимое поведение |
|
||||
| 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 без собственной логики не нужен |
|
||||
|
||||
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 выполняет
|
||||
RTL cleanup, auth reset и MSW reset: [test client](../../src/test/query.tsx).
|
||||
Тестовый клиент отключает retries запросов и мутаций для предсказуемого исхода;
|
||||
это не меняет [политику обновления приложения](../../../docs/adr/007-react-query-fetch-policy.md).
|
||||
это не меняет [политику обновления приложения](data.md#auth-и-invalidation).
|
||||
|
||||
## Важные случаи
|
||||
|
||||
@@ -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,28 @@ Mantine component и общую тему. Для выпадающего выбо
|
||||
ограничения JSDOM решай в test setup, сохраняя production UI.
|
||||
Семантический HTML для структуры страницы остаётся уместным.
|
||||
|
||||
Icons ищи у существующего owner (например,
|
||||
[BankOperationIcon](../../src/entities/bank-card/ui/BankOperationIcon.tsx));
|
||||
общая icon library сейчас не принята. Не добавляй пакет ради одного символа. Business/domain
|
||||
components живут у feature/entity/page, даже при повторном использовании.
|
||||
|
||||
Wrapper нужен для проектной ответственности, а не ради нового имени
|
||||
для 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 |
|
||||
| Параметр навигации, который должен переживать переход/ссылку | Router/URL |
|
||||
| Локальное открытие, focus, rendering fallback | React UI state |
|
||||
| Значение, вычисляемое из уже доступных inputs | Вычисление при render/в VM, без копирования через effect в state |
|
||||
|
||||
Effect нужен для синхронизации с внешней системой; действие пользователя
|
||||
обрабатывай в handler. Не добавляй store, memoization или abstraction без текущей
|
||||
потребности. Inspect ближайший component до создания нового pattern.
|
||||
State, который нужен в ссылке, back/forward или после navigation, хранится в URL
|
||||
через existing router search params. Остальной UI state остаётся у ближайшего
|
||||
owner. Shared client store нужен только нескольким consumers без подходящего
|
||||
общего owner; наличие двух компонентов само по себе его не требует.
|
||||
Hooks/effects/derived state — по [TypeScript/React](typescript-react.md#hooks-и-derived-state).
|
||||
|
||||
## Container, VM и view
|
||||
|
||||
@@ -76,71 +83,12 @@ Button loading при mutation и компактный cached-snapshot progress
|
||||
|
||||
## Код и components
|
||||
|
||||
Style/type automation задают configs. Используй `import type`; `enum` и
|
||||
`namespace` в frontend не применяются. Named components — const-valued; Biome
|
||||
проверяет declarations, no-default-export и exports-last в своём scope.
|
||||
|
||||
Обязательный review: `FC<Props>` и named props рядом/в types-файле; без inline
|
||||
props typing и destructuring в параметрах. Принимай `props`, destructure в body.
|
||||
Только children — `FC<PropsWithChildren>`; дополнительные props — named type
|
||||
на основе `PropsWithChildren<{ ... }>`. Без props — `FC`.
|
||||
Своди обычные exports к читаемому нижнему named block; barrel делает прямой
|
||||
re-export без промежуточного import.
|
||||
|
||||
CSF `*.stories.tsx` сохраняют default meta и прямые story exports для indexer.
|
||||
Vite/Vitest configs и `.storybook/main.ts`/`preview.tsx` имеют только
|
||||
конфигурационное default-export exception. Scope исключений принадлежит biome.json.
|
||||
Types, props, hooks и memoization — в [TypeScript/React](typescript-react.md).
|
||||
|
||||
## Domain literals and magic values
|
||||
|
||||
Finite business vocabulary must be modeled explicitly; incidental implementation
|
||||
literals stay inline. Это относится к error codes, statuses, operation/account/
|
||||
instrument/transaction types, permissions, roles, feature states и бизнес-режимам.
|
||||
|
||||
Перед новым определением найди existing owner/type/value. В branching и comparisons
|
||||
используй символическое значение владельца; не повторяй raw domain literals.
|
||||
Храни словарь у domain/module/entity с соблюдением границ слоёв, без глобальной
|
||||
свалки `constants.ts`. Сохраняй принятый pattern; для нового project-owned словаря
|
||||
без подходящего аналога используй `as const` с derived union:
|
||||
|
||||
```ts
|
||||
const BankErrorCode = {
|
||||
InvalidDate: "BANK_INVALID_DATE",
|
||||
ImmutableOperation: "BANK_IMMUTABLE_OPERATION",
|
||||
} as const;
|
||||
type BankErrorCode = (typeof BankErrorCode)[keyof typeof BankErrorCode];
|
||||
|
||||
// Вместо code === "BANK_INVALID_DATE":
|
||||
if (code === BankErrorCode.InvalidDate) { /* existing handling */ }
|
||||
```
|
||||
|
||||
Значимые numeric policies (timeout, retry, page size, threshold, coefficient)
|
||||
называй по смыслу и единицам: `REQUEST_TIMEOUT_MS`, `CACHE_TTL_SECONDS`,
|
||||
`MAX_RETRY_COUNT`, `PAGE_SIZE`. Оставляй inline UI labels в принятом месте,
|
||||
log messages, индексы, `index + 1`, `Math.max(value, 0)`, `page ?? 1`,
|
||||
`percentage * 100` и очевидные локальные детали без semantic benefit.
|
||||
При неясном owner/смысле оставь значение и укажи ограничение в review.
|
||||
|
||||
Не мигрируй корректные existing enum/union styles массово. Не добавляй ради
|
||||
правила factories, registries, schemas, loaders, abstraction layers, dependencies,
|
||||
custom lint/AST rules, generation/validation scripts или тесты существования
|
||||
констант. Semantic review проверяет ownership, единое написание и неизменность
|
||||
wire values; обычные behavior tests проверяют поведение.
|
||||
|
||||
Backend API vocabulary бери из generated OpenAPI types/client, runtime values —
|
||||
когда генератор их предоставляет. Не создавай ручную копию backend enum/object.
|
||||
Текущий `schema.d.ts` предоставляет только types: используй indexed-access type
|
||||
из `paths`; typed literals в запросах/сравнениях допустимы при отсутствии
|
||||
runtime values. `ProblemDetailsDto.code` сейчас `string`: не выдумывай закрытый
|
||||
frontend error enum. Развитие API source — отдельное contract-решение.
|
||||
Frontend `enum` по-прежнему запрещён локальным TS/style profile.
|
||||
|
||||
`noMagicNumbers` включён как error в Biome. Fixtures, tests и stories исключены
|
||||
из этого правила; остальные проверки для них сохраняются. Используй имена
|
||||
политик/единиц и existing values. Точечное подавление допустимо для очевидного
|
||||
incidental значения с объяснением, например перевода доли в проценты; не подавляй
|
||||
скрытые бизнес-лимиты. Semantic magic strings проверяются conventions/review: в
|
||||
установленном Biome нет такого встроенного правила, новый инструмент не добавляем.
|
||||
Правило и generated API exception — в
|
||||
[TypeScript/React](typescript-react.md#domain-literals-and-magic-values).
|
||||
|
||||
## Строки и валидация
|
||||
|
||||
@@ -153,6 +101,16 @@ incidental значения с объяснением, например пере
|
||||
## Проверка
|
||||
|
||||
Type/style: `npm run typecheck`, `npm run lint`. Для risk behavior/изменения тестов
|
||||
используй [Testing](frontend-testing.md). UI: keyboard, narrow viewport,
|
||||
loading/error/empty/loaded и recovery по применимости. [Storybook](../../README.md#ui-каталог-storybook)
|
||||
уже установлен; используй его как reference, но сверяй UI с задачей отдельно от build.
|
||||
используй [Testing](testing.md). UI: keyboard, narrow viewport,
|
||||
loading/error/empty/loaded и recovery по применимости. [Storybook](storybook.md) задаёт выбор stories и изоляцию каталога;
|
||||
сверяй UI с задачей отдельно от build.
|
||||
|
||||
## Визуальная основа
|
||||
|
||||
Общая тема живёт в `src/shared/theme`: `tokens.json` задаёт переносимые значения,
|
||||
`theme.ts` адаптирует их к Mantine. Используй public API темы и её semantic roles,
|
||||
без отдельной палитры в page/component. Поддерживается светлая схема.
|
||||
Цвет дополняет подпись или знак; проверяй контраст конкретной пары text/background.
|
||||
Warning не используй для мелкого текста на белом. Деньги сохраняют валюту, знак
|
||||
и различие между нулём и неизвестной суммой. Общие состояния демонстрирует
|
||||
Storybook; presentation stories используют synthetic data без application API.
|
||||
@@ -0,0 +1,15 @@
|
||||
**
|
||||
!package.json
|
||||
!package-lock.json
|
||||
!.nvmrc
|
||||
!index.html
|
||||
!tsconfig*.json
|
||||
!vite.config.ts
|
||||
!.storybook/
|
||||
!.storybook/**
|
||||
!src/
|
||||
!src/**
|
||||
!public/
|
||||
!public/**
|
||||
!docker/
|
||||
!docker/**
|
||||
@@ -0,0 +1,26 @@
|
||||
name: Conventional commits
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, edited]
|
||||
|
||||
jobs:
|
||||
commits:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: https://github.com/actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
fetch-depth: 0
|
||||
- uses: https://github.com/actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
- run: npm ci --ignore-scripts
|
||||
- name: Check PR title and commits
|
||||
env:
|
||||
PR_TITLE: ${{ github.event.pull_request.title }}
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
run: |
|
||||
printf '%s\n' "$PR_TITLE" | npm run commitlint -- --strict
|
||||
npm run commitlint -- --strict --from "$BASE_SHA" --to "$HEAD_SHA"
|
||||
@@ -0,0 +1,61 @@
|
||||
name: Frontend image
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
|
||||
concurrency:
|
||||
group: frontend-image-publication
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
IMAGE: git.personal.ksv741.ru/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 package writer
|
||||
env:
|
||||
REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
|
||||
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||
run: |
|
||||
test -n "$REGISTRY_USERNAME" && test -n "$REGISTRY_TOKEN"
|
||||
install -d -m 700 "$DOCKER_CONFIG"
|
||||
printf '%s' "$REGISTRY_TOKEN" | docker login git.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
|
||||
echo 'Refusing to overwrite an existing release tag'; exit 1
|
||||
fi
|
||||
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"]')"
|
||||
docker pull "$IMAGE@$DIGEST"
|
||||
test "$(docker image inspect "$IMAGE@$DIGEST" --format '{{index .Config.Labels "org.opencontainers.image.revision"}}')" = "$REVISION"
|
||||
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"
|
||||
@@ -4,6 +4,7 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- '**'
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
{
|
||||
"git": {
|
||||
"requireBranch": "release/*",
|
||||
"requireCleanWorkingDir": true,
|
||||
"requireUpstream": false,
|
||||
"requireCommits": true,
|
||||
"commitMessage": "chore(release): ${version}",
|
||||
"tagName": "v${version}",
|
||||
"tag": false,
|
||||
"push": false
|
||||
},
|
||||
"npm": {
|
||||
"publish": false
|
||||
},
|
||||
"github": {
|
||||
"release": false
|
||||
},
|
||||
"gitlab": {
|
||||
"release": false
|
||||
},
|
||||
"hooks": {
|
||||
"after:git:init": "node scripts/check-release.cjs"
|
||||
},
|
||||
"plugins": {
|
||||
"@release-it/conventional-changelog": {
|
||||
"infile": "CHANGELOG.md",
|
||||
"preset": {
|
||||
"name": "conventionalcommits",
|
||||
"types": [
|
||||
{
|
||||
"type": "chore",
|
||||
"scope": "release",
|
||||
"effect": "hidden"
|
||||
},
|
||||
{
|
||||
"type": "feat",
|
||||
"section": "Features",
|
||||
"effect": "bump"
|
||||
},
|
||||
{
|
||||
"type": "fix",
|
||||
"section": "Bug Fixes",
|
||||
"effect": "bump"
|
||||
},
|
||||
{
|
||||
"type": "perf",
|
||||
"section": "Performance",
|
||||
"effect": "bump"
|
||||
},
|
||||
{
|
||||
"type": "docs",
|
||||
"section": "Documentation",
|
||||
"effect": "bump"
|
||||
},
|
||||
{
|
||||
"type": "spec",
|
||||
"section": "Specifications",
|
||||
"effect": "bump"
|
||||
},
|
||||
{
|
||||
"type": "refactor",
|
||||
"section": "Refactoring",
|
||||
"effect": "bump"
|
||||
},
|
||||
{
|
||||
"type": "build",
|
||||
"section": "Build",
|
||||
"effect": "bump"
|
||||
},
|
||||
{
|
||||
"type": "ci",
|
||||
"section": "CI",
|
||||
"effect": "bump"
|
||||
},
|
||||
{
|
||||
"type": "test",
|
||||
"section": "Tests",
|
||||
"effect": "bump"
|
||||
},
|
||||
{
|
||||
"type": "style",
|
||||
"section": "Styles",
|
||||
"effect": "bump"
|
||||
},
|
||||
{
|
||||
"type": "chore",
|
||||
"section": "Maintenance",
|
||||
"effect": "bump"
|
||||
},
|
||||
{
|
||||
"type": "revert",
|
||||
"section": "Reverts",
|
||||
"effect": "bump"
|
||||
}
|
||||
]
|
||||
},
|
||||
"context": {
|
||||
"host": "https://git.personal.ksv741.ru",
|
||||
"owner": "WealthLedger",
|
||||
"repository": "frontend",
|
||||
"linkReferences": true,
|
||||
"commit": "commit"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,29 +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`.
|
||||
После lockfile install `npm ci` полный gate — `npm run verify`.
|
||||
Он проверяет OpenAPI drift, TypeScript, Biome, Vitest/coverage, Knip,
|
||||
dependency boundaries и сборки приложения/Storybook без backend.
|
||||
Точные scripts принадлежат `package.json`; targeted checks — у выбранного convention.
|
||||
Показ query state не означает изменение fetching. Изменение тестов активирует
|
||||
Testing и без production diff. Перед завершением повтори routing по новым и
|
||||
изменённым файлам. Для Git/release прочитай
|
||||
[Git и релизы](.ai/conventions/engineering.md#git-и-релизы).
|
||||
|
||||
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; неясное ожидание уточни до изменения |
|
||||
| Versions/scripts/check scope | Manifest/lockfile, Biome/TypeScript/dependency configs |
|
||||
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
# Changelog
|
||||
|
||||
## [0.2.0](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.1.0...v0.2.0) (2026-09-16)
|
||||
|
||||
### Features
|
||||
|
||||
* add frontend container delivery ([e31ab35](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/e31ab35a5ac51b7dbd1509e35c4ce8e9f8fd4e92))
|
||||
|
||||
### Documentation
|
||||
|
||||
* make frontend instructions self-contained ([d9ada27](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/d9ada2762169b3347a0dc4b7e7ce6c7cd207af76))
|
||||
* refine frontend conventions and routing ([718365c](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/718365cd5ab51e7c696c777b71095f7ee41b471d))
|
||||
* simplify conventions layout ([9f7e342](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/9f7e342333b80bfacfd5bc394a2dcd0613d33ff3))
|
||||
|
||||
## 0.1.0 (2026-09-14)
|
||||
|
||||
### Features
|
||||
|
||||
* **account-operations:** require explicit ledger filters ([7d748a6](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/7d748a65d384e76220e234aa37a21b05b81e442a))
|
||||
* **accounts:** enrich brokerage account list ([fd93133](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/fd93133cfcdfd9372b2630cacaa7f5195f1beb58))
|
||||
* **account:** wrap portfolio sections in Mantine Accordion ([c1a8674](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/c1a8674f164117018236bf461bd457208ac9ad00))
|
||||
* add all-accounts portfolio pages ([daf1dca](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/daf1dca6666035cbca3ba020d8ae0b2a8789dc3a))
|
||||
* add authorization ([3448fea](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/3448fea1407f246e0b093e64edd7b672ae8992a9))
|
||||
* add bond pages and portfolio navigation ([232d7f9](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/232d7f999040e4c91c27d5b382f2fcdfc4542d5a))
|
||||
* add breadcrumbs ([719a6ed](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/719a6ed8b73f8a552778a1b78f65776f02d4127c))
|
||||
* add brocker account list ([6e89c1a](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/6e89c1a8f765025bd7be37b59c696d092fd4bbe4))
|
||||
* add manual bank card screens ([ff4e88e](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/ff4e88edbeb9de244c2a6094ab70d9e48a4768a7))
|
||||
* add operations page ([4f3ee7d](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/4f3ee7ddb289284f8a6a0677438f270e8756a3fb))
|
||||
* add portfolio ([9156f29](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/9156f297073fefa2fe1c5cb9659495e2d532ac89))
|
||||
* add stock pages and ticker navigation ([561222e](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/561222e4686bde1dc98454a4216025c4cbc02d65))
|
||||
* add Storybook for WealthLedger components ([e63fd89](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/e63fd89a3922cd4dd7f194e33b320b4178985a5f))
|
||||
* add tbank tokens ([32e21de](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/32e21de17d00de5b3a4b074a2300e6a29a81e3ae))
|
||||
* add агегку events ([da55de5](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/da55de5b5008cce0ea24def664e13f3239174324))
|
||||
* animate page transitions with Motion ([c906dfa](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/c906dfa2e290164e6b089764be18edc99f10e775))
|
||||
* **broker-operation:** show operation type label in ledger entries ([d53ce50](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/d53ce50e2842e8d69a709b92417888ba851774b4))
|
||||
* **card:** refine header and inline actions ([cf21a5b](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/cf21a5bd178a18753321811b6d8ac81ff848d676))
|
||||
* **cards:** filter operations by date range ([9bb385b](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/9bb385b9f02cc780e27d9da8f30fae374ab0f08c))
|
||||
* **cards:** refine controls and modal transitions ([aba4cf1](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/aba4cf1ce83ea62082f35be358c2081d797f6645))
|
||||
* **cards:** show operation icons on hover ([dedfec1](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/dedfec10d1e94b76a21e0d9ee90b6cf7fea5a4a9))
|
||||
* compact portfolio currency totals ([47fbc21](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/47fbc212831058f1a0f1226dd262bf5c37870e34))
|
||||
* consume money projected event amounts ([1fd9a3a](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/1fd9a3a861a8b915b6c64861a018db39e2598a83))
|
||||
* enforce frontend quality guardrails ([1fc269a](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/1fc269adec9f0cfeacdc365c6e59a30c4620dba7))
|
||||
* establish frontend foundation ([1e13ada](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/1e13adabd32412de9707f452e42d2c65e73c106f))
|
||||
* **events:** add date filters to upcoming events ([9469dd2](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/9469dd2fdc03df47c202da2afdcdadb49dbb2748))
|
||||
* improve bank card expenses summary ([d3ac8c2](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/d3ac8c242de1d30cd3c4ca8e5850700192c2c259))
|
||||
* improve card operations pagination and scroll behavior ([9a65687](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/9a65687d3875d264b6de088d6886e6cb916d3426))
|
||||
* improve ledger event rows ([488ccad](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/488ccad540c771e862fb795edf2df6c6cea315af))
|
||||
* **income:** add account income analytics ([9364568](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/93645682028947d3fbd212bc9929dd2195715c69))
|
||||
* initial commit ([3331b7f](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/3331b7f684f2ccc6d3934436d0326d877d1c3899))
|
||||
* polish bank operation cards and dates ([6b310db](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/6b310db0b8c37cb4cffe54acf3b7e9799f9f3ea0))
|
||||
* polish stock position cards ([273778c](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/273778c4cfa6ef8bd3ab421e03c57b6e31f7d925))
|
||||
* **portfolio:** add expanded layout for bond position cards ([bcf9369](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/bcf93691aa874114faf75cb9c36d1426dd7b8903))
|
||||
* **portfolio:** extend instrument logo rendering to bonds ([c04025a](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/c04025a3924ad76ae06e9bbbd32df4d18c85b34a))
|
||||
* **portfolio:** show stock tickers ([8f9caa9](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/8f9caa946ee99e2db2b495a384b17a0ce90ddcfd))
|
||||
* **portfolio:** visualize asset allocation ([0306526](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/0306526d3330d508d817aedecf74f0b74583dea7))
|
||||
* redesign portfolio position cards ([5168870](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/5168870cf2d5ac19a6d08ad8fee35f2952cdda87))
|
||||
* redesign year-over-year income comparison ([91eaeb5](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/91eaeb5661706f30171f5f15bf22e419fe2ee57c))
|
||||
* render stock logos with signed returns on account page ([a6d3051](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/a6d305127057bf6413825ffddba1c15b53e65a73))
|
||||
* replace loading spinners with skeletons ([71a214d](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/71a214d7adfcf5fc57cd5518fb008021d50e7723))
|
||||
* replace paired date inputs with range pickers ([24d332e](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/24d332e06341ccfb0d0d7046793ca145669cec44))
|
||||
* show page context in browser tab titles ([2580134](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/2580134683cbe036bb07b635aab6262d3702f270))
|
||||
* simplify income page filters and payments ([26f229b](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/26f229ba3e0f8335dde297bf6c4575f7014e9f28))
|
||||
* **ui:** animate navigation and operation icons ([8e58c01](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/8e58c016d2dccfbdc6089480f6ccc113b6719850))
|
||||
* **ui:** animate sidebar icons on hover ([ebba6ab](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/ebba6ab25dc968c278d525fd2fd4194c8422d8d1))
|
||||
* **ui:** establish shared design system foundations ([d762ba5](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/d762ba50342cd96e4387a51bac12a0c4c43c648c))
|
||||
* unify upcoming event cards across pages ([451400b](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/451400b63be0011a7a3b4dfd77e9365f7bcca467))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **frontend:** complete audit remediation ([9e42148](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/9e42148f6a9ad620b4fc9f6aef9ee2d80d73702b))
|
||||
* harden frontend dependency and env hygiene ([826936c](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/826936c6a4a7160b07224f0fa94b6d2d941bc6dc))
|
||||
* little fixes ([2e32d22](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/2e32d226d321f2d51653f1823ade8bace17fc5e5))
|
||||
* preserve cached data during refresh failures ([6d892da](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/6d892da9cec9d8522520cec3c26d343e81f4a51d))
|
||||
* remove income analytics period limit ([ab1b536](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/ab1b53680d811e5b5f91e8e14a7f219274e57313))
|
||||
* separate portfolio cash presentation ([3017fc8](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/3017fc810ee10f2790dbc04902ad4e2f2cbadbd4))
|
||||
* stabilize frontend query cache contracts ([1250581](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/1250581ee3336e901bd01f757328ae4c4dd091c8))
|
||||
* **tbank:** reset connection-derived query cache ([175727b](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/175727bc93876f950280d0ad35515a6d4acffbaf))
|
||||
* **ui:** align page layouts and add navigation icons ([d7e8963](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/d7e8963d1cfabd0900051e30e33ec30284282a7c))
|
||||
|
||||
### Documentation
|
||||
|
||||
* **agents:** link audit remediation registry ([b285719](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/b285719c1bcea32e490f9d960d7893bd21ba9e81))
|
||||
* **agents:** restore openspec authority ([fd72fb2](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/fd72fb2239849cb87d441c552b194b6358c9dc8a))
|
||||
* **ai:** route frontend conventions by task ([bcc034f](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/bcc034f19839a1aefadad978c5bb3a89d81ebe63))
|
||||
* align OpenAPI workflow guidance [#3](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/3) ([7a89356](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/7a89356f8783a14d6dde752358ee995d0dcadd66))
|
||||
* define canonical OpenSpec store ([d870d53](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/d870d535d7090aa3051de6f1b0fd979eaf6d7154))
|
||||
* document runtime OpenAPI verification ([7a3048c](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/7a3048c3476675528203fbe74338131723354e1d))
|
||||
* refresh frontend onboarding ([be80ef2](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/be80ef2f1bffc01867ee97f5f78c0cba7764a24e))
|
||||
* remove useless ([7ab043d](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/7ab043dce63a3fbacbfc9ac7d15b00dd714a541f))
|
||||
* update routes to system documentation ([a42f104](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/a42f104bed4daf982f2a72f0634887e4ea067dec))
|
||||
* update system documentation references ([dc3434c](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/dc3434c3716f09cfb1ef4aa3006e9db12f6b3bcf))
|
||||
|
||||
### Refactoring
|
||||
|
||||
* **account-operations:** split page state views into components ([695cda0](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/695cda0456970fe3a46d09dcec718c741ee6b18d))
|
||||
* align frontend ownership boundaries ([c97f62b](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/c97f62bd983d6b5327132f4ec42e767118720913))
|
||||
* centralize frontend auth query gating ([268acdf](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/268acdf2e1057ed0f6c19384bfb6477aff773d1d))
|
||||
* enforce account page view model boundary ([fff36f2](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/fff36f252aa1a7bb18042c8fc2d06262b687b0b1))
|
||||
* enforce semantic values and numeric lint rules ([53c852b](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/53c852b437ee1174843a4f959722239132e9150a))
|
||||
* little structure refactor ([2cca503](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/2cca503519888762067c770c188ed2d977979cbb))
|
||||
* refactor foundation ([da585b1](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/da585b157a5350753a91abb7f10aa00c7e9cf2c3))
|
||||
* simplify local design token consumption ([8b29cdf](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/8b29cdfd98790cb3316f1db0f8933c8b6bc4b335))
|
||||
* source shared design tokens from JSON ([0f50f15](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/0f50f156584b6b0bf3e473d047c3960284cf0cdd))
|
||||
* use Mantine Breadcrumbs for app navigation ([3c459e6](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/3c459e66cc640cad58267cbaac2be4fbcaee4fdf))
|
||||
|
||||
### CI
|
||||
|
||||
* configure Renovate dependency updates [#5](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/5) ([4b97395](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/4b973953853785660b5c34ef96c90d518ab6c561))
|
||||
* disable memory-heavy Knip raw transfer [#1](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/1) ([2f26e4f](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/2f26e4fe0d8aa4e693c3ca425db04b04afbba75f))
|
||||
* run Biome on branch pushes in Gitea ([ccff422](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/ccff422f367bbcf5e19f510119dbe8b63de9b87a))
|
||||
* run full frontend verification [#1](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/1) ([22e331e](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/22e331e2ff4c5f68b3273de89fe9968029a1343d))
|
||||
|
||||
### Tests
|
||||
|
||||
* allow UI scenarios more time in CI [#1](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/1) ([942ed3d](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/942ed3d453d71547dc8883924a9bb2f76f7e997f))
|
||||
* keep portfolio metadata authoritative in cards ([427ca23](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/427ca23a433a20be25b1f4373f32c9e1f6f8c400))
|
||||
|
||||
### Maintenance
|
||||
|
||||
* align SDD routing and instruction commits ([3669832](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/36698322b7273b3a9eae1d078bcc9cddf2c8295b))
|
||||
* codify frontend local verification ([11be786](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/11be786943024699a4eccf91a8d1ad32a6d29e5f))
|
||||
* codify React component style ([d10e1dd](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/d10e1dd1827094e6e52768f0ccd2ea060aef95a1))
|
||||
* configure releases and develop workflow ([53b18c6](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/53b18c6e86f433bcb967721232c150fba4f7cc9f))
|
||||
* **deps:** update non-major dependencies ([0c6bac8](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/0c6bac8b902b88dc0b447b9198968e938db72c82))
|
||||
* make issue references optional and use chore for dependency updates [#5](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/5) ([82b9043](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/82b904393dcf65d9876fd06d1864dddef7d70bdb))
|
||||
* save pending changes ([ae06f6e](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/ae06f6e6e0f98a2be208d66105ca53ecf2d86bfd))
|
||||
* secure hooks and update dependencies [#4](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/4) [#9](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/9) ([3be6e61](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/3be6e61b8fc85d4b16199dbe9910b38894159cb8))
|
||||
* simplify frontend verification ([f09baa6](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/f09baa68fcecfd210f95a7bfe8a67dc3741abce8))
|
||||
* simplify frontend verification ([3d9b619](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/3d9b6194c60b373996a590c4bd56653e0935e8c6))
|
||||
* upgrade Node to 24 LTS ([117e74c](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/117e74cdfc29cbf63f549ea88e8106ab25300541))
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
FROM node:24.21.0-bookworm-slim AS dependencies
|
||||
WORKDIR /app
|
||||
ENV HUSKY=0
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
FROM dependencies AS development
|
||||
COPY . .
|
||||
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
|
||||
@@ -23,6 +23,31 @@ staged diff с полной редакцией секретов, затем за
|
||||
Находка или отсутствие Gitleaks блокирует commit.
|
||||
Проверка этого поведения: `node --test scripts/test-pre-commit.mjs`.
|
||||
|
||||
## Контейнерный image
|
||||
|
||||
`Dockerfile` имеет targets `development` (Vite HMR и proxy `/api/` во внутренний backend)
|
||||
и `production` (nginx на 8080, SPA fallback и same-origin API proxy). Node соответствует `.nvmrc`.
|
||||
Build context ограничен `.dockerignore`; `.env`, local DB и host node_modules
|
||||
не попадают в image.
|
||||
|
||||
```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. Dedicated package writer задаётся Actions secrets
|
||||
`REGISTRY_USERNAME`/`REGISTRY_TOKEN`; server использует отдельную read-only
|
||||
identity. Публикуются 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.
|
||||
|
||||
## Проверка
|
||||
|
||||
```bash
|
||||
@@ -55,21 +80,59 @@ document и затем выполните `npm run openapi:generate`.
|
||||
`npm run build:catalog`. Каталог использует общую тему приложения, вымышленные
|
||||
данные и локальные действия без application API. Примеры не доказывают
|
||||
восстановление реального запроса. Визуальные роли описаны в
|
||||
[дизайн-системе](../docs/design/overview.md).
|
||||
[UI convention](.ai/conventions/ui.md#визуальная-основа).
|
||||
|
||||
## Документация
|
||||
|
||||
- [Router conventions](.ai/CONVENTIONS.md) и [источники](.ai/SOURCES.md)
|
||||
- [Выбор owner/FSD](.ai/conventions/frontend-architecture.md)
|
||||
- [UI, state, формы и компоненты](.ai/conventions/frontend-ui.md)
|
||||
- [Data/API/cache](.ai/conventions/frontend-data.md)
|
||||
- [Testing](.ai/conventions/frontend-testing.md)
|
||||
- [AGENTS: правила и источники](AGENTS.md)
|
||||
- [Выбор owner/FSD](.ai/architecture.md)
|
||||
- [UI, state, формы и компоненты](.ai/conventions/ui.md)
|
||||
- [Data/API/cache](.ai/conventions/data.md)
|
||||
- [Testing](.ai/conventions/testing.md)
|
||||
- [UI-каталог Storybook](#ui-каталог-storybook)
|
||||
- [Обзор поставленной системы](../docs/overview.md)
|
||||
- [Карта проектных фактов](../docs/README.md)
|
||||
|
||||
Runtime OpenAPI backend сверяется с frontend snapshot отдельной read-only
|
||||
backend командой `npm run test:openapi-contract`.
|
||||
Разработка идёт напрямую по задаче пользователя. Каждый affected repo проходит
|
||||
свой verify; при изменении wire contract дополнительно выполняется contract check.
|
||||
Обязательного OpenSpec/SDD lifecycle нет.
|
||||
Checkout frontend содержит все входы сборки и проверок. Публичная схема API
|
||||
поступает как отдельный artifact; команды frontend используют только её
|
||||
локальную копию и не обращаются к исходникам или CI сервера. Доставка новой
|
||||
схемы — явное обновление snapshot с review и `npm run openapi:generate`.
|
||||
Runtime URL API задаётся окружением, а не расположением другого репозитория.
|
||||
Разработка идёт напрямую по задаче пользователя; OpenSpec/SDD — по явному запросу.
|
||||
|
||||
Knip исключает `conventional-changelog-conventionalcommits`: release-it загружает
|
||||
preset по имени из `.release-it.json`. Версия preset закреплена напрямую.
|
||||
|
||||
## Релизы
|
||||
|
||||
Репозиторий выпускается независимо. `develop` — интеграция, `main` — принятые
|
||||
релизы. Работа: `codex/<task>` от актуального `develop`, PR в `develop`.
|
||||
Обычные PR допускают squash; release и обратная синхронизация сохраняют историю.
|
||||
Commits и PR titles — Conventional Commits, включая `spec:`. Версии вручную не повышай.
|
||||
|
||||
1. Получи `main`, `develop` и теги: `git fetch origin --tags`. Убедись, что
|
||||
`develop` содержит последний релиз. Создай `release/<name>` от проверенного
|
||||
`develop`; `nvm use --silent`, `npm ci`. Hotfix начинается от `main` в
|
||||
`release/hotfix-<name>` и проходит тот же процесс.
|
||||
2. На чистой ветке выполни `npm run release:preview`, просмотри версию/changelog,
|
||||
затем `npm run release:prepare`. Команда создаёт `chore(release): X.Y.Z`,
|
||||
обновляет manifest/lockfile/CHANGELOG; тег и push не выполняет. Не обходи
|
||||
guards ветки, чистого дерева, отсутствующих тегов или уже подготовленной версии.
|
||||
3. Проверь diff и штатные gates этого репозитория. Отправь только release-ветку,
|
||||
открой PR в `main` с заголовком `chore(release): X.Y.Z`. После зелёных
|
||||
`verify`, `security`, `commits` выполни fast-forward-only merge. Если `main`
|
||||
изменился, согласуй историю и повтори проверки кандидата.
|
||||
4. Получи удалённый `main`, сравни его HEAD с проверенным release SHA и версией
|
||||
manifest/lockfile. Создай аннотированный `vX.Y.Z` именно на этом SHA:
|
||||
`git tag -a vX.Y.Z <release-sha> -m "Release X.Y.Z"`, затем отправь только
|
||||
`git push origin refs/tags/vX.Y.Z`. Не запускай release-it повторно на `main`.
|
||||
5. Верни release-коммит через PR `main → develop` без squash/rebase; проверь,
|
||||
что `develop` содержит тег. Опубликованные теги не перемещай. При сбое после
|
||||
merge создай отсутствующий тег без нового bump; до merge исправь и проверь
|
||||
существующий кандидат без повторного повышения версии.
|
||||
|
||||
`feat:` повышает minor, `fix:`/`perf:` и прочие разрешённые типы — patch;
|
||||
`!`/`BREAKING CHANGE:` — major, включая версии до 1.0. `chore(release):`
|
||||
исключён из рекомендации и changelog. Конфигурация — `.release-it.json`.
|
||||
В Gitea для `main`/`develop` должны быть запрещены прямой/force push и обход
|
||||
администратором, обязательны `verify`, `security`, `commits`; теги `v*` защищены.
|
||||
Workflow сам не включает эти настройки. Отдельное review approval для одного
|
||||
владельца не требуется. Npm publishing, deploy и Gitea Releases не включены.
|
||||
|
||||
@@ -1,3 +1,23 @@
|
||||
module.exports = {
|
||||
extends: ["@commitlint/config-conventional"],
|
||||
rules: {
|
||||
"type-enum": [
|
||||
2,
|
||||
"always",
|
||||
[
|
||||
"feat",
|
||||
"fix",
|
||||
"perf",
|
||||
"docs",
|
||||
"spec",
|
||||
"refactor",
|
||||
"build",
|
||||
"ci",
|
||||
"test",
|
||||
"style",
|
||||
"chore",
|
||||
"revert",
|
||||
],
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
{
|
||||
"project": ["src/**/*.{ts,tsx}", "!src/shared/api/generated/**"]
|
||||
"project": ["src/**/*.{ts,tsx}", "!src/shared/api/generated/**"],
|
||||
"ignoreDependencies": ["conventional-changelog-conventionalcommits"]
|
||||
}
|
||||
|
||||
Generated
+2197
-18
File diff suppressed because it is too large
Load Diff
+8
-2
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "wealth-ledger-frontend",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"version": "0.2.0",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": "24.21.0"
|
||||
@@ -24,7 +24,10 @@
|
||||
"verify": "npm run openapi:check && npm run typecheck && npm run lint && npm run test:coverage && npm run knip && npm run deps && npm run deps:storybook && npm run build && npm run build:catalog",
|
||||
"prepare": "husky",
|
||||
"preview": "vite preview",
|
||||
"deps:storybook": "depcruise src .storybook/preview.tsx --config .storybook/dependency-cruiser.cjs --output-type err-long"
|
||||
"deps:storybook": "depcruise src .storybook/preview.tsx --config .storybook/dependency-cruiser.cjs --output-type err-long",
|
||||
"release:preview": "release-it --dry-run --ci",
|
||||
"release:prepare": "release-it --ci",
|
||||
"commitlint": "commitlint"
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.{css,html,json,md,ts,tsx}": "biome format --write --no-errors-on-unmatched"
|
||||
@@ -55,6 +58,7 @@
|
||||
"@biomejs/biome": "2.5.13",
|
||||
"@commitlint/cli": "21.2.2",
|
||||
"@commitlint/config-conventional": "21.2.2",
|
||||
"@release-it/conventional-changelog": "12.0.0",
|
||||
"@rolldown/plugin-babel": "0.2.4",
|
||||
"@storybook/addon-docs": "10.6.0",
|
||||
"@storybook/react-vite": "10.6.0",
|
||||
@@ -66,6 +70,7 @@
|
||||
"@vitejs/plugin-react": "6.1.1",
|
||||
"@vitest/coverage-v8": "5.0.0",
|
||||
"babel-plugin-react-compiler": "1.0.0",
|
||||
"conventional-changelog-conventionalcommits": "10.4.0",
|
||||
"dependency-cruiser": "18.2.0",
|
||||
"husky": "9.1.7",
|
||||
"jsdom": "30.0.1",
|
||||
@@ -73,6 +78,7 @@
|
||||
"lint-staged": "17.5.1",
|
||||
"msw": "2.15.0",
|
||||
"openapi-typescript": "7.13.0",
|
||||
"release-it": "21.0.2",
|
||||
"storybook": "10.6.0",
|
||||
"typescript": "5.9.3",
|
||||
"vite": "8.3.0",
|
||||
|
||||
+3
-2
@@ -4,7 +4,7 @@
|
||||
"timezone": "Europe/Moscow",
|
||||
"labels": ["dependencies"],
|
||||
"dependencyDashboard": true,
|
||||
"rangeStrategy": "bump",
|
||||
"rangeStrategy": "pin",
|
||||
"packageRules": [
|
||||
{
|
||||
"matchUpdateTypes": ["minor", "patch"],
|
||||
@@ -14,5 +14,6 @@
|
||||
"matchUpdateTypes": ["major"],
|
||||
"dependencyDashboardApproval": true
|
||||
}
|
||||
]
|
||||
],
|
||||
"baseBranchPatterns": ["develop"]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const { execFileSync } = require("node:child_process");
|
||||
const { version } = require("../package.json");
|
||||
const git = (...args) => execFileSync("git", args, { encoding: "utf8" }).trim();
|
||||
|
||||
assert.equal(
|
||||
git("status", "--porcelain"),
|
||||
"",
|
||||
"Commit all changes before preparing a release",
|
||||
);
|
||||
const tags = git(
|
||||
"tag",
|
||||
"--merged",
|
||||
"HEAD",
|
||||
"--list",
|
||||
"v[0-9]*",
|
||||
"--sort=-version:refname",
|
||||
)
|
||||
.split("\n")
|
||||
.filter((tag) => /^v\d+\.\d+\.\d+$/.test(tag));
|
||||
assert.equal(
|
||||
version,
|
||||
tags[0]?.slice(1) ?? "0.0.0",
|
||||
"Version is already prepared or release tags are missing. Fetch tags; finish the existing release before preparing another.",
|
||||
);
|
||||
@@ -7,4 +7,11 @@ import { defineConfig } from "vite";
|
||||
export default defineConfig({
|
||||
plugins: [react(), babel({ presets: [reactCompilerPreset()] })],
|
||||
resolve: { alias: { "@": fileURLToPath(new URL("./src", import.meta.url)) } },
|
||||
server: {
|
||||
proxy: {
|
||||
"/api/": {
|
||||
target: process.env.API_PROXY_TARGET ?? "http://localhost:3000",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user