20 Commits
Author SHA1 Message Date
ksv741 b34c1c860a chore(release): 0.4.0
Frontend image / publish (push) Successful in 6m44s
Conventional commits / commits (pull_request) Successful in 27s
Frontend security / security (pull_request) Successful in 10s
Frontend verify / verify (pull_request) Successful in 5m46s
Frontend security / security (push) Successful in 10s
Frontend verify / verify (push) Successful in 6m57s
2026-09-26 22:10:01 +03:00
ksv741 a005e8b13b chore: synchronize develop before release
Conventional commits / commits (pull_request) Successful in 27s
Frontend security / security (pull_request) Successful in 10s
Frontend verify / verify (pull_request) Successful in 6m6s
Frontend security / security (push) Successful in 10s
Frontend verify / verify (push) Successful in 7m5s
2026-09-26 21:30:58 +03:00
ksv741 4e5f564fa1 feat: show persisted investment data and sync state
Consume the provided resource-envelope API snapshot. Preserve financial snapshots during
refresh, observe synchronization without importing, and fence late responses across
account and connection changes.
2026-09-26 21:22:49 +03:00
codex-bot cd09ec698c refactor: colocate frontend component files (#35)
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Successful in 6m53s
2026-09-23 08:49:01 +03:00
ksv741 b987fd8e78 refactor: colocate frontend component files
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Successful in 5m10s
Conventional commits / commits (pull_request) Successful in 25s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 5m10s
2026-09-23 08:34:58 +03:00
ksv741 85fcfe3d07 refactor: establish local frontend workspace boundaries
Conventional commits / commits (pull_request) Successful in 24s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 5m18s
Frontend security / security (push) Successful in 10s
Frontend verify / verify (push) Successful in 6m45s
OpenSpec change: evolve-frontend-stack
2026-09-22 22:11:02 +03:00
ksv741 c86be7bf73 fix(ui): improve financial text contrast
TD-010: use readable semantic text colors on financial surfaces while preserving signs
and state meanings.
2026-09-21 21:10:10 +03:00
ksv741 6a87379813 fix(ci): resume verification of immutable release images
TD-009: retry verification of an existing digest without republishing. Paired backend
workflow fix: 82eccc3.
2026-09-21 21:09:53 +03:00
ksv741 db184c8cae fix(api): update validation and conflict response contract
TD-003 and TD-005: explicitly deliver OpenAPI and generated types from backend commit 1667991.
2026-09-21 21:09:41 +03:00
ksv741 a209d71589 fix(auth): isolate session races and financial caches
TD-001 and TD-002: serialize cookie writes, ignore stale responses and reset financial
queries on identity changes. Backend cookie lifecycle regression: ec5780d.
2026-09-21 21:09:23 +03:00
ksv741 3c99debe88 chore(release): 0.3.0
Frontend image / publish (push) Successful in 5m45s
Conventional commits / commits (pull_request) Successful in 27s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 4m42s
Frontend security / security (push) Successful in 10s
Frontend verify / verify (push) Successful in 6m17s
2026-09-20 20:09:11 +03:00
ksv741 bb30935f73 feat: add installable PWA #30
Conventional commits / commits (pull_request) Successful in 30s
Frontend security / security (pull_request) Successful in 1m7s
Frontend verify / verify (pull_request) Successful in 4m48s
Frontend security / security (push) Successful in 11s
Frontend verify / verify (push) Successful in 6m17s
2026-09-20 19:55:53 +03:00
ksv741 f486ae4fb2 chore(release): 0.2.3
Frontend image / publish (push) Successful in 4m51s
Conventional commits / commits (pull_request) Successful in 21s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 3m56s
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Successful in 5m27s
2026-09-19 16:25:12 +03:00
ksv741 9171b9f5c8 fix: correct Nexus routing and SonarQube host 2026-09-19 16:24:07 +03:00
ksv741 d68ec3b15b chore(release): 0.2.2
Frontend image / publish (push) Failing after 3m59s
Conventional commits / commits (pull_request) Successful in 20s
Frontend security / security (pull_request) Successful in 10s
Frontend verify / verify (pull_request) Successful in 4m5s
Frontend security / security (push) Successful in 10s
Frontend verify / verify (push) Failing after 4m26s
2026-09-19 15:04:33 +03:00
ksv741 bac95ebb39 fix: update Nexus registry host
Conventional commits / commits (pull_request) Successful in 21s
Frontend security / security (pull_request) Successful in 8s
Frontend verify / verify (pull_request) Successful in 4m11s
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Failing after 4m7s
2026-09-19 14:51:25 +03:00
ksv741 8183b66e2f chore(release): 0.2.1
Conventional commits / commits (pull_request) Successful in 20s
Frontend security / security (pull_request) Successful in 8s
Frontend verify / verify (pull_request) Successful in 3m36s
Frontend image / publish (push) Failing after 3m56s
Frontend security / security (push) Successful in 8s
Frontend verify / verify (push) Failing after 4m13s
2026-09-18 08:12:21 +03:00
ksv741 1ad578fb37 docs: use shared Nexus account #21
Frontend security / security (pull_request) Successful in 53s
Frontend verify / verify (pull_request) Successful in 3m52s
Conventional commits / commits (pull_request) Successful in 20s
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Failing after 7m49s
2026-09-17 20:53:03 +03:00
ksv741 999b8590ec ci: publish frontend images to Nexus #21
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Successful in 3m57s
Conventional commits / commits (pull_request) Failing after 19s
Frontend security / security (pull_request) Successful in 32s
Frontend verify / verify (pull_request) Successful in 3m54s
2026-09-17 20:41:12 +03:00
ksv741 3f19b3643f ci: add frontend SonarQube analysis #19
Conventional commits / commits (pull_request) Successful in 22s
Frontend security / security (pull_request) Successful in 16s
Frontend verify / verify (pull_request) Successful in 3m59s
Frontend security / security (push) Successful in 18s
Frontend verify / verify (push) Successful in 9m45s
2026-09-16 20:08:51 +03:00
282 changed files with 15116 additions and 5321 deletions
+21 -12
View File
@@ -51,31 +51,40 @@ Cross-slice consumer использует `@/` и `index.ts` владельца,
композиция принадлежит вышележащему owner. Existing меж-slice исключения композиция принадлежит вышележащему owner. Existing меж-slice исключения
не являются разрешением добавлять новые. не являются разрешением добавлять новые.
Направление зависимостей и public imports частично проверяет Направление зависимостей, public imports и запрет соседних slices в
`npm run deps`; Knip проверяет использование exports, а не смысл placement. `pages`, `features`, `entities` проверяет `npm run deps`. Внутренние imports
одного slice и связи shared segments этот запрет не ограничивает.
Knip проверяет использование exports, а не смысл placement.
## UI foundation ## UI foundation
`shared/theme/tokens.json` — переносимый source design tokens; `theme.ts` Private workspace `packages/tokens` экспортирует переносимый source design tokens
как `@wealthledger/tokens/tokens.json`. Private workspace `packages/ui`
адаптирует доверенный JSON к Mantine без runtime schema. App и Storybook читают адаптирует доверенный JSON к Mantine без runtime schema. App и Storybook читают
public API `shared/theme`. Storybook показывает synthetic presentation states, `@wealthledger/ui/theme` и явно подключают `@wealthledger/ui/styles.css` после
Mantine CSS. Потребители используют public exports пакетов напрямую. Storybook показывает synthetic presentation states,
не использует application API. RTL/MSW проверяют поведение приложения отдельно. не использует application API. RTL/MSW проверяют поведение приложения отдельно.
Existing route-aware AppShell расположен в shared/ui; это legacy placement, Route-aware AppShell и его navigation styles принадлежат `app/ui`;
а не образец нового shared primitive. При изменении foundation прочитай `ProtectedLayout` использует public API этого владельца. При изменении foundation прочитай
[UI](conventions/ui.md#визуальная-основа) и [Storybook](conventions/storybook.md). [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](../src/shared/ui/LoadingSkeleton.tsx), а не domain widget в shared. - Общая busy-область: существующий [LoadingSkeleton](../packages/ui/src/LoadingSkeleton/LoadingSkeleton.tsx), а не domain widget в shared.
- Account-income state views: [страница](../src/pages/account-income/ui/AccountIncomePage.tsx) и её flat `components/*.view.tsx`; новый page-local filter остаётся здесь. - Account-income state views: [страница](../src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.tsx) и её `components/`; новый page-local filter остаётся здесь. Комплекты файлов группируются по [UI convention](conventions/ui.md#размещение-файлов-компонента).
- Portfolio query: [entity public API](../src/entities/portfolio/index.ts); новая UI-сводка с бизнес-смыслом не становится shared только из-за нескольких экранов. - Portfolio query: [entity public API](../src/entities/portfolio/index.ts); новая UI-сводка с бизнес-смыслом не становится shared только из-за нескольких экранов.
## Проверка ## Проверка
После placement/import change: `npm run deps`, `npm run typecheck`, `npm run knip`; После placement/import change: `npm run deps`, `npm run typecheck`, `npm run knip`;
после собственного behavior — применимые tests. Финальный gate указан в AGENTS. после собственного behavior — применимые tests. Финальный gate указан в AGENTS.
Existing dependency config не запрещает все same-layer imports: их и смысл Graph `src` и `packages` проверяет текущий dependency-cruiser; зависимости
owner проверяет review. Не объявляй Steiger установленным; graph проверяет из packages в код приложения `src` запрещены. Generated `packages/*/dist`
текущий dependency-cruiser. Review отдельно проверяет смысл owner: разрешённый dependency graph не доказывает не анализируется как исходник; все package sources остаются в graph. Review отдельно проверяет смысл
правильный выбор слоя. owner: разрешённый dependency graph не доказывает правильный выбор слоя.
+4 -1
View File
@@ -1,5 +1,8 @@
# Storybook # Storybook
Единый каталог включает stories приложения и `packages/*/src`; общие
StateView/LoadingSkeleton и их stories принадлежат `packages/ui`.
## Когда нужна story ## Когда нужна story
- Shared UI/theme: показывай принятые visual roles и переиспользуемое поведение. - Shared UI/theme: показывай принятые visual roles и переиспользуемое поведение.
@@ -23,7 +26,7 @@ Stories не достигают application API, auth, VM и query providers д
контракт: keyboard activation, доступность действия, local callback. Не повторяй контракт: keyboard activation, доступность действия, local callback. Не повторяй
RTL suite и не тестируй внутренности Mantine. Существующий RTL suite и не тестируй внутренности Mantine. Существующий
[Button](../../src/shared/ui/Button.stories.tsx) показывает themed control [Button](../../src/shared/ui/Button.stories.tsx) показывает themed control
без production wrapper; [LoadingSkeleton](../../src/shared/ui/LoadingSkeleton.stories.tsx) без production wrapper; [LoadingSkeleton](../../packages/ui/src/LoadingSkeleton/LoadingSkeleton.stories.tsx)
— значимые busy states. — значимые busy states.
`npm run typecheck`, `npm run deps:storybook`, `npm run build:catalog` проверяют `npm run typecheck`, `npm run deps:storybook`, `npm run build:catalog` проверяют
+1 -1
View File
@@ -45,7 +45,7 @@ Finance: loading/error/empty/loaded, cached snapshot при refetch failure, ret
отсутствие старых данных после session/connection switch. ErrorBoundary: test-only отсутствие старых данных после session/connection switch. ErrorBoundary: test-only
throwing route, безопасная ссылка и reset после navigation. throwing route, безопасная ссылка и reset после navigation.
Примеры: [AuthForm test](../../src/features/auth/ui/AuthForm.test.tsx), Примеры: [AuthForm test](../../src/features/auth/ui/AuthForm/AuthForm.test.tsx),
[client test](../../src/shared/api/client.test.ts), [client test](../../src/shared/api/client.test.ts),
[usePortfolio test](../../src/entities/portfolio/api/usePortfolio.test.tsx). [usePortfolio test](../../src/entities/portfolio/api/usePortfolio.test.tsx).
Не копируй fixtures/сценарии целиком, если задача затрагивает один исход. Не копируй fixtures/сценарии целиком, если задача затрагивает один исход.
+55 -10
View File
@@ -12,8 +12,11 @@ Mantine component и общую тему. Для выпадающего выбо
Семантический HTML для структуры страницы остаётся уместным. Семантический HTML для структуры страницы остаётся уместным.
Icons ищи у существующего owner (например, Icons ищи у существующего owner (например,
[BankOperationIcon](../../src/entities/bank-card/ui/BankOperationIcon.tsx)); [BankOperationIcon](../../src/entities/bank-card/ui/BankOperationIcon/BankOperationIcon.tsx));
общая icon library сейчас не принята. Не добавляй пакет ради одного символа. Business/domain статичные 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, даже при повторном использовании. components живут у feature/entity/page, даже при повторном использовании.
Wrapper нужен для проектной ответственности, а не ради нового имени Wrapper нужен для проектной ответственности, а не ради нового имени
@@ -53,11 +56,34 @@ retry callbacks, domain grouping и derived presentation data. View получа
image fallback) и formatter одного переданного значения. Группировка/доли image fallback) и formatter одного переданного значения. Группировка/доли
коллекции готовятся в VM. Перенос fetch во view ради меньшего container нарушает границу. коллекции готовятся в VM. Перенос fetch во view ради меньшего container нарушает границу.
Отдельный state/section с самостоятельной responsibility выноси в flat Отдельный state/section с самостоятельной responsibility выноси в
`components/*.view.tsx`. Небольшой tightly-coupled renderer оставляй рядом. `components/` своего component. Небольшой tightly-coupled renderer оставляй
Не создавай folder/barrel/test/CSS для каждого view и не дроби по line count. рядом; размер файла сам по себе не требует разделения.
Пример: [AccountIncomePage](../../src/pages/account-income/ui/AccountIncomePage.tsx) Пример: [AccountIncomePage](../../src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.tsx)
и [его VM](../../src/pages/account-income/ui/AccountIncomePage.vm.ts). и [его VM](../../src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.vm.ts).
## Размещение файлов компонента
Правило действует в `src` и `packages`: компонент с сопутствующими файлами
(view, VM, types, CSS, tests, stories) размещай в папке `Component/`.
Сохраняй полные имена файлов: `Component.tsx`, `Component.view.tsx`,
`Component.test.tsx`. Создавай только нужные файлы; одиночный компонент
оставляй непосредственно в `ui`, `components` или source-каталоге пакета.
Внутренние части принадлежат папке родителя; для набора state/section views
используй её `components/`. Внутри него действует то же правило: отдельная
папка объединяет комплект файлов, одиночный view остаётся файлом.
Стили и хуки нескольких соседних компонентов остаются у ближайшего общего
владельца; не копируй их и не прячь внутрь одного потребителя.
Папка компонента не создаёт новую FSD-границу. Публичные exports остаются в
существующем `index.ts` slice/segment или entry пакета; внутри используй
прямые относительные imports без дополнительных barrels на каждый компонент.
При переносе обновляй imports, ссылки документации и проверки, зависящие от пути.
Пример: [BankCardForm](../../src/entities/bank-card/ui/BankCardForm/BankCardForm.tsx)
лежит рядом со своим view, тестом и story; общий `BankForms.module.css`
остаётся в `bank-card/ui`.
## Формы ## Формы
@@ -107,10 +133,29 @@ loading/error/empty/loaded и recovery по применимости. [Storybook
## Визуальная основа ## Визуальная основа
Общая тема живёт в `src/shared/theme`: `tokens.json` задаёт переносимые значения, Private workspace `packages/tokens` владеет переносимыми значениями
`theme.ts` адаптирует их к Mantine. Используй public API темы и её semantic roles, `tokens.json`; `packages/ui/src/theme.ts` читает export пакета
без отдельной палитры в page/component. Поддерживается светлая схема. `@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. Цвет дополняет подпись или знак; проверяй контраст конкретной пары text/background.
Warning не используй для мелкого текста на белом. Деньги сохраняют валюту, знак Warning не используй для мелкого текста на белом. Деньги сохраняют валюту, знак
и различие между нулём и неизвестной суммой. Общие состояния демонстрирует и различие между нулём и неизвестной суммой. Общие состояния демонстрирует
Storybook; presentation stories используют synthetic data без application API. 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`; вывод о разделении фаз
банковских форм на этот сценарий автоматически не распространяется.
+27
View File
@@ -13,3 +13,30 @@
!public/** !public/**
!docker/ !docker/
!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
+9 -7
View File
@@ -12,7 +12,7 @@ jobs:
publish: publish:
runs-on: ubuntu-latest runs-on: ubuntu-latest
env: env:
IMAGE: git.personal.ksv741.ru/wealthledger/frontend IMAGE: nexus.personal.ksv741.ru/docker-hosted/wealthledger/frontend
RELEASE_TAG: ${{ gitea.ref_name }} RELEASE_TAG: ${{ gitea.ref_name }}
REVISION: ${{ gitea.sha }} REVISION: ${{ gitea.sha }}
DOCKER_CONFIG: ${{ runner.temp }}/wealthledger-frontend-docker DOCKER_CONFIG: ${{ runner.temp }}/wealthledger-frontend-docker
@@ -33,27 +33,29 @@ jobs:
- run: npm run verify - run: npm run verify
env: env:
KNIP_DISABLE_RAW_TRANSFER: '1' KNIP_DISABLE_RAW_TRANSFER: '1'
- name: Login with dedicated package writer - name: Login with dedicated Nexus writer
env: env:
REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }} REGISTRY_USERNAME: ${{ secrets.NEXUS_USERNAME }}
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} REGISTRY_TOKEN: ${{ secrets.NEXUS_PASSWORD }}
run: | run: |
test -n "$REGISTRY_USERNAME" && test -n "$REGISTRY_TOKEN" test -n "$REGISTRY_USERNAME" && test -n "$REGISTRY_TOKEN"
install -d -m 700 "$DOCKER_CONFIG" install -d -m 700 "$DOCKER_CONFIG"
printf '%s' "$REGISTRY_TOKEN" | docker login git.personal.ksv741.ru --username "$REGISTRY_USERNAME" --password-stdin printf '%s' "$REGISTRY_TOKEN" | docker login nexus.personal.ksv741.ru --username "$REGISTRY_USERNAME" --password-stdin
- name: Publish immutable release tag - name: Publish immutable release tag
run: | run: |
VERSION="${RELEASE_TAG#v}" VERSION="${RELEASE_TAG#v}"
if docker manifest inspect "$IMAGE:$VERSION" >/dev/null 2>manifest-error.log; then if docker manifest inspect "$IMAGE:$VERSION" >/dev/null 2>manifest-error.log; then
echo 'Refusing to overwrite an existing release tag'; exit 1 DIGEST="$(docker buildx imagetools inspect "$IMAGE:$VERSION" --format '{{.Manifest.Digest}}')"
fi else
if ! grep -Eq 'manifest unknown|no such manifest' manifest-error.log; then if ! grep -Eq 'manifest unknown|no such manifest' manifest-error.log; then
echo 'Cannot prove tag absence; refusing publication'; exit 1 echo 'Cannot prove tag absence; refusing publication'; exit 1
fi fi
docker buildx build --target production --build-arg VERSION="$VERSION" --build-arg REVISION="$REVISION" --tag "$IMAGE:$VERSION" --metadata-file image-metadata.json --push . 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"]')" DIGEST="$(node --input-type=commonjs -p 'require("./image-metadata.json")["containerimage.digest"]')"
fi
docker pull "$IMAGE@$DIGEST" 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.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/' 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" printf 'Frontend image: %s@%s\n' "$IMAGE" "$DIGEST"
- name: Remove registry session - name: Remove registry session
+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
@@ -9,7 +9,7 @@ module.exports = {
severity: "error", severity: "error",
from: { path: "\\.stories\\.tsx$|^\\.storybook/preview\\.tsx$" }, from: { path: "\\.stories\\.tsx$|^\\.storybook/preview\\.tsx$" },
to: { to: {
path: "^src/(shared/api|features/auth|app/routes|app/ui)/|^src/(entities|features)/[^/]+/api/|\\.vm\\.ts$|^src/pages/[^/]+/ui/[^/]+Page\\.tsx$|node_modules/(@tanstack/react-query|openapi-fetch|openapi-react-query)/", path: "^src/(shared/api|features/auth|app/routes|app/ui)/|^src/(entities|features)/[^/]+/api/|\\.vm\\.ts$|^src/pages/[^/]+/ui/.*Page\\.tsx$|node_modules/(@tanstack/react-query|openapi-fetch|openapi-react-query)/",
reachable: true, reachable: true,
}, },
}, },
+1 -1
View File
@@ -1,7 +1,7 @@
import type { StorybookConfig } from "@storybook/react-vite"; import type { StorybookConfig } from "@storybook/react-vite";
const config: StorybookConfig = { const config: StorybookConfig = {
stories: ["../src/**/*.stories.tsx"], stories: ["../src/**/*.stories.tsx", "../packages/*/src/**/*.stories.tsx"],
addons: ["@storybook/addon-docs"], addons: ["@storybook/addon-docs"],
framework: "@storybook/react-vite", framework: "@storybook/react-vite",
core: { disableTelemetry: true }, core: { disableTelemetry: true },
+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,
+47
View File
@@ -1,5 +1,52 @@
# Changelog # Changelog
## [0.4.0](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.3.0...v0.4.0) (2026-09-26)
### Features
* show persisted investment data and sync state ([4e5f564](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/4e5f564fa1d583013fb3e7febdb3baa9737446b4))
### Bug Fixes
* **api:** update validation and conflict response contract ([db184c8](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/db184c8caec01609e8a3df3b16097ce634e5eff0))
* **auth:** isolate session races and financial caches ([a209d71](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/a209d715892862bb6d48084df0c84a10b8d56bf1))
* **ci:** resume verification of immutable release images ([6a87379](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/6a87379813ba1d4002779b23b2a65446b4d10258))
* **ui:** improve financial text contrast ([c86be7b](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/c86be7bf73d0141e0606d259ada6453c0d8e3dec))
### Refactoring
* colocate frontend component files ([b987fd8](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/b987fd8e780963dfe1dde0c714232697a52e0475))
* establish local frontend workspace boundaries ([85fcfe3](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/85fcfe3d073f80e759dafb14281c9462c1d7410d))
## [0.3.0](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.2.3...v0.3.0) (2026-09-20)
### Features
* add installable PWA [#30](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/30) ([bb30935](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/bb30935f73bfcbb77c10663cf6c683d8f0caca85))
## [0.2.3](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.2.2...v0.2.3) (2026-09-19)
### Bug Fixes
* correct Nexus routing and SonarQube host ([9171b9f](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/9171b9f5c8e0b694a2310e5a200fa2f8d3f28a61))
## [0.2.2](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.2.1...v0.2.2) (2026-09-19)
### Bug Fixes
* update Nexus registry host ([bac95eb](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/bac95ebb392febb667a9fc2f1fa4f06fa110d685))
## [0.2.1](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.2.0...v0.2.1) (2026-09-18)
### Documentation
* use shared Nexus account [#21](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/21) ([1ad578f](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/1ad578fb37b8dd6161dc362541d9c0cd0b008b75))
### CI
* add frontend SonarQube analysis [#19](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/19) ([3f19b36](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/3f19b3643f88e36d10e7c374262351f61947ed47))
* publish frontend images to Nexus [#21](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/21) ([999b859](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/999b8590ecd0a551da628c349d005ebb9b318883))
## [0.2.0](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.1.0...v0.2.0) (2026-09-16) ## [0.2.0](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.1.0...v0.2.0) (2026-09-16)
### Features ### Features
+4
View File
@@ -2,10 +2,14 @@ FROM node:24.21.0-bookworm-slim AS dependencies
WORKDIR /app WORKDIR /app
ENV HUSKY=0 ENV HUSKY=0
COPY package.json package-lock.json ./ 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 RUN npm ci
FROM dependencies AS development FROM dependencies AS development
COPY . . COPY . .
RUN npm run build:packages
ENV VITE_API_BASE_URL="" API_PROXY_TARGET=http://backend:3000 ENV VITE_API_BASE_URL="" API_PROXY_TARGET=http://backend:3000
EXPOSE 8080 EXPOSE 8080
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "8080", "--strictPort"] CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "8080", "--strictPort"]
+94 -5
View File
@@ -28,7 +28,8 @@ staged diff с полной редакцией секретов, затем за
`Dockerfile` имеет targets `development` (Vite HMR и proxy `/api/` во внутренний backend) `Dockerfile` имеет targets `development` (Vite HMR и proxy `/api/` во внутренний backend)
и `production` (nginx на 8080, SPA fallback и same-origin API proxy). Node соответствует `.nvmrc`. и `production` (nginx на 8080, SPA fallback и same-origin API proxy). Node соответствует `.nvmrc`.
Build context ограничен `.dockerignore`; `.env`, local DB и host node_modules Build context ограничен `.dockerignore`; `.env`, local DB и host node_modules
не попадают в image. не попадают в image. Изменение `packages/tokens` или `packages/ui` требует rebuild development
image, если локальный запуск использует bind-mount только `src`/`public`.
```bash ```bash
docker build --target development -t wealthledger-frontend:development . docker build --target development -t wealthledger-frontend:development .
@@ -37,10 +38,13 @@ docker build --target production -t wealthledger-frontend:production .
Gitea `image.yml` запускается на защищённом release tag `vX.Y.Z`, проверяет Gitea `image.yml` запускается на защищённом release tag `vX.Y.Z`, проверяет
package/lock version и canonical gates. Runner `ubuntu-latest` должен иметь package/lock version и canonical gates. Runner `ubuntu-latest` должен иметь
Docker/buildx. Dedicated package writer задаётся Actions secrets Docker/buildx. Образы хранятся в Nexus:
`REGISTRY_USERNAME`/`REGISTRY_TOKEN`; server использует отдельную read-only `nexus.personal.ksv741.ru/docker-hosted/wealthledger/frontend`. Пользователь `wealthledger-ci`
identity. Публикуются semver tags, без `latest`; существующие задаётся Actions secrets `NEXUS_USERNAME`/`NEXUS_PASSWORD`; эта же учётная
release tags не перезаписываются. Production выбирает опубликованный version tag. запись используется сервером для загрузки образов. Docker endpoint и token realm должны использовать
HTTPS; в `docker-hosted` включается запрет redeploy. Прежние Gitea secrets
сохраняются на время перехода и не передаются в Nexus.
Публикуются semver tags, без `latest`; существующие release tags не перезаписываются. Production выбирает опубликованный version tag.
Compose topology принадлежит workspace, эксплуатационная последовательность — Compose topology принадлежит workspace, эксплуатационная последовательность —
[документация](https://git.personal.ksv741.ru/WealthLedger/docs), [документация](https://git.personal.ksv741.ru/WealthLedger/docs),
@@ -48,6 +52,25 @@ Compose topology принадлежит workspace, эксплуатационн
Проверка публикации требует настроенного registry/runner; локальный build Проверка публикации требует настроенного registry/runner; локальный build
не доказывает package permissions. не доказывает 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
@@ -74,6 +97,42 @@ 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`; статическая сборка —
@@ -136,3 +195,33 @@ Commits и PR titles — Conventional Commits, включая `spec:`. Верс
администратором, обязательны `verify`, `security`, `commits`; теги `v*` защищены. администратором, обязательны `verify`, `security`, `commits`; теги `v*` защищены.
Workflow сам не включает эти настройки. Отдельное review approval для одного Workflow сам не включает эти настройки. Отдельное review approval для одного
владельца не требуется. Npm publishing, deploy и Gitea Releases не включены. владельца не требуется. 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,
+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.2.0", "version": "0.4.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) {
@@ -0,0 +1,37 @@
import { Button } from "@mantine/core";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { fn } from "storybook/test";
import { EntryCard } from "./EntryCard";
const meta = {
title: "Design System/Components/EntryCard",
component: EntryCard,
tags: ["autodocs"],
args: {
title:
"Учебная запись с очень длинным названием для проверки узкого экрана",
metadata: "22.09.2026 · Синтетические данные",
initial: "У",
imageSrc: "data:image/png;base64,invalid",
value: "−1 250,00 ₽",
valueLabel: "Тестовое значение",
tone: "negative",
actions: (
<Button size="compact-sm" onClick={fn()}>
Открыть пример
</Button>
),
},
parameters: {
docs: {
description: {
component:
"Готовые строки и slots без финансовых вычислений. Невалидное локальное изображение показывает fallback; действие доступно с клавиатуры и на узком экране. Данные вымышлены.",
},
},
},
} satisfies Meta<typeof EntryCard>;
export default meta;
type Story = StoryObj<typeof meta>;
export const LongContentAndFallback: Story = {};
@@ -0,0 +1,35 @@
import { MantineProvider } from "@mantine/core";
import { fireEvent, render, screen } from "@testing-library/react";
import { assert, describe, expect, it } from "vitest";
import { EntryCard } from "./EntryCard";
describe("EntryCard", () => {
it("keeps the fallback after an image fails", () => {
const props = {
title: "Пример",
metadata: "Описание",
initial: "У",
value: "—",
valueLabel: "Неизвестно",
tone: "neutral" as const,
imageSrc: "data:image/png;base64,invalid",
};
const { container, rerender } = render(
<MantineProvider>
<EntryCard {...props} />
</MantineProvider>,
);
// Decorative image has no accessible name; trigger its actual failure event.
const image = container.querySelector("img");
assert(image);
fireEvent.error(image);
rerender(
<MantineProvider>
<EntryCard {...props} title="Обновлённый пример" />
</MantineProvider>,
);
expect(container.querySelector("img")).toBeNull();
expect(screen.getByText("У")).toBeInTheDocument();
expect(screen.getByText("Обновлённый пример")).toBeInTheDocument();
});
});
@@ -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,7 +1,7 @@
import { MantineProvider } from "@mantine/core"; import { MantineProvider } from "@mantine/core";
import { render, screen } from "@testing-library/react"; import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { LoadingSkeleton } from "./LoadingSkeleton"; import { LoadingSkeleton } from "../LoadingSkeleton/LoadingSkeleton";
import { StateView } from "./StateView"; import { StateView } from "./StateView";
describe("StateView", () => { describe("StateView", () => {
+3
View File
@@ -0,0 +1,3 @@
export { EntryCard } from "./EntryCard/EntryCard";
export { LoadingSkeleton } from "./LoadingSkeleton/LoadingSkeleton";
export { StateView } from "./StateView/StateView";
@@ -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
@@ -16,6 +16,7 @@ import type { IncomeAnalytics } from "@/entities/income";
import type { Portfolio } from "@/entities/portfolio"; import type { Portfolio } from "@/entities/portfolio";
import { AuthProvider } from "@/features/auth"; import { AuthProvider } from "@/features/auth";
import { createTestQueryClient } from "@/test/query"; import { createTestQueryClient } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server"; import { server } from "@/test/server";
import { AppRoutes } from "./AppRoutes"; import { AppRoutes } from "./AppRoutes";
@@ -132,6 +133,7 @@ beforeEach(() => {
), ),
http.get("*/api/v1/brokerage-accounts", () => http.get("*/api/v1/brokerage-accounts", () =>
HttpResponse.json( HttpResponse.json(
resource(
accounts.map((account) => ({ accounts.map((account) => ({
...account, ...account,
type: "BROKERAGE", type: "BROKERAGE",
@@ -140,13 +142,15 @@ beforeEach(() => {
})), })),
), ),
), ),
),
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () => http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
HttpResponse.json(portfolio), HttpResponse.json(resource(portfolio)),
), ),
http.get( http.get(
"*/api/v1/brokerage-accounts/:accountId/operations", "*/api/v1/brokerage-accounts/:accountId/operations",
({ params }) => ({ params }) =>
HttpResponse.json({ HttpResponse.json(
resource({
accountId: params.accountId, accountId: params.accountId,
items, items,
hasNext: false, hasNext: false,
@@ -154,11 +158,13 @@ beforeEach(() => {
observedAt: receipt.occurredAt, observedAt: receipt.occurredAt,
}), }),
), ),
),
http.get("*/api/v1/brokerage-accounts/:accountId/income-analytics", () => http.get("*/api/v1/brokerage-accounts/:accountId/income-analytics", () =>
HttpResponse.json(analytics), HttpResponse.json(resource(analytics)),
), ),
http.get("*/api/v1/brokerage-accounts/:accountId/events", () => http.get("*/api/v1/brokerage-accounts/:accountId/events", () =>
HttpResponse.json({ HttpResponse.json(
resource({
accountId: "all", accountId: "all",
calculatedAt: receipt.occurredAt, calculatedAt: receipt.occurredAt,
incomeTotalsByCurrency: [], incomeTotalsByCurrency: [],
@@ -177,6 +183,7 @@ beforeEach(() => {
})), })),
}), }),
), ),
),
); );
}); });
@@ -224,7 +231,8 @@ describe("All accounts routes", () => {
({ request, params }) => { ({ request, params }) => {
const url = new URL(request.url); const url = new URL(request.url);
requests.push(url); requests.push(url);
return HttpResponse.json({ return HttpResponse.json(
resource({
accountId: params.accountId, accountId: params.accountId,
items: [ items: [
{ {
@@ -237,7 +245,8 @@ describe("All accounts routes", () => {
hasNext: !url.searchParams.has("cursor"), hasNext: !url.searchParams.has("cursor"),
nextCursor: url.searchParams.has("cursor") ? null : "next", nextCursor: url.searchParams.has("cursor") ? null : "next",
observedAt: receipt.occurredAt, observedAt: receipt.occurredAt,
}); }),
);
}, },
), ),
); );
@@ -274,7 +283,8 @@ describe("All accounts routes", () => {
{ code: "INVALID_OPERATIONS_CURSOR" }, { code: "INVALID_OPERATIONS_CURSOR" },
{ status: 400 }, { status: 400 },
) )
: HttpResponse.json({ : HttpResponse.json(
resource({
accountId: "all", accountId: "all",
items, items,
hasNext: true, hasNext: true,
@@ -282,6 +292,7 @@ describe("All accounts routes", () => {
observedAt: receipt.occurredAt, observedAt: receipt.occurredAt,
}), }),
), ),
),
); );
renderPage("/accounts/all/operations?from=2026-08-01&to=2026-08-31"); renderPage("/accounts/all/operations?from=2026-08-01&to=2026-08-31");
await screen.findAllByText("Выплата купона"); await screen.findAllByText("Выплата купона");
@@ -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,8 +1,8 @@
import type { FC } from "react"; import type { FC } from "react";
import { lazy } from "react"; import { lazy } from "react";
import { Navigate, Route, Routes } from "react-router"; import { Navigate, Route, Routes } from "react-router";
import { LazyPage } from "./RouteFallback"; import { LazyPage } from "../RouteFallback";
import { Protected, Public } from "./RouteGuards"; import { Protected, Public } from "../RouteGuards";
const CardPage = lazy(async () => { const CardPage = lazy(async () => {
const { CardPage } = await import("@/pages/card"); const { CardPage } = await import("@/pages/card");
@@ -65,7 +65,7 @@ const SettingsPage = lazy(async () => {
return { default: SettingsPage }; return { default: SettingsPage };
}); });
const ProtectedLayout = lazy(async () => { const ProtectedLayout = lazy(async () => {
const { ProtectedLayout } = await import("./ProtectedLayout"); const { ProtectedLayout } = await import("../ProtectedLayout");
return { default: ProtectedLayout }; return { default: ProtectedLayout };
}); });
@@ -12,6 +12,7 @@ import { MemoryRouter, useNavigate } from "react-router";
import { beforeEach, describe, expect, it } from "vitest"; import { beforeEach, describe, expect, it } from "vitest";
import { AuthProvider } from "@/features/auth"; import { AuthProvider } from "@/features/auth";
import { createTestQueryClient } from "@/test/query"; import { createTestQueryClient } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server"; import { server } from "@/test/server";
import { ProtectedDocumentTitle } from "./DocumentTitle"; import { ProtectedDocumentTitle } from "./DocumentTitle";
@@ -62,7 +63,7 @@ describe("document titles", () => {
server.use( server.use(
http.get("*/api/v1/brokerage-accounts", async () => { http.get("*/api/v1/brokerage-accounts", async () => {
await accountsReady; await accountsReady;
return HttpResponse.json([{ id: "a", name: "ИИС" }]); return HttpResponse.json(resource([{ id: "a", name: "ИИС" }]));
}), }),
); );
renderTitle("/accounts/a/income?from=2026-01-01&to=2026-08-31"); renderTitle("/accounts/a/income?from=2026-01-01&to=2026-08-31");
@@ -85,7 +86,7 @@ describe("document titles", () => {
async (kind, id, fallback, name) => { async (kind, id, fallback, name) => {
server.use( server.use(
http.get(`*/api/v1/${kind}/by-ticker/:ticker`, () => http.get(`*/api/v1/${kind}/by-ticker/:ticker`, () =>
HttpResponse.json({ name }), HttpResponse.json(resource({ name })),
), ),
); );
renderTitle(`/${kind}/${id}`); renderTitle(`/${kind}/${id}`);
+2 -3
View File
@@ -1,7 +1,6 @@
import type { FC } from "react"; import type { FC } from "react";
import { AppBreadcrumbs } from "@/app/ui"; import { AppBreadcrumbs, AppShell } from "@/app/ui";
import { AppShell } from "@/shared/ui"; import { ProtectedDocumentTitle } from "./DocumentTitle/DocumentTitle";
import { ProtectedDocumentTitle } from "./DocumentTitle";
const ProtectedLayout: FC = () => { const ProtectedLayout: FC = () => {
return ( return (
+2 -2
View File
@@ -1,2 +1,2 @@
export { AppRoutes } from "./AppRoutes"; export { AppRoutes } from "./AppRoutes/AppRoutes";
export { RouteErrorBoundary } from "./RouteErrorBoundary"; export { RouteErrorBoundary } from "./RouteErrorBoundary/RouteErrorBoundary";
+1 -1
View File
@@ -1,11 +1,11 @@
import { MantineProvider } from "@mantine/core"; import { MantineProvider } from "@mantine/core";
import { DatesProvider } from "@mantine/dates"; import { DatesProvider } from "@mantine/dates";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { cssVariablesResolver, theme } from "@wealthledger/ui/theme";
import type { FC } from "react"; import type { FC } from "react";
import { BrowserRouter } from "react-router"; import { BrowserRouter } from "react-router";
import { AppRoutes, RouteErrorBoundary } from "@/app/routes"; import { AppRoutes, RouteErrorBoundary } from "@/app/routes";
import { AuthProvider } from "@/features/auth"; import { AuthProvider } from "@/features/auth";
import { cssVariablesResolver, theme } from "@/shared/theme";
const queryClient = new QueryClient({ const queryClient = new QueryClient({
defaultOptions: { defaultOptions: {
@@ -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 = {
+2 -1
View File
@@ -1 +1,2 @@
export { AppBreadcrumbs } from "./AppBreadcrumbs"; export { AppBreadcrumbs } from "./AppBreadcrumbs/AppBreadcrumbs";
export { AppShell } from "./AppShell/AppShell";
+6 -5
View File
@@ -18,12 +18,13 @@ 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/BankCardFace";
export { BankCardForm } from "./ui/BankCardForm"; export { BankCardForm } from "./ui/BankCardForm/BankCardForm";
export { BankFeedback } from "./ui/BankFeedback"; export { BankFeedback } from "./ui/BankFeedback";
export { BankOperationIcon } from "./ui/BankOperationIcon"; export { BankOperationIcon } from "./ui/BankOperationIcon/BankOperationIcon";
export { BankPeriodPicker } from "./ui/BankPeriodPicker"; export { BankPeriodPicker } from "./ui/BankPeriodPicker";
export { BankSummaryView } from "./ui/BankSummary.view"; export { BankSummaryView } from "./ui/BankSummary/BankSummary.view";
export { CategoryManager } from "./ui/CategoryManager"; export { CategoryManager } from "./ui/CategoryManager/CategoryManager";
export { useBankFormFocus } from "./ui/useBankFormFocus"; export { useBankFormFocus } from "./ui/useBankFormFocus";
@@ -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,7 +1,7 @@
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { formatMoney } from "@/shared/lib"; import { formatMoney } from "@/shared/lib";
import type { BankCard } from "../api/queries"; import type { BankCard } from "../../api/queries";
import classes from "./BankCardFace.module.css"; import classes from "./BankCardFace.module.css";
type BankCardFaceProps = { card: BankCard }; type BankCardFaceProps = { card: BankCard };
@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from "@storybook/react-vite"; import type { Meta, StoryObj } from "@storybook/react-vite";
import { FormProvider, useForm } from "react-hook-form"; import { FormProvider, useForm } from "react-hook-form";
import type { BankCardValues } from "../model/form-validation"; import type { BankCardValues } from "../../model/form-validation";
import { BankCardFields } from "./BankCardForm.view"; import { BankCardFields } from "./BankCardForm.view";
const meta = { const meta = {
@@ -6,7 +6,7 @@ import { describe, expect, it, vi } from "vitest";
import { configureAuthClient } from "@/shared/api"; import { configureAuthClient } from "@/shared/api";
import { createTestQueryClient } from "@/test/query"; import { createTestQueryClient } from "@/test/query";
import { server } from "@/test/server"; import { server } from "@/test/server";
import type { BankCard } from "../api/queries"; import type { BankCard } from "../../api/queries";
import { BankCardForm } from "./BankCardForm"; import { BankCardForm } from "./BankCardForm";
const card: BankCard = { const card: BankCard = {
@@ -4,18 +4,18 @@ import { type FC, useState } from "react";
import { FormProvider, useForm } from "react-hook-form"; import { FormProvider, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { formatDate } from "@/shared/lib"; import { formatDate } from "@/shared/lib";
import { useBankMutations } from "../api/mutations"; import { useBankMutations } from "../../api/mutations";
import { type BankCard, useBankCard } from "../api/queries"; import { type BankCard, useBankCard } from "../../api/queries";
import { import {
type BankCardValues, type BankCardValues,
bankCardSchema, bankCardSchema,
bankMoneyValue, bankMoneyValue,
bankToday, bankToday,
} from "../model/form-validation"; } from "../../model/form-validation";
import { BankFeedback } from "../BankFeedback";
import classes from "../BankForms.module.css";
import { useBankFormFocus } from "../useBankFormFocus";
import { BankCardFields } from "./BankCardForm.view"; import { BankCardFields } from "./BankCardForm.view";
import { BankFeedback } from "./BankFeedback";
import classes from "./BankForms.module.css";
import { useBankFormFocus } from "./useBankFormFocus";
type BankCardFormProps = { card?: BankCard; onClose: () => void }; type BankCardFormProps = { card?: BankCard; onClose: () => void };
const BankCardForm: FC<BankCardFormProps> = (props) => { const BankCardForm: FC<BankCardFormProps> = (props) => {
@@ -8,7 +8,7 @@ import {
bankDateInputValue, bankDateInputValue,
bankDateSchema, bankDateSchema,
bankToday, bankToday,
} from "../model/form-validation"; } from "../../model/form-validation";
type BankCardFieldsProps = { archived: boolean }; type BankCardFieldsProps = { archived: boolean };
const BankCardFields: FC<BankCardFieldsProps> = (props) => { const BankCardFields: FC<BankCardFieldsProps> = (props) => {
@@ -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 type { FC } from "react"; import type { FC } from "react";
import { bindIconAnimation } from "@/shared/lib"; import { bindIconAnimation } from "@/shared/lib";
import type { BankOperation } from "../api/queries"; import type { BankOperation } from "../../api/queries";
import { bankOperationAppearance } from "../model/operation-appearance"; import { bankOperationAppearance } from "../../model/operation-appearance";
import classes from "./BankOperationIcon.module.css"; import classes from "./BankOperationIcon.module.css";
type BankOperationIconProps = { type BankOperationIconProps = {
@@ -1,10 +1,10 @@
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/BankOperationIcon";
import { BankOperationIcon } from "./BankOperationIcon";
import classes from "./BankSummary.module.css"; import classes from "./BankSummary.module.css";
type BankSummaryViewProps = { type BankSummaryViewProps = {
@@ -18,12 +18,12 @@ import {
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { z } from "zod"; import { z } from "zod";
import { validationMessage } from "@/shared/i18n"; import { validationMessage } from "@/shared/i18n";
import { useBankMutations } from "../api/mutations"; import { useBankMutations } from "../../api/mutations";
import { type ExpenseCategory, useBankCategories } from "../api/queries"; import { type ExpenseCategory, useBankCategories } from "../../api/queries";
import { BankFeedback } from "./BankFeedback"; import { BankFeedback } from "../BankFeedback";
import classes from "./BankForms.module.css"; import classes from "../BankForms.module.css";
import { BankOperationIcon } from "./BankOperationIcon"; import { BankOperationIcon } from "../BankOperationIcon/BankOperationIcon";
import { useBankFormFocus } from "./useBankFormFocus"; import { useBankFormFocus } from "../useBankFormFocus";
const MAX_CATEGORY_NAME_LENGTH = 80; const MAX_CATEGORY_NAME_LENGTH = 80;
+11 -13
View File
@@ -1,8 +1,4 @@
import { import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
apiQueryClient,
type paths,
useAuthenticatedQuery,
} from "@/shared/api";
type BondPeriod = NonNullable< type BondPeriod = NonNullable<
NonNullable< NonNullable<
@@ -13,7 +9,7 @@ type BondPeriod = NonNullable<
const BOND_STALE_TIME_MS = 30_000; const BOND_STALE_TIME_MS = 30_000;
function useBondSearch(query: string) { function useBondSearch(query: string) {
return useAuthenticatedQuery({ return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bonds", { ...apiQueryClient.queryOptions("get", "/api/v1/bonds", {
params: { query: { query } }, params: { query: { query } },
}), }),
@@ -36,11 +32,11 @@ function useBond(identifier: string) {
identifier, identifier,
); );
const byUid = useAuthenticatedQuery({ const byUid = useResourceQuery({
...bondQueryOptions(identifier), ...bondQueryOptions(identifier),
enabled: Boolean(identifier) && isUid, enabled: Boolean(identifier) && isUid,
}); });
const byTicker = useAuthenticatedQuery({ const byTicker = useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bonds/by-ticker/{ticker}", { ...apiQueryClient.queryOptions("get", "/api/v1/bonds/by-ticker/{ticker}", {
params: { path: { ticker: identifier } }, params: { path: { ticker: identifier } },
}), }),
@@ -50,7 +46,7 @@ function useBond(identifier: string) {
return isUid ? byUid : byTicker; return isUid ? byUid : byTicker;
} }
function useBondMetrics(uid: string) { function useBondMetrics(uid: string) {
return useAuthenticatedQuery({ return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/metrics", { ...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/metrics", {
params: { path: { uid } }, params: { path: { uid } },
}), }),
@@ -59,7 +55,7 @@ function useBondMetrics(uid: string) {
}); });
} }
function useBondQuote(uid: string) { function useBondQuote(uid: string) {
return useAuthenticatedQuery({ return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/quote", { ...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/quote", {
params: { path: { uid } }, params: { path: { uid } },
}), }),
@@ -68,7 +64,7 @@ function useBondQuote(uid: string) {
}); });
} }
function useBondCandles(uid: string, period: BondPeriod) { function useBondCandles(uid: string, period: BondPeriod) {
return useAuthenticatedQuery({ return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/candles", { ...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/candles", {
params: { path: { uid }, query: { period } }, params: { path: { uid }, query: { period } },
}), }),
@@ -77,7 +73,8 @@ function useBondCandles(uid: string, period: BondPeriod) {
}); });
} }
function useBondPosition(uid: string) { function useBondPosition(uid: string) {
return useAuthenticatedQuery({ return useResourceQuery({
meta: { accessGroup: "brokerage" },
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/position", { ...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/position", {
params: { path: { uid } }, params: { path: { uid } },
}), }),
@@ -86,7 +83,8 @@ function useBondPosition(uid: string) {
}); });
} }
function useBondCoupons(uid: string) { function useBondCoupons(uid: string) {
return useAuthenticatedQuery({ return useResourceQuery({
meta: { accessGroup: "brokerage" },
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/coupons", { ...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/coupons", {
params: { path: { uid } }, params: { path: { uid } },
}), }),
@@ -1,16 +1,14 @@
import { import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
apiQueryClient,
type paths,
useAuthenticatedQuery,
} from "@/shared/api";
type OperationsEndpoint = type OperationsEndpoint =
paths["/api/v1/brokerage-accounts/{accountId}/operations"]["get"]; paths["/api/v1/brokerage-accounts/{accountId}/operations"]["get"];
type BrokerageOperation = type BrokerageOperation = NonNullable<
OperationsEndpoint["responses"][200]["content"]["application/json"]["items"][number]; OperationsEndpoint["responses"][200]["content"]["application/json"]["data"]
type BrokerageOperationsQuery = NonNullable< >["items"][number];
OperationsEndpoint["parameters"]["query"] type BrokerageOperationsQuery = Omit<
NonNullable<OperationsEndpoint["parameters"]["query"]>,
"sync"
>; >;
type OperationCategory = BrokerageOperation["category"]; type OperationCategory = BrokerageOperation["category"];
@@ -56,7 +54,8 @@ function useBrokerageOperations(
accountId: string | undefined, accountId: string | undefined,
query: BrokerageOperationsQuery = {}, query: BrokerageOperationsQuery = {},
) { ) {
return useAuthenticatedQuery({ return useResourceQuery({
meta: { accessGroup: "brokerage" },
...brokerageOperationsQueryOptions(accountId, query), ...brokerageOperationsQueryOptions(accountId, query),
enabled: Boolean(accountId), enabled: Boolean(accountId),
staleTime: 30_000, staleTime: 30_000,
@@ -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";
@@ -3,6 +3,7 @@ import { HttpResponse, http } from "msw";
import { describe, expect, it, vi } from "vitest"; import { describe, expect, it, vi } from "vitest";
import { configureAuthClient } from "@/shared/api"; import { configureAuthClient } from "@/shared/api";
import { createQueryWrapper } from "@/test/query"; import { createQueryWrapper } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server"; import { server } from "@/test/server";
import { useBrokerageAccounts } from "./useBrokerageAccounts"; import { useBrokerageAccounts } from "./useBrokerageAccounts";
@@ -15,7 +16,8 @@ describe("useBrokerageAccounts", () => {
}); });
server.use( server.use(
http.get("*/api/v1/brokerage-accounts", () => http.get("*/api/v1/brokerage-accounts", () =>
HttpResponse.json([ HttpResponse.json(
resource([
{ {
id: "account-1", id: "account-1",
name: "Основной", name: "Основной",
@@ -24,6 +26,7 @@ describe("useBrokerageAccounts", () => {
}, },
]), ]),
), ),
),
); );
const { result } = renderHook(() => useBrokerageAccounts(), { const { result } = renderHook(() => useBrokerageAccounts(), {
@@ -52,14 +55,16 @@ describe("useBrokerageAccounts", () => {
http.get("*/api/v1/brokerage-accounts", () => { http.get("*/api/v1/brokerage-accounts", () => {
calls += 1; calls += 1;
return calls === 1 return calls === 1
? HttpResponse.json([ ? HttpResponse.json(
resource([
{ {
id: "account-1", id: "account-1",
name: "Основной", name: "Основной",
type: "BROKERAGE", type: "BROKERAGE",
openedOn: "2024-08-13", openedOn: "2024-08-13",
}, },
]) ]),
)
: HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }); : HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 });
}), }),
); );
@@ -1,19 +1,17 @@
import { import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
apiQueryClient,
type paths,
useAuthenticatedQuery,
} from "@/shared/api";
const brokerageAccountsQueryOptions = () => const brokerageAccountsQueryOptions = () =>
apiQueryClient.queryOptions("get", "/api/v1/brokerage-accounts"); apiQueryClient.queryOptions("get", "/api/v1/brokerage-accounts");
const brokerageAccountsQueryKey = brokerageAccountsQueryOptions().queryKey; const brokerageAccountsQueryKey = brokerageAccountsQueryOptions().queryKey;
type BrokerageAccount = type BrokerageAccount = NonNullable<
paths["/api/v1/brokerage-accounts"]["get"]["responses"][200]["content"]["application/json"][number]; paths["/api/v1/brokerage-accounts"]["get"]["responses"][200]["content"]["application/json"]["data"]
>[number];
function useBrokerageAccounts() { function useBrokerageAccounts() {
return useAuthenticatedQuery({ return useResourceQuery({
meta: { accessGroup: "brokerage" },
...brokerageAccountsQueryOptions(), ...brokerageAccountsQueryOptions(),
staleTime: 60_000, staleTime: 60_000,
}); });
+1 -1
View File
@@ -8,4 +8,4 @@ export {
type BrokerageAccountCard, type BrokerageAccountCard,
brokerageAccountCards, brokerageAccountCards,
} from "./model/display"; } from "./model/display";
export { BrokerageAccountList } from "./ui/BrokerageAccountList"; export { BrokerageAccountList } from "./ui/BrokerageAccountList/BrokerageAccountList";
@@ -1,10 +1,18 @@
import type { BrokerageAccount } from "../api/useBrokerageAccounts"; import type {
BrokerageAccount,
useBrokerageAccounts,
} from "../api/useBrokerageAccounts";
type Money = NonNullable< type Money = NonNullable<
BrokerageAccount["portfolioSummary"] BrokerageAccount["portfolioSummary"]
>["totalsByCurrency"][number]; >["totalsByCurrency"][number];
type BrokerageAccountCard = { type BrokerageAccountCard = {
source?: NonNullable<
ReturnType<typeof useBrokerageAccounts>["meta"]
>["dependencies"] extends (infer T)[] | undefined
? T
: never;
account: BrokerageAccount; account: BrokerageAccount;
positionCounts: { stocks: number; bonds: number } | null; positionCounts: { stocks: number; bonds: number } | null;
summary: summary:
@@ -19,11 +27,19 @@ function accountTypeKey(type: BrokerageAccount["type"]) {
function brokerageAccountCards( function brokerageAccountCards(
accounts: BrokerageAccount[], accounts: BrokerageAccount[],
dependencies: NonNullable<
ReturnType<typeof useBrokerageAccounts>["meta"]
>["dependencies"] = [],
): BrokerageAccountCard[] { ): BrokerageAccountCard[] {
return accounts.map((account) => { return accounts.map((account) => {
const source = dependencies.find(
(item) =>
item.resourceKey === `portfolio/${encodeURIComponent(account.id)}`,
);
const summary = account.portfolioSummary; const summary = account.portfolioSummary;
if (!summary) if (!summary)
return { return {
source,
account, account,
positionCounts: null, positionCounts: null,
summary: { state: "unavailable" }, summary: { state: "unavailable" },
@@ -33,8 +49,9 @@ function brokerageAccountCards(
bonds: summary.bondPositionCount, bonds: summary.bondPositionCount,
}; };
if (!summary.totalsByCurrency.length) if (!summary.totalsByCurrency.length)
return { account, positionCounts, summary: { state: "empty" } }; return { source, account, positionCounts, summary: { state: "empty" } };
return { return {
source,
account, account,
positionCounts, positionCounts,
summary: { summary: {

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