15 Commits
Author SHA1 Message Date
ksv741 85fcfe3d07 refactor: establish local frontend workspace boundaries
Conventional commits / commits (pull_request) Successful in 24s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 5m18s
Frontend security / security (push) Successful in 10s
Frontend verify / verify (push) Successful in 6m45s
OpenSpec change: evolve-frontend-stack
2026-09-22 22:11:02 +03:00
ksv741 c86be7bf73 fix(ui): improve financial text contrast
TD-010: use readable semantic text colors on financial surfaces while preserving signs
and state meanings.
2026-09-21 21:10:10 +03:00
ksv741 6a87379813 fix(ci): resume verification of immutable release images
TD-009: retry verification of an existing digest without republishing. Paired backend
workflow fix: 82eccc3.
2026-09-21 21:09:53 +03:00
ksv741 db184c8cae fix(api): update validation and conflict response contract
TD-003 and TD-005: explicitly deliver OpenAPI and generated types from backend commit 1667991.
2026-09-21 21:09:41 +03:00
ksv741 a209d71589 fix(auth): isolate session races and financial caches
TD-001 and TD-002: serialize cookie writes, ignore stale responses and reset financial
queries on identity changes. Backend cookie lifecycle regression: ec5780d.
2026-09-21 21:09:23 +03:00
ksv741 3c99debe88 chore(release): 0.3.0
Frontend image / publish (push) Successful in 5m45s
Conventional commits / commits (pull_request) Successful in 27s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 4m42s
Frontend security / security (push) Successful in 10s
Frontend verify / verify (push) Successful in 6m17s
2026-09-20 20:09:11 +03:00
ksv741 bb30935f73 feat: add installable PWA #30
Conventional commits / commits (pull_request) Successful in 30s
Frontend security / security (pull_request) Successful in 1m7s
Frontend verify / verify (pull_request) Successful in 4m48s
Frontend security / security (push) Successful in 11s
Frontend verify / verify (push) Successful in 6m17s
2026-09-20 19:55:53 +03:00
ksv741 f486ae4fb2 chore(release): 0.2.3
Frontend image / publish (push) Successful in 4m51s
Conventional commits / commits (pull_request) Successful in 21s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 3m56s
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Successful in 5m27s
2026-09-19 16:25:12 +03:00
ksv741 9171b9f5c8 fix: correct Nexus routing and SonarQube host 2026-09-19 16:24:07 +03:00
ksv741 d68ec3b15b chore(release): 0.2.2
Frontend image / publish (push) Failing after 3m59s
Conventional commits / commits (pull_request) Successful in 20s
Frontend security / security (pull_request) Successful in 10s
Frontend verify / verify (pull_request) Successful in 4m5s
Frontend security / security (push) Successful in 10s
Frontend verify / verify (push) Failing after 4m26s
2026-09-19 15:04:33 +03:00
ksv741 bac95ebb39 fix: update Nexus registry host
Conventional commits / commits (pull_request) Successful in 21s
Frontend security / security (pull_request) Successful in 8s
Frontend verify / verify (pull_request) Successful in 4m11s
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Failing after 4m7s
2026-09-19 14:51:25 +03:00
ksv741 8183b66e2f chore(release): 0.2.1
Conventional commits / commits (pull_request) Successful in 20s
Frontend security / security (pull_request) Successful in 8s
Frontend verify / verify (pull_request) Successful in 3m36s
Frontend image / publish (push) Failing after 3m56s
Frontend security / security (push) Successful in 8s
Frontend verify / verify (push) Failing after 4m13s
2026-09-18 08:12:21 +03:00
ksv741 1ad578fb37 docs: use shared Nexus account #21
Frontend security / security (pull_request) Successful in 53s
Frontend verify / verify (pull_request) Successful in 3m52s
Conventional commits / commits (pull_request) Successful in 20s
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Failing after 7m49s
2026-09-17 20:53:03 +03:00
ksv741 999b8590ec ci: publish frontend images to Nexus #21
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Successful in 3m57s
Conventional commits / commits (pull_request) Failing after 19s
Frontend security / security (pull_request) Successful in 32s
Frontend verify / verify (pull_request) Successful in 3m54s
2026-09-17 20:41:12 +03:00
ksv741 3f19b3643f ci: add frontend SonarQube analysis #19
Conventional commits / commits (pull_request) Successful in 22s
Frontend security / security (pull_request) Successful in 16s
Frontend verify / verify (pull_request) Successful in 3m59s
Frontend security / security (push) Successful in 18s
Frontend verify / verify (push) Successful in 9m45s
2026-09-16 20:08:51 +03:00
120 changed files with 10322 additions and 3862 deletions
+20 -11
View File
@@ -51,23 +51,32 @@ Cross-slice consumer использует `@/` и `index.ts` владельца,
композиция принадлежит вышележащему owner. Existing меж-slice исключения
не являются разрешением добавлять новые.
Направление зависимостей и public imports частично проверяет
`npm run deps`; Knip проверяет использование exports, а не смысл placement.
Направление зависимостей, public imports и запрет соседних slices в
`pages`, `features`, `entities` проверяет `npm run deps`. Внутренние imports
одного slice и связи shared segments этот запрет не ограничивает.
Knip проверяет использование exports, а не смысл placement.
## 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 читают
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 проверяют поведение приложения отдельно.
Existing route-aware AppShell расположен в shared/ui; это legacy placement,
а не образец нового shared primitive. При изменении foundation прочитай
Route-aware AppShell и его navigation styles принадлежат `app/ui`;
`ProtectedLayout` использует public API этого владельца. При изменении foundation прочитай
[UI](conventions/ui.md#визуальная-основа) и [Storybook](conventions/storybook.md).
Статичные Add/Edit/Delete и публичный `IconProps` принадлежат private
`packages/icons`; package не зависит от UI, domain или motion.
`BankOperationIcon` и mappings остаются у entity. Card/Cards используют package
Add/Edit/Delete; restore/category SVG остаются локальными.
## Примеры
- Общая busy-область: существующий [LoadingSkeleton](../src/shared/ui/LoadingSkeleton.tsx), а не domain widget в shared.
- Общая busy-область: существующий [LoadingSkeleton](../packages/ui/src/LoadingSkeleton.tsx), а не domain widget в shared.
- Account-income state views: [страница](../src/pages/account-income/ui/AccountIncomePage.tsx) и её flat `components/*.view.tsx`; новый page-local filter остаётся здесь.
- Portfolio query: [entity public API](../src/entities/portfolio/index.ts); новая UI-сводка с бизнес-смыслом не становится shared только из-за нескольких экранов.
@@ -75,7 +84,7 @@ Existing route-aware AppShell расположен в shared/ui; это legacy p
После 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 не доказывает
правильный выбор слоя.
Graph `src` и `packages` проверяет текущий dependency-cruiser; зависимости
из packages в код приложения `src` запрещены. Generated `packages/*/dist`
не анализируется как исходник; все package sources остаются в graph. Review отдельно проверяет смысл
owner: разрешённый dependency graph не доказывает правильный выбор слоя.
+4 -1
View File
@@ -1,5 +1,8 @@
# Storybook
Единый каталог включает stories приложения и `packages/*/src`; общие
StateView/LoadingSkeleton и их stories принадлежат `packages/ui`.
## Когда нужна story
- Shared UI/theme: показывай принятые visual roles и переиспользуемое поведение.
@@ -23,7 +26,7 @@ Stories не достигают application API, auth, VM и query providers д
контракт: 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)
без production wrapper; [LoadingSkeleton](../../packages/ui/src/LoadingSkeleton.stories.tsx)
— значимые busy states.
`npm run typecheck`, `npm run deps:storybook`, `npm run build:catalog` проверяют
+26 -4
View File
@@ -13,7 +13,10 @@ Mantine component и общую тему. Для выпадающего выбо
Icons ищи у существующего owner (например,
[BankOperationIcon](../../src/entities/bank-card/ui/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, даже при повторном использовании.
Wrapper нужен для проектной ответственности, а не ради нового имени
@@ -107,10 +110,29 @@ loading/error/empty/loaded и recovery по применимости. [Storybook
## Визуальная основа
Общая тема живёт в `src/shared/theme`: `tokens.json` задаёт переносимые значения,
`theme.ts` адаптирует их к Mantine. Используй public API темы и её semantic roles,
без отдельной палитры в page/component. Поддерживается светлая схема.
Private workspace `packages/tokens` владеет переносимыми значениями
`tokens.json`; `packages/ui/src/theme.ts` читает export пакета
`@wealthledger/tokens/tokens.json` и адаптирует его к Mantine. Используй
`@wealthledger/ui/theme` и его semantic roles; runtime подключает
`@wealthledger/ui/styles.css` после Mantine CSS. Providers остаются у runtime.
Палитра page/component следует этим semantic roles. Поддерживается светлая схема.
Цвет дополняет подпись или знак; проверяй контраст конкретной пары text/background.
Warning не используй для мелкого текста на белом. Деньги сохраняют валюту, знак
и различие между нулём и неизвестной суммой. Общие состояния демонстрирует
Storybook; presentation stories используют synthetic data без application API.
EntryCard, StateView и LoadingSkeleton принадлежат `packages/ui`; публичный import —
`@wealthledger/ui`. Переводы, retry и формы skeleton остаются у callers.
Compatibility re-exports удалены; callers используют public export пакета.
## Modal animation
BankCardForm, OperationForm, DeleteOperation и CategoryManager монтируют Modal
с `opened=true`: Mantine Transition начинает в состоянии `entered`.
CSS `modal-appear`/`modal-backdrop-appear` в `packages/ui/src/styles.css`
обеспечивает появление при mount (220ms, только no-preference). Mantine theme
владеет exit transition (180ms), overlay blur и completion callback;
`onExitTransitionEnd` позволяет дождаться закрытия перед unmount и вернуть фокус.
Удаление CSS без изменения mount lifecycle убирает вступительную анимацию.
TbankConnection Modal использует toggle `opened`; вывод о разделении фаз
банковских форм на этот сценарий автоматически не распространяется.
+27
View File
@@ -13,3 +13,30 @@
!public/**
!docker/
!docker/**
!packages/
!packages/tokens/
!packages/tokens/package.json
!packages/tokens/tokens.json
!packages/ui/
!packages/ui/package.json
!packages/ui/vite.config.ts
!packages/ui/tsconfig.json
!packages/ui/src/
!packages/ui/src/theme.ts
!packages/ui/src/styles.css
!packages/ui/src/index.ts
!packages/ui/src/StateView.tsx
!packages/ui/src/LoadingSkeleton.tsx
!packages/ui/src/EntryCard.tsx
!packages/ui/src/EntryCard.module.css
!packages/icons/
!packages/icons/package.json
!packages/icons/tsconfig.json
!packages/icons/vite.config.ts
!packages/icons/src/
!packages/icons/src/index.ts
!packages/icons/src/types.ts
!packages/icons/src/svg/
!packages/icons/src/svg/AddIcon.tsx
!packages/icons/src/svg/EditIcon.tsx
!packages/icons/src/svg/DeleteIcon.tsx
+13 -11
View File
@@ -12,7 +12,7 @@ jobs:
publish:
runs-on: ubuntu-latest
env:
IMAGE: git.personal.ksv741.ru/wealthledger/frontend
IMAGE: nexus.personal.ksv741.ru/docker-hosted/wealthledger/frontend
RELEASE_TAG: ${{ gitea.ref_name }}
REVISION: ${{ gitea.sha }}
DOCKER_CONFIG: ${{ runner.temp }}/wealthledger-frontend-docker
@@ -33,27 +33,29 @@ jobs:
- run: npm run verify
env:
KNIP_DISABLE_RAW_TRANSFER: '1'
- name: Login with dedicated package writer
- name: Login with dedicated Nexus writer
env:
REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
REGISTRY_USERNAME: ${{ secrets.NEXUS_USERNAME }}
REGISTRY_TOKEN: ${{ secrets.NEXUS_PASSWORD }}
run: |
test -n "$REGISTRY_USERNAME" && test -n "$REGISTRY_TOKEN"
install -d -m 700 "$DOCKER_CONFIG"
printf '%s' "$REGISTRY_TOKEN" | docker login 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
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
DIGEST="$(docker buildx imagetools inspect "$IMAGE:$VERSION" --format '{{.Manifest.Digest}}')"
else
if ! grep -Eq 'manifest unknown|no such manifest' manifest-error.log; then
echo 'Cannot prove tag absence; refusing publication'; exit 1
fi
docker buildx build --target production --build-arg VERSION="$VERSION" --build-arg REVISION="$REVISION" --tag "$IMAGE:$VERSION" --metadata-file image-metadata.json --push .
DIGEST="$(node --input-type=commonjs -p 'require("./image-metadata.json")["containerimage.digest"]')"
fi
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"
test "$(docker image inspect "$IMAGE@$DIGEST" --format '{{index .Config.Labels "org.opencontainers.image.version"}}')" = "$VERSION"
docker run --rm --entrypoint sh "$IMAGE@$DIGEST" -c 'test -s /usr/share/nginx/html/index.html && nginx -t && nginx && wget -q -O /dev/null http://127.0.0.1:8080/'
printf 'Frontend image: %s@%s\n' "$IMAGE" "$DIGEST"
- name: Remove registry session
+10
View File
@@ -11,6 +11,8 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: https://github.com/actions/checkout@v4
with:
fetch-depth: 0
- name: Record checked revision
run: git rev-parse HEAD
- uses: https://github.com/actions/setup-node@v4
@@ -24,3 +26,11 @@ jobs:
env:
# OXC raw transfer allocates a ~6 GiB buffer; use the standard parser in CI.
KNIP_DISABLE_RAW_TRANSFER: '1'
- name: Analyze develop with SonarQube
if: gitea.event_name == 'push' && gitea.ref == 'refs/heads/develop'
# v2.3.0: Docker-based scanner for the SonarQube 9.9 server.
uses: https://github.com/SonarSource/sonarqube-scan-action@aecaf43ae57e412bd97d70ef9ce6076e672fe0a9
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
with:
args: -Dsonar.qualitygate.wait=true
+1
View File
@@ -12,6 +12,7 @@ dist
storybook-static
dist-ssr
coverage
.scannerwork
*.local
# Local runtime configuration
+1 -1
View File
@@ -1,7 +1,7 @@
import type { StorybookConfig } from "@storybook/react-vite";
const config: StorybookConfig = {
stories: ["../src/**/*.stories.tsx"],
stories: ["../src/**/*.stories.tsx", "../packages/*/src/**/*.stories.tsx"],
addons: ["@storybook/addon-docs"],
framework: "@storybook/react-vite",
core: { disableTelemetry: true },
+2 -1
View File
@@ -1,12 +1,13 @@
import "@mantine/core/styles.css";
import "@mantine/charts/styles.css";
import "@mantine/dates/styles.css";
import "@wealthledger/ui/styles.css";
import "dayjs/locale/ru";
import "../src/shared/i18n";
import { MantineProvider } from "@mantine/core";
import { DatesProvider } from "@mantine/dates";
import type { Preview } from "@storybook/react-vite";
import { cssVariablesResolver, theme } from "@/shared/theme";
import { cssVariablesResolver, theme } from "@wealthledger/ui/theme";
const colorSchemeManager = {
get: () => "light" as const,
+29
View File
@@ -1,5 +1,34 @@
# Changelog
## [0.3.0](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.2.3...v0.3.0) (2026-09-20)
### Features
* add installable PWA [#30](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/30) ([bb30935](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/bb30935f73bfcbb77c10663cf6c683d8f0caca85))
## [0.2.3](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.2.2...v0.2.3) (2026-09-19)
### Bug Fixes
* correct Nexus routing and SonarQube host ([9171b9f](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/9171b9f5c8e0b694a2310e5a200fa2f8d3f28a61))
## [0.2.2](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.2.1...v0.2.2) (2026-09-19)
### Bug Fixes
* update Nexus registry host ([bac95eb](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/bac95ebb392febb667a9fc2f1fa4f06fa110d685))
## [0.2.1](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.2.0...v0.2.1) (2026-09-18)
### Documentation
* use shared Nexus account [#21](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/21) ([1ad578f](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/1ad578fb37b8dd6161dc362541d9c0cd0b008b75))
### CI
* add frontend SonarQube analysis [#19](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/19) ([3f19b36](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/3f19b3643f88e36d10e7c374262351f61947ed47))
* publish frontend images to Nexus [#21](https://git.personal.ksv741.ru/WealthLedger/frontend/issues/21) ([999b859](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/999b8590ecd0a551da628c349d005ebb9b318883))
## [0.2.0](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.1.0...v0.2.0) (2026-09-16)
### Features
+4
View File
@@ -2,10 +2,14 @@ FROM node:24.21.0-bookworm-slim AS dependencies
WORKDIR /app
ENV HUSKY=0
COPY package.json package-lock.json ./
COPY packages/tokens/package.json ./packages/tokens/
COPY packages/ui/package.json ./packages/ui/
COPY packages/icons/package.json ./packages/icons/
RUN npm ci
FROM dependencies AS development
COPY . .
RUN npm run build:packages
ENV VITE_API_BASE_URL="" API_PROXY_TARGET=http://backend:3000
EXPOSE 8080
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "8080", "--strictPort"]
+94 -5
View File
@@ -28,7 +28,8 @@ staged diff с полной редакцией секретов, затем за
`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.
не попадают в image. Изменение `packages/tokens` или `packages/ui` требует rebuild development
image, если локальный запуск использует bind-mount только `src`/`public`.
```bash
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`, проверяет
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.
Docker/buildx. Образы хранятся в Nexus:
`nexus.personal.ksv741.ru/docker-hosted/wealthledger/frontend`. Пользователь `wealthledger-ci`
задаётся Actions secrets `NEXUS_USERNAME`/`NEXUS_PASSWORD`; эта же учётная
запись используется сервером для загрузки образов. Docker endpoint и token realm должны использовать
HTTPS; в `docker-hosted` включается запрет redeploy. Прежние Gitea secrets
сохраняются на время перехода и не передаются в Nexus.
Публикуются semver tags, без `latest`; существующие release tags не перезаписываются. Production выбирает опубликованный version tag.
Compose topology принадлежит workspace, эксплуатационная последовательность —
[документация](https://git.personal.ksv741.ru/WealthLedger/docs),
@@ -48,6 +52,25 @@ Compose topology принадлежит workspace, эксплуатационн
Проверка публикации требует настроенного registry/runner; локальный build
не доказывает package permissions.
## Установка как приложение (PWA)
Production-сборка поддерживает установку WealthLedger в отдельное окно через
`vite-plugin-pwa`. Нужен HTTPS или localhost. В Chrome/Edge выберите «Установить
WealthLedger» в меню браузера или значок установки в адресной строке; на iPhone
и iPad — Safari → «Поделиться» → «На экран Домой». Доступность установки зависит
от браузера и ОС.
Service worker кеширует только статическую оболочку, включая страницы SPA.
Вход, финансовые данные и сохранение изменений требуют сети: API, токены и
ответы API не сохраняются в Cache Storage. Это не автономный финансовый
клиент. Новая версия загружается в фоне и применяется после закрытия всех
вкладок и окон WealthLedger и повторного открытия; открытые формы автоматически
не перезагружаются.
Локальная проверка: `nvm use --silent`, `npm run build`, `npm run preview`.
В DevTools → Application проверьте Manifest, Service Workers и Cache Storage.
В режиме `npm run dev` и в Storybook service worker не включается.
## Проверка
```bash
@@ -74,6 +97,42 @@ TypeScript остаётся на 5.9.3: `openapi-typescript@7.13.0` требуе
обновите `src/shared/api/spec/openapi.json` копированием backend OpenAPI
document и затем выполните `npm run openapi:generate`.
## SonarQube
Проект `wealthledger-frontend` использует настройки из
`sonar-project.properties`. Анализируются исходники `src`; тесты учитываются
отдельно, а Storybook fixtures, test helpers, generated API types и OpenAPI
snapshot исключены. `npm run test:coverage` (также входит в `npm run verify`)
создаёт `coverage/lcov.info` для импорта покрытия.
Для первого анализа установите SonarScanner CLI, совместимый с версией сервера,
и выполните из корня frontend:
```bash
nvm use --silent
npm ci
npm run test:coverage
# SONAR_TOKEN передайте через окружение; не сохраняйте токен в репозитории.
sonar-scanner
```
В Gitea откройте frontend → Settings → Actions → Secrets и добавьте
`SONAR_TOKEN` с токеном анализа проекта. Переименовывать основную ветку в
SonarQube не требуется; `sonar.branch.name` не задаётся.
Используется Community Edition 9.9.8: CI отправляет только
push в `develop`, после успешного `verify`, и ожидает результат Quality Gate.
PR и остальные ветки проходят обычные проверки без отправки в SonarQube.
Отрицательный Quality Gate или ошибка scanner завершает `verify` с ошибкой.
Runner должен поддерживать Docker actions и иметь HTTPS-доступ к
`https://sonarqube.personal.ksv741.ru`, GitHub и Docker Hub. Docker action
SonarSource закреплён на commit версии 2.3.0; scanner запускается отдельно от
Node 24, используемого для сборки. `tsconfig.sonar.json` содержит совместимые
со старым анализатором TS настройки; приложение проверяется штатным TypeScript
5.9 через `npm run verify`. После обновления сервера пересмотрите scanner и
возможность использовать основной tsconfig. Успешный локальный `verify` не
доказывает доступность сервера и успешность анализа в CI.
## UI-каталог Storybook
После `nvm use --silent` выполните `npm run dev:catalog`; статическая сборка —
@@ -136,3 +195,33 @@ Commits и PR titles — Conventional Commits, включая `spec:`. Верс
администратором, обязательны `verify`, `security`, `commits`; теги `v*` защищены.
Workflow сам не включает эти настройки. Отдельное review approval для одного
владельца не требуется. Npm publishing, deploy и Gitea Releases не включены.
## Локальные пакеты
`packages/tokens` — private npm workspace с единственным export
`@wealthledger/tokens/tokens.json`. `packages/ui` экспортирует собранные
`@wealthledger/ui/theme` (JS + declarations) и `@wealthledger/ui/styles.css`.
Корневой export `@wealthledger/ui` содержит EntryCard, StateView и LoadingSkeleton;
Потребители импортируют компоненты напрямую из `@wealthledger/ui`.
CSS явно подключается после Mantine; providers остаются в приложении/Storybook.
Тема доступна через `@wealthledger/ui/theme`; compatibility re-exports удалены.
JSON не требует сборки. `npm ci` связывает workspaces, а существующие команды
разработки, проверок и сборки сначала выполняют `npm run build:packages`.
Library build использует отдельный Vite config без app plugins и TypeScript
для declarations. После изменения package sources перезапустите `npm run dev`
или `npm run dev:catalog`; отдельный watch-процесс пока не нужен.
Начальная версия manifest взята из приложения; отдельный release-процесс
и публикация не настроены.
Private `@wealthledger/icons` экспортирует `AddIcon`, `EditIcon`, `DeleteIcon`
и type `IconProps`. Единственный source рисунка — TSX в `packages/icons/src/svg`;
поставка содержит ESM/declarations, без raw SVG, CSS, Mantine и motion.
React — peer/external. Размер `size` по умолчанию 24, `strokeWidth` — 1.5;
цвет наследуется через `currentColor`, SVG props можно передать явно.
В action используйте декоративный `<AddIcon size={20} strokeWidth={2} />`,
доступное имя задавайте кнопке. Standalone пример:
`<EditIcon aria-hidden={false} role="img" aria-label="Редактирование" />`.
Поддерживается также стандартный `aria-labelledby`; подпись выбирает caller.
Card/Cards используют пакетные Add/Edit/Delete с прежними размерами/strokeWidth.
Restore/category SVG и предметный BankOperationIcon остаются в приложении.
+3 -1
View File
@@ -7,6 +7,7 @@
"includes": [
"**",
"!dist",
"!packages/*/dist",
"!storybook-static",
"!src/shared/api/generated",
"!src/shared/api/spec",
@@ -38,7 +39,8 @@
"vite.config.ts",
"vitest.config.ts",
".storybook/main.ts",
".storybook/preview.tsx"
".storybook/preview.tsx",
"packages/*/vite.config.ts"
],
"linter": {
"rules": {
+13
View File
@@ -1,5 +1,11 @@
module.exports = {
forbidden: [
{
name: "packages-must-not-depend-on-app",
severity: "error",
from: { path: "^packages/" },
to: { path: "^src/" },
},
{
name: "no-circular",
severity: "error",
@@ -17,6 +23,12 @@ module.exports = {
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",
severity: "error",
@@ -43,6 +55,7 @@ module.exports = {
},
],
options: {
exclude: "^packages/[^/]+/dist/",
doNotFollow: { path: "node_modules" },
tsConfig: { fileName: "tsconfig.app.json" },
tsPreCompilationDeps: true,
+3 -1
View File
@@ -1,8 +1,10 @@
<!doctype html>
<html lang="en">
<html lang="ru">
<head>
<meta charset="UTF-8" />
<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" />
<title>WealthLedger</title>
</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",
"private": true,
"version": "0.2.0",
"version": "0.3.0",
"type": "module",
"engines": {
"node": "24.21.0"
},
"scripts": {
"dev": "vite",
"dev:catalog": "storybook dev -p 6006 --no-open --disable-telemetry",
"build:catalog": "storybook build --output-dir storybook-static --disable-telemetry",
"dev": "npm run build:packages && vite",
"dev:catalog": "npm run build:packages && storybook dev -p 6006 --no-open --disable-telemetry",
"build:catalog": "npm run build:packages && storybook build --output-dir storybook-static --disable-telemetry",
"preview:catalog": "vite preview --outDir storybook-static",
"typecheck": "tsc -b --noEmit",
"build": "tsc -b && vite build",
"typecheck": "npm run build:packages && tsc -b --noEmit",
"build": "npm run build:packages && tsc -b && vite build",
"lint": "biome check .",
"test": "vitest",
"test:run": "vitest run",
"test:coverage": "vitest run --coverage",
"test": "npm run build:packages && vitest",
"test:run": "npm run build:packages && vitest run",
"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:check": "node scripts/check-openapi.mjs",
"knip": "knip",
"deps": "depcruise src --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",
"knip": "npm run build:packages && knip",
"deps": "npm run build:packages && depcruise src packages --config dependency-cruiser.cjs --output-type err-long",
"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",
"preview": "vite preview",
"deps:storybook": "depcruise src .storybook/preview.tsx --config .storybook/dependency-cruiser.cjs --output-type err-long",
"deps:storybook": "npm run build:packages && depcruise src packages .storybook/preview.tsx --config .storybook/dependency-cruiser.cjs --output-type err-long",
"release:preview": "release-it --dry-run --ci",
"release:prepare": "release-it --ci",
"commitlint": "commitlint"
"commitlint": "commitlint",
"build:packages": "npm run build --workspaces --if-present"
},
"lint-staged": {
"*.{css,html,json,md,ts,tsx}": "biome format --write --no-errors-on-unmatched"
@@ -39,6 +40,9 @@
"@mantine/dates": "9.6.1",
"@mantine/hooks": "9.6.1",
"@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",
"i18next": "26.4.2",
"motion": "13.2.0",
@@ -82,10 +86,14 @@
"storybook": "10.6.0",
"typescript": "5.9.3",
"vite": "8.3.0",
"vite-plugin-pwa": "1.3.0",
"vitest": "5.0.0"
},
"allowScripts": {
"esbuild@0.28.2": true,
"fsevents@2.3.3": true
}
},
"workspaces": [
"packages/*"
]
}
+30
View File
@@ -0,0 +1,30 @@
{
"name": "@wealthledger/icons",
"version": "0.3.0",
"private": true,
"type": "module",
"files": [
"dist"
],
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"sideEffects": false,
"scripts": {
"build": "vite build && tsc -p tsconfig.json"
},
"peerDependencies": {
"react": "19.3.0"
},
"devDependencies": {
"@storybook/react-vite": "10.6.0",
"@testing-library/react": "16.3.3",
"@types/react": "19.3.0",
"typescript": "5.9.3",
"vite": "8.3.0",
"vitest": "5.0.0"
}
}
+45
View File
@@ -0,0 +1,45 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { AddIcon, DeleteIcon, EditIcon } from "./index";
const meta = {
title: "Design System/Icons",
component: AddIcon,
tags: ["autodocs"],
parameters: {
docs: {
description: {
component:
"Статичные SVG: size по умолчанию 24, strokeWidth 1.5, цвет currentColor. В кнопке иконка декоративная, имя принадлежит действию. Для самостоятельного изображения задайте aria-hidden={false}, role=img и aria-label либо aria-labelledby. Геометрия взята из Card/Cards; подписи и действия остаются у приложения.",
},
},
},
} satisfies Meta<typeof AddIcon>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Decorative: Story = {
render: () => (
<div style={{ display: "flex", gap: 16, color: "#2563eb" }}>
<button type="button" aria-label="Добавить пример">
<AddIcon size={20} strokeWidth={2} />
</button>
<button type="button" aria-label="Изменить пример">
<EditIcon size={18} />
</button>
<button type="button" aria-label="Удалить пример">
<DeleteIcon size={18} />
</button>
</div>
),
};
export const Meaningful: Story = {
render: () => (
<div style={{ display: "flex", gap: 16, color: "#2563eb" }}>
<AddIcon aria-hidden={false} role="img" aria-label="Добавление" />
<EditIcon aria-hidden={false} role="img" aria-label="Редактирование" />
<DeleteIcon aria-hidden={false} role="img" aria-label="Удаление" />
</div>
),
};
+34
View File
@@ -0,0 +1,34 @@
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { AddIcon, DeleteIcon, EditIcon } from "./index";
describe("icon accessibility", () => {
it.each([AddIcon, EditIcon, DeleteIcon])(
"keeps decoration hidden and exposes explicitly named images: %s",
(Icon) => {
const { rerender } = render(
<button type="button" aria-label="Действие">
<Icon />
</button>,
);
expect(screen.queryByRole("img")).not.toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Действие" }).querySelector("svg"),
).toHaveAttribute("focusable", "false");
rerender(
<Icon
aria-hidden={false}
role="img"
aria-label="Пример"
size={18}
strokeWidth={2}
/>,
);
const icon = screen.getByRole("img", { name: "Пример" });
expect(icon).toHaveAttribute("width", "18");
expect(icon).toHaveAttribute("height", "18");
expect(icon).toHaveAttribute("stroke-width", "2");
expect(icon).toHaveAttribute("stroke", "currentColor");
},
);
});
+4
View File
@@ -0,0 +1,4 @@
export { AddIcon } from "./svg/AddIcon";
export { DeleteIcon } from "./svg/DeleteIcon";
export { EditIcon } from "./svg/EditIcon";
export type { IconProps } from "./types";
+24
View File
@@ -0,0 +1,24 @@
import type { FC } from "react";
import type { IconProps } from "../types";
const AddIcon: FC<IconProps> = (props) => {
const { size = "24", ...svgProps } = props;
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
aria-hidden="true"
focusable="false"
{...svgProps}
>
<path d="M12 5v14 M5 12h14" />
</svg>
);
};
export { AddIcon };
+25
View File
@@ -0,0 +1,25 @@
import type { FC } from "react";
import type { IconProps } from "../types";
const DeleteIcon: FC<IconProps> = (props) => {
const { size = "24", ...svgProps } = props;
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
{...svgProps}
>
<path d="M3 6h18 M9 6V3h6v3 M5 6l1 15h12l1-15 M10 10v7 M14 10v7" />
</svg>
);
};
export { DeleteIcon };
+25
View File
@@ -0,0 +1,25 @@
import type { FC } from "react";
import type { IconProps } from "../types";
const EditIcon: FC<IconProps> = (props) => {
const { size = "24", ...svgProps } = props;
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
{...svgProps}
>
<path d="m16 3 5 5-12 12-6 1 1-6L16 3Z M13 6l5 5" />
</svg>
);
};
export { EditIcon };
+10
View File
@@ -0,0 +1,10 @@
import type { ComponentPropsWithoutRef } from "react";
type IconProps = Omit<
ComponentPropsWithoutRef<"svg">,
"children" | "dangerouslySetInnerHTML"
> & {
size?: number | string;
};
export type { IconProps };
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2023",
"lib": ["ES2023", "DOM"],
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"skipLibCheck": true,
"verbatimModuleSyntax": true,
"declaration": true,
"emitDeclarationOnly": true,
"rootDir": "src",
"outDir": "dist",
"jsx": "react-jsx"
},
"include": ["src/index.ts"]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from "vite";
export default defineConfig({
build: {
lib: { entry: "src/index.ts", formats: ["es"], fileName: "index" },
rolldownOptions: { external: /^react(\/|$)/ },
},
});
+12
View File
@@ -0,0 +1,12 @@
{
"name": "@wealthledger/tokens",
"version": "0.3.0",
"private": true,
"type": "module",
"files": [
"tokens.json"
],
"exports": {
"./tokens.json": "./tokens.json"
}
}
@@ -53,7 +53,7 @@
"#40c057",
"#37b24d",
"#2f9e44",
"#2b8a3e"
"#237032"
],
"red": [
"#fff5f5",
@@ -151,12 +151,12 @@
},
"positive": {
"color": "green",
"shade": 6,
"shade": 9,
"description": "Положительный результат; дополните знаком и текстом"
},
"negative": {
"color": "red",
"shade": 6,
"shade": 9,
"description": "Ошибка / отрицательный результат; дополните текстом"
},
"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);
align-items: center;
padding: var(--mantine-spacing-md);
border-color: var(--mantine-color-gray-3);
background: var(--mantine-color-gray-0);
border-color: var(--wl-color-border);
background: var(--wl-color-subtle);
}
.identity,
@@ -19,15 +19,15 @@
}
.positive {
color: var(--mantine-color-green-6);
color: var(--wl-color-positive);
}
.negative {
color: var(--mantine-color-red-6);
color: var(--wl-color-negative);
}
.neutral {
color: var(--mantine-color-dimmed);
color: var(--mantine-color-gray-7);
}
@media (max-width: 36em) {
+37
View File
@@ -0,0 +1,37 @@
import { Button } from "@mantine/core";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { fn } from "storybook/test";
import { EntryCard } from "./EntryCard";
const meta = {
title: "Design System/Components/EntryCard",
component: EntryCard,
tags: ["autodocs"],
args: {
title:
"Учебная запись с очень длинным названием для проверки узкого экрана",
metadata: "22.09.2026 · Синтетические данные",
initial: "У",
imageSrc: "data:image/png;base64,invalid",
value: "−1 250,00 ₽",
valueLabel: "Тестовое значение",
tone: "negative",
actions: (
<Button size="compact-sm" onClick={fn()}>
Открыть пример
</Button>
),
},
parameters: {
docs: {
description: {
component:
"Готовые строки и slots без финансовых вычислений. Невалидное локальное изображение показывает fallback; действие доступно с клавиатуры и на узком экране. Данные вымышлены.",
},
},
},
} satisfies Meta<typeof EntryCard>;
export default meta;
type Story = StoryObj<typeof meta>;
export const LongContentAndFallback: Story = {};
+35
View File
@@ -0,0 +1,35 @@
import { MantineProvider } from "@mantine/core";
import { fireEvent, render, screen } from "@testing-library/react";
import { assert, describe, expect, it } from "vitest";
import { EntryCard } from "./EntryCard";
describe("EntryCard", () => {
it("keeps the fallback after an image fails", () => {
const props = {
title: "Пример",
metadata: "Описание",
initial: "У",
value: "—",
valueLabel: "Неизвестно",
tone: "neutral" as const,
imageSrc: "data:image/png;base64,invalid",
};
const { container, rerender } = render(
<MantineProvider>
<EntryCard {...props} />
</MantineProvider>,
);
// Decorative image has no accessible name; trigger its actual failure event.
const image = container.querySelector("img");
assert(image);
fireEvent.error(image);
rerender(
<MantineProvider>
<EntryCard {...props} title="Обновлённый пример" />
</MantineProvider>,
);
expect(container.querySelector("img")).toBeNull();
expect(screen.getByText("У")).toBeInTheDocument();
expect(screen.getByText("Обновлённый пример")).toBeInTheDocument();
});
});
@@ -25,7 +25,7 @@ const EntryCard: FC<EntryCardProps> = (props) => {
style={
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
}
@@ -1,4 +1,3 @@
export { AppShell } from "./AppShell";
export { EntryCard } from "./EntryCard";
export { LoadingSkeleton } from "./LoadingSkeleton";
export { StateView } from "./StateView";
@@ -1,7 +1,7 @@
import { DEFAULT_THEME, mergeMantineTheme } from "@mantine/core";
import source from "@wealthledger/tokens/tokens.json";
import { describe, expect, it } from "vitest";
import { colorRoles, cssVariablesResolver, theme } from "./theme";
import source from "./tokens.json";
describe("design theme adapter", () => {
it("preserves scale-aware sizes, unscaled breakpoints and shadow layers", () => {
@@ -1,3 +1,4 @@
import "./styles.css";
import {
type CSSVariablesResolver,
colorsTuple,
@@ -8,7 +9,7 @@ import {
rem,
rgba,
} from "@mantine/core";
import designTokens from "./tokens.json";
import designTokens from "@wealthledger/tokens/tokens.json";
const { color, typography, spacing, radius, shadows, breakpoints } =
designTokens;
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2023",
"lib": ["ES2023", "DOM"],
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"strict": true,
"skipLibCheck": true,
"verbatimModuleSyntax": true,
"declaration": true,
"emitDeclarationOnly": true,
"rootDir": "src",
"outDir": "dist",
"jsx": "react-jsx",
"types": ["vite/client"]
},
"include": ["src/index.ts", "src/theme.ts"]
}
+14
View File
@@ -0,0 +1,14 @@
import { defineConfig } from "vite";
export default defineConfig({
build: {
lib: {
entry: { index: "src/index.ts", theme: "src/theme.ts" },
formats: ["es"],
cssFileName: "styles",
},
rolldownOptions: {
external: /^(react(?:-dom)?|@mantine\/[^/]+|@wealthledger\/tokens)(\/|$)/,
},
},
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

+75
View File
@@ -0,0 +1,75 @@
const { test } = require("node:test");
const assert = require("node:assert/strict");
const {
mkdtempSync,
readFileSync,
writeFileSync,
chmodSync,
rmSync,
} = require("node:fs");
const { tmpdir } = require("node:os");
const { join, resolve } = require("node:path");
const EXECUTABLE_MODE = 0o755;
const { spawnSync } = require("node:child_process");
test("immutable publication resumes exact digest checks after post-push failure", () => {
const directory = mkdtempSync(join(tmpdir(), "wl-image-retry-"));
const workflow = readFileSync(
resolve(__dirname, "../.gitea/workflows/image.yml"),
"utf8",
);
const block = workflow
.split(" - name: Publish immutable release tag\n run: |\n")[1]
.split(" - name:")[0]
.replace(/^ {10}/gm, "");
const double = `#!${process.execPath}
const fs = require('node:fs');
const args = process.argv.slice(2).join(' ');
fs.appendFileSync('calls', args + '\\n');
if (args.startsWith('manifest inspect')) {
if (!fs.existsSync('published')) { console.error('manifest unknown'); process.exit(1); }
} else if (args.startsWith('buildx imagetools inspect')) {
console.log('sha256:exact');
} else if (args.startsWith('buildx build')) {
fs.writeFileSync('published', 'yes');
fs.writeFileSync('image-metadata.json', JSON.stringify({'containerimage.digest': 'sha256:exact'}));
} else if (args.startsWith('pull')) {
if (!fs.existsSync('pull-failed')) { fs.writeFileSync('pull-failed', 'yes'); process.exit(1); }
} else if (args.startsWith('image inspect')) {
console.log(args.includes('image.version') ? '1.2.3' : process.env.BAD_REVISION ? 'other' : 'commit');
} else if (args.startsWith('run') && process.env.BAD_SMOKE) process.exit(1);
`;
try {
for (const name of ["docker", "npm"]) {
writeFileSync(join(directory, name), double);
chmodSync(join(directory, name), EXECUTABLE_MODE);
}
const run = (extra = {}) =>
spawnSync("/bin/sh", ["-ec", block], {
cwd: directory,
encoding: "utf8",
env: {
...process.env,
PATH: `${directory}:${process.env.PATH}`,
IMAGE: "synthetic/image",
RELEASE_TAG: "v1.2.3",
REVISION: "commit",
...extra,
},
});
assert.notEqual(run().status, 0);
const retry = run();
assert.equal(retry.status, 0, retry.stdout + retry.stderr);
assert.notEqual(run({ BAD_REVISION: "1" }).status, 0);
assert.notEqual(run({ BAD_SMOKE: "1" }).status, 0);
const calls = readFileSync(join(directory, "calls"), "utf8");
assert.equal(
calls.split("\n").filter((line) => line.startsWith("buildx build"))
.length,
1,
);
assert.ok(calls.includes("synthetic/image@sha256:exact"));
} finally {
rmSync(directory, { recursive: true, force: true });
}
});
+12
View File
@@ -0,0 +1,12 @@
sonar.projectKey=wealthledger-frontend
sonar.projectName=WealthLedger frontend
sonar.host.url=https://sonarqube.personal.ksv741.ru
sonar.sourceEncoding=UTF-8
sonar.sources=src
sonar.tests=src
sonar.test.inclusions=src/**/*.test.ts,src/**/*.test.tsx
sonar.exclusions=src/**/*.test.ts,src/**/*.test.tsx,src/**/*.stories.tsx,src/test/**,src/shared/api/generated/**,src/shared/api/spec/**
sonar.javascript.lcov.reportPaths=coverage/lcov.info
# SonarQube 9.9 embeds an older TypeScript analyzer than the application compiler.
sonar.typescript.tsconfigPaths=tsconfig.sonar.json
+1 -2
View File
@@ -1,12 +1,11 @@
import { MantineProvider } from "@mantine/core";
import { QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { cssVariablesResolver, theme } from "@wealthledger/ui/theme";
import { HttpResponse, http } from "msw";
import { MemoryRouter } from "react-router";
import { describe, expect, it } from "vitest";
import { AuthProvider } from "@/features/auth";
import { cssVariablesResolver, theme } from "@/shared/theme";
import { createTestQueryClient } from "@/test/query";
import { server } from "@/test/server";
import { AppRoutes } from "./AppRoutes";
+1 -2
View File
@@ -1,6 +1,5 @@
import type { FC } from "react";
import { AppBreadcrumbs } from "@/app/ui";
import { AppShell } from "@/shared/ui";
import { AppBreadcrumbs, AppShell } from "@/app/ui";
import { ProtectedDocumentTitle } from "./DocumentTitle";
const ProtectedLayout: FC = () => {
+1 -1
View File
@@ -1,11 +1,11 @@
import { MantineProvider } from "@mantine/core";
import { DatesProvider } from "@mantine/dates";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { cssVariablesResolver, theme } from "@wealthledger/ui/theme";
import type { FC } from "react";
import { BrowserRouter } from "react-router";
import { AppRoutes, RouteErrorBoundary } from "@/app/routes";
import { AuthProvider } from "@/features/auth";
import { cssVariablesResolver, theme } from "@/shared/theme";
const queryClient = new QueryClient({
defaultOptions: {
@@ -2,7 +2,7 @@ import { AppShell as MantineAppShell, NavLink, Text } from "@mantine/core";
import type { FC, ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Outlet, NavLink as RouterNavLink, useLocation } from "react-router";
import { bindIconAnimation } from "../lib";
import { bindIconAnimation } from "@/shared/lib";
import classes from "./AppShell.module.css";
type AppShellProps = {
+1
View File
@@ -1 +1,2 @@
export { AppBreadcrumbs } from "./AppBreadcrumbs";
export { AppShell } from "./AppShell";
+1
View File
@@ -18,6 +18,7 @@ export {
moneyCents,
positiveMoneySchema,
} from "./model/form-validation";
export { bankOperationKinds } from "./model/operation-kinds";
export { bankPeriod } from "./model/period";
export { BankCardFace } from "./ui/BankCardFace";
export { BankCardForm } from "./ui/BankCardForm";
@@ -0,0 +1,10 @@
import type { BankOperation } from "../api/queries";
const bankOperationKinds = [
"expense",
"topup",
"transfer",
"refund",
] as const satisfies readonly BankOperation["kind"][];
export { bankOperationKinds };
@@ -1,6 +1,6 @@
import { Stack } from "@mantine/core";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { EntryCard } from "@/shared/ui";
import { EntryCard } from "@wealthledger/ui";
import { BankOperationIcon } from "./BankOperationIcon";
const meta = {
@@ -1,8 +1,8 @@
import { Button, Group, Skeleton, Stack, Text, Title } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { CSSProperties, FC } from "react";
import { useTranslation } from "react-i18next";
import { formatMoney } from "@/shared/lib";
import { LoadingSkeleton } from "@/shared/ui";
import type { BankSummary } from "../api/queries";
import { BankOperationIcon } from "./BankOperationIcon";
import classes from "./BankSummary.module.css";
@@ -1,4 +1,5 @@
import { Anchor, Group, Text } from "@mantine/core";
import { EntryCard } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
@@ -8,7 +9,6 @@ import {
formatSnapshotTime,
instrumentLogoUrl,
} from "@/shared/lib";
import { EntryCard } from "@/shared/ui";
import type { BrokerageOperation } from "../api/useBrokerageOperations";
import { operationLabelKey, paymentPresentation } from "../model/display";
@@ -1,7 +1,7 @@
import { EntryCard } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { formatDate, formatMoney, instrumentLogoUrl } from "@/shared/lib";
import { EntryCard } from "@/shared/ui";
import type { BrokerageEvent } from "../api/useBrokerageEvents";
type BrokerageEventCardProps = { event: BrokerageEvent };
@@ -1,8 +1,8 @@
import { Alert, Button, Skeleton, Stack, Text } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { LoadingSkeleton } from "@/shared/ui";
import type { BrokerageEvent } from "../api/useBrokerageEvents";
import { BrokerageEventCard } from "./BrokerageEventCard";
+161 -1
View File
@@ -3,7 +3,7 @@ import { act, renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import type { FC, PropsWithChildren } from "react";
import { describe, expect, it } from "vitest";
import { apiClient, apiQueryClient } from "@/shared/api";
import { apiClient, apiQueryClient, useAuthenticatedQuery } from "@/shared/api";
import { createTestQueryClient } from "@/test/query";
import { server } from "@/test/server";
import { AuthProvider, useAuth } from "./auth";
@@ -167,4 +167,164 @@ describe("AuthProvider", () => {
expect(queryClient.getQueryData(portfolioKey)).toBeUndefined();
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
});
it.each([
[false, false],
[true, false],
[false, true],
[true, true],
])(
"serializes late refresh (failure=%s, login=%s)",
async (failure, loginAfterLogout) => {
let release!: () => void;
const pending = new Promise<void>((resolve) => {
release = resolve;
});
let calls = 0;
const order: string[] = [];
server.use(
http.post("*/api/v1/auth/refresh", async () => {
if (++calls > 1) {
order.push("refresh-start");
await pending;
order.push("refresh-cookie");
}
return failure && calls > 1
? HttpResponse.error()
: HttpResponse.json({
accessToken: "a",
user: { id: "a", email: "a@example.com" },
});
}),
http.post("*/api/v1/auth/logout", () => {
order.push("logout-cookie");
return new HttpResponse(null, { status: 204 });
}),
http.post("*/api/v1/auth/login", () => {
order.push("login-cookie");
return HttpResponse.json({
accessToken: "b",
user: { id: "b", email: "b@example.com" },
});
}),
http.get("*/api/v1/brokerage-accounts", () =>
HttpResponse.json({ code: "UNAUTHORIZED" }, { status: 401 }),
),
);
const queryClient = createTestQueryClient();
const wrapper: FC<PropsWithChildren> = ({ children }) => (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(result.current.ready).toBe(true));
const oldRequest = apiClient
.GET("/api/v1/brokerage-accounts")
.catch(() => null);
await waitFor(() => expect(order).toContain("refresh-start"));
let logout!: Promise<void>;
act(() => {
logout = result.current.logout();
});
await waitFor(() => expect(result.current.user).toBeNull());
let login!: Promise<void>;
act(() => {
login = loginAfterLogout
? result.current.login("b@example.com", "password")
: Promise.resolve();
});
await act(async () => {
release();
await Promise.all([oldRequest, logout, login]);
});
expect(result.current.user?.id ?? null).toBe(
loginAfterLogout ? "b" : null,
);
expect(order).toEqual([
"refresh-start",
"refresh-cookie",
"logout-cookie",
...(loginAfterLogout ? ["login-cookie"] : []),
]);
},
);
it("preserves same-user cache and removes inactive and pending data on refresh identity change", async () => {
let identity = "a";
server.use(
http.post("*/api/v1/auth/refresh", () =>
HttpResponse.json({
accessToken: identity,
user: { id: identity, email: `${identity}@example.com` },
}),
),
);
const queryClient = createTestQueryClient();
const wrapper: FC<PropsWithChildren> = ({ children }) => (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(result.current.ready).toBe(true));
queryClient.setQueryData(bankCardsKey, [{ id: "a-card" }]);
await act(() => result.current.refresh());
expect(queryClient.getQueryData(bankCardsKey)).toEqual([{ id: "a-card" }]);
let release!: (value: string) => void;
const pending = queryClient
.fetchQuery({
queryKey: ["pending-finance"],
queryFn: () =>
new Promise<string>((resolve) => {
release = resolve;
}),
})
.catch(() => null);
identity = "b";
await act(() => result.current.refresh());
release("a-data");
await pending;
expect(result.current.user?.id).toBe("b");
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
expect(queryClient.getQueryData(["pending-finance"])).toBeUndefined();
});
it("replaces an observed financial query when refresh changes identity", async () => {
let identity = "a";
server.use(
http.post("*/api/v1/auth/refresh", () =>
HttpResponse.json({
accessToken: identity,
user: { id: identity, email: `${identity}@example.com` },
}),
),
http.get("*/api/v1/bank-cards", () =>
HttpResponse.json([{ id: `${identity}-card` }]),
),
);
const queryClient = createTestQueryClient();
const wrapper: FC<PropsWithChildren> = (props) => (
<QueryClientProvider client={queryClient}>
<AuthProvider>{props.children}</AuthProvider>
</QueryClientProvider>
);
const { result } = renderHook(
() => ({
auth: useAuth(),
cards: useAuthenticatedQuery(
apiQueryClient.queryOptions("get", "/api/v1/bank-cards", {
params: { query: { includeArchived: "false" } },
}),
),
}),
{ wrapper },
);
await waitFor(() =>
expect(result.current.cards.data?.[0].id).toBe("a-card"),
);
identity = "b";
await act(() => result.current.auth.refresh());
await waitFor(() =>
expect(result.current.cards.data?.[0].id).toBe("b-card"),
);
});
});
+57 -32
View File
@@ -47,49 +47,70 @@ const AuthProvider: FC<PropsWithChildren> = (props) => {
const accessTokenRef = useRef<string | null>(null);
const [ready, setReady] = useState(false);
const generation = useRef(0);
const userRef = useRef<User | null>(null);
const authQueue = useRef<Promise<unknown>>(Promise.resolve());
const refreshPromise = useRef<Promise<boolean> | null>(null);
const applyAuthentication = useCallback((authentication: Authentication) => {
setUser(authentication.user);
setAccessToken(authentication.accessToken);
accessTokenRef.current = authentication.accessToken;
// Cookie-writing requests share ordering, including across tabs with Web Locks.
const serialize = useCallback(<T,>(run: () => Promise<T>): Promise<T> => {
const next = authQueue.current.then(async () =>
"locks" in navigator
? navigator.locks.request("wealth-ledger-refresh", run)
: run(),
);
authQueue.current = next.catch(() => undefined);
return next;
}, []);
const applyAuthentication = useCallback(
(authentication: Authentication) => {
const changedIdentity =
userRef.current && userRef.current.id !== authentication.user.id;
accessTokenRef.current = authentication.accessToken;
if (changedIdentity) {
generation.current += 1;
queryClient.removeQueries({ type: "inactive" });
queryClient.getMutationCache().clear();
void queryClient.resetQueries();
}
userRef.current = authentication.user;
setUser(authentication.user);
setAccessToken(authentication.accessToken);
},
[queryClient],
);
const clearSession = useCallback(() => {
generation.current += 1;
userRef.current = null;
setUser(null);
setAccessToken(null);
accessTokenRef.current = null;
queryClient.clear();
}, [queryClient]);
const refresh = useCallback(async (): Promise<boolean> => {
const refresh = useCallback((): Promise<boolean> => {
if (refreshPromise.current) return refreshPromise.current;
refreshPromise.current = (async () => {
const run = async () => {
try {
const { data } = await apiClient.POST("/api/v1/auth/refresh");
if (!data) {
clearSession();
return false;
}
applyAuthentication(data as Authentication);
return true;
} catch {
const started = generation.current;
const pending = serialize(async () => {
if (started !== generation.current) return false;
try {
const { data } = await apiClient.POST("/api/v1/auth/refresh");
if (started !== generation.current) return false;
if (!data) {
clearSession();
return false;
}
};
try {
return "locks" in navigator
? navigator.locks.request("wealth-ledger-refresh", run)
: run();
applyAuthentication(data);
return true;
} catch {
clearSession();
if (started === generation.current) clearSession();
return false;
}
})().finally(() => {
refreshPromise.current = null;
}).finally(() => {
if (refreshPromise.current === pending) refreshPromise.current = null;
});
return refreshPromise.current;
}, [applyAuthentication, clearSession]);
refreshPromise.current = pending;
return pending;
}, [applyAuthentication, clearSession, serialize]);
useEffect(() => {
void refresh().finally(() => setReady(true));
@@ -100,21 +121,25 @@ const AuthProvider: FC<PropsWithChildren> = (props) => {
email: string,
password: string,
) {
const authentication = await request(path, email, password);
applyAuthentication(authentication);
clearSession();
const started = generation.current;
await serialize(async () => {
const authentication = await request(path, email, password);
if (started === generation.current) applyAuthentication(authentication);
});
}
async function logout() {
try {
clearSession();
await serialize(async () => {
await apiClient.POST("/api/v1/auth/logout");
} finally {
clearSession();
}
});
}
useEffect(() => {
configureAuthClient({
accessToken: () => accessTokenRef.current,
generation: () => generation.current,
refresh,
clear: clearSession,
});
@@ -8,9 +8,9 @@ import {
Text,
Title,
} from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC, PropsWithChildren, ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { LoadingSkeleton } from "@/shared/ui";
import type { SectionState } from "../model/section";
import classes from "./InstrumentDetails.module.css";
@@ -1,7 +1,7 @@
import { Alert, Button, Skeleton } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { LoadingSkeleton } from "@/shared/ui";
type TbankConnectionErrorProps = {
retry: () => void;
+1
View File
@@ -3,6 +3,7 @@ import { createRoot } from "react-dom/client";
import "@mantine/core/styles.css";
import "@mantine/charts/styles.css";
import "@mantine/dates/styles.css";
import "@wealthledger/ui/styles.css";
import "dayjs/locale/ru";
import "./shared/i18n";
import { App } from "./app";
@@ -1,6 +1,6 @@
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { StateView } from "@/shared/ui";
const AccountEventsPageEmpty: FC = () => {
const { t } = useTranslation();
@@ -1,7 +1,7 @@
import { Button } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { StateView } from "@/shared/ui";
type AccountEventsPageErrorProps = { retry: () => void };
@@ -1,7 +1,7 @@
import { Group, Skeleton } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { LoadingSkeleton } from "@/shared/ui";
const skeletonRowIds = ["first", "second", "third", "fourth"];
+46
View File
@@ -0,0 +1,46 @@
type IncomePeriod = { from: string; to: string };
type IncomeForm = IncomePeriod;
const datePattern = /^\d{4}-\d{2}-\d{2}$/;
function formatDraftDate(value: string): string {
const [year, month, day] = value.split("-");
return `${day}.${month}.${year}`;
}
function parseDraftDate(value: string): string | null {
if (!/^\d{2}\.\d{2}\.\d{4}$/.test(value)) return null;
const [day, month, year] = value.split(".");
const date = `${year}-${month}-${day}`;
return isDate(date) ? date : null;
}
function isDate(value: string): boolean {
if (!datePattern.test(value)) return false;
const parsed = new Date(`${value}T00:00:00Z`);
return (
Number.isFinite(parsed.valueOf()) &&
parsed.toISOString().slice(0, 10) === value
);
}
function moscowDate(value: Date): string {
const parts = new Intl.DateTimeFormat("en-CA", {
timeZone: "Europe/Moscow",
year: "numeric",
month: "2-digit",
day: "2-digit",
}).formatToParts(value);
const part = (type: string) =>
parts.find((item) => item.type === type)?.value;
return `${part("year")}-${part("month")}-${part("day")}`;
}
export {
formatDraftDate,
type IncomeForm,
type IncomePeriod,
isDate,
moscowDate,
parseDraftDate,
};
@@ -23,8 +23,9 @@ import type { IncomeAnalytics } from "@/entities/income";
import { configureAuthClient } from "@/shared/api";
import { createQueryWrapper } from "@/test/query";
import { server } from "@/test/server";
import { isDate } from "../model/period";
import { AccountIncomePage } from "./AccountIncomePage";
import { isDate, toIncomeDisplayModel } from "./AccountIncomePage.vm";
import { toIncomeDisplayModel } from "./AccountIncomePage.vm";
import { IncomePayments } from "./components/IncomePayments.view";
const analytics = {
@@ -6,12 +6,17 @@ import { z } from "zod";
import { type IncomeAnalytics, useIncomeAnalytics } from "@/entities/income";
import { validationMessage } from "@/shared/i18n";
import { formatDate } from "@/shared/lib";
import {
formatDraftDate,
type IncomeForm,
type IncomePeriod,
isDate,
moscowDate,
parseDraftDate,
} from "../model/period";
const ISO_MONTH_LENGTH = 7;
type IncomePeriod = { from: string; to: string };
type IncomeForm = IncomePeriod;
type IncomeDisplayModel = {
entries: { key: string; operation: IncomeAnalytics["entries"][number] }[];
comparison: {
@@ -41,7 +46,6 @@ type AccountIncomePageViewModel =
onSubmit: (values: IncomeForm) => void;
};
const datePattern = /^\d{4}-\d{2}-\d{2}$/;
const draftDate = z
.string()
.refine((value) => parseDraftDate(value) !== null, {
@@ -129,18 +133,6 @@ const useAccountIncomePageViewModel = (
};
};
function formatDraftDate(value: string): string {
const [year, month, day] = value.split("-");
return `${day}.${month}.${year}`;
}
function parseDraftDate(value: string): string | null {
if (!/^\d{2}\.\d{2}\.\d{4}$/.test(value)) return null;
const [day, month, year] = value.split(".");
const date = `${year}-${month}-${day}`;
return isDate(date) ? date : null;
}
function draftPeriod(period: IncomePeriod): IncomeForm {
return { from: formatDraftDate(period.from), to: formatDraftDate(period.to) };
}
@@ -163,15 +155,6 @@ function validPeriod(period: IncomePeriod): period is IncomePeriod {
);
}
function isDate(value: string): boolean {
if (!datePattern.test(value)) return false;
const parsed = new Date(`${value}T00:00:00Z`);
return (
Number.isFinite(parsed.valueOf()) &&
parsed.toISOString().slice(0, 10) === value
);
}
function toIncomeDisplayModel(
analytics: IncomeAnalytics,
): IncomeDisplayModel | null {
@@ -276,26 +259,9 @@ function formatIncomeChange(
}).format(ratio);
}
function moscowDate(value: Date): string {
const parts = new Intl.DateTimeFormat("en-CA", {
timeZone: "Europe/Moscow",
year: "numeric",
month: "2-digit",
day: "2-digit",
}).formatToParts(value);
const part = (type: string) =>
parts.find((item) => item.type === type)?.value;
return `${part("year")}-${part("month")}-${part("day")}`;
}
export {
type AccountIncomePageViewModel,
formatDraftDate,
type IncomeDisplayModel,
type IncomeForm,
isDate,
moscowDate,
parseDraftDate,
toIncomeDisplayModel,
useAccountIncomePageViewModel,
};
@@ -1,7 +1,7 @@
import { Button } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { StateView } from "@/shared/ui";
import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
type ErrorProps = Extract<AccountIncomePageViewModel, { state: "error" }>;
@@ -7,10 +7,10 @@ import {
Text,
Title,
} from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { FormProvider } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { StateView } from "@/shared/ui";
import classes from "../AccountIncomePage.module.css";
import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
import { IncomeComparisons } from "./IncomeComparisons.view";
@@ -1,7 +1,7 @@
import { Paper, Skeleton, Stack } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { LoadingSkeleton } from "@/shared/ui";
import classes from "../AccountIncomePage.module.css";
const AccountIncomePageLoading: FC = () => {
@@ -0,0 +1,58 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import type { FC } from "react";
import { FormProvider, useForm, useFormState } from "react-hook-form";
import type { IncomeForm } from "../../model/period";
import { IncomePeriodForm } from "./IncomePeriodForm.view";
const period = { from: "01.08.2026", to: "27.08.2026" };
const errors = {
to: { type: "manual", message: "Синтетическая ошибка периода" },
};
type PeriodExampleProps = { invalid?: boolean };
const PeriodExample: FC<PeriodExampleProps> = (props) => {
const methods = useForm<IncomeForm>({
defaultValues: period,
errors: props.invalid ? errors : undefined,
});
const { isSubmitSuccessful } = useFormState({ control: methods.control });
const submitted = isSubmitSuccessful ? methods.getValues() : null;
return (
<FormProvider {...methods}>
<IncomePeriodForm
onSubmit={methods.handleSubmit(() => undefined)}
onReset={() => {
methods.reset(period);
}}
/>
<output aria-live="polite">
{submitted
? `Применено: ${submitted.from} – ${submitted.to}`
: "Период не применён"}
</output>
</FormProvider>
);
};
const meta = {
title: "Product/IncomePeriodForm",
component: PeriodExample,
tags: ["autodocs"],
parameters: {
docs: {
description: {
component:
"Изолированная форма с синтетическим периодом. Submit показывает значения локально; reset возвращает fixture. Ошибка задана явно: query, URL и production validation остаются у page VM, API и router providers не используются.",
},
},
},
render: () => <PeriodExample />,
} satisfies Meta<typeof PeriodExample>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Default: Story = {};
export const ValidationError: Story = {
render: () => <PeriodExample invalid />,
};
@@ -3,13 +3,13 @@ import { DatePickerInput } from "@mantine/dates";
import type { FC, FormEventHandler } from "react";
import { useController, useFormContext, useWatch } from "react-hook-form";
import { useTranslation } from "react-i18next";
import classes from "../AccountIncomePage.module.css";
import {
formatDraftDate,
type IncomeForm,
moscowDate,
parseDraftDate,
} from "../AccountIncomePage.vm";
} from "../../model/period";
import classes from "../AccountIncomePage.module.css";
type IncomePeriodFormProps = {
onSubmit: FormEventHandler<HTMLFormElement>;
@@ -1,7 +1,7 @@
import { Button } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { StateView } from "@/shared/ui";
import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm";
type AccountOperationsPageErrorProps = Extract<
@@ -8,6 +8,7 @@ import {
Title,
} from "@mantine/core";
import { DatePickerInput } from "@mantine/dates";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import {
@@ -15,7 +16,6 @@ import {
type OperationCategory,
operationCategories,
} from "@/entities/broker-operation";
import { StateView } from "@/shared/ui";
import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm";
type AccountOperationsPageLoadedProps = Extract<
@@ -1,7 +1,7 @@
import { Group, Skeleton, Stack } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { LoadingSkeleton } from "@/shared/ui";
const skeletonRowIds = ["first", "second", "third", "fourth"];
+2 -2
View File
@@ -63,11 +63,11 @@
}
.positive {
color: var(--mantine-color-green-6);
color: var(--wl-color-positive);
}
.negative {
color: var(--mantine-color-red-6);
color: var(--wl-color-negative);
}
.expandedCard {
@@ -1,9 +1,9 @@
import { Stack } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import type { BrokerageAccount } from "@/entities/brokerage-account";
import { BrokerageEventsPreview } from "@/entities/brokerage-event";
import { StateView } from "@/shared/ui";
import type {
AccountPageIncomeSummary,
AccountPageRecentEvents,
@@ -1,8 +1,8 @@
import { Button } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { StateView } from "@/shared/ui";
type AccountPageErrorProps = { code?: string; retry: () => void };
@@ -1,7 +1,7 @@
import { Paper, SimpleGrid, Skeleton } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { LoadingSkeleton } from "@/shared/ui";
import classes from "../AccountPage.module.css";
const AccountPageLoading: FC = () => {
@@ -1,10 +1,10 @@
import { Button, Paper, Stack, Text } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import type { IncomeSummary as IncomeSummaryData } from "@/entities/income";
import { formatMoney } from "@/shared/lib";
import { StateView } from "@/shared/ui";
type IncomeSummaryProps =
| { state: "loading"; to: string }
@@ -1,9 +1,9 @@
import { Alert, Button, Skeleton, Stack, Text } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { LedgerEntryRow } from "@/entities/broker-operation";
import { LoadingSkeleton } from "@/shared/ui";
import type { AccountPageRecentOperations } from "../AccountPage.vm";
type RecentOperationsProps = {
@@ -1,7 +1,7 @@
import { Stack } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { StateView } from "@/shared/ui";
import {
AccountsRefreshState,
type AccountsRefreshStateProps,
@@ -1,8 +1,8 @@
import { Button, Stack } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { StateView } from "@/shared/ui";
type AccountsPageErrorProps = { code?: string; retry?: () => void };
@@ -1,7 +1,7 @@
import { Card, Group, SimpleGrid, Skeleton, Stack } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { LoadingSkeleton } from "@/shared/ui";
const AccountsPageLoading: FC = () => {
const { t } = useTranslation();
+1 -1
View File
@@ -1,8 +1,8 @@
import { Anchor, Button, Skeleton, Stack, Text, Title } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link, Navigate } from "react-router";
import { LoadingSkeleton } from "@/shared/ui";
import { BondPageView } from "./BondPage.view";
import { useBondPageVm } from "./BondPage.vm";
+1 -1
View File
@@ -12,6 +12,7 @@ import {
Text,
Title,
} from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import {
@@ -26,7 +27,6 @@ import {
formatMoney,
formatSnapshotTime,
} from "@/shared/lib";
import { LoadingSkeleton } from "@/shared/ui";
import classes from "./BondPage.module.css";
import type { BondPageVm } from "./BondPage.vm";
+1 -1
View File
@@ -12,6 +12,7 @@ import {
TextInput,
Title,
} from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
@@ -21,7 +22,6 @@ import {
formatMoney,
formatSnapshotTime,
} from "@/shared/lib";
import { LoadingSkeleton } from "@/shared/ui";
import classes from "./BondsPage.module.css";
import type { BondsPageVm } from "./BondsPage.vm";
+23 -71
View File
@@ -10,6 +10,8 @@ import {
Text,
Title,
} from "@mantine/core";
import { AddIcon, DeleteIcon, EditIcon } from "@wealthledger/icons";
import { EntryCard, LoadingSkeleton, StateView } from "@wealthledger/ui";
import { type FC, useLayoutEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
@@ -20,7 +22,6 @@ import {
BankPeriodPicker,
BankSummaryView,
} from "@/entities/bank-card";
import { EntryCard, LoadingSkeleton, StateView } from "@/shared/ui";
import classes from "./CardPage.module.css";
import type { CardPageVm } from "./CardPage.vm";
@@ -106,19 +107,7 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
title={t("bank.editCard")}
onClick={() => vm.setEditingCard(true)}
>
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<path d="m16 3 5 5-12 12-6 1 1-6L16 3Z M13 6l5 5" />
</svg>
<EditIcon size={18} strokeWidth={1.5} />
</ActionIcon>
<ActionIcon
variant="subtle"
@@ -130,25 +119,23 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
loading={vm.archivePending}
onClick={() => void vm.toggleArchive()}
>
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<path
d={
card.archivedAt
? "M3 3h18v4H3z M5 7v14h14V7 M12 17V10m-3 3 3-3 3 3"
: "M3 6h18 M9 6V3h6v3 M5 6l1 15h12l1-15 M10 10v7 M14 10v7"
}
/>
</svg>
{card.archivedAt ? (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<path d="M3 3h18v4H3z M5 7v14h14V7 M12 17V10m-3 3 3-3 3 3" />
</svg>
) : (
<DeleteIcon size={18} strokeWidth={1.5} />
)}
</ActionIcon>
</Group>
</div>
@@ -196,18 +183,7 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
disabled={Boolean(card.archivedAt) || !vm.cards.data}
onClick={() => vm.setOperation("new")}
>
<svg
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
aria-hidden="true"
>
<path d="M12 5v14 M5 12h14" />
</svg>
<AddIcon size={20} strokeWidth={1.5} />
</ActionIcon>
</Group>
<Select
@@ -279,19 +255,7 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
title={t("bank.edit")}
onClick={() => vm.setOperation(row.item)}
>
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<path d="m16 3 5 5-12 12-6 1 1-6L16 3Z M13 6l5 5" />
</svg>
<EditIcon size={18} strokeWidth={1.5} />
</ActionIcon>
<ActionIcon
variant="subtle"
@@ -306,19 +270,7 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
title={t("bank.delete")}
onClick={() => vm.setDeleting(row.item)}
>
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<path d="M3 6h18 M9 6V3h6v3 M5 6l1 15h12l1-15 M10 10v7 M14 10v7" />
</svg>
<DeleteIcon size={18} strokeWidth={1.5} />
</ActionIcon>
</Group>
}
+113
View File
@@ -0,0 +1,113 @@
import { Alert } from "@mantine/core";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { type FC, useState } from "react";
import { FormProvider, useForm, useWatch } from "react-hook-form";
import type { OperationValues } from "./OperationForm.types";
import { OperationFormView } from "./OperationForm.view";
type ExampleProps = { pending?: boolean; conflict?: boolean };
const OperationExample: FC<ExampleProps> = (props) => {
const [opened, setOpened] = useState(true);
const [action, setAction] = useState("");
const methods = useForm<OperationValues>({
defaultValues: {
kind: "refund",
cardId: "demo",
targetCardId: "",
categoryId: "",
originalExpenseId: "purchase",
amount: "500",
date: "2026-08-01",
description: "Синтетический возврат",
},
});
const kind = useWatch({ control: methods.control, name: "kind" });
return (
<FormProvider {...methods}>
<OperationFormView
opened={opened}
pending={Boolean(props.pending)}
editing
categoriesOpen={false}
onClose={() => !props.pending && setOpened(false)}
onCancel={() => setOpened(false)}
onExitTransitionEnd={() => setAction("Форма закрыта")}
onSubmit={(event) => {
event.preventDefault();
setAction("Локальный submit");
}}
fields={{
editing: true,
refundCardId: "demo",
kind,
cards: [{ value: "demo", label: "Учебная карта" }],
targets: [],
categories: [],
defaultCategory: "",
kinds: [{ value: "refund", label: "Возврат" }],
dateInputValue: () => "2026-08-01",
validDate: (value) => value === "2026-08-01",
maxDate: () => "2026-08-27",
}}
refund={{
editing: true,
expenses: [
{
value: "purchase",
label: "01.07.2026 · Учебная покупка · 500 ₽",
},
],
onSelect: () => undefined,
limit: { currency: "RUB", value: "500" },
}}
loadingExpenses={false}
emptyExpenses={false}
sourcePage={1}
previousDisabled
nextDisabled
onPrevious={() => undefined}
onNext={() => undefined}
onAddCategory={() => undefined}
saveDisabled={false}
feedback={
props.conflict && (
<Alert color="orange" role="alert">
Синтетический конфликт версии
</Alert>
)
}
onReload={
props.conflict ? () => setAction("Локальный reload") : undefined
}
latest={
props.conflict
? {
version: 2,
details: "Учебная версия",
onAdopt: () => setAction("Локальное принятие версии"),
}
: undefined
}
/>
<output aria-live="polite">{action}</output>
</FormProvider>
);
};
const meta = {
title: "Product/OperationForm",
component: OperationExample,
tags: ["autodocs"],
parameters: {
docs: {
description: {
component:
"Synthetic presentation без API/VM. Date callbacks фиксируют fixture 01.08.2026; денежная validation, recovery и nested category flow проверяются application tests. Actions только локальные.",
},
},
},
} satisfies Meta<typeof OperationExample>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Refund: Story = {};
export const Pending: Story = { args: { pending: true } };
export const Conflict: Story = { args: { conflict: true } };
+38
View File
@@ -70,6 +70,43 @@ async function select(label: string, value: string | RegExp) {
fireEvent.click(await screen.findByRole("option", { name: value }));
}
describe("OperationForm", () => {
it("blocks closing and editing while save is pending, then closes after success", async () => {
let finish: () => void = () => {};
const response = new Promise<void>((resolve) => {
finish = resolve;
});
const received = vi.fn();
server.use(
http.post("*/api/v1/bank-cards/operations", async () => {
received();
await response;
return HttpResponse.json({}, { status: 201 });
}),
);
const close = setup();
await waitFor(() =>
expect(screen.getByRole("combobox", { name: /Категория/ })).toHaveValue(
"Остальное",
),
);
fireEvent.change(screen.getByLabelText(/Сумма/), {
target: { value: "10" },
});
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
await waitFor(() => expect(received).toHaveBeenCalledOnce());
try {
expect(screen.getByLabelText(/Сумма/)).toBeDisabled();
expect(screen.getByRole("button", { name: "Закрыть" })).toBeDisabled();
expect(screen.getByRole("button", { name: "Отмена" })).toBeDisabled();
fireEvent.keyDown(document, { key: "Escape" });
expect(close).not.toHaveBeenCalled();
expect(screen.getByRole("dialog")).toBeInTheDocument();
} finally {
finish();
}
await waitFor(() => expect(close).toHaveBeenCalledOnce());
});
it("uses renamed default category and exact maximum positive money despite zero balance", async () => {
const close = setup();
await waitFor(() =>
@@ -95,6 +132,7 @@ describe("OperationForm", () => {
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
await waitFor(() => expect(close).toHaveBeenCalled());
expect(body).toMatchObject({
kind: "expense",
categoryId: "default",
date: "2026-08-07",
amount: money("92233720368547758.07"),
+42 -411
View File
@@ -1,420 +1,51 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { Button, Group, Modal, Stack, Text } from "@mantine/core";
import { type FC, useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { z } from "zod";
import {
type BankCard,
BankFeedback,
type BankOperation,
bankDateSchema,
bankMoneyValue,
bankToday,
CategoryManager,
moneyCents,
positiveMoneySchema,
useBankCategories,
useBankExpenses,
useBankFormFocus,
useBankMutations,
useBankOperation,
} from "@/entities/bank-card";
import { validationMessage } from "@/shared/i18n";
import { formatDate, formatMoney } from "@/shared/lib";
import classes from "./OperationForm.module.css";
import type { OperationValues } from "./OperationForm.types";
import { OperationFields, RefundFields } from "./OperationForm.view";
import type { FC } from "react";
import { FormProvider } from "react-hook-form";
import { BankFeedback, CategoryManager } from "@/entities/bank-card";
import type { OperationFormProps } from "./OperationForm.types";
import { OperationFormView } from "./OperationForm.view";
import { useOperationFormVm } from "./OperationForm.vm";
const MAX_DESCRIPTION_LENGTH = 500;
const operationSchema = z.object({
kind: z.enum(["expense", "topup", "transfer", "refund"]),
cardId: z.string(),
targetCardId: z.string(),
categoryId: z.string(),
originalExpenseId: z.string(),
amount: positiveMoneySchema,
date: bankDateSchema,
description: z
.string()
.max(
MAX_DESCRIPTION_LENGTH,
validationMessage("bank.validation.description")(undefined),
),
});
type OperationFormProps = {
card: BankCard;
cards: BankCard[];
operation?: BankOperation;
onClose: () => void;
};
const OperationForm: FC<OperationFormProps> = (props) => {
useBankFormFocus();
const [opened, setOpened] = useState(true);
const { t } = useTranslation();
const [categoriesOpen, setCategoriesOpen] = useState(false);
const [version, setVersion] = useState(props.operation?.version ?? 1);
const [latest, setLatest] = useState<BankOperation>();
const [sourcePage, setSourcePage] = useState(1);
const [sourceId, setSourceId] = useState(
props.operation?.originalExpenseId ?? "",
);
const sourceQuery = useBankOperation(sourceId || undefined);
const currentQuery = useBankOperation(props.operation?.id);
const [refundLimit, setRefundLimit] = useState(
props.operation?.availableRefund,
);
const [intent] = useState(() => crypto.randomUUID());
const [submittedValues, setSubmittedValues] = useState<OperationValues>();
const [error, setError] = useState<unknown>();
const categories = useBankCategories();
const mutation = useBankMutations();
const methods = useForm<OperationValues>({
resolver: zodResolver(
operationSchema.superRefine((values, ctx) => {
// Repeated intent reaches server idempotency even after its source changed.
if (
submittedValues &&
JSON.stringify(values) === JSON.stringify(submittedValues)
)
return;
const source = props.cards.find((c) => c.id === values.cardId);
const target = props.cards.find((c) => c.id === values.targetCardId);
if (!source || source.archivedAt)
ctx.addIssue({
code: "custom",
path: ["cardId"],
...validationMessage("bank.validation.required")(undefined),
});
if (
values.kind === "transfer" &&
(!target || target.archivedAt || target.id === values.cardId)
)
ctx.addIssue({
code: "custom",
path: ["targetCardId"],
...validationMessage("bank.validation.destination")(undefined),
});
if (
(source && values.date < source.openingDate) ||
(values.kind === "transfer" &&
target &&
values.date < target.openingDate)
)
ctx.addIssue({
code: "custom",
path: ["date"],
...validationMessage("bank.validation.start")(undefined),
});
if (values.kind === "refund") {
const expense = sourceQuery.data;
if (!expense || expense.cardId !== values.cardId)
ctx.addIssue({
code: "custom",
path: ["originalExpenseId"],
...validationMessage("bank.validation.required")(undefined),
});
if (expense && values.date < expense.date)
ctx.addIssue({
code: "custom",
path: ["date"],
...validationMessage("bank.validation.start")(undefined),
});
const limit = props.operation
? refundLimit
: expense?.availableRefund;
const amount = moneyCents(values.amount);
if (
limit &&
amount !== null &&
amount > (moneyCents(limit.value) ?? 0n)
)
ctx.addIssue({
code: "custom",
path: ["amount"],
...validationMessage("bank.validation.refund")(undefined),
});
}
if (
values.kind === "expense" &&
!categories.data?.some(
(c) =>
c.id ===
(values.categoryId ||
categories.data?.find((c) => c.isDefault)?.id),
)
)
ctx.addIssue({
code: "custom",
path: ["categoryId"],
...validationMessage("bank.validation.required")(undefined),
});
}),
),
defaultValues: {
kind: props.operation?.kind ?? "expense",
cardId: props.operation?.cardId ?? props.card.id,
targetCardId: props.operation?.targetCardId ?? "",
categoryId: props.operation?.categoryId ?? "",
originalExpenseId: props.operation?.originalExpenseId ?? "",
amount: props.operation?.amount.value ?? "",
date: props.operation?.date ?? bankToday(),
description: props.operation?.description ?? "",
},
});
const kind = methods.watch("kind");
const expenses = useBankExpenses(
kind === "refund" ? props.card.id : undefined,
{ page: sourcePage },
);
const source = methods.watch("cardId");
const pending = !opened || methods.formState.isSubmitting;
const options = props.cards
.filter((c) => !c.archivedAt)
.map((c) => ({ value: c.id, label: c.name }));
const vm = useOperationFormVm(props);
return (
<>
<Modal
opened={opened}
onExitTransitionEnd={props.onClose}
onClose={() => !pending && !categoriesOpen && setOpened(false)}
title={t(props.operation ? "bank.editOperation" : "bank.addOperation")}
closeOnEscape={!pending && !categoriesOpen}
closeOnClickOutside={!pending && !categoriesOpen}
closeButtonProps={{ "aria-label": t("bank.close"), disabled: pending }}
>
<FormProvider {...methods}>
<form
onSubmit={methods.handleSubmit(async (values) => {
setSubmittedValues(values);
setError(undefined);
try {
const body = {
kind: values.kind,
cardId: values.cardId,
...(values.kind === "transfer"
? { targetCardId: values.targetCardId }
: {}),
...(values.kind === "expense"
? {
categoryId:
values.categoryId ||
categories.data?.find((c) => c.isDefault)?.id,
}
: {}),
...(values.kind === "refund"
? { originalExpenseId: values.originalExpenseId }
: {}),
amount: {
currency: "RUB" as const,
value: bankMoneyValue(values.amount),
},
date: values.date,
description: values.description,
};
if (props.operation)
await mutation.updateOperation.mutateAsync({
id: props.operation.id,
body: { ...body, version },
});
else
await mutation.createOperation.mutateAsync({
id: intent,
...body,
});
setOpened(false);
} catch (failure) {
setError(failure);
}
})}
>
<fieldset disabled={pending} className={classes.fieldset}>
<Stack>
<OperationFields
refundCardId={props.card.id}
editing={Boolean(props.operation)}
kind={kind}
cards={options}
targets={options.filter((c) => c.value !== source)}
categories={
categories.data?.map((c) => ({
value: c.id,
label: c.name,
})) ?? []
}
defaultCategory={
categories.data?.find((c) => c.isDefault)?.id ?? ""
}
<FormProvider {...vm.methods}>
<OperationFormView
{...vm.view}
refundFeedback={
<>
{vm.expensesError && (
<BankFeedback
loadingError
error={vm.expensesError}
retry={vm.retryExpenses}
/>
{kind === "refund" && (
<>
<RefundFields
editing={Boolean(props.operation)}
expenses={
expenses.data?.items.map((item) => ({
value: item.id,
label: t("bank.expenseChoice", {
date: formatDate(item.date),
name: item.description || item.categoryName,
amount: formatMoney(item.amount),
available: formatMoney(item.availableRefund),
}),
})) ?? []
}
selected={
sourceQuery.data
? {
value: sourceQuery.data.id,
label: t("bank.expenseChoice", {
date: formatDate(sourceQuery.data.date),
name:
sourceQuery.data.description ||
sourceQuery.data.categoryName,
amount: formatMoney(sourceQuery.data.amount),
available: formatMoney(
sourceQuery.data.availableRefund,
),
}),
}
: undefined
}
onSelect={setSourceId}
limit={
props.operation
? refundLimit
: sourceQuery.data?.availableRefund
}
/>
{expenses.isLoading && (
<Text role="status">{t("bank.loadingHistory")}</Text>
)}
{expenses.data &&
!expenses.data.items.length &&
!props.operation && <Text>{t("bank.noPurchases")}</Text>}
{!props.operation && (
<Group>
<Button
variant="default"
disabled={sourcePage === 1 || expenses.isFetching}
onClick={() => setSourcePage(sourcePage - 1)}
>
{t("bank.previous")}
</Button>
<Text>{t("bank.page", { page: sourcePage })}</Text>
<Button
variant="default"
disabled={
!expenses.data?.hasNext || expenses.isFetching
}
onClick={() => setSourcePage(sourcePage + 1)}
>
{t("bank.next")}
</Button>
</Group>
)}
{expenses.isError && (
<BankFeedback
loadingError
error={expenses.error}
retry={() => void expenses.refetch()}
/>
)}{" "}
{sourceQuery.isError && (
<BankFeedback
loadingError
error={sourceQuery.error}
retry={() => void sourceQuery.refetch()}
/>
)}
</>
)}
{kind === "expense" && (
<Button
variant="subtle"
onClick={() => setCategoriesOpen(true)}
>
{t("bank.addCategory")}
</Button>
)}
{categories.isError && (
<BankFeedback
loadingError
error={categories.error}
retry={() => void categories.refetch()}
/>
)}
{error ? (
<>
<BankFeedback error={error} />
{(props.operation || sourceId) && (
<Button
variant="default"
onClick={async () => {
const query = props.operation
? currentQuery
: sourceQuery;
const result = await query.refetch();
if (result.data && !result.error) {
if (props.operation) {
setLatest(result.data);
setRefundLimit(result.data.availableRefund);
} else setError(undefined);
} else setError(result.error);
}}
>
{t("bank.reloadRecord")}
</Button>
)}
</>
) : null}
{latest && (
<>
<Text>
{t("bank.versionHint", {
details: `${formatDate(latest.date)} · ${formatMoney(latest.amount)} · ${latest.description ?? ""}`,
})}
</Text>
<Button
variant="default"
onClick={() => {
setVersion(latest.version);
setLatest(undefined);
setError(undefined);
}}
>
{t("bank.adoptVersion", { version: latest.version })}
</Button>
</>
)}
<Group>
<Button
type="submit"
loading={pending}
disabled={
(kind === "expense" && !categories.data) ||
(kind === "refund" && !sourceQuery.data)
}
>
{t("bank.save")}
</Button>
<Button variant="default" onClick={() => setOpened(false)}>
{t("bank.cancel")}
</Button>
</Group>
</Stack>
</fieldset>
</form>
</FormProvider>
</Modal>
{categoriesOpen && (
)}{" "}
{vm.sourceError && (
<BankFeedback
loadingError
error={vm.sourceError}
retry={vm.retrySource}
/>
)}
</>
}
categoriesFeedback={
vm.categoriesError && (
<BankFeedback
loadingError
error={vm.categoriesError}
retry={vm.retryCategories}
/>
)
}
feedback={vm.error ? <BankFeedback error={vm.error} /> : null}
/>
</FormProvider>
{vm.categoriesOpen && (
<CategoryManager
onClose={() => setCategoriesOpen(false)}
onCreated={(id) => {
methods.setValue("categoryId", id);
setCategoriesOpen(false);
}}
onClose={vm.closeCategories}
onCreated={vm.onCategoryCreated}
/>
)}
</>
+9 -2
View File
@@ -1,4 +1,4 @@
import type { BankOperation } from "@/entities/bank-card";
import type { BankCard, BankOperation } from "@/entities/bank-card";
type OperationValues = {
kind: BankOperation["kind"];
@@ -11,4 +11,11 @@ type OperationValues = {
description: string;
};
export type { OperationValues };
type OperationFormProps = {
card: BankCard;
cards: BankCard[];
operation?: BankOperation;
onClose: () => void;
};
export type { OperationFormProps, OperationValues };

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