Compare commits
5
Commits
v0.3.0
...
f876411a37
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f876411a37 | ||
|
|
5b2c6bb7cb | ||
|
|
60f9538886 | ||
|
|
fd73466073 | ||
|
|
edd54892cd |
+20
-11
@@ -51,23 +51,32 @@ Cross-slice consumer использует `@/` и `index.ts` владельца,
|
|||||||
композиция принадлежит вышележащему owner. Existing меж-slice исключения
|
композиция принадлежит вышележащему owner. Existing меж-slice исключения
|
||||||
не являются разрешением добавлять новые.
|
не являются разрешением добавлять новые.
|
||||||
|
|
||||||
Направление зависимостей и public imports частично проверяет
|
Направление зависимостей, public imports и запрет соседних slices в
|
||||||
`npm run deps`; Knip проверяет использование exports, а не смысл placement.
|
`pages`, `features`, `entities` проверяет `npm run deps`. Внутренние imports
|
||||||
|
одного slice и связи shared segments этот запрет не ограничивает.
|
||||||
|
Knip проверяет использование exports, а не смысл placement.
|
||||||
|
|
||||||
## UI foundation
|
## UI foundation
|
||||||
|
|
||||||
`shared/theme/tokens.json` — переносимый source design tokens; `theme.ts`
|
Private workspace `packages/tokens` экспортирует переносимый source design tokens
|
||||||
|
как `@wealthledger/tokens/tokens.json`. Private workspace `packages/ui`
|
||||||
адаптирует доверенный JSON к Mantine без runtime schema. App и Storybook читают
|
адаптирует доверенный JSON к Mantine без runtime schema. App и Storybook читают
|
||||||
public API `shared/theme`. Storybook показывает synthetic presentation states,
|
`@wealthledger/ui/theme` и явно подключают `@wealthledger/ui/styles.css` после
|
||||||
|
Mantine CSS. Потребители используют public exports пакетов напрямую. Storybook показывает synthetic presentation states,
|
||||||
не использует application API. RTL/MSW проверяют поведение приложения отдельно.
|
не использует application API. RTL/MSW проверяют поведение приложения отдельно.
|
||||||
|
|
||||||
Existing route-aware AppShell расположен в shared/ui; это legacy placement,
|
Route-aware AppShell и его navigation styles принадлежат `app/ui`;
|
||||||
а не образец нового shared primitive. При изменении foundation прочитай
|
`ProtectedLayout` использует public API этого владельца. При изменении foundation прочитай
|
||||||
[UI](conventions/ui.md#визуальная-основа) и [Storybook](conventions/storybook.md).
|
[UI](conventions/ui.md#визуальная-основа) и [Storybook](conventions/storybook.md).
|
||||||
|
|
||||||
|
Статичные Add/Edit/Delete и публичный `IconProps` принадлежат private
|
||||||
|
`packages/icons`; package не зависит от UI, domain или motion.
|
||||||
|
`BankOperationIcon` и mappings остаются у entity. Card/Cards используют package
|
||||||
|
Add/Edit/Delete; restore/category SVG остаются локальными.
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
|
|
||||||
- Общая busy-область: существующий [LoadingSkeleton](../src/shared/ui/LoadingSkeleton.tsx), а не domain widget в shared.
|
- Общая busy-область: существующий [LoadingSkeleton](../packages/ui/src/LoadingSkeleton.tsx), а не domain widget в shared.
|
||||||
- Account-income state views: [страница](../src/pages/account-income/ui/AccountIncomePage.tsx) и её flat `components/*.view.tsx`; новый page-local filter остаётся здесь.
|
- Account-income state views: [страница](../src/pages/account-income/ui/AccountIncomePage.tsx) и её flat `components/*.view.tsx`; новый page-local filter остаётся здесь.
|
||||||
- Portfolio query: [entity public API](../src/entities/portfolio/index.ts); новая UI-сводка с бизнес-смыслом не становится shared только из-за нескольких экранов.
|
- 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`;
|
После placement/import change: `npm run deps`, `npm run typecheck`, `npm run knip`;
|
||||||
после собственного behavior — применимые tests. Финальный gate указан в AGENTS.
|
после собственного behavior — применимые tests. Финальный gate указан в AGENTS.
|
||||||
Existing dependency config не запрещает все same-layer imports: их и смысл
|
Graph `src` и `packages` проверяет текущий dependency-cruiser; зависимости
|
||||||
owner проверяет review. Не объявляй Steiger установленным; graph проверяет
|
из packages в код приложения `src` запрещены. Generated `packages/*/dist`
|
||||||
текущий dependency-cruiser. Review отдельно проверяет смысл owner: разрешённый dependency graph не доказывает
|
не анализируется как исходник; все package sources остаются в graph. Review отдельно проверяет смысл
|
||||||
правильный выбор слоя.
|
owner: разрешённый dependency graph не доказывает правильный выбор слоя.
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
# Storybook
|
# Storybook
|
||||||
|
|
||||||
|
Единый каталог включает stories приложения и `packages/*/src`; общие
|
||||||
|
StateView/LoadingSkeleton и их stories принадлежат `packages/ui`.
|
||||||
|
|
||||||
## Когда нужна story
|
## Когда нужна story
|
||||||
|
|
||||||
- Shared UI/theme: показывай принятые visual roles и переиспользуемое поведение.
|
- Shared UI/theme: показывай принятые visual roles и переиспользуемое поведение.
|
||||||
@@ -23,7 +26,7 @@ Stories не достигают application API, auth, VM и query providers д
|
|||||||
контракт: keyboard activation, доступность действия, local callback. Не повторяй
|
контракт: keyboard activation, доступность действия, local callback. Не повторяй
|
||||||
RTL suite и не тестируй внутренности Mantine. Существующий
|
RTL suite и не тестируй внутренности Mantine. Существующий
|
||||||
[Button](../../src/shared/ui/Button.stories.tsx) показывает themed control
|
[Button](../../src/shared/ui/Button.stories.tsx) показывает themed control
|
||||||
без production wrapper; [LoadingSkeleton](../../src/shared/ui/LoadingSkeleton.stories.tsx)
|
без production wrapper; [LoadingSkeleton](../../packages/ui/src/LoadingSkeleton.stories.tsx)
|
||||||
— значимые busy states.
|
— значимые busy states.
|
||||||
|
|
||||||
`npm run typecheck`, `npm run deps:storybook`, `npm run build:catalog` проверяют
|
`npm run typecheck`, `npm run deps:storybook`, `npm run build:catalog` проверяют
|
||||||
|
|||||||
+26
-4
@@ -13,7 +13,10 @@ Mantine component и общую тему. Для выпадающего выбо
|
|||||||
|
|
||||||
Icons ищи у существующего owner (например,
|
Icons ищи у существующего owner (например,
|
||||||
[BankOperationIcon](../../src/entities/bank-card/ui/BankOperationIcon.tsx));
|
[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, даже при повторном использовании.
|
components живут у feature/entity/page, даже при повторном использовании.
|
||||||
|
|
||||||
Wrapper нужен для проектной ответственности, а не ради нового имени
|
Wrapper нужен для проектной ответственности, а не ради нового имени
|
||||||
@@ -107,10 +110,29 @@ loading/error/empty/loaded и recovery по применимости. [Storybook
|
|||||||
|
|
||||||
## Визуальная основа
|
## Визуальная основа
|
||||||
|
|
||||||
Общая тема живёт в `src/shared/theme`: `tokens.json` задаёт переносимые значения,
|
Private workspace `packages/tokens` владеет переносимыми значениями
|
||||||
`theme.ts` адаптирует их к Mantine. Используй public API темы и её semantic roles,
|
`tokens.json`; `packages/ui/src/theme.ts` читает export пакета
|
||||||
без отдельной палитры в page/component. Поддерживается светлая схема.
|
`@wealthledger/tokens/tokens.json` и адаптирует его к Mantine. Используй
|
||||||
|
`@wealthledger/ui/theme` и его semantic roles; runtime подключает
|
||||||
|
`@wealthledger/ui/styles.css` после Mantine CSS. Providers остаются у runtime.
|
||||||
|
Палитра page/component следует этим semantic roles. Поддерживается светлая схема.
|
||||||
Цвет дополняет подпись или знак; проверяй контраст конкретной пары text/background.
|
Цвет дополняет подпись или знак; проверяй контраст конкретной пары text/background.
|
||||||
Warning не используй для мелкого текста на белом. Деньги сохраняют валюту, знак
|
Warning не используй для мелкого текста на белом. Деньги сохраняют валюту, знак
|
||||||
и различие между нулём и неизвестной суммой. Общие состояния демонстрирует
|
и различие между нулём и неизвестной суммой. Общие состояния демонстрирует
|
||||||
Storybook; presentation stories используют synthetic data без application API.
|
Storybook; presentation stories используют synthetic data без application API.
|
||||||
|
|
||||||
|
EntryCard, StateView и LoadingSkeleton принадлежат `packages/ui`; публичный import —
|
||||||
|
`@wealthledger/ui`. Переводы, retry и формы skeleton остаются у callers.
|
||||||
|
Compatibility re-exports удалены; callers используют public export пакета.
|
||||||
|
|
||||||
|
## Modal animation
|
||||||
|
|
||||||
|
BankCardForm, OperationForm, DeleteOperation и CategoryManager монтируют Modal
|
||||||
|
с `opened=true`: Mantine Transition начинает в состоянии `entered`.
|
||||||
|
CSS `modal-appear`/`modal-backdrop-appear` в `packages/ui/src/styles.css`
|
||||||
|
обеспечивает появление при mount (220ms, только no-preference). Mantine theme
|
||||||
|
владеет exit transition (180ms), overlay blur и completion callback;
|
||||||
|
`onExitTransitionEnd` позволяет дождаться закрытия перед unmount и вернуть фокус.
|
||||||
|
Удаление CSS без изменения mount lifecycle убирает вступительную анимацию.
|
||||||
|
TbankConnection Modal использует toggle `opened`; вывод о разделении фаз
|
||||||
|
банковских форм на этот сценарий автоматически не распространяется.
|
||||||
|
|||||||
@@ -13,3 +13,30 @@
|
|||||||
!public/**
|
!public/**
|
||||||
!docker/
|
!docker/
|
||||||
!docker/**
|
!docker/**
|
||||||
|
!packages/
|
||||||
|
!packages/tokens/
|
||||||
|
!packages/tokens/package.json
|
||||||
|
!packages/tokens/tokens.json
|
||||||
|
!packages/ui/
|
||||||
|
!packages/ui/package.json
|
||||||
|
!packages/ui/vite.config.ts
|
||||||
|
!packages/ui/tsconfig.json
|
||||||
|
!packages/ui/src/
|
||||||
|
!packages/ui/src/theme.ts
|
||||||
|
!packages/ui/src/styles.css
|
||||||
|
!packages/ui/src/index.ts
|
||||||
|
!packages/ui/src/StateView.tsx
|
||||||
|
!packages/ui/src/LoadingSkeleton.tsx
|
||||||
|
!packages/ui/src/EntryCard.tsx
|
||||||
|
!packages/ui/src/EntryCard.module.css
|
||||||
|
!packages/icons/
|
||||||
|
!packages/icons/package.json
|
||||||
|
!packages/icons/tsconfig.json
|
||||||
|
!packages/icons/vite.config.ts
|
||||||
|
!packages/icons/src/
|
||||||
|
!packages/icons/src/index.ts
|
||||||
|
!packages/icons/src/types.ts
|
||||||
|
!packages/icons/src/svg/
|
||||||
|
!packages/icons/src/svg/AddIcon.tsx
|
||||||
|
!packages/icons/src/svg/EditIcon.tsx
|
||||||
|
!packages/icons/src/svg/DeleteIcon.tsx
|
||||||
|
|||||||
@@ -45,15 +45,17 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
VERSION="${RELEASE_TAG#v}"
|
VERSION="${RELEASE_TAG#v}"
|
||||||
if docker manifest inspect "$IMAGE:$VERSION" >/dev/null 2>manifest-error.log; then
|
if docker manifest inspect "$IMAGE:$VERSION" >/dev/null 2>manifest-error.log; then
|
||||||
echo 'Refusing to overwrite an existing release tag'; exit 1
|
DIGEST="$(docker buildx imagetools inspect "$IMAGE:$VERSION" --format '{{.Manifest.Digest}}')"
|
||||||
|
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
|
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"
|
docker pull "$IMAGE@$DIGEST"
|
||||||
test "$(docker image inspect "$IMAGE@$DIGEST" --format '{{index .Config.Labels "org.opencontainers.image.revision"}}')" = "$REVISION"
|
test "$(docker image inspect "$IMAGE@$DIGEST" --format '{{index .Config.Labels "org.opencontainers.image.revision"}}')" = "$REVISION"
|
||||||
|
test "$(docker image inspect "$IMAGE@$DIGEST" --format '{{index .Config.Labels "org.opencontainers.image.version"}}')" = "$VERSION"
|
||||||
docker run --rm --entrypoint sh "$IMAGE@$DIGEST" -c 'test -s /usr/share/nginx/html/index.html && nginx -t && nginx && wget -q -O /dev/null http://127.0.0.1:8080/'
|
docker run --rm --entrypoint sh "$IMAGE@$DIGEST" -c 'test -s /usr/share/nginx/html/index.html && nginx -t && nginx && wget -q -O /dev/null http://127.0.0.1:8080/'
|
||||||
printf 'Frontend image: %s@%s\n' "$IMAGE" "$DIGEST"
|
printf 'Frontend image: %s@%s\n' "$IMAGE" "$DIGEST"
|
||||||
- name: Remove registry session
|
- name: Remove registry session
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
import type { StorybookConfig } from "@storybook/react-vite";
|
import type { StorybookConfig } from "@storybook/react-vite";
|
||||||
|
|
||||||
const config: StorybookConfig = {
|
const config: StorybookConfig = {
|
||||||
stories: ["../src/**/*.stories.tsx"],
|
stories: ["../src/**/*.stories.tsx", "../packages/*/src/**/*.stories.tsx"],
|
||||||
addons: ["@storybook/addon-docs"],
|
addons: ["@storybook/addon-docs"],
|
||||||
framework: "@storybook/react-vite",
|
framework: "@storybook/react-vite",
|
||||||
core: { disableTelemetry: true },
|
core: { disableTelemetry: true },
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import "@mantine/core/styles.css";
|
import "@mantine/core/styles.css";
|
||||||
import "@mantine/charts/styles.css";
|
import "@mantine/charts/styles.css";
|
||||||
import "@mantine/dates/styles.css";
|
import "@mantine/dates/styles.css";
|
||||||
|
import "@wealthledger/ui/styles.css";
|
||||||
import "dayjs/locale/ru";
|
import "dayjs/locale/ru";
|
||||||
import "../src/shared/i18n";
|
import "../src/shared/i18n";
|
||||||
import { MantineProvider } from "@mantine/core";
|
import { MantineProvider } from "@mantine/core";
|
||||||
import { DatesProvider } from "@mantine/dates";
|
import { DatesProvider } from "@mantine/dates";
|
||||||
import type { Preview } from "@storybook/react-vite";
|
import type { Preview } from "@storybook/react-vite";
|
||||||
import { cssVariablesResolver, theme } from "@/shared/theme";
|
import { cssVariablesResolver, theme } from "@wealthledger/ui/theme";
|
||||||
|
|
||||||
const colorSchemeManager = {
|
const colorSchemeManager = {
|
||||||
get: () => "light" as const,
|
get: () => "light" as const,
|
||||||
|
|||||||
@@ -2,10 +2,14 @@ FROM node:24.21.0-bookworm-slim AS dependencies
|
|||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
ENV HUSKY=0
|
ENV HUSKY=0
|
||||||
COPY package.json package-lock.json ./
|
COPY package.json package-lock.json ./
|
||||||
|
COPY packages/tokens/package.json ./packages/tokens/
|
||||||
|
COPY packages/ui/package.json ./packages/ui/
|
||||||
|
COPY packages/icons/package.json ./packages/icons/
|
||||||
RUN npm ci
|
RUN npm ci
|
||||||
|
|
||||||
FROM dependencies AS development
|
FROM dependencies AS development
|
||||||
COPY . .
|
COPY . .
|
||||||
|
RUN npm run build:packages
|
||||||
ENV VITE_API_BASE_URL="" API_PROXY_TARGET=http://backend:3000
|
ENV VITE_API_BASE_URL="" API_PROXY_TARGET=http://backend:3000
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "8080", "--strictPort"]
|
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "8080", "--strictPort"]
|
||||||
|
|||||||
@@ -28,7 +28,8 @@ staged diff с полной редакцией секретов, затем за
|
|||||||
`Dockerfile` имеет targets `development` (Vite HMR и proxy `/api/` во внутренний backend)
|
`Dockerfile` имеет targets `development` (Vite HMR и proxy `/api/` во внутренний backend)
|
||||||
и `production` (nginx на 8080, SPA fallback и same-origin API proxy). Node соответствует `.nvmrc`.
|
и `production` (nginx на 8080, SPA fallback и same-origin API proxy). Node соответствует `.nvmrc`.
|
||||||
Build context ограничен `.dockerignore`; `.env`, local DB и host node_modules
|
Build context ограничен `.dockerignore`; `.env`, local DB и host node_modules
|
||||||
не попадают в image.
|
не попадают в image. Изменение `packages/tokens` или `packages/ui` требует rebuild development
|
||||||
|
image, если локальный запуск использует bind-mount только `src`/`public`.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker build --target development -t wealthledger-frontend:development .
|
docker build --target development -t wealthledger-frontend:development .
|
||||||
@@ -194,3 +195,33 @@ Commits и PR titles — Conventional Commits, включая `spec:`. Верс
|
|||||||
администратором, обязательны `verify`, `security`, `commits`; теги `v*` защищены.
|
администратором, обязательны `verify`, `security`, `commits`; теги `v*` защищены.
|
||||||
Workflow сам не включает эти настройки. Отдельное review approval для одного
|
Workflow сам не включает эти настройки. Отдельное review approval для одного
|
||||||
владельца не требуется. Npm publishing, deploy и Gitea Releases не включены.
|
владельца не требуется. Npm publishing, deploy и Gitea Releases не включены.
|
||||||
|
|
||||||
|
## Локальные пакеты
|
||||||
|
|
||||||
|
`packages/tokens` — private npm workspace с единственным export
|
||||||
|
`@wealthledger/tokens/tokens.json`. `packages/ui` экспортирует собранные
|
||||||
|
`@wealthledger/ui/theme` (JS + declarations) и `@wealthledger/ui/styles.css`.
|
||||||
|
Корневой export `@wealthledger/ui` содержит EntryCard, StateView и LoadingSkeleton;
|
||||||
|
Потребители импортируют компоненты напрямую из `@wealthledger/ui`.
|
||||||
|
CSS явно подключается после Mantine; providers остаются в приложении/Storybook.
|
||||||
|
Тема доступна через `@wealthledger/ui/theme`; compatibility re-exports удалены.
|
||||||
|
|
||||||
|
JSON не требует сборки. `npm ci` связывает workspaces, а существующие команды
|
||||||
|
разработки, проверок и сборки сначала выполняют `npm run build:packages`.
|
||||||
|
Library build использует отдельный Vite config без app plugins и TypeScript
|
||||||
|
для declarations. После изменения package sources перезапустите `npm run dev`
|
||||||
|
или `npm run dev:catalog`; отдельный watch-процесс пока не нужен.
|
||||||
|
Начальная версия manifest взята из приложения; отдельный release-процесс
|
||||||
|
и публикация не настроены.
|
||||||
|
|
||||||
|
Private `@wealthledger/icons` экспортирует `AddIcon`, `EditIcon`, `DeleteIcon`
|
||||||
|
и type `IconProps`. Единственный source рисунка — TSX в `packages/icons/src/svg`;
|
||||||
|
поставка содержит ESM/declarations, без raw SVG, CSS, Mantine и motion.
|
||||||
|
React — peer/external. Размер `size` по умолчанию 24, `strokeWidth` — 1.5;
|
||||||
|
цвет наследуется через `currentColor`, SVG props можно передать явно.
|
||||||
|
В action используйте декоративный `<AddIcon size={20} strokeWidth={2} />`,
|
||||||
|
доступное имя задавайте кнопке. Standalone пример:
|
||||||
|
`<EditIcon aria-hidden={false} role="img" aria-label="Редактирование" />`.
|
||||||
|
Поддерживается также стандартный `aria-labelledby`; подпись выбирает caller.
|
||||||
|
Card/Cards используют пакетные Add/Edit/Delete с прежними размерами/strokeWidth.
|
||||||
|
Restore/category SVG и предметный BankOperationIcon остаются в приложении.
|
||||||
|
|||||||
+3
-1
@@ -7,6 +7,7 @@
|
|||||||
"includes": [
|
"includes": [
|
||||||
"**",
|
"**",
|
||||||
"!dist",
|
"!dist",
|
||||||
|
"!packages/*/dist",
|
||||||
"!storybook-static",
|
"!storybook-static",
|
||||||
"!src/shared/api/generated",
|
"!src/shared/api/generated",
|
||||||
"!src/shared/api/spec",
|
"!src/shared/api/spec",
|
||||||
@@ -38,7 +39,8 @@
|
|||||||
"vite.config.ts",
|
"vite.config.ts",
|
||||||
"vitest.config.ts",
|
"vitest.config.ts",
|
||||||
".storybook/main.ts",
|
".storybook/main.ts",
|
||||||
".storybook/preview.tsx"
|
".storybook/preview.tsx",
|
||||||
|
"packages/*/vite.config.ts"
|
||||||
],
|
],
|
||||||
"linter": {
|
"linter": {
|
||||||
"rules": {
|
"rules": {
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
module.exports = {
|
module.exports = {
|
||||||
forbidden: [
|
forbidden: [
|
||||||
|
{
|
||||||
|
name: "packages-must-not-depend-on-app",
|
||||||
|
severity: "error",
|
||||||
|
from: { path: "^packages/" },
|
||||||
|
to: { path: "^src/" },
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "no-circular",
|
name: "no-circular",
|
||||||
severity: "error",
|
severity: "error",
|
||||||
@@ -17,6 +23,12 @@ module.exports = {
|
|||||||
pathNot: "^src/$1/$2/",
|
pathNot: "^src/$1/$2/",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "no-same-layer-cross-slice-imports",
|
||||||
|
severity: "error",
|
||||||
|
from: { path: "^src/(pages|features|entities)/([^/]+)/" },
|
||||||
|
to: { path: "^src/$1/", pathNot: "^src/$1/$2/" },
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "shared-must-not-depend-on-layers",
|
name: "shared-must-not-depend-on-layers",
|
||||||
severity: "error",
|
severity: "error",
|
||||||
@@ -43,6 +55,7 @@ module.exports = {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
options: {
|
options: {
|
||||||
|
exclude: "^packages/[^/]+/dist/",
|
||||||
doNotFollow: { path: "node_modules" },
|
doNotFollow: { path: "node_modules" },
|
||||||
tsConfig: { fileName: "tsconfig.app.json" },
|
tsConfig: { fileName: "tsconfig.app.json" },
|
||||||
tsPreCompilationDeps: true,
|
tsPreCompilationDeps: true,
|
||||||
|
|||||||
@@ -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}"]
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+59
@@ -7,6 +7,9 @@
|
|||||||
"": {
|
"": {
|
||||||
"name": "wealth-ledger-frontend",
|
"name": "wealth-ledger-frontend",
|
||||||
"version": "0.3.0",
|
"version": "0.3.0",
|
||||||
|
"workspaces": [
|
||||||
|
"packages/*"
|
||||||
|
],
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@hookform/resolvers": "5.9.1",
|
"@hookform/resolvers": "5.9.1",
|
||||||
"@mantine/charts": "9.6.1",
|
"@mantine/charts": "9.6.1",
|
||||||
@@ -14,6 +17,9 @@
|
|||||||
"@mantine/dates": "9.6.1",
|
"@mantine/dates": "9.6.1",
|
||||||
"@mantine/hooks": "9.6.1",
|
"@mantine/hooks": "9.6.1",
|
||||||
"@tanstack/react-query": "5.102.8",
|
"@tanstack/react-query": "5.102.8",
|
||||||
|
"@wealthledger/icons": "file:packages/icons",
|
||||||
|
"@wealthledger/tokens": "file:packages/tokens",
|
||||||
|
"@wealthledger/ui": "file:packages/ui",
|
||||||
"dayjs": "1.11.23",
|
"dayjs": "1.11.23",
|
||||||
"i18next": "26.4.2",
|
"i18next": "26.4.2",
|
||||||
"motion": "13.2.0",
|
"motion": "13.2.0",
|
||||||
@@ -5460,6 +5466,18 @@
|
|||||||
"url": "https://opencollective.com/vitest"
|
"url": "https://opencollective.com/vitest"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@wealthledger/icons": {
|
||||||
|
"resolved": "packages/icons",
|
||||||
|
"link": true
|
||||||
|
},
|
||||||
|
"node_modules/@wealthledger/tokens": {
|
||||||
|
"resolved": "packages/tokens",
|
||||||
|
"link": true
|
||||||
|
},
|
||||||
|
"node_modules/@wealthledger/ui": {
|
||||||
|
"resolved": "packages/ui",
|
||||||
|
"link": true
|
||||||
|
},
|
||||||
"node_modules/@webcontainer/env": {
|
"node_modules/@webcontainer/env": {
|
||||||
"version": "1.1.1",
|
"version": "1.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/@webcontainer/env/-/env-1.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/@webcontainer/env/-/env-1.1.1.tgz",
|
||||||
@@ -16399,6 +16417,47 @@
|
|||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://github.com/sponsors/colinhacks"
|
"url": "https://github.com/sponsors/colinhacks"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"packages/icons": {
|
||||||
|
"name": "@wealthledger/icons",
|
||||||
|
"version": "0.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"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "19.3.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"packages/tokens": {
|
||||||
|
"name": "@wealthledger/tokens",
|
||||||
|
"version": "0.3.0"
|
||||||
|
},
|
||||||
|
"packages/ui": {
|
||||||
|
"name": "@wealthledger/ui",
|
||||||
|
"version": "0.3.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@wealthledger/tokens": "0.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"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@mantine/core": "9.6.1",
|
||||||
|
"@mantine/hooks": "9.6.1",
|
||||||
|
"react": "19.3.0",
|
||||||
|
"react-dom": "19.3.0"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+21
-14
@@ -7,27 +7,28 @@
|
|||||||
"node": "24.21.0"
|
"node": "24.21.0"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "npm run build:packages && vite",
|
||||||
"dev:catalog": "storybook dev -p 6006 --no-open --disable-telemetry",
|
"dev:catalog": "npm run build:packages && storybook dev -p 6006 --no-open --disable-telemetry",
|
||||||
"build:catalog": "storybook build --output-dir storybook-static --disable-telemetry",
|
"build:catalog": "npm run build:packages && storybook build --output-dir storybook-static --disable-telemetry",
|
||||||
"preview:catalog": "vite preview --outDir storybook-static",
|
"preview:catalog": "vite preview --outDir storybook-static",
|
||||||
"typecheck": "tsc -b --noEmit",
|
"typecheck": "npm run build:packages && tsc -b --noEmit",
|
||||||
"build": "tsc -b && vite build",
|
"build": "npm run build:packages && tsc -b && vite build",
|
||||||
"lint": "biome check .",
|
"lint": "biome check .",
|
||||||
"test": "vitest",
|
"test": "npm run build:packages && vitest",
|
||||||
"test:run": "vitest run",
|
"test:run": "npm run build:packages && vitest run",
|
||||||
"test:coverage": "vitest run --coverage",
|
"test:coverage": "npm run build:packages && vitest run --coverage",
|
||||||
"openapi:generate": "openapi-typescript src/shared/api/spec/openapi.json -o src/shared/api/generated/schema.d.ts",
|
"openapi:generate": "openapi-typescript src/shared/api/spec/openapi.json -o src/shared/api/generated/schema.d.ts",
|
||||||
"openapi:check": "node scripts/check-openapi.mjs",
|
"openapi:check": "node scripts/check-openapi.mjs",
|
||||||
"knip": "knip",
|
"knip": "npm run build:packages && knip",
|
||||||
"deps": "depcruise src --config dependency-cruiser.cjs --output-type err-long",
|
"deps": "npm run build:packages && depcruise src packages --config dependency-cruiser.cjs --output-type err-long",
|
||||||
"verify": "npm run openapi:check && npm run typecheck && npm run lint && npm run test:coverage && npm run knip && npm run deps && npm run deps:storybook && npm run build && npm run build:catalog",
|
"verify": "npm run build:packages && npm run openapi:check && npm run typecheck && npm run lint && npm run test:coverage && npm run knip && npm run deps && npm run deps:storybook && npm run build && npm run build:catalog",
|
||||||
"prepare": "husky",
|
"prepare": "husky",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"deps:storybook": "depcruise src .storybook/preview.tsx --config .storybook/dependency-cruiser.cjs --output-type err-long",
|
"deps:storybook": "npm run build:packages && depcruise src packages .storybook/preview.tsx --config .storybook/dependency-cruiser.cjs --output-type err-long",
|
||||||
"release:preview": "release-it --dry-run --ci",
|
"release:preview": "release-it --dry-run --ci",
|
||||||
"release:prepare": "release-it --ci",
|
"release:prepare": "release-it --ci",
|
||||||
"commitlint": "commitlint"
|
"commitlint": "commitlint",
|
||||||
|
"build:packages": "npm run build --workspaces --if-present"
|
||||||
},
|
},
|
||||||
"lint-staged": {
|
"lint-staged": {
|
||||||
"*.{css,html,json,md,ts,tsx}": "biome format --write --no-errors-on-unmatched"
|
"*.{css,html,json,md,ts,tsx}": "biome format --write --no-errors-on-unmatched"
|
||||||
@@ -39,6 +40,9 @@
|
|||||||
"@mantine/dates": "9.6.1",
|
"@mantine/dates": "9.6.1",
|
||||||
"@mantine/hooks": "9.6.1",
|
"@mantine/hooks": "9.6.1",
|
||||||
"@tanstack/react-query": "5.102.8",
|
"@tanstack/react-query": "5.102.8",
|
||||||
|
"@wealthledger/icons": "file:packages/icons",
|
||||||
|
"@wealthledger/tokens": "file:packages/tokens",
|
||||||
|
"@wealthledger/ui": "file:packages/ui",
|
||||||
"dayjs": "1.11.23",
|
"dayjs": "1.11.23",
|
||||||
"i18next": "26.4.2",
|
"i18next": "26.4.2",
|
||||||
"motion": "13.2.0",
|
"motion": "13.2.0",
|
||||||
@@ -88,5 +92,8 @@
|
|||||||
"allowScripts": {
|
"allowScripts": {
|
||||||
"esbuild@0.28.2": true,
|
"esbuild@0.28.2": true,
|
||||||
"fsevents@2.3.3": true
|
"fsevents@2.3.3": true
|
||||||
}
|
},
|
||||||
|
"workspaces": [
|
||||||
|
"packages/*"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
),
|
||||||
|
};
|
||||||
@@ -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");
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
export { AddIcon } from "./svg/AddIcon";
|
||||||
|
export { DeleteIcon } from "./svg/DeleteIcon";
|
||||||
|
export { EditIcon } from "./svg/EditIcon";
|
||||||
|
export type { IconProps } from "./types";
|
||||||
@@ -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 };
|
||||||
@@ -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 };
|
||||||
@@ -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 };
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import type { ComponentPropsWithoutRef } from "react";
|
||||||
|
|
||||||
|
type IconProps = Omit<
|
||||||
|
ComponentPropsWithoutRef<"svg">,
|
||||||
|
"children" | "dangerouslySetInnerHTML"
|
||||||
|
> & {
|
||||||
|
size?: number | string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type { IconProps };
|
||||||
@@ -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"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { defineConfig } from "vite";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
build: {
|
||||||
|
lib: { entry: "src/index.ts", formats: ["es"], fileName: "index" },
|
||||||
|
rolldownOptions: { external: /^react(\/|$)/ },
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"name": "@wealthledger/tokens",
|
||||||
|
"version": "0.3.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"files": [
|
||||||
|
"tokens.json"
|
||||||
|
],
|
||||||
|
"exports": {
|
||||||
|
"./tokens.json": "./tokens.json"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -53,7 +53,7 @@
|
|||||||
"#40c057",
|
"#40c057",
|
||||||
"#37b24d",
|
"#37b24d",
|
||||||
"#2f9e44",
|
"#2f9e44",
|
||||||
"#2b8a3e"
|
"#237032"
|
||||||
],
|
],
|
||||||
"red": [
|
"red": [
|
||||||
"#fff5f5",
|
"#fff5f5",
|
||||||
@@ -151,12 +151,12 @@
|
|||||||
},
|
},
|
||||||
"positive": {
|
"positive": {
|
||||||
"color": "green",
|
"color": "green",
|
||||||
"shade": 6,
|
"shade": 9,
|
||||||
"description": "Положительный результат; дополните знаком и текстом"
|
"description": "Положительный результат; дополните знаком и текстом"
|
||||||
},
|
},
|
||||||
"negative": {
|
"negative": {
|
||||||
"color": "red",
|
"color": "red",
|
||||||
"shade": 6,
|
"shade": 9,
|
||||||
"description": "Ошибка / отрицательный результат; дополните текстом"
|
"description": "Ошибка / отрицательный результат; дополните текстом"
|
||||||
},
|
},
|
||||||
"warning": {
|
"warning": {
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
{
|
||||||
|
"name": "@wealthledger/ui",
|
||||||
|
"version": "0.3.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"files": [
|
||||||
|
"dist"
|
||||||
|
],
|
||||||
|
"exports": {
|
||||||
|
".": {
|
||||||
|
"types": "./dist/index.d.ts",
|
||||||
|
"import": "./dist/index.js"
|
||||||
|
},
|
||||||
|
"./theme": {
|
||||||
|
"types": "./dist/theme.d.ts",
|
||||||
|
"import": "./dist/theme.js"
|
||||||
|
},
|
||||||
|
"./styles.css": "./dist/styles.css"
|
||||||
|
},
|
||||||
|
"sideEffects": [
|
||||||
|
"**/*.css"
|
||||||
|
],
|
||||||
|
"scripts": {
|
||||||
|
"build": "vite build && tsc -p tsconfig.json"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@wealthledger/tokens": "0.3.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@mantine/core": "9.6.1",
|
||||||
|
"@mantine/hooks": "9.6.1",
|
||||||
|
"react": "19.3.0",
|
||||||
|
"react-dom": "19.3.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@storybook/react-vite": "10.6.0",
|
||||||
|
"@testing-library/react": "16.3.3",
|
||||||
|
"@types/react": "19.3.0",
|
||||||
|
"storybook": "10.6.0",
|
||||||
|
"typescript": "5.9.3",
|
||||||
|
"vite": "8.3.0",
|
||||||
|
"vitest": "5.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,8 +4,8 @@
|
|||||||
gap: var(--mantine-spacing-sm);
|
gap: var(--mantine-spacing-sm);
|
||||||
align-items: center;
|
align-items: center;
|
||||||
padding: var(--mantine-spacing-md);
|
padding: var(--mantine-spacing-md);
|
||||||
border-color: var(--mantine-color-gray-3);
|
border-color: var(--wl-color-border);
|
||||||
background: var(--mantine-color-gray-0);
|
background: var(--wl-color-subtle);
|
||||||
}
|
}
|
||||||
|
|
||||||
.identity,
|
.identity,
|
||||||
@@ -19,15 +19,15 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.positive {
|
.positive {
|
||||||
color: var(--mantine-color-green-6);
|
color: var(--wl-color-positive);
|
||||||
}
|
}
|
||||||
|
|
||||||
.negative {
|
.negative {
|
||||||
color: var(--mantine-color-red-6);
|
color: var(--wl-color-negative);
|
||||||
}
|
}
|
||||||
|
|
||||||
.neutral {
|
.neutral {
|
||||||
color: var(--mantine-color-dimmed);
|
color: var(--mantine-color-gray-7);
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 36em) {
|
@media (max-width: 36em) {
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { Button } from "@mantine/core";
|
||||||
|
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||||
|
import { fn } from "storybook/test";
|
||||||
|
import { EntryCard } from "./EntryCard";
|
||||||
|
|
||||||
|
const meta = {
|
||||||
|
title: "Design System/Components/EntryCard",
|
||||||
|
component: EntryCard,
|
||||||
|
tags: ["autodocs"],
|
||||||
|
args: {
|
||||||
|
title:
|
||||||
|
"Учебная запись с очень длинным названием для проверки узкого экрана",
|
||||||
|
metadata: "22.09.2026 · Синтетические данные",
|
||||||
|
initial: "У",
|
||||||
|
imageSrc: "data:image/png;base64,invalid",
|
||||||
|
value: "−1 250,00 ₽",
|
||||||
|
valueLabel: "Тестовое значение",
|
||||||
|
tone: "negative",
|
||||||
|
actions: (
|
||||||
|
<Button size="compact-sm" onClick={fn()}>
|
||||||
|
Открыть пример
|
||||||
|
</Button>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
parameters: {
|
||||||
|
docs: {
|
||||||
|
description: {
|
||||||
|
component:
|
||||||
|
"Готовые строки и slots без финансовых вычислений. Невалидное локальное изображение показывает fallback; действие доступно с клавиатуры и на узком экране. Данные вымышлены.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} satisfies Meta<typeof EntryCard>;
|
||||||
|
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof meta>;
|
||||||
|
export const LongContentAndFallback: Story = {};
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { MantineProvider } from "@mantine/core";
|
||||||
|
import { fireEvent, render, screen } from "@testing-library/react";
|
||||||
|
import { assert, describe, expect, it } from "vitest";
|
||||||
|
import { EntryCard } from "./EntryCard";
|
||||||
|
|
||||||
|
describe("EntryCard", () => {
|
||||||
|
it("keeps the fallback after an image fails", () => {
|
||||||
|
const props = {
|
||||||
|
title: "Пример",
|
||||||
|
metadata: "Описание",
|
||||||
|
initial: "У",
|
||||||
|
value: "—",
|
||||||
|
valueLabel: "Неизвестно",
|
||||||
|
tone: "neutral" as const,
|
||||||
|
imageSrc: "data:image/png;base64,invalid",
|
||||||
|
};
|
||||||
|
const { container, rerender } = render(
|
||||||
|
<MantineProvider>
|
||||||
|
<EntryCard {...props} />
|
||||||
|
</MantineProvider>,
|
||||||
|
);
|
||||||
|
// Decorative image has no accessible name; trigger its actual failure event.
|
||||||
|
const image = container.querySelector("img");
|
||||||
|
assert(image);
|
||||||
|
fireEvent.error(image);
|
||||||
|
rerender(
|
||||||
|
<MantineProvider>
|
||||||
|
<EntryCard {...props} title="Обновлённый пример" />
|
||||||
|
</MantineProvider>,
|
||||||
|
);
|
||||||
|
expect(container.querySelector("img")).toBeNull();
|
||||||
|
expect(screen.getByText("У")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Обновлённый пример")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -25,7 +25,7 @@ const EntryCard: FC<EntryCardProps> = (props) => {
|
|||||||
style={
|
style={
|
||||||
props.color
|
props.color
|
||||||
? {
|
? {
|
||||||
background: `color-mix(in srgb, var(--mantine-color-${props.color}-0) 45%, white)`,
|
background: `color-mix(in srgb, var(--mantine-color-${props.color}-0) 45%, var(--wl-color-surface))`,
|
||||||
}
|
}
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
export { AppShell } from "./AppShell";
|
|
||||||
export { EntryCard } from "./EntryCard";
|
export { EntryCard } from "./EntryCard";
|
||||||
export { LoadingSkeleton } from "./LoadingSkeleton";
|
export { LoadingSkeleton } from "./LoadingSkeleton";
|
||||||
export { StateView } from "./StateView";
|
export { StateView } from "./StateView";
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { DEFAULT_THEME, mergeMantineTheme } from "@mantine/core";
|
import { DEFAULT_THEME, mergeMantineTheme } from "@mantine/core";
|
||||||
|
import source from "@wealthledger/tokens/tokens.json";
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import { colorRoles, cssVariablesResolver, theme } from "./theme";
|
import { colorRoles, cssVariablesResolver, theme } from "./theme";
|
||||||
import source from "./tokens.json";
|
|
||||||
|
|
||||||
describe("design theme adapter", () => {
|
describe("design theme adapter", () => {
|
||||||
it("preserves scale-aware sizes, unscaled breakpoints and shadow layers", () => {
|
it("preserves scale-aware sizes, unscaled breakpoints and shadow layers", () => {
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import "./styles.css";
|
||||||
import {
|
import {
|
||||||
type CSSVariablesResolver,
|
type CSSVariablesResolver,
|
||||||
colorsTuple,
|
colorsTuple,
|
||||||
@@ -8,7 +9,7 @@ import {
|
|||||||
rem,
|
rem,
|
||||||
rgba,
|
rgba,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
import designTokens from "./tokens.json";
|
import designTokens from "@wealthledger/tokens/tokens.json";
|
||||||
|
|
||||||
const { color, typography, spacing, radius, shadows, breakpoints } =
|
const { color, typography, spacing, radius, shadows, breakpoints } =
|
||||||
designTokens;
|
designTokens;
|
||||||
@@ -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"]
|
||||||
|
}
|
||||||
@@ -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)(\/|$)/,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,12 +1,11 @@
|
|||||||
import { MantineProvider } from "@mantine/core";
|
import { MantineProvider } from "@mantine/core";
|
||||||
import { QueryClientProvider } from "@tanstack/react-query";
|
import { QueryClientProvider } from "@tanstack/react-query";
|
||||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||||
|
import { cssVariablesResolver, theme } from "@wealthledger/ui/theme";
|
||||||
import { HttpResponse, http } from "msw";
|
import { HttpResponse, http } from "msw";
|
||||||
import { MemoryRouter } from "react-router";
|
import { MemoryRouter } from "react-router";
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import { AuthProvider } from "@/features/auth";
|
import { AuthProvider } from "@/features/auth";
|
||||||
import { cssVariablesResolver, theme } from "@/shared/theme";
|
|
||||||
import { createTestQueryClient } from "@/test/query";
|
import { createTestQueryClient } from "@/test/query";
|
||||||
import { server } from "@/test/server";
|
import { server } from "@/test/server";
|
||||||
import { AppRoutes } from "./AppRoutes";
|
import { AppRoutes } from "./AppRoutes";
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { AppBreadcrumbs } from "@/app/ui";
|
import { AppBreadcrumbs, AppShell } from "@/app/ui";
|
||||||
import { AppShell } from "@/shared/ui";
|
|
||||||
import { ProtectedDocumentTitle } from "./DocumentTitle";
|
import { ProtectedDocumentTitle } from "./DocumentTitle";
|
||||||
|
|
||||||
const ProtectedLayout: FC = () => {
|
const ProtectedLayout: FC = () => {
|
||||||
|
|||||||
+1
-1
@@ -1,11 +1,11 @@
|
|||||||
import { MantineProvider } from "@mantine/core";
|
import { MantineProvider } from "@mantine/core";
|
||||||
import { DatesProvider } from "@mantine/dates";
|
import { DatesProvider } from "@mantine/dates";
|
||||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import { cssVariablesResolver, theme } from "@wealthledger/ui/theme";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { BrowserRouter } from "react-router";
|
import { BrowserRouter } from "react-router";
|
||||||
import { AppRoutes, RouteErrorBoundary } from "@/app/routes";
|
import { AppRoutes, RouteErrorBoundary } from "@/app/routes";
|
||||||
import { AuthProvider } from "@/features/auth";
|
import { AuthProvider } from "@/features/auth";
|
||||||
import { cssVariablesResolver, theme } from "@/shared/theme";
|
|
||||||
|
|
||||||
const queryClient = new QueryClient({
|
const queryClient = new QueryClient({
|
||||||
defaultOptions: {
|
defaultOptions: {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { AppShell as MantineAppShell, NavLink, Text } from "@mantine/core";
|
|||||||
import type { FC, ReactNode } from "react";
|
import type { FC, ReactNode } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Outlet, NavLink as RouterNavLink, useLocation } from "react-router";
|
import { Outlet, NavLink as RouterNavLink, useLocation } from "react-router";
|
||||||
import { bindIconAnimation } from "../lib";
|
import { bindIconAnimation } from "@/shared/lib";
|
||||||
import classes from "./AppShell.module.css";
|
import classes from "./AppShell.module.css";
|
||||||
|
|
||||||
type AppShellProps = {
|
type AppShellProps = {
|
||||||
@@ -1 +1,2 @@
|
|||||||
export { AppBreadcrumbs } from "./AppBreadcrumbs";
|
export { AppBreadcrumbs } from "./AppBreadcrumbs";
|
||||||
|
export { AppShell } from "./AppShell";
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ export {
|
|||||||
moneyCents,
|
moneyCents,
|
||||||
positiveMoneySchema,
|
positiveMoneySchema,
|
||||||
} from "./model/form-validation";
|
} from "./model/form-validation";
|
||||||
|
export { bankOperationKinds } from "./model/operation-kinds";
|
||||||
export { bankPeriod } from "./model/period";
|
export { bankPeriod } from "./model/period";
|
||||||
export { BankCardFace } from "./ui/BankCardFace";
|
export { BankCardFace } from "./ui/BankCardFace";
|
||||||
export { BankCardForm } from "./ui/BankCardForm";
|
export { BankCardForm } from "./ui/BankCardForm";
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import type { BankOperation } from "../api/queries";
|
||||||
|
|
||||||
|
const bankOperationKinds = [
|
||||||
|
"expense",
|
||||||
|
"topup",
|
||||||
|
"transfer",
|
||||||
|
"refund",
|
||||||
|
] as const satisfies readonly BankOperation["kind"][];
|
||||||
|
|
||||||
|
export { bankOperationKinds };
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Stack } from "@mantine/core";
|
import { Stack } from "@mantine/core";
|
||||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||||
import { EntryCard } from "@/shared/ui";
|
import { EntryCard } from "@wealthledger/ui";
|
||||||
import { BankOperationIcon } from "./BankOperationIcon";
|
import { BankOperationIcon } from "./BankOperationIcon";
|
||||||
|
|
||||||
const meta = {
|
const meta = {
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { Button, Group, Skeleton, Stack, Text, Title } from "@mantine/core";
|
import { Button, Group, Skeleton, Stack, Text, Title } from "@mantine/core";
|
||||||
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import type { CSSProperties, FC } from "react";
|
import type { CSSProperties, FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { formatMoney } from "@/shared/lib";
|
import { formatMoney } from "@/shared/lib";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
|
||||||
import type { BankSummary } from "../api/queries";
|
import type { BankSummary } from "../api/queries";
|
||||||
import { BankOperationIcon } from "./BankOperationIcon";
|
import { BankOperationIcon } from "./BankOperationIcon";
|
||||||
import classes from "./BankSummary.module.css";
|
import classes from "./BankSummary.module.css";
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Anchor, Group, Text } from "@mantine/core";
|
import { Anchor, Group, Text } from "@mantine/core";
|
||||||
|
import { EntryCard } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
@@ -8,7 +9,6 @@ import {
|
|||||||
formatSnapshotTime,
|
formatSnapshotTime,
|
||||||
instrumentLogoUrl,
|
instrumentLogoUrl,
|
||||||
} from "@/shared/lib";
|
} from "@/shared/lib";
|
||||||
import { EntryCard } from "@/shared/ui";
|
|
||||||
import type { BrokerageOperation } from "../api/useBrokerageOperations";
|
import type { BrokerageOperation } from "../api/useBrokerageOperations";
|
||||||
import { operationLabelKey, paymentPresentation } from "../model/display";
|
import { operationLabelKey, paymentPresentation } from "../model/display";
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
|
import { EntryCard } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { formatDate, formatMoney, instrumentLogoUrl } from "@/shared/lib";
|
import { formatDate, formatMoney, instrumentLogoUrl } from "@/shared/lib";
|
||||||
import { EntryCard } from "@/shared/ui";
|
|
||||||
import type { BrokerageEvent } from "../api/useBrokerageEvents";
|
import type { BrokerageEvent } from "../api/useBrokerageEvents";
|
||||||
|
|
||||||
type BrokerageEventCardProps = { event: BrokerageEvent };
|
type BrokerageEventCardProps = { event: BrokerageEvent };
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { Alert, Button, Skeleton, Stack, Text } from "@mantine/core";
|
import { Alert, Button, Skeleton, Stack, Text } from "@mantine/core";
|
||||||
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
|
||||||
import type { BrokerageEvent } from "../api/useBrokerageEvents";
|
import type { BrokerageEvent } from "../api/useBrokerageEvents";
|
||||||
import { BrokerageEventCard } from "./BrokerageEventCard";
|
import { BrokerageEventCard } from "./BrokerageEventCard";
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { act, renderHook, waitFor } from "@testing-library/react";
|
|||||||
import { HttpResponse, http } from "msw";
|
import { HttpResponse, http } from "msw";
|
||||||
import type { FC, PropsWithChildren } from "react";
|
import type { FC, PropsWithChildren } from "react";
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import { apiClient, apiQueryClient } from "@/shared/api";
|
import { apiClient, apiQueryClient, useAuthenticatedQuery } from "@/shared/api";
|
||||||
import { createTestQueryClient } from "@/test/query";
|
import { createTestQueryClient } from "@/test/query";
|
||||||
import { server } from "@/test/server";
|
import { server } from "@/test/server";
|
||||||
import { AuthProvider, useAuth } from "./auth";
|
import { AuthProvider, useAuth } from "./auth";
|
||||||
@@ -167,4 +167,164 @@ describe("AuthProvider", () => {
|
|||||||
expect(queryClient.getQueryData(portfolioKey)).toBeUndefined();
|
expect(queryClient.getQueryData(portfolioKey)).toBeUndefined();
|
||||||
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
|
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
it.each([
|
||||||
|
[false, false],
|
||||||
|
[true, false],
|
||||||
|
[false, true],
|
||||||
|
[true, true],
|
||||||
|
])(
|
||||||
|
"serializes late refresh (failure=%s, login=%s)",
|
||||||
|
async (failure, loginAfterLogout) => {
|
||||||
|
let release!: () => void;
|
||||||
|
const pending = new Promise<void>((resolve) => {
|
||||||
|
release = resolve;
|
||||||
|
});
|
||||||
|
let calls = 0;
|
||||||
|
const order: string[] = [];
|
||||||
|
server.use(
|
||||||
|
http.post("*/api/v1/auth/refresh", async () => {
|
||||||
|
if (++calls > 1) {
|
||||||
|
order.push("refresh-start");
|
||||||
|
await pending;
|
||||||
|
order.push("refresh-cookie");
|
||||||
|
}
|
||||||
|
return failure && calls > 1
|
||||||
|
? HttpResponse.error()
|
||||||
|
: HttpResponse.json({
|
||||||
|
accessToken: "a",
|
||||||
|
user: { id: "a", email: "a@example.com" },
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
http.post("*/api/v1/auth/logout", () => {
|
||||||
|
order.push("logout-cookie");
|
||||||
|
return new HttpResponse(null, { status: 204 });
|
||||||
|
}),
|
||||||
|
http.post("*/api/v1/auth/login", () => {
|
||||||
|
order.push("login-cookie");
|
||||||
|
return HttpResponse.json({
|
||||||
|
accessToken: "b",
|
||||||
|
user: { id: "b", email: "b@example.com" },
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
http.get("*/api/v1/brokerage-accounts", () =>
|
||||||
|
HttpResponse.json({ code: "UNAUTHORIZED" }, { status: 401 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const queryClient = createTestQueryClient();
|
||||||
|
const wrapper: FC<PropsWithChildren> = ({ children }) => (
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<AuthProvider>{children}</AuthProvider>
|
||||||
|
</QueryClientProvider>
|
||||||
|
);
|
||||||
|
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||||
|
await waitFor(() => expect(result.current.ready).toBe(true));
|
||||||
|
const oldRequest = apiClient
|
||||||
|
.GET("/api/v1/brokerage-accounts")
|
||||||
|
.catch(() => null);
|
||||||
|
await waitFor(() => expect(order).toContain("refresh-start"));
|
||||||
|
let logout!: Promise<void>;
|
||||||
|
act(() => {
|
||||||
|
logout = result.current.logout();
|
||||||
|
});
|
||||||
|
await waitFor(() => expect(result.current.user).toBeNull());
|
||||||
|
let login!: Promise<void>;
|
||||||
|
act(() => {
|
||||||
|
login = loginAfterLogout
|
||||||
|
? result.current.login("b@example.com", "password")
|
||||||
|
: Promise.resolve();
|
||||||
|
});
|
||||||
|
await act(async () => {
|
||||||
|
release();
|
||||||
|
await Promise.all([oldRequest, logout, login]);
|
||||||
|
});
|
||||||
|
expect(result.current.user?.id ?? null).toBe(
|
||||||
|
loginAfterLogout ? "b" : null,
|
||||||
|
);
|
||||||
|
expect(order).toEqual([
|
||||||
|
"refresh-start",
|
||||||
|
"refresh-cookie",
|
||||||
|
"logout-cookie",
|
||||||
|
...(loginAfterLogout ? ["login-cookie"] : []),
|
||||||
|
]);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it("preserves same-user cache and removes inactive and pending data on refresh identity change", async () => {
|
||||||
|
let identity = "a";
|
||||||
|
server.use(
|
||||||
|
http.post("*/api/v1/auth/refresh", () =>
|
||||||
|
HttpResponse.json({
|
||||||
|
accessToken: identity,
|
||||||
|
user: { id: identity, email: `${identity}@example.com` },
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const queryClient = createTestQueryClient();
|
||||||
|
const wrapper: FC<PropsWithChildren> = ({ children }) => (
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<AuthProvider>{children}</AuthProvider>
|
||||||
|
</QueryClientProvider>
|
||||||
|
);
|
||||||
|
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||||
|
await waitFor(() => expect(result.current.ready).toBe(true));
|
||||||
|
queryClient.setQueryData(bankCardsKey, [{ id: "a-card" }]);
|
||||||
|
await act(() => result.current.refresh());
|
||||||
|
expect(queryClient.getQueryData(bankCardsKey)).toEqual([{ id: "a-card" }]);
|
||||||
|
let release!: (value: string) => void;
|
||||||
|
const pending = queryClient
|
||||||
|
.fetchQuery({
|
||||||
|
queryKey: ["pending-finance"],
|
||||||
|
queryFn: () =>
|
||||||
|
new Promise<string>((resolve) => {
|
||||||
|
release = resolve;
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.catch(() => null);
|
||||||
|
identity = "b";
|
||||||
|
await act(() => result.current.refresh());
|
||||||
|
release("a-data");
|
||||||
|
await pending;
|
||||||
|
expect(result.current.user?.id).toBe("b");
|
||||||
|
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
|
||||||
|
expect(queryClient.getQueryData(["pending-finance"])).toBeUndefined();
|
||||||
|
});
|
||||||
|
it("replaces an observed financial query when refresh changes identity", async () => {
|
||||||
|
let identity = "a";
|
||||||
|
server.use(
|
||||||
|
http.post("*/api/v1/auth/refresh", () =>
|
||||||
|
HttpResponse.json({
|
||||||
|
accessToken: identity,
|
||||||
|
user: { id: identity, email: `${identity}@example.com` },
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
http.get("*/api/v1/bank-cards", () =>
|
||||||
|
HttpResponse.json([{ id: `${identity}-card` }]),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const queryClient = createTestQueryClient();
|
||||||
|
const wrapper: FC<PropsWithChildren> = (props) => (
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<AuthProvider>{props.children}</AuthProvider>
|
||||||
|
</QueryClientProvider>
|
||||||
|
);
|
||||||
|
const { result } = renderHook(
|
||||||
|
() => ({
|
||||||
|
auth: useAuth(),
|
||||||
|
cards: useAuthenticatedQuery(
|
||||||
|
apiQueryClient.queryOptions("get", "/api/v1/bank-cards", {
|
||||||
|
params: { query: { includeArchived: "false" } },
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
{ wrapper },
|
||||||
|
);
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(result.current.cards.data?.[0].id).toBe("a-card"),
|
||||||
|
);
|
||||||
|
identity = "b";
|
||||||
|
await act(() => result.current.auth.refresh());
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(result.current.cards.data?.[0].id).toBe("b-card"),
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -47,49 +47,70 @@ const AuthProvider: FC<PropsWithChildren> = (props) => {
|
|||||||
const accessTokenRef = useRef<string | null>(null);
|
const accessTokenRef = useRef<string | null>(null);
|
||||||
const [ready, setReady] = useState(false);
|
const [ready, setReady] = useState(false);
|
||||||
|
|
||||||
|
const generation = useRef(0);
|
||||||
|
const userRef = useRef<User | null>(null);
|
||||||
|
const authQueue = useRef<Promise<unknown>>(Promise.resolve());
|
||||||
const refreshPromise = useRef<Promise<boolean> | null>(null);
|
const refreshPromise = useRef<Promise<boolean> | null>(null);
|
||||||
const applyAuthentication = useCallback((authentication: Authentication) => {
|
// Cookie-writing requests share ordering, including across tabs with Web Locks.
|
||||||
setUser(authentication.user);
|
const serialize = useCallback(<T,>(run: () => Promise<T>): Promise<T> => {
|
||||||
setAccessToken(authentication.accessToken);
|
const next = authQueue.current.then(async () =>
|
||||||
accessTokenRef.current = authentication.accessToken;
|
"locks" in navigator
|
||||||
|
? navigator.locks.request("wealth-ledger-refresh", run)
|
||||||
|
: run(),
|
||||||
|
);
|
||||||
|
authQueue.current = next.catch(() => undefined);
|
||||||
|
return next;
|
||||||
}, []);
|
}, []);
|
||||||
|
const applyAuthentication = useCallback(
|
||||||
|
(authentication: Authentication) => {
|
||||||
|
const changedIdentity =
|
||||||
|
userRef.current && userRef.current.id !== authentication.user.id;
|
||||||
|
accessTokenRef.current = authentication.accessToken;
|
||||||
|
if (changedIdentity) {
|
||||||
|
generation.current += 1;
|
||||||
|
queryClient.removeQueries({ type: "inactive" });
|
||||||
|
queryClient.getMutationCache().clear();
|
||||||
|
void queryClient.resetQueries();
|
||||||
|
}
|
||||||
|
userRef.current = authentication.user;
|
||||||
|
setUser(authentication.user);
|
||||||
|
setAccessToken(authentication.accessToken);
|
||||||
|
},
|
||||||
|
[queryClient],
|
||||||
|
);
|
||||||
const clearSession = useCallback(() => {
|
const clearSession = useCallback(() => {
|
||||||
|
generation.current += 1;
|
||||||
|
userRef.current = null;
|
||||||
setUser(null);
|
setUser(null);
|
||||||
setAccessToken(null);
|
setAccessToken(null);
|
||||||
accessTokenRef.current = null;
|
accessTokenRef.current = null;
|
||||||
queryClient.clear();
|
queryClient.clear();
|
||||||
}, [queryClient]);
|
}, [queryClient]);
|
||||||
|
|
||||||
const refresh = useCallback(async (): Promise<boolean> => {
|
const refresh = useCallback((): Promise<boolean> => {
|
||||||
if (refreshPromise.current) return refreshPromise.current;
|
if (refreshPromise.current) return refreshPromise.current;
|
||||||
refreshPromise.current = (async () => {
|
const started = generation.current;
|
||||||
const run = async () => {
|
const pending = serialize(async () => {
|
||||||
try {
|
if (started !== generation.current) return false;
|
||||||
const { data } = await apiClient.POST("/api/v1/auth/refresh");
|
try {
|
||||||
if (!data) {
|
const { data } = await apiClient.POST("/api/v1/auth/refresh");
|
||||||
clearSession();
|
if (started !== generation.current) return false;
|
||||||
return false;
|
if (!data) {
|
||||||
}
|
|
||||||
applyAuthentication(data as Authentication);
|
|
||||||
return true;
|
|
||||||
} catch {
|
|
||||||
clearSession();
|
clearSession();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
};
|
applyAuthentication(data);
|
||||||
try {
|
return true;
|
||||||
return "locks" in navigator
|
|
||||||
? navigator.locks.request("wealth-ledger-refresh", run)
|
|
||||||
: run();
|
|
||||||
} catch {
|
} catch {
|
||||||
clearSession();
|
if (started === generation.current) clearSession();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
})().finally(() => {
|
}).finally(() => {
|
||||||
refreshPromise.current = null;
|
if (refreshPromise.current === pending) refreshPromise.current = null;
|
||||||
});
|
});
|
||||||
return refreshPromise.current;
|
refreshPromise.current = pending;
|
||||||
}, [applyAuthentication, clearSession]);
|
return pending;
|
||||||
|
}, [applyAuthentication, clearSession, serialize]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void refresh().finally(() => setReady(true));
|
void refresh().finally(() => setReady(true));
|
||||||
@@ -100,21 +121,25 @@ const AuthProvider: FC<PropsWithChildren> = (props) => {
|
|||||||
email: string,
|
email: string,
|
||||||
password: string,
|
password: string,
|
||||||
) {
|
) {
|
||||||
const authentication = await request(path, email, password);
|
clearSession();
|
||||||
applyAuthentication(authentication);
|
const started = generation.current;
|
||||||
|
await serialize(async () => {
|
||||||
|
const authentication = await request(path, email, password);
|
||||||
|
if (started === generation.current) applyAuthentication(authentication);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function logout() {
|
async function logout() {
|
||||||
try {
|
clearSession();
|
||||||
|
await serialize(async () => {
|
||||||
await apiClient.POST("/api/v1/auth/logout");
|
await apiClient.POST("/api/v1/auth/logout");
|
||||||
} finally {
|
});
|
||||||
clearSession();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
configureAuthClient({
|
configureAuthClient({
|
||||||
accessToken: () => accessTokenRef.current,
|
accessToken: () => accessTokenRef.current,
|
||||||
|
generation: () => generation.current,
|
||||||
refresh,
|
refresh,
|
||||||
clear: clearSession,
|
clear: clearSession,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -8,9 +8,9 @@ import {
|
|||||||
Text,
|
Text,
|
||||||
Title,
|
Title,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import type { FC, PropsWithChildren, ReactNode } from "react";
|
import type { FC, PropsWithChildren, ReactNode } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
|
||||||
import type { SectionState } from "../model/section";
|
import type { SectionState } from "../model/section";
|
||||||
import classes from "./InstrumentDetails.module.css";
|
import classes from "./InstrumentDetails.module.css";
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Alert, Button, Skeleton } from "@mantine/core";
|
import { Alert, Button, Skeleton } from "@mantine/core";
|
||||||
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
|
||||||
|
|
||||||
type TbankConnectionErrorProps = {
|
type TbankConnectionErrorProps = {
|
||||||
retry: () => void;
|
retry: () => void;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { createRoot } from "react-dom/client";
|
|||||||
import "@mantine/core/styles.css";
|
import "@mantine/core/styles.css";
|
||||||
import "@mantine/charts/styles.css";
|
import "@mantine/charts/styles.css";
|
||||||
import "@mantine/dates/styles.css";
|
import "@mantine/dates/styles.css";
|
||||||
|
import "@wealthledger/ui/styles.css";
|
||||||
import "dayjs/locale/ru";
|
import "dayjs/locale/ru";
|
||||||
import "./shared/i18n";
|
import "./shared/i18n";
|
||||||
import { App } from "./app";
|
import { App } from "./app";
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
|
import { StateView } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { StateView } from "@/shared/ui";
|
|
||||||
|
|
||||||
const AccountEventsPageEmpty: FC = () => {
|
const AccountEventsPageEmpty: FC = () => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Button } from "@mantine/core";
|
import { Button } from "@mantine/core";
|
||||||
|
import { StateView } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { StateView } from "@/shared/ui";
|
|
||||||
|
|
||||||
type AccountEventsPageErrorProps = { retry: () => void };
|
type AccountEventsPageErrorProps = { retry: () => void };
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Group, Skeleton } from "@mantine/core";
|
import { Group, Skeleton } from "@mantine/core";
|
||||||
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
|
||||||
|
|
||||||
const skeletonRowIds = ["first", "second", "third", "fourth"];
|
const skeletonRowIds = ["first", "second", "third", "fourth"];
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
type IncomePeriod = { from: string; to: string };
|
||||||
|
type IncomeForm = IncomePeriod;
|
||||||
|
|
||||||
|
const datePattern = /^\d{4}-\d{2}-\d{2}$/;
|
||||||
|
|
||||||
|
function formatDraftDate(value: string): string {
|
||||||
|
const [year, month, day] = value.split("-");
|
||||||
|
return `${day}.${month}.${year}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseDraftDate(value: string): string | null {
|
||||||
|
if (!/^\d{2}\.\d{2}\.\d{4}$/.test(value)) return null;
|
||||||
|
const [day, month, year] = value.split(".");
|
||||||
|
const date = `${year}-${month}-${day}`;
|
||||||
|
return isDate(date) ? date : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isDate(value: string): boolean {
|
||||||
|
if (!datePattern.test(value)) return false;
|
||||||
|
const parsed = new Date(`${value}T00:00:00Z`);
|
||||||
|
return (
|
||||||
|
Number.isFinite(parsed.valueOf()) &&
|
||||||
|
parsed.toISOString().slice(0, 10) === value
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function moscowDate(value: Date): string {
|
||||||
|
const parts = new Intl.DateTimeFormat("en-CA", {
|
||||||
|
timeZone: "Europe/Moscow",
|
||||||
|
year: "numeric",
|
||||||
|
month: "2-digit",
|
||||||
|
day: "2-digit",
|
||||||
|
}).formatToParts(value);
|
||||||
|
const part = (type: string) =>
|
||||||
|
parts.find((item) => item.type === type)?.value;
|
||||||
|
return `${part("year")}-${part("month")}-${part("day")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
formatDraftDate,
|
||||||
|
type IncomeForm,
|
||||||
|
type IncomePeriod,
|
||||||
|
isDate,
|
||||||
|
moscowDate,
|
||||||
|
parseDraftDate,
|
||||||
|
};
|
||||||
@@ -23,8 +23,9 @@ import type { IncomeAnalytics } from "@/entities/income";
|
|||||||
import { configureAuthClient } from "@/shared/api";
|
import { configureAuthClient } from "@/shared/api";
|
||||||
import { createQueryWrapper } from "@/test/query";
|
import { createQueryWrapper } from "@/test/query";
|
||||||
import { server } from "@/test/server";
|
import { server } from "@/test/server";
|
||||||
|
import { isDate } from "../model/period";
|
||||||
import { AccountIncomePage } from "./AccountIncomePage";
|
import { AccountIncomePage } from "./AccountIncomePage";
|
||||||
import { isDate, toIncomeDisplayModel } from "./AccountIncomePage.vm";
|
import { toIncomeDisplayModel } from "./AccountIncomePage.vm";
|
||||||
import { IncomePayments } from "./components/IncomePayments.view";
|
import { IncomePayments } from "./components/IncomePayments.view";
|
||||||
|
|
||||||
const analytics = {
|
const analytics = {
|
||||||
|
|||||||
@@ -6,12 +6,17 @@ import { z } from "zod";
|
|||||||
import { type IncomeAnalytics, useIncomeAnalytics } from "@/entities/income";
|
import { type IncomeAnalytics, useIncomeAnalytics } from "@/entities/income";
|
||||||
import { validationMessage } from "@/shared/i18n";
|
import { validationMessage } from "@/shared/i18n";
|
||||||
import { formatDate } from "@/shared/lib";
|
import { formatDate } from "@/shared/lib";
|
||||||
|
import {
|
||||||
|
formatDraftDate,
|
||||||
|
type IncomeForm,
|
||||||
|
type IncomePeriod,
|
||||||
|
isDate,
|
||||||
|
moscowDate,
|
||||||
|
parseDraftDate,
|
||||||
|
} from "../model/period";
|
||||||
|
|
||||||
const ISO_MONTH_LENGTH = 7;
|
const ISO_MONTH_LENGTH = 7;
|
||||||
|
|
||||||
type IncomePeriod = { from: string; to: string };
|
|
||||||
type IncomeForm = IncomePeriod;
|
|
||||||
|
|
||||||
type IncomeDisplayModel = {
|
type IncomeDisplayModel = {
|
||||||
entries: { key: string; operation: IncomeAnalytics["entries"][number] }[];
|
entries: { key: string; operation: IncomeAnalytics["entries"][number] }[];
|
||||||
comparison: {
|
comparison: {
|
||||||
@@ -41,7 +46,6 @@ type AccountIncomePageViewModel =
|
|||||||
onSubmit: (values: IncomeForm) => void;
|
onSubmit: (values: IncomeForm) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
const datePattern = /^\d{4}-\d{2}-\d{2}$/;
|
|
||||||
const draftDate = z
|
const draftDate = z
|
||||||
.string()
|
.string()
|
||||||
.refine((value) => parseDraftDate(value) !== null, {
|
.refine((value) => parseDraftDate(value) !== null, {
|
||||||
@@ -129,18 +133,6 @@ const useAccountIncomePageViewModel = (
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
function formatDraftDate(value: string): string {
|
|
||||||
const [year, month, day] = value.split("-");
|
|
||||||
return `${day}.${month}.${year}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseDraftDate(value: string): string | null {
|
|
||||||
if (!/^\d{2}\.\d{2}\.\d{4}$/.test(value)) return null;
|
|
||||||
const [day, month, year] = value.split(".");
|
|
||||||
const date = `${year}-${month}-${day}`;
|
|
||||||
return isDate(date) ? date : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function draftPeriod(period: IncomePeriod): IncomeForm {
|
function draftPeriod(period: IncomePeriod): IncomeForm {
|
||||||
return { from: formatDraftDate(period.from), to: formatDraftDate(period.to) };
|
return { from: formatDraftDate(period.from), to: formatDraftDate(period.to) };
|
||||||
}
|
}
|
||||||
@@ -163,15 +155,6 @@ function validPeriod(period: IncomePeriod): period is IncomePeriod {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function isDate(value: string): boolean {
|
|
||||||
if (!datePattern.test(value)) return false;
|
|
||||||
const parsed = new Date(`${value}T00:00:00Z`);
|
|
||||||
return (
|
|
||||||
Number.isFinite(parsed.valueOf()) &&
|
|
||||||
parsed.toISOString().slice(0, 10) === value
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function toIncomeDisplayModel(
|
function toIncomeDisplayModel(
|
||||||
analytics: IncomeAnalytics,
|
analytics: IncomeAnalytics,
|
||||||
): IncomeDisplayModel | null {
|
): IncomeDisplayModel | null {
|
||||||
@@ -276,26 +259,9 @@ function formatIncomeChange(
|
|||||||
}).format(ratio);
|
}).format(ratio);
|
||||||
}
|
}
|
||||||
|
|
||||||
function moscowDate(value: Date): string {
|
|
||||||
const parts = new Intl.DateTimeFormat("en-CA", {
|
|
||||||
timeZone: "Europe/Moscow",
|
|
||||||
year: "numeric",
|
|
||||||
month: "2-digit",
|
|
||||||
day: "2-digit",
|
|
||||||
}).formatToParts(value);
|
|
||||||
const part = (type: string) =>
|
|
||||||
parts.find((item) => item.type === type)?.value;
|
|
||||||
return `${part("year")}-${part("month")}-${part("day")}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export {
|
export {
|
||||||
type AccountIncomePageViewModel,
|
type AccountIncomePageViewModel,
|
||||||
formatDraftDate,
|
|
||||||
type IncomeDisplayModel,
|
type IncomeDisplayModel,
|
||||||
type IncomeForm,
|
|
||||||
isDate,
|
|
||||||
moscowDate,
|
|
||||||
parseDraftDate,
|
|
||||||
toIncomeDisplayModel,
|
toIncomeDisplayModel,
|
||||||
useAccountIncomePageViewModel,
|
useAccountIncomePageViewModel,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Button } from "@mantine/core";
|
import { Button } from "@mantine/core";
|
||||||
|
import { StateView } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { StateView } from "@/shared/ui";
|
|
||||||
import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
|
import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
|
||||||
|
|
||||||
type ErrorProps = Extract<AccountIncomePageViewModel, { state: "error" }>;
|
type ErrorProps = Extract<AccountIncomePageViewModel, { state: "error" }>;
|
||||||
|
|||||||
@@ -7,10 +7,10 @@ import {
|
|||||||
Text,
|
Text,
|
||||||
Title,
|
Title,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
|
import { StateView } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { FormProvider } from "react-hook-form";
|
import { FormProvider } from "react-hook-form";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { StateView } from "@/shared/ui";
|
|
||||||
import classes from "../AccountIncomePage.module.css";
|
import classes from "../AccountIncomePage.module.css";
|
||||||
import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
|
import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
|
||||||
import { IncomeComparisons } from "./IncomeComparisons.view";
|
import { IncomeComparisons } from "./IncomeComparisons.view";
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Paper, Skeleton, Stack } from "@mantine/core";
|
import { Paper, Skeleton, Stack } from "@mantine/core";
|
||||||
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
|
||||||
import classes from "../AccountIncomePage.module.css";
|
import classes from "../AccountIncomePage.module.css";
|
||||||
|
|
||||||
const AccountIncomePageLoading: FC = () => {
|
const AccountIncomePageLoading: FC = () => {
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||||
|
import type { FC } from "react";
|
||||||
|
import { FormProvider, useForm, useFormState } from "react-hook-form";
|
||||||
|
import type { IncomeForm } from "../../model/period";
|
||||||
|
import { IncomePeriodForm } from "./IncomePeriodForm.view";
|
||||||
|
|
||||||
|
const period = { from: "01.08.2026", to: "27.08.2026" };
|
||||||
|
const errors = {
|
||||||
|
to: { type: "manual", message: "Синтетическая ошибка периода" },
|
||||||
|
};
|
||||||
|
|
||||||
|
type PeriodExampleProps = { invalid?: boolean };
|
||||||
|
|
||||||
|
const PeriodExample: FC<PeriodExampleProps> = (props) => {
|
||||||
|
const methods = useForm<IncomeForm>({
|
||||||
|
defaultValues: period,
|
||||||
|
errors: props.invalid ? errors : undefined,
|
||||||
|
});
|
||||||
|
const { isSubmitSuccessful } = useFormState({ control: methods.control });
|
||||||
|
const submitted = isSubmitSuccessful ? methods.getValues() : null;
|
||||||
|
return (
|
||||||
|
<FormProvider {...methods}>
|
||||||
|
<IncomePeriodForm
|
||||||
|
onSubmit={methods.handleSubmit(() => undefined)}
|
||||||
|
onReset={() => {
|
||||||
|
methods.reset(period);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<output aria-live="polite">
|
||||||
|
{submitted
|
||||||
|
? `Применено: ${submitted.from} – ${submitted.to}`
|
||||||
|
: "Период не применён"}
|
||||||
|
</output>
|
||||||
|
</FormProvider>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const meta = {
|
||||||
|
title: "Product/IncomePeriodForm",
|
||||||
|
component: PeriodExample,
|
||||||
|
tags: ["autodocs"],
|
||||||
|
parameters: {
|
||||||
|
docs: {
|
||||||
|
description: {
|
||||||
|
component:
|
||||||
|
"Изолированная форма с синтетическим периодом. Submit показывает значения локально; reset возвращает fixture. Ошибка задана явно: query, URL и production validation остаются у page VM, API и router providers не используются.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
render: () => <PeriodExample />,
|
||||||
|
} satisfies Meta<typeof PeriodExample>;
|
||||||
|
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof meta>;
|
||||||
|
export const Default: Story = {};
|
||||||
|
export const ValidationError: Story = {
|
||||||
|
render: () => <PeriodExample invalid />,
|
||||||
|
};
|
||||||
@@ -3,13 +3,13 @@ import { DatePickerInput } from "@mantine/dates";
|
|||||||
import type { FC, FormEventHandler } from "react";
|
import type { FC, FormEventHandler } from "react";
|
||||||
import { useController, useFormContext, useWatch } from "react-hook-form";
|
import { useController, useFormContext, useWatch } from "react-hook-form";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import classes from "../AccountIncomePage.module.css";
|
|
||||||
import {
|
import {
|
||||||
formatDraftDate,
|
formatDraftDate,
|
||||||
type IncomeForm,
|
type IncomeForm,
|
||||||
moscowDate,
|
moscowDate,
|
||||||
parseDraftDate,
|
parseDraftDate,
|
||||||
} from "../AccountIncomePage.vm";
|
} from "../../model/period";
|
||||||
|
import classes from "../AccountIncomePage.module.css";
|
||||||
|
|
||||||
type IncomePeriodFormProps = {
|
type IncomePeriodFormProps = {
|
||||||
onSubmit: FormEventHandler<HTMLFormElement>;
|
onSubmit: FormEventHandler<HTMLFormElement>;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Button } from "@mantine/core";
|
import { Button } from "@mantine/core";
|
||||||
|
import { StateView } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { StateView } from "@/shared/ui";
|
|
||||||
import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm";
|
import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm";
|
||||||
|
|
||||||
type AccountOperationsPageErrorProps = Extract<
|
type AccountOperationsPageErrorProps = Extract<
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
Title,
|
Title,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
import { DatePickerInput } from "@mantine/dates";
|
import { DatePickerInput } from "@mantine/dates";
|
||||||
|
import { StateView } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import {
|
||||||
@@ -15,7 +16,6 @@ import {
|
|||||||
type OperationCategory,
|
type OperationCategory,
|
||||||
operationCategories,
|
operationCategories,
|
||||||
} from "@/entities/broker-operation";
|
} from "@/entities/broker-operation";
|
||||||
import { StateView } from "@/shared/ui";
|
|
||||||
import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm";
|
import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm";
|
||||||
|
|
||||||
type AccountOperationsPageLoadedProps = Extract<
|
type AccountOperationsPageLoadedProps = Extract<
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Group, Skeleton, Stack } from "@mantine/core";
|
import { Group, Skeleton, Stack } from "@mantine/core";
|
||||||
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
|
||||||
|
|
||||||
const skeletonRowIds = ["first", "second", "third", "fourth"];
|
const skeletonRowIds = ["first", "second", "third", "fourth"];
|
||||||
|
|
||||||
|
|||||||
@@ -63,11 +63,11 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.positive {
|
.positive {
|
||||||
color: var(--mantine-color-green-6);
|
color: var(--wl-color-positive);
|
||||||
}
|
}
|
||||||
|
|
||||||
.negative {
|
.negative {
|
||||||
color: var(--mantine-color-red-6);
|
color: var(--wl-color-negative);
|
||||||
}
|
}
|
||||||
|
|
||||||
.expandedCard {
|
.expandedCard {
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { Stack } from "@mantine/core";
|
import { Stack } from "@mantine/core";
|
||||||
|
import { StateView } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import type { BrokerageAccount } from "@/entities/brokerage-account";
|
import type { BrokerageAccount } from "@/entities/brokerage-account";
|
||||||
import { BrokerageEventsPreview } from "@/entities/brokerage-event";
|
import { BrokerageEventsPreview } from "@/entities/brokerage-event";
|
||||||
import { StateView } from "@/shared/ui";
|
|
||||||
import type {
|
import type {
|
||||||
AccountPageIncomeSummary,
|
AccountPageIncomeSummary,
|
||||||
AccountPageRecentEvents,
|
AccountPageRecentEvents,
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { Button } from "@mantine/core";
|
import { Button } from "@mantine/core";
|
||||||
|
import { StateView } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
import { StateView } from "@/shared/ui";
|
|
||||||
|
|
||||||
type AccountPageErrorProps = { code?: string; retry: () => void };
|
type AccountPageErrorProps = { code?: string; retry: () => void };
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Paper, SimpleGrid, Skeleton } from "@mantine/core";
|
import { Paper, SimpleGrid, Skeleton } from "@mantine/core";
|
||||||
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
|
||||||
import classes from "../AccountPage.module.css";
|
import classes from "../AccountPage.module.css";
|
||||||
|
|
||||||
const AccountPageLoading: FC = () => {
|
const AccountPageLoading: FC = () => {
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { Button, Paper, Stack, Text } from "@mantine/core";
|
import { Button, Paper, Stack, Text } from "@mantine/core";
|
||||||
|
import { StateView } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
import type { IncomeSummary as IncomeSummaryData } from "@/entities/income";
|
import type { IncomeSummary as IncomeSummaryData } from "@/entities/income";
|
||||||
import { formatMoney } from "@/shared/lib";
|
import { formatMoney } from "@/shared/lib";
|
||||||
import { StateView } from "@/shared/ui";
|
|
||||||
|
|
||||||
type IncomeSummaryProps =
|
type IncomeSummaryProps =
|
||||||
| { state: "loading"; to: string }
|
| { state: "loading"; to: string }
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { Alert, Button, Skeleton, Stack, Text } from "@mantine/core";
|
import { Alert, Button, Skeleton, Stack, Text } from "@mantine/core";
|
||||||
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
import { LedgerEntryRow } from "@/entities/broker-operation";
|
import { LedgerEntryRow } from "@/entities/broker-operation";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
|
||||||
import type { AccountPageRecentOperations } from "../AccountPage.vm";
|
import type { AccountPageRecentOperations } from "../AccountPage.vm";
|
||||||
|
|
||||||
type RecentOperationsProps = {
|
type RecentOperationsProps = {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Stack } from "@mantine/core";
|
import { Stack } from "@mantine/core";
|
||||||
|
import { StateView } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { StateView } from "@/shared/ui";
|
|
||||||
import {
|
import {
|
||||||
AccountsRefreshState,
|
AccountsRefreshState,
|
||||||
type AccountsRefreshStateProps,
|
type AccountsRefreshStateProps,
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { Button, Stack } from "@mantine/core";
|
import { Button, Stack } from "@mantine/core";
|
||||||
|
import { StateView } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
import { StateView } from "@/shared/ui";
|
|
||||||
|
|
||||||
type AccountsPageErrorProps = { code?: string; retry?: () => void };
|
type AccountsPageErrorProps = { code?: string; retry?: () => void };
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Card, Group, SimpleGrid, Skeleton, Stack } from "@mantine/core";
|
import { Card, Group, SimpleGrid, Skeleton, Stack } from "@mantine/core";
|
||||||
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
|
||||||
|
|
||||||
const AccountsPageLoading: FC = () => {
|
const AccountsPageLoading: FC = () => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { Anchor, Button, Skeleton, Stack, Text, Title } from "@mantine/core";
|
import { Anchor, Button, Skeleton, Stack, Text, Title } from "@mantine/core";
|
||||||
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link, Navigate } from "react-router";
|
import { Link, Navigate } from "react-router";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
|
||||||
import { BondPageView } from "./BondPage.view";
|
import { BondPageView } from "./BondPage.view";
|
||||||
import { useBondPageVm } from "./BondPage.vm";
|
import { useBondPageVm } from "./BondPage.vm";
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
Text,
|
Text,
|
||||||
Title,
|
Title,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import {
|
||||||
@@ -26,7 +27,6 @@ import {
|
|||||||
formatMoney,
|
formatMoney,
|
||||||
formatSnapshotTime,
|
formatSnapshotTime,
|
||||||
} from "@/shared/lib";
|
} from "@/shared/lib";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
|
||||||
import classes from "./BondPage.module.css";
|
import classes from "./BondPage.module.css";
|
||||||
import type { BondPageVm } from "./BondPage.vm";
|
import type { BondPageVm } from "./BondPage.vm";
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
TextInput,
|
TextInput,
|
||||||
Title,
|
Title,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
@@ -21,7 +22,6 @@ import {
|
|||||||
formatMoney,
|
formatMoney,
|
||||||
formatSnapshotTime,
|
formatSnapshotTime,
|
||||||
} from "@/shared/lib";
|
} from "@/shared/lib";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
|
||||||
import classes from "./BondsPage.module.css";
|
import classes from "./BondsPage.module.css";
|
||||||
import type { BondsPageVm } from "./BondsPage.vm";
|
import type { BondsPageVm } from "./BondsPage.vm";
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import {
|
|||||||
Text,
|
Text,
|
||||||
Title,
|
Title,
|
||||||
} from "@mantine/core";
|
} 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 { type FC, useLayoutEffect, useRef } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
@@ -20,7 +22,6 @@ import {
|
|||||||
BankPeriodPicker,
|
BankPeriodPicker,
|
||||||
BankSummaryView,
|
BankSummaryView,
|
||||||
} from "@/entities/bank-card";
|
} from "@/entities/bank-card";
|
||||||
import { EntryCard, LoadingSkeleton, StateView } from "@/shared/ui";
|
|
||||||
import classes from "./CardPage.module.css";
|
import classes from "./CardPage.module.css";
|
||||||
import type { CardPageVm } from "./CardPage.vm";
|
import type { CardPageVm } from "./CardPage.vm";
|
||||||
|
|
||||||
@@ -106,19 +107,7 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
|
|||||||
title={t("bank.editCard")}
|
title={t("bank.editCard")}
|
||||||
onClick={() => vm.setEditingCard(true)}
|
onClick={() => vm.setEditingCard(true)}
|
||||||
>
|
>
|
||||||
<svg
|
<EditIcon size={18} strokeWidth={1.5} />
|
||||||
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>
|
|
||||||
</ActionIcon>
|
</ActionIcon>
|
||||||
<ActionIcon
|
<ActionIcon
|
||||||
variant="subtle"
|
variant="subtle"
|
||||||
@@ -130,25 +119,23 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
|
|||||||
loading={vm.archivePending}
|
loading={vm.archivePending}
|
||||||
onClick={() => void vm.toggleArchive()}
|
onClick={() => void vm.toggleArchive()}
|
||||||
>
|
>
|
||||||
<svg
|
{card.archivedAt ? (
|
||||||
width="18"
|
<svg
|
||||||
height="18"
|
width="18"
|
||||||
viewBox="0 0 24 24"
|
height="18"
|
||||||
fill="none"
|
viewBox="0 0 24 24"
|
||||||
stroke="currentColor"
|
fill="none"
|
||||||
strokeWidth="1.5"
|
stroke="currentColor"
|
||||||
strokeLinecap="round"
|
strokeWidth="1.5"
|
||||||
strokeLinejoin="round"
|
strokeLinecap="round"
|
||||||
aria-hidden="true"
|
strokeLinejoin="round"
|
||||||
>
|
aria-hidden="true"
|
||||||
<path
|
>
|
||||||
d={
|
<path d="M3 3h18v4H3z M5 7v14h14V7 M12 17V10m-3 3 3-3 3 3" />
|
||||||
card.archivedAt
|
</svg>
|
||||||
? "M3 3h18v4H3z M5 7v14h14V7 M12 17V10m-3 3 3-3 3 3"
|
) : (
|
||||||
: "M3 6h18 M9 6V3h6v3 M5 6l1 15h12l1-15 M10 10v7 M14 10v7"
|
<DeleteIcon size={18} strokeWidth={1.5} />
|
||||||
}
|
)}
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
</ActionIcon>
|
</ActionIcon>
|
||||||
</Group>
|
</Group>
|
||||||
</div>
|
</div>
|
||||||
@@ -196,18 +183,7 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
|
|||||||
disabled={Boolean(card.archivedAt) || !vm.cards.data}
|
disabled={Boolean(card.archivedAt) || !vm.cards.data}
|
||||||
onClick={() => vm.setOperation("new")}
|
onClick={() => vm.setOperation("new")}
|
||||||
>
|
>
|
||||||
<svg
|
<AddIcon size={20} strokeWidth={1.5} />
|
||||||
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>
|
|
||||||
</ActionIcon>
|
</ActionIcon>
|
||||||
</Group>
|
</Group>
|
||||||
<Select
|
<Select
|
||||||
@@ -279,19 +255,7 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
|
|||||||
title={t("bank.edit")}
|
title={t("bank.edit")}
|
||||||
onClick={() => vm.setOperation(row.item)}
|
onClick={() => vm.setOperation(row.item)}
|
||||||
>
|
>
|
||||||
<svg
|
<EditIcon size={18} strokeWidth={1.5} />
|
||||||
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>
|
|
||||||
</ActionIcon>
|
</ActionIcon>
|
||||||
<ActionIcon
|
<ActionIcon
|
||||||
variant="subtle"
|
variant="subtle"
|
||||||
@@ -306,19 +270,7 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
|
|||||||
title={t("bank.delete")}
|
title={t("bank.delete")}
|
||||||
onClick={() => vm.setDeleting(row.item)}
|
onClick={() => vm.setDeleting(row.item)}
|
||||||
>
|
>
|
||||||
<svg
|
<DeleteIcon size={18} strokeWidth={1.5} />
|
||||||
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>
|
|
||||||
</ActionIcon>
|
</ActionIcon>
|
||||||
</Group>
|
</Group>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 } };
|
||||||
@@ -70,6 +70,43 @@ async function select(label: string, value: string | RegExp) {
|
|||||||
fireEvent.click(await screen.findByRole("option", { name: value }));
|
fireEvent.click(await screen.findByRole("option", { name: value }));
|
||||||
}
|
}
|
||||||
describe("OperationForm", () => {
|
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 () => {
|
it("uses renamed default category and exact maximum positive money despite zero balance", async () => {
|
||||||
const close = setup();
|
const close = setup();
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
@@ -95,6 +132,7 @@ describe("OperationForm", () => {
|
|||||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||||
await waitFor(() => expect(close).toHaveBeenCalled());
|
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||||
expect(body).toMatchObject({
|
expect(body).toMatchObject({
|
||||||
|
kind: "expense",
|
||||||
categoryId: "default",
|
categoryId: "default",
|
||||||
date: "2026-08-07",
|
date: "2026-08-07",
|
||||||
amount: money("92233720368547758.07"),
|
amount: money("92233720368547758.07"),
|
||||||
|
|||||||
@@ -1,420 +1,51 @@
|
|||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import type { FC } from "react";
|
||||||
import { Button, Group, Modal, Stack, Text } from "@mantine/core";
|
import { FormProvider } from "react-hook-form";
|
||||||
import { type FC, useState } from "react";
|
import { BankFeedback, CategoryManager } from "@/entities/bank-card";
|
||||||
import { FormProvider, useForm } from "react-hook-form";
|
import type { OperationFormProps } from "./OperationForm.types";
|
||||||
import { useTranslation } from "react-i18next";
|
import { OperationFormView } from "./OperationForm.view";
|
||||||
import { z } from "zod";
|
import { useOperationFormVm } from "./OperationForm.vm";
|
||||||
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";
|
|
||||||
|
|
||||||
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) => {
|
const OperationForm: FC<OperationFormProps> = (props) => {
|
||||||
useBankFormFocus();
|
const vm = useOperationFormVm(props);
|
||||||
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 }));
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Modal
|
<FormProvider {...vm.methods}>
|
||||||
opened={opened}
|
<OperationFormView
|
||||||
onExitTransitionEnd={props.onClose}
|
{...vm.view}
|
||||||
onClose={() => !pending && !categoriesOpen && setOpened(false)}
|
refundFeedback={
|
||||||
title={t(props.operation ? "bank.editOperation" : "bank.addOperation")}
|
<>
|
||||||
closeOnEscape={!pending && !categoriesOpen}
|
{vm.expensesError && (
|
||||||
closeOnClickOutside={!pending && !categoriesOpen}
|
<BankFeedback
|
||||||
closeButtonProps={{ "aria-label": t("bank.close"), disabled: pending }}
|
loadingError
|
||||||
>
|
error={vm.expensesError}
|
||||||
<FormProvider {...methods}>
|
retry={vm.retryExpenses}
|
||||||
<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 ?? ""
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
{kind === "refund" && (
|
)}{" "}
|
||||||
<>
|
{vm.sourceError && (
|
||||||
<RefundFields
|
<BankFeedback
|
||||||
editing={Boolean(props.operation)}
|
loadingError
|
||||||
expenses={
|
error={vm.sourceError}
|
||||||
expenses.data?.items.map((item) => ({
|
retry={vm.retrySource}
|
||||||
value: item.id,
|
/>
|
||||||
label: t("bank.expenseChoice", {
|
)}
|
||||||
date: formatDate(item.date),
|
</>
|
||||||
name: item.description || item.categoryName,
|
}
|
||||||
amount: formatMoney(item.amount),
|
categoriesFeedback={
|
||||||
available: formatMoney(item.availableRefund),
|
vm.categoriesError && (
|
||||||
}),
|
<BankFeedback
|
||||||
})) ?? []
|
loadingError
|
||||||
}
|
error={vm.categoriesError}
|
||||||
selected={
|
retry={vm.retryCategories}
|
||||||
sourceQuery.data
|
/>
|
||||||
? {
|
)
|
||||||
value: sourceQuery.data.id,
|
}
|
||||||
label: t("bank.expenseChoice", {
|
feedback={vm.error ? <BankFeedback error={vm.error} /> : null}
|
||||||
date: formatDate(sourceQuery.data.date),
|
/>
|
||||||
name:
|
</FormProvider>
|
||||||
sourceQuery.data.description ||
|
{vm.categoriesOpen && (
|
||||||
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 && (
|
|
||||||
<CategoryManager
|
<CategoryManager
|
||||||
onClose={() => setCategoriesOpen(false)}
|
onClose={vm.closeCategories}
|
||||||
onCreated={(id) => {
|
onCreated={vm.onCategoryCreated}
|
||||||
methods.setValue("categoryId", id);
|
|
||||||
setCategoriesOpen(false);
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { BankOperation } from "@/entities/bank-card";
|
import type { BankCard, BankOperation } from "@/entities/bank-card";
|
||||||
|
|
||||||
type OperationValues = {
|
type OperationValues = {
|
||||||
kind: BankOperation["kind"];
|
kind: BankOperation["kind"];
|
||||||
@@ -11,4 +11,11 @@ type OperationValues = {
|
|||||||
description: string;
|
description: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type { OperationValues };
|
type OperationFormProps = {
|
||||||
|
card: BankCard;
|
||||||
|
cards: BankCard[];
|
||||||
|
operation?: BankOperation;
|
||||||
|
onClose: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type { OperationFormProps, OperationValues };
|
||||||
|
|||||||
@@ -1,15 +1,20 @@
|
|||||||
import { Select, Stack, Text, Textarea, TextInput } from "@mantine/core";
|
import {
|
||||||
|
Button,
|
||||||
|
Group,
|
||||||
|
Modal,
|
||||||
|
Select,
|
||||||
|
Stack,
|
||||||
|
Text,
|
||||||
|
Textarea,
|
||||||
|
TextInput,
|
||||||
|
} from "@mantine/core";
|
||||||
import { DateInput } from "@mantine/dates";
|
import { DateInput } from "@mantine/dates";
|
||||||
import type { FC } from "react";
|
import type { FC, FormEventHandler, ReactNode } from "react";
|
||||||
import { Controller, useFormContext } from "react-hook-form";
|
import { Controller, useFormContext } from "react-hook-form";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import type { BankOperation } from "@/entities/bank-card";
|
||||||
type BankOperation,
|
|
||||||
bankDateInputValue,
|
|
||||||
bankDateSchema,
|
|
||||||
bankToday,
|
|
||||||
} from "@/entities/bank-card";
|
|
||||||
import { formatMoney } from "@/shared/lib";
|
import { formatMoney } from "@/shared/lib";
|
||||||
|
import classes from "./OperationForm.module.css";
|
||||||
import type { OperationValues } from "./OperationForm.types";
|
import type { OperationValues } from "./OperationForm.types";
|
||||||
|
|
||||||
type Choice = { value: string; label: string };
|
type Choice = { value: string; label: string };
|
||||||
@@ -21,6 +26,10 @@ type OperationFieldsProps = {
|
|||||||
targets: Choice[];
|
targets: Choice[];
|
||||||
categories: Choice[];
|
categories: Choice[];
|
||||||
defaultCategory: string;
|
defaultCategory: string;
|
||||||
|
kinds: Choice[];
|
||||||
|
dateInputValue: (value: string) => string;
|
||||||
|
validDate: (value: string) => boolean;
|
||||||
|
maxDate: () => string;
|
||||||
};
|
};
|
||||||
const OperationFields: FC<OperationFieldsProps> = (props) => {
|
const OperationFields: FC<OperationFieldsProps> = (props) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -39,9 +48,7 @@ const OperationFields: FC<OperationFieldsProps> = (props) => {
|
|||||||
<Select
|
<Select
|
||||||
label={t("bank.kind")}
|
label={t("bank.kind")}
|
||||||
required
|
required
|
||||||
data={(["expense", "topup", "transfer", "refund"] as const).map(
|
data={props.kinds}
|
||||||
(value) => ({ value, label: t(`bank.kinds.${value}`) }),
|
|
||||||
)}
|
|
||||||
{...field}
|
{...field}
|
||||||
disabled={isSubmitting || props.editing}
|
disabled={isSubmitting || props.editing}
|
||||||
onChange={(value) => {
|
onChange={(value) => {
|
||||||
@@ -99,24 +106,22 @@ const OperationFields: FC<OperationFieldsProps> = (props) => {
|
|||||||
label={t("bank.date")}
|
label={t("bank.date")}
|
||||||
required
|
required
|
||||||
valueFormat="DD.MM.YYYY"
|
valueFormat="DD.MM.YYYY"
|
||||||
value={
|
value={props.validDate(field.value) ? field.value : null}
|
||||||
bankDateSchema.safeParse(field.value).success ? field.value : null
|
|
||||||
}
|
|
||||||
dateParser={(value) =>
|
dateParser={(value) =>
|
||||||
bankDateSchema.safeParse(bankDateInputValue(value)).success
|
props.validDate(props.dateInputValue(value))
|
||||||
? bankDateInputValue(value)
|
? props.dateInputValue(value)
|
||||||
: null
|
: null
|
||||||
}
|
}
|
||||||
fixOnBlur={false}
|
fixOnBlur={false}
|
||||||
onInput={(event) =>
|
onInput={(event) =>
|
||||||
field.onChange(bankDateInputValue(event.currentTarget.value))
|
field.onChange(props.dateInputValue(event.currentTarget.value))
|
||||||
}
|
}
|
||||||
onChange={(value) => field.onChange(value ?? "")}
|
onChange={(value) => field.onChange(value ?? "")}
|
||||||
onBlur={(event) => {
|
onBlur={(event) => {
|
||||||
field.onChange(bankDateInputValue(event.currentTarget.value));
|
field.onChange(props.dateInputValue(event.currentTarget.value));
|
||||||
field.onBlur();
|
field.onBlur();
|
||||||
}}
|
}}
|
||||||
maxDate={bankToday()}
|
maxDate={props.maxDate()}
|
||||||
popoverProps={{
|
popoverProps={{
|
||||||
withinPortal: false,
|
withinPortal: false,
|
||||||
middlewares: { shift: { crossAxis: true } },
|
middlewares: { shift: { crossAxis: true } },
|
||||||
@@ -153,7 +158,6 @@ const OperationFields: FC<OperationFieldsProps> = (props) => {
|
|||||||
type RefundFieldsProps = {
|
type RefundFieldsProps = {
|
||||||
editing: boolean;
|
editing: boolean;
|
||||||
expenses: Choice[];
|
expenses: Choice[];
|
||||||
selected?: Choice;
|
|
||||||
onSelect: (id: string) => void;
|
onSelect: (id: string) => void;
|
||||||
limit: BankOperation["availableRefund"] | undefined;
|
limit: BankOperation["availableRefund"] | undefined;
|
||||||
};
|
};
|
||||||
@@ -172,14 +176,7 @@ const RefundFields: FC<RefundFieldsProps> = (props) => {
|
|||||||
<Select
|
<Select
|
||||||
label={t("bank.expense")}
|
label={t("bank.expense")}
|
||||||
required
|
required
|
||||||
data={
|
data={props.expenses}
|
||||||
props.selected &&
|
|
||||||
!props.expenses.some(
|
|
||||||
(item) => item.value === props.selected?.value,
|
|
||||||
)
|
|
||||||
? [props.selected, ...props.expenses]
|
|
||||||
: props.expenses
|
|
||||||
}
|
|
||||||
{...field}
|
{...field}
|
||||||
onChange={(value) => {
|
onChange={(value) => {
|
||||||
field.onChange(value ?? "");
|
field.onChange(value ?? "");
|
||||||
@@ -200,4 +197,119 @@ const RefundFields: FC<RefundFieldsProps> = (props) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export { OperationFields, RefundFields };
|
type OperationFormViewProps = {
|
||||||
|
opened: boolean;
|
||||||
|
pending: boolean;
|
||||||
|
categoriesOpen: boolean;
|
||||||
|
editing: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
onExitTransitionEnd: () => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
onSubmit: FormEventHandler<HTMLFormElement>;
|
||||||
|
fields: OperationFieldsProps;
|
||||||
|
refund: RefundFieldsProps;
|
||||||
|
loadingExpenses: boolean;
|
||||||
|
emptyExpenses: boolean;
|
||||||
|
sourcePage: number;
|
||||||
|
previousDisabled: boolean;
|
||||||
|
nextDisabled: boolean;
|
||||||
|
onPrevious: () => void;
|
||||||
|
onNext: () => void;
|
||||||
|
onAddCategory: () => void;
|
||||||
|
onReload?: () => void;
|
||||||
|
latest?: { version: number; details: string; onAdopt: () => void };
|
||||||
|
saveDisabled: boolean;
|
||||||
|
refundFeedback?: ReactNode;
|
||||||
|
categoriesFeedback?: ReactNode;
|
||||||
|
feedback?: ReactNode;
|
||||||
|
};
|
||||||
|
const OperationFormView: FC<OperationFormViewProps> = (props) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
opened={props.opened}
|
||||||
|
onExitTransitionEnd={props.onExitTransitionEnd}
|
||||||
|
onClose={props.onClose}
|
||||||
|
title={t(props.editing ? "bank.editOperation" : "bank.addOperation")}
|
||||||
|
closeOnEscape={!props.pending && !props.categoriesOpen}
|
||||||
|
closeOnClickOutside={!props.pending && !props.categoriesOpen}
|
||||||
|
closeButtonProps={{
|
||||||
|
"aria-label": t("bank.close"),
|
||||||
|
disabled: props.pending,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<form onSubmit={props.onSubmit}>
|
||||||
|
<fieldset disabled={props.pending} className={classes.fieldset}>
|
||||||
|
<Stack>
|
||||||
|
<OperationFields {...props.fields} />
|
||||||
|
{props.fields.kind === "refund" && (
|
||||||
|
<>
|
||||||
|
<RefundFields {...props.refund} />
|
||||||
|
{props.loadingExpenses && (
|
||||||
|
<Text role="status">{t("bank.loadingHistory")}</Text>
|
||||||
|
)}
|
||||||
|
{props.emptyExpenses && <Text>{t("bank.noPurchases")}</Text>}
|
||||||
|
{!props.editing && (
|
||||||
|
<Group>
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
disabled={props.previousDisabled}
|
||||||
|
onClick={props.onPrevious}
|
||||||
|
>
|
||||||
|
{t("bank.previous")}
|
||||||
|
</Button>
|
||||||
|
<Text>{t("bank.page", { page: props.sourcePage })}</Text>
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
disabled={props.nextDisabled}
|
||||||
|
onClick={props.onNext}
|
||||||
|
>
|
||||||
|
{t("bank.next")}
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
)}
|
||||||
|
{props.refundFeedback}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{props.fields.kind === "expense" && (
|
||||||
|
<Button variant="subtle" onClick={props.onAddCategory}>
|
||||||
|
{t("bank.addCategory")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{props.categoriesFeedback}
|
||||||
|
{props.feedback}
|
||||||
|
{props.onReload && (
|
||||||
|
<Button variant="default" onClick={props.onReload}>
|
||||||
|
{t("bank.reloadRecord")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{props.latest && (
|
||||||
|
<>
|
||||||
|
<Text>
|
||||||
|
{t("bank.versionHint", { details: props.latest.details })}
|
||||||
|
</Text>
|
||||||
|
<Button variant="default" onClick={props.latest.onAdopt}>
|
||||||
|
{t("bank.adoptVersion", { version: props.latest.version })}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<Group>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
loading={props.pending}
|
||||||
|
disabled={props.saveDisabled}
|
||||||
|
>
|
||||||
|
{t("bank.save")}
|
||||||
|
</Button>
|
||||||
|
<Button variant="default" onClick={props.onCancel}>
|
||||||
|
{t("bank.cancel")}
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
</Stack>
|
||||||
|
</fieldset>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { OperationFormView };
|
||||||
|
|||||||
@@ -0,0 +1,318 @@
|
|||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useForm } from "react-hook-form";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { z } from "zod";
|
||||||
|
import {
|
||||||
|
type BankOperation,
|
||||||
|
bankDateInputValue,
|
||||||
|
bankDateSchema,
|
||||||
|
bankMoneyValue,
|
||||||
|
bankOperationKinds,
|
||||||
|
bankToday,
|
||||||
|
moneyCents,
|
||||||
|
positiveMoneySchema,
|
||||||
|
useBankCategories,
|
||||||
|
useBankExpenses,
|
||||||
|
useBankFormFocus,
|
||||||
|
useBankMutations,
|
||||||
|
useBankOperation,
|
||||||
|
} from "@/entities/bank-card";
|
||||||
|
import { validationMessage } from "@/shared/i18n";
|
||||||
|
import { formatDate, formatMoney } from "@/shared/lib";
|
||||||
|
import type {
|
||||||
|
OperationFormProps,
|
||||||
|
OperationValues,
|
||||||
|
} from "./OperationForm.types";
|
||||||
|
|
||||||
|
const MAX_DESCRIPTION_LENGTH = 500;
|
||||||
|
|
||||||
|
const operationSchema = z.object({
|
||||||
|
kind: z.enum(bankOperationKinds),
|
||||||
|
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),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
const useOperationFormVm = (props: OperationFormProps) => {
|
||||||
|
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 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);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const onReload = 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);
|
||||||
|
};
|
||||||
|
|
||||||
|
const expenseChoice = (item: BankOperation) => ({
|
||||||
|
value: item.id,
|
||||||
|
label: t("bank.expenseChoice", {
|
||||||
|
date: formatDate(item.date),
|
||||||
|
name: item.description || item.categoryName,
|
||||||
|
amount: formatMoney(item.amount),
|
||||||
|
available: formatMoney(item.availableRefund),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const expenseOptions = expenses.data?.items.map(expenseChoice) ?? [];
|
||||||
|
const selected = sourceQuery.data
|
||||||
|
? expenseChoice(sourceQuery.data)
|
||||||
|
: undefined;
|
||||||
|
return {
|
||||||
|
methods,
|
||||||
|
categoriesOpen,
|
||||||
|
error,
|
||||||
|
categoriesError: categories.isError ? categories.error : null,
|
||||||
|
expensesError: expenses.isError ? expenses.error : null,
|
||||||
|
sourceError: sourceQuery.isError ? sourceQuery.error : null,
|
||||||
|
retryCategories: () => void categories.refetch(),
|
||||||
|
retryExpenses: () => void expenses.refetch(),
|
||||||
|
retrySource: () => void sourceQuery.refetch(),
|
||||||
|
closeCategories: () => setCategoriesOpen(false),
|
||||||
|
onCategoryCreated: (id: string) => {
|
||||||
|
methods.setValue("categoryId", id);
|
||||||
|
setCategoriesOpen(false);
|
||||||
|
},
|
||||||
|
view: {
|
||||||
|
opened,
|
||||||
|
pending,
|
||||||
|
categoriesOpen,
|
||||||
|
editing: Boolean(props.operation),
|
||||||
|
onClose: () => !pending && !categoriesOpen && setOpened(false),
|
||||||
|
onExitTransitionEnd: props.onClose,
|
||||||
|
onCancel: () => setOpened(false),
|
||||||
|
onSubmit,
|
||||||
|
fields: {
|
||||||
|
refundCardId: props.card.id,
|
||||||
|
editing: Boolean(props.operation),
|
||||||
|
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 ?? "",
|
||||||
|
kinds: bankOperationKinds.map((value) => ({
|
||||||
|
value,
|
||||||
|
label: t(`bank.kinds.${value}`),
|
||||||
|
})),
|
||||||
|
dateInputValue: bankDateInputValue,
|
||||||
|
validDate: (value: string) => bankDateSchema.safeParse(value).success,
|
||||||
|
maxDate: bankToday,
|
||||||
|
},
|
||||||
|
refund: {
|
||||||
|
editing: Boolean(props.operation),
|
||||||
|
expenses:
|
||||||
|
selected &&
|
||||||
|
!expenseOptions.some((item) => item.value === selected.value)
|
||||||
|
? [selected, ...expenseOptions]
|
||||||
|
: expenseOptions,
|
||||||
|
onSelect: setSourceId,
|
||||||
|
limit: props.operation
|
||||||
|
? refundLimit
|
||||||
|
: sourceQuery.data?.availableRefund,
|
||||||
|
},
|
||||||
|
loadingExpenses: expenses.isLoading,
|
||||||
|
emptyExpenses: Boolean(
|
||||||
|
expenses.data && !expenses.data.items.length && !props.operation,
|
||||||
|
),
|
||||||
|
sourcePage,
|
||||||
|
previousDisabled: sourcePage === 1 || expenses.isFetching,
|
||||||
|
nextDisabled: !expenses.data?.hasNext || expenses.isFetching,
|
||||||
|
onPrevious: () => setSourcePage(sourcePage - 1),
|
||||||
|
onNext: () => setSourcePage(sourcePage + 1),
|
||||||
|
onAddCategory: () => setCategoriesOpen(true),
|
||||||
|
onReload: error && (props.operation || sourceId) ? onReload : undefined,
|
||||||
|
latest: latest
|
||||||
|
? {
|
||||||
|
version: latest.version,
|
||||||
|
details: `${formatDate(latest.date)} · ${formatMoney(latest.amount)} · ${latest.description ?? ""}`,
|
||||||
|
onAdopt: () => {
|
||||||
|
setVersion(latest.version);
|
||||||
|
setLatest(undefined);
|
||||||
|
setError(undefined);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
saveDisabled:
|
||||||
|
(kind === "expense" && !categories.data) ||
|
||||||
|
(kind === "refund" && !sourceQuery.data),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export { useOperationFormVm };
|
||||||
@@ -10,6 +10,8 @@ import {
|
|||||||
Text,
|
Text,
|
||||||
Title,
|
Title,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
|
import { AddIcon } from "@wealthledger/icons";
|
||||||
|
import { LoadingSkeleton, StateView } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
@@ -19,7 +21,6 @@ import {
|
|||||||
BankPeriodPicker,
|
BankPeriodPicker,
|
||||||
BankSummaryView,
|
BankSummaryView,
|
||||||
} from "@/entities/bank-card";
|
} from "@/entities/bank-card";
|
||||||
import { LoadingSkeleton, StateView } from "@/shared/ui";
|
|
||||||
import classes from "./CardsPage.module.css";
|
import classes from "./CardsPage.module.css";
|
||||||
import type { CardsPageVm } from "./CardsPage.vm";
|
import type { CardsPageVm } from "./CardsPage.vm";
|
||||||
|
|
||||||
@@ -38,18 +39,7 @@ const CardsPageView: FC<CardsPageViewProps> = (props) => {
|
|||||||
title={t("bank.addCard")}
|
title={t("bank.addCard")}
|
||||||
onClick={() => vm.setAdding(true)}
|
onClick={() => vm.setAdding(true)}
|
||||||
>
|
>
|
||||||
<svg
|
<AddIcon size={20} strokeWidth={2} />
|
||||||
width="20"
|
|
||||||
height="20"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="2"
|
|
||||||
strokeLinecap="round"
|
|
||||||
aria-hidden="true"
|
|
||||||
>
|
|
||||||
<path d="M12 5v14M5 12h14" />
|
|
||||||
</svg>
|
|
||||||
</ActionIcon>
|
</ActionIcon>
|
||||||
</Group>
|
</Group>
|
||||||
<Switch
|
<Switch
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { Button, Stack, Title } from "@mantine/core";
|
import { Button, Stack, Title } from "@mantine/core";
|
||||||
import { useDocumentTitle } from "@mantine/hooks";
|
import { useDocumentTitle } from "@mantine/hooks";
|
||||||
|
import { StateView } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
import { StateView } from "@/shared/ui";
|
|
||||||
|
|
||||||
const NotFoundPage: FC = () => {
|
const NotFoundPage: FC = () => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { Anchor, Button, Skeleton, Stack, Text, Title } from "@mantine/core";
|
import { Anchor, Button, Skeleton, Stack, Text, Title } from "@mantine/core";
|
||||||
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link, Navigate } from "react-router";
|
import { Link, Navigate } from "react-router";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
|
||||||
import { StockPageView } from "./StockPage.view";
|
import { StockPageView } from "./StockPage.view";
|
||||||
import { useStockPageVm } from "./StockPage.vm";
|
import { useStockPageVm } from "./StockPage.vm";
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
Text,
|
Text,
|
||||||
Title,
|
Title,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import {
|
||||||
@@ -24,7 +25,6 @@ import {
|
|||||||
formatMoney,
|
formatMoney,
|
||||||
formatSnapshotTime,
|
formatSnapshotTime,
|
||||||
} from "@/shared/lib";
|
} from "@/shared/lib";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
|
||||||
import { StockDividends } from "./components/StockEvents.view";
|
import { StockDividends } from "./components/StockEvents.view";
|
||||||
import classes from "./StockPage.module.css";
|
import classes from "./StockPage.module.css";
|
||||||
import type { StockPageVm } from "./StockPage.vm";
|
import type { StockPageVm } from "./StockPage.vm";
|
||||||
|
|||||||
@@ -12,11 +12,11 @@ import {
|
|||||||
TextInput,
|
TextInput,
|
||||||
Title,
|
Title,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
import { formatMoney, formatSnapshotTime } from "@/shared/lib";
|
import { formatMoney, formatSnapshotTime } from "@/shared/lib";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
|
||||||
import classes from "./StocksPage.module.css";
|
import classes from "./StocksPage.module.css";
|
||||||
import type { StocksPageVm } from "./StocksPage.vm";
|
import type { StocksPageVm } from "./StocksPage.vm";
|
||||||
|
|
||||||
|
|||||||
@@ -64,4 +64,33 @@ describe("apiClient authentication", () => {
|
|||||||
|
|
||||||
expect(authorization).toBeNull();
|
expect(authorization).toBeNull();
|
||||||
});
|
});
|
||||||
|
it("discards a retried request response after another session takes over", async () => {
|
||||||
|
let generation = 0;
|
||||||
|
let calls = 0;
|
||||||
|
let release!: () => void;
|
||||||
|
const pending = new Promise<void>((resolve) => {
|
||||||
|
release = resolve;
|
||||||
|
});
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/brokerage-accounts", async () => {
|
||||||
|
if (++calls === 1)
|
||||||
|
return HttpResponse.json({ code: "UNAUTHORIZED" }, { status: 401 });
|
||||||
|
await pending;
|
||||||
|
return HttpResponse.json([{ id: "previous-user-account" }]);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
configureAuthClient({
|
||||||
|
accessToken: () => "synthetic",
|
||||||
|
generation: () => generation,
|
||||||
|
refresh: async () => true,
|
||||||
|
clear: vi.fn(),
|
||||||
|
});
|
||||||
|
const response = expect(
|
||||||
|
apiClient.GET("/api/v1/brokerage-accounts"),
|
||||||
|
).rejects.toMatchObject({ name: "AbortError" });
|
||||||
|
await vi.waitFor(() => expect(calls).toBe(2));
|
||||||
|
generation += 1;
|
||||||
|
release();
|
||||||
|
await response;
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user