diff --git a/.ai/architecture.md b/.ai/architecture.md index 592142c..a5b6fbb 100644 --- a/.ai/architecture.md +++ b/.ai/architecture.md @@ -69,10 +69,11 @@ Route-aware AppShell и его navigation styles принадлежат `app/ui` `ProtectedLayout` использует public API этого владельца. При изменении foundation прочитай [UI](conventions/ui.md#визуальная-основа) и [Storybook](conventions/storybook.md). -Статичные Add/Edit/Delete и публичный `IconProps` принадлежат private -`packages/icons`; package не зависит от UI, domain или motion. -`BankOperationIcon` и mappings остаются у entity. Card/Cards используют package -Add/Edit/Delete; restore/category SVG остаются локальными. +Все SVG, их геометрия и анимации принадлежат private `packages/icons`. +Приложение импортирует компоненты из `@wealthledger/icons` и подключает +`@wealthledger/icons/styles.css`. В `src` нет SVG-файлов и компонентов, +единственная задача которых — рисовать иконку. Domain mapping категории в +параметры `OperationIcon` остаётся в `entities/bank-card/model`. ## Примеры diff --git a/.ai/conventions/storybook.md b/.ai/conventions/storybook.md index 519437f..f9cb91b 100644 --- a/.ai/conventions/storybook.md +++ b/.ai/conventions/storybook.md @@ -19,7 +19,9 @@ StateView/LoadingSkeleton и их stories принадлежат `packages/ui`. Используй CSF, `Meta`/`StoryObj`, `satisfies Meta`, локальные fixtures и actions. Общие Mantine/theme/i18n/Dates providers уже есть в [preview](../../.storybook/preview.tsx); не создавай второй theme source. -Stories не достигают application API, auth, VM и query providers даже транзитивно; +Stories не достигают application API, auth и query providers даже транзитивно. +Presentation VM с form-context/UI-only state допустима; data VM остаётся за +этой границей, которую проверяет полный reachable graph; границу проверяет `deps:storybook`. Не добавляй MSW worker ради каталога. `play` через `storybook/test` нужен, когда interaction иллюстрирует собственный diff --git a/.ai/conventions/typescript-react.md b/.ai/conventions/typescript-react.md index c9420f0..3593ce5 100644 --- a/.ai/conventions/typescript-react.md +++ b/.ai/conventions/typescript-react.md @@ -17,6 +17,33 @@ CSF сохраняет default meta и прямые story exports; configuration exceptions заданы в [ESLint](../../eslint.config.mjs). Не распространяй их на application code. +## Читаемость: ESLint и review + +ESLint проверяет ограничение 80 символов (tab = 2), пустые строки между +JSX siblings и вокруг многострочных declarations/control-flow/return, вынос +функций и условных выражений из JSX props, отдельные Zod schema files, +отсутствие SVG в приложении, optional trailing parameters и многострочные +сложные union types. Generated artifacts не форматируй вручную. +URL, строковые/template/regex literals и комментарии исключены из `max-len`; +это исключение для содержимого, а не повод собирать длинные expressions. +Однострочный JSX не требует обрамляющих скобок; многострочный — требует. +`unicorn/no-null` отключён: API DTO, React refs и Mantine используют `null`. +Сохраняй различие `null`/`undefined` из контракта вместо массовых suppressions. +CSS и Markdown также держи в 80 колонках там, где это не ломает данные/ссылки. + +Review проверяет то, чего синтаксис не доказывает: + +- Пустая строка отделяет смысловые шаги: inputs, вычисления, действие, результат. +- Имена derived values описывают значение, например `projectedAmount`. +- Тернарник остаётся коротким выбором двух значений. Mapping, несколько веток + и многострочное преобразование — отдельная функция с guard и `if/else`. +- Union из object shapes оформляй несколькими строками; nullable scalar + `null | string` остаётся компактным. Для повторяемого shape используй named type. +- Последний необязательный аргумент — `accountId?: string`. Required аргумент + перед следующим required параметром может сохранять `T | undefined`. +- Helpers и действия размещай по [UI ownership](ui.md#container-vm-и-view); + перенос не меняет null/zero, validation, recovery, closures и hook ordering. + ## Hooks и derived state Hooks вызываются без условий и ранних выходов перед ними; custom hook нужен diff --git a/.ai/conventions/ui.md b/.ai/conventions/ui.md index 163ff83..69db119 100644 --- a/.ai/conventions/ui.md +++ b/.ai/conventions/ui.md @@ -11,13 +11,17 @@ Mantine component и общую тему. Для выпадающего выбо ограничения JSDOM решай в test setup, сохраняя production UI. Семантический HTML для структуры страницы остаётся уместным. -Icons ищи у существующего owner (например, -[BankOperationIcon](../../src/entities/bank-card/ui/BankOperationIcon/BankOperationIcon.tsx)); -статичные Add/Edit/Delete доступны в `@wealthledger/icons`. Их SVG декоративны -по умолчанию; имя action принадлежит кнопке. Standalone meaningful icon получает -`aria-hidden={false}`, `role="img"` и доступное имя. Category/kind mappings -и анимации остаются в entity. Не добавляй пакет ради одного символа. Business/domain -components живут у feature/entity/page, даже при повторном использовании. +Icons импортируй из `@wealthledger/icons`; геометрия, SVG assets и animation +lifecycle принадлежат этому пакету. Domain/category lookup возвращает параметры +иконки из model сущности. Каждый SVG хранится цельным декларативным +компонентом: не разбивай path-строки и не собирай геометрию в runtime. +Русские category names из API — данные для нормализованного сопоставления, +не ключи реестра иконок; неизвестные/переименованные категории имеют fallback. +Известные названия банков принадлежат enum `BankName` в bank-card model; +свободный ввод пользовательского названия остаётся строкой. +SVG декоративны по умолчанию; доступное имя action +принадлежит кнопке. Meaningful icon получает `aria-hidden={false}`, `role="img"` +и доступное имя. Приложение и Storybook подключают CSS пакета. Wrapper нужен для проектной ответственности, а не ради нового имени для Button. Локальный CSS module принадлежит component; общий token вводи для @@ -51,10 +55,34 @@ retry callbacks, domain grouping и derived presentation data. View получа | `Component.types.ts` | Переиспользуемые props/local types, когда отдельный owner полезен | | `Component.module.css` | Локальные стили | -Во view нет data/auth/router/navigation/VM hooks и вычислений по domain collection. -Допустимы `useTranslation`, form-context hooks, UI-only state (например failed -image fallback) и formatter одного переданного значения. Группировка/доли -коллекции готовятся в VM. Перенос fetch во view ради меньшего container нарушает границу. +View получает готовые данные и именованные действия. Container вызывает VM; +VM владеет запросами, формой, состоянием, обработчиками и derived values. +Во view нет data/auth/router/navigation hooks и domain grouping. Data VM +вызывает container; presentation hook не должен скрывать fetching во view. +Presentation VM для form-context/UI-only state может использоваться автономно +в каталоге: её граф зависимостей не достигает application data/API. +`useTranslation` и декларативный вывод коллекции допустимы во view. + +JSX props получают ссылки на функции, включая `onClick`, render props, +`dateParser` и callbacks внутри объектов props. Для React Hook Form предпочитай +`useController` в VM вместо inline `Controller.render`. Значение prop с условием +сначала получает предметное имя: `projectedAmount`, `archiveActionLabel`. +Проверяй narrowing при переносе: выражение не должно читать отсутствующие данные +до ветки, которая раньше защищала доступ; обработчик сохраняет актуальный snapshot. + +Внутри компонента нет именованных helpers. Чистые функции форматирования и +адаптации UI inputs выноси в `shared/lib`, передавая явные аргументы. Domain +преобразование остаётся в model своего owner; shared не импортирует entities/pages. +Closure над состоянием, mutations и refs является действием VM, а не shared helper. + +VM собирает связные предметные hooks, когда внутри смешиваются независимые +сценарии. Например, `useOpeningDateField` владеет draft/date parsing и событиями +даты, `usePaymentSystemField` — выбором платёжной системы. Каждый такой hook +возвращает данные и действия своей ответственности, VM объединяет их для view. +Не группируй несвязанные функции только по префиксу `on*` и не создавай +passthrough hook над одним вызовом ради формального дробления. + +Render-helper замени самостоятельным presentation component у того же owner. Отдельный state/section с самостоятельной responsibility выноси в `components/` своего component. Небольшой tightly-coupled renderer оставляй @@ -87,6 +115,10 @@ image fallback) и formatter одного переданного значени ## Формы +Схемы Zod объявляй в `*.schema.ts`, включая `.refine`/`.superRefine`. +Зависимая от текущих данных схема — фабрика с явными inputs в том же файле; +VM вызывает фабрику. Сохраняй актуальность данных и deferred validation messages. + Используй `react-hook-form`, `zodResolver`, `FormProvider`. Container/VM создаёт form state, view получает `onSubmit`/`disabled`, fields используют `useFormContext`. Во время submit блокируй все действия формы. Zod errors показывай у поля; diff --git a/.storybook/dependency-cruiser.cjs b/.storybook/dependency-cruiser.cjs index 6576ed2..b8b42d1 100644 --- a/.storybook/dependency-cruiser.cjs +++ b/.storybook/dependency-cruiser.cjs @@ -5,11 +5,16 @@ module.exports = { forbidden: [ ...base.forbidden, { - from: { path: String.raw`\.stories\.tsx$|^\.storybook/preview\.tsx$` }, + from: { path: "[.]stories[.]tsx$|^[.]storybook/preview[.]tsx$" }, name: "stories-must-not-reach-application-data", severity: "error", to: { - path: String.raw`^src/(shared/api|features/auth|app/routes|app/ui)/|^src/(entities|features)/[^/]+/api/|\.vm\.ts$|^src/pages/[^/]+/ui/.*Page\.tsx$|node_modules/(@tanstack/react-query|openapi-fetch|openapi-react-query)/`, + path: [ + "^src/(shared/api|features/auth|app/routes|app/ui)/", + "^src/(entities|features)/[^/]+/api/", + "^src/pages/[^/]+/ui/.*Page[.]tsx$", + "node_modules/(@tanstack/react-query|openapi-fetch|openapi-react-query)/", + ], reachable: true, }, }, diff --git a/.storybook/preview.tsx b/.storybook/preview.tsx index 267c854..e5ef2ca 100644 --- a/.storybook/preview.tsx +++ b/.storybook/preview.tsx @@ -1,12 +1,14 @@ -import "@mantine/core/styles.css"; import "@mantine/charts/styles.css"; +import "@mantine/core/styles.css"; import "@mantine/dates/styles.css"; +import "@wealthledger/icons/styles.css"; import "@wealthledger/ui/styles.css"; import "dayjs/locale/ru"; -import "../src/shared/i18n"; import type { Preview } from "@storybook/react-vite"; +import "../src/shared/i18n"; + import { MantineProvider } from "@mantine/core"; import { DatesProvider } from "@mantine/dates"; import { cssVariablesResolver, theme } from "@wealthledger/ui/theme"; diff --git a/README.md b/README.md index e57f40d..0ebf4da 100644 --- a/README.md +++ b/README.md @@ -262,14 +262,14 @@ Library build использует отдельный Vite config без app plu Начальная версия 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 используйте декоративный ``, -доступное имя задавайте кнопке. Standalone пример: -``. -Поддерживается также стандартный `aria-labelledby`; подпись выбирает caller. -Card/Cards используют пакетные Add/Edit/Delete с прежними размерами/strokeWidth. -Restore/category SVG и предметный BankOperationIcon остаются в приложении. +Private `@wealthledger/icons` содержит все SVG приложения: действия, +навигацию, contactless/wallet и геометрию `OperationIcon`. Пакет поставляет +ESM, declarations и `@wealthledger/icons/styles.css`; приложение и Storybook +подключают CSS явно. В `src` нет raw SVG и компонентов только для рисования +иконок. Category/kind mapping остаётся в model `entities/bank-card`. + +Статичные иконки принимают `IconProps`: `size` по умолчанию 24, +`strokeWidth` 1.5, цвет через `currentColor`. В кнопке иконка декоративная, +имя принадлежит действию. Для самостоятельного изображения передайте +`aria-hidden={false}`, `role="img"` и `aria-label` либо `aria-labelledby`. +Анимации сохраняют hover/focus lifecycle и `prefers-reduced-motion`. diff --git a/eslint-rules.mjs b/eslint-rules.mjs new file mode 100644 index 0000000..bbb543c --- /dev/null +++ b/eslint-rules.mjs @@ -0,0 +1,178 @@ +const readability = { + create(context) { + const filename = context.filename; + + function checkParameters(node) { + const last = node.params.at(-1); + if ( + last?.type === "Identifier" + && !last.optional + && last.typeAnnotation?.typeAnnotation.type === "TSUnionType" + && last.typeAnnotation.typeAnnotation.types.some( + type => type.type === "TSUndefinedKeyword", + ) + ) + context.report({ messageId: "optional", node: last }); + } + + return { + ArrowFunctionExpression: checkParameters, + CallExpression(node) { + if ( + node.callee.type === "MemberExpression" + && ["refine", "superRefine"].includes(node.callee.property.name) + && !filename.endsWith(".schema.ts") + ) + context.report({ messageId: "schema", node }); + }, + FunctionDeclaration: checkParameters, + FunctionExpression: checkParameters, + ImportDeclaration(node) { + if ( + node.source.value === "zod" + && node.importKind !== "type" + && !filename.endsWith(".schema.ts") + ) + context.report({ messageId: "schema", node }); + }, + JSXOpeningElement(node) { + if ( + !filename.includes("/packages/icons/") + && node.name.type === "JSXIdentifier" + && /^(?:svg|path|circle|ellipse|rect|polygon|polyline|line|g|defs|use|symbol)$/.test( + node.name.name, + ) + ) + context.report({ messageId: "svg", node }); + }, + TSUnionType(node) { + const complex + = node.types.length > 2 + || node.types.some(type => type.type === "TSTypeLiteral"); + + if ( + complex + && node.types.some( + (type, index) => + index > 0 + && type.loc.start.line === node.types[index - 1].loc.end.line, + ) + ) + context.report({ messageId: "union", node }); + }, + VariableDeclarator(node) { + if ( + !/^[A-Z]/.test(node.id.name ?? "") + || node.init?.type !== "ArrowFunctionExpression" + || node.init.body.type !== "BlockStatement" + ) + return; + + for (const statement of node.init.body.body) { + if (statement.type === "FunctionDeclaration") + context.report({ messageId: "helper", node: statement }); + + else if (statement.type === "VariableDeclaration") { + for (const declaration of statement.declarations) { + if ( + ["ArrowFunctionExpression", "FunctionExpression"].includes( + declaration.init?.type, + ) + ) + context.report({ messageId: "helper", node: declaration }); + } + } + } + }, + }; + }, + meta: { + messages: { + helper: + "Move helpers outside components; actions belong to the ViewModel.", + optional: + "Use an optional trailing parameter instead of a union with undefined.", + schema: "Declare Zod schemas in a dedicated *.schema.ts file.", + svg: "Own SVG markup in packages/icons, and import its public component.", + union: "Put complex union members on separate lines.", + }, + schema: [], + type: "suggestion", + }, +}; + +function isComponent(node) { + const pending = [node]; + + while (pending.length > 0) { + const child = pending.pop(); + if (!child) continue; + + switch (child.type) { + case "JSXElement": { + return true; + } + + case "JSXFragment": { + return true; + } + + case "JSXExpressionContainer": { + pending.push(child.expression); + continue; + } + + case "LogicalExpression": { + pending.push(child.right); + continue; + } + + case "ConditionalExpression": { + pending.push(child.consequent, child.alternate); + continue; + } + } + } + + return false; +} + +const jsxSpacing = { + create(context) { + function check(node) { + let previous; + + for (const child of node.children) { + if (child.type === "JSXText" && !child.value.trim()) continue; + if (isComponent(child)) { + if (previous) { + const gap = context.sourceCode.text.slice( + previous.range[1], + child.range[0], + ); + + if (!/\n\s*\n/.test(gap)) + context.report({ + fix: fixer => fixer.insertTextAfter(previous, "\n"), + messageId: "space", + node: child, + }); + } + + previous = child; + } + else previous = undefined; + } + } + + return { JSXElement: check, JSXFragment: check }; + }, + meta: { + fixable: "whitespace", + messages: { space: "Separate sibling JSX components with a blank line." }, + schema: [], + type: "layout", + }, +}; + +export default { rules: { "jsx-spacing": jsxSpacing, readability } }; diff --git a/eslint.config.mjs b/eslint.config.mjs index 75cc19b..2885a5a 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -20,10 +20,24 @@ import { defineConfig, globalIgnores } from "eslint/config"; import globals from "globals"; import tseslint from "typescript-eslint"; +import frontend from "./eslint-rules.mjs"; + export default defineConfig( + { + files: ["src/**/*.{ts,tsx}", "packages/*/src/**/*.{ts,tsx}"], + ignores: ["**/*.test.{ts,tsx}", "**/*.stories.tsx", "src/test/**"], + plugins: { frontend }, + rules: { "frontend/jsx-spacing": "error", "frontend/readability": "error" }, + }, globalIgnores([ - "**/dist/**", "dist-ssr/**", "storybook-static/**", "coverage/**", - ".vitest/**", ".scannerwork/**", "src/shared/api/generated/**", "src/shared/api/spec/**", + "**/dist/**", + "dist-ssr/**", + "storybook-static/**", + "coverage/**", + ".vitest/**", + ".scannerwork/**", + "src/shared/api/generated/**", + "src/shared/api/spec/**", ]), { extends: [ @@ -35,32 +49,91 @@ export default defineConfig( security.configs.recommended, noUnsanitized.configs.recommended, perfectionist.configs["recommended-natural"], - stylistic.configs.customize({ indent: "tab", jsx: true, quotes: "double", semi: true }), + stylistic.configs.customize({ + indent: "tab", + jsx: true, + quotes: "double", + semi: true, + }), ], files: ["**/*.{js,mjs,cjs,ts,tsx}"], linterOptions: { reportUnusedDisableDirectives: "error" }, rules: { // A comma disambiguates generic arrow functions from JSX in TSX. - "@stylistic/comma-dangle": ["error", { - arrays: "always-multiline", enums: "always-multiline", exports: "always-multiline", - functions: "always-multiline", generics: "ignore", imports: "always-multiline", - objects: "always-multiline", tuples: "always-multiline", - }], + "@stylistic/comma-dangle": [ + "error", + { + arrays: "always-multiline", + enums: "always-multiline", + exports: "always-multiline", + functions: "always-multiline", + generics: "ignore", + imports: "always-multiline", + objects: "always-multiline", + tuples: "always-multiline", + }, + ], + // Keep text/interpolation together: splitting can change rendered whitespace. "@stylistic/jsx-one-expression-per-line": ["error", { allow: "non-jsx" }], + "@stylistic/max-len": [ + "error", + { + code: 80, + ignoreComments: true, + ignoreRegExpLiterals: true, + ignoreStrings: true, + ignoreTemplateLiterals: true, + ignoreTrailingComments: true, + ignoreUrls: true, + tabWidth: 2, + }, + ], + "@stylistic/multiline-ternary": ["error", "always-multiline"], "@stylistic/no-tabs": ["error", { allowIndentationTabs: true }], "@stylistic/operator-linebreak": ["error", "before"], - "perfectionist/sort-classes": ["error", { groups: ["static-method", "property", "method", "unknown"], type: "natural" }], + "@stylistic/padding-line-between-statements": [ + "error", + { blankLine: "always", next: "return", prev: "*" }, + { + blankLine: "always", + next: "*", + prev: ["multiline-const", "multiline-let", "block-like", "type"], + }, + { + blankLine: "always", + next: ["multiline-const", "multiline-let", "block-like", "type"], + prev: "*", + }, + { blankLine: "any", next: "cjs-import", prev: "cjs-import" }, + ], + "no-nested-ternary": "error", + "perfectionist/sort-classes": [ + "error", + { + groups: ["static-method", "property", "method", "unknown"], + type: "natural", + }, + ], // Preserve the repository's component, hook and config file naming conventions. - "unicorn/filename-case": ["error", { cases: { camelCase: true, kebabCase: true, pascalCase: true } }], + "unicorn/filename-case": [ + "error", + { cases: { camelCase: true, kebabCase: true, pascalCase: true } }, + ], // React uses Props/Ref names, including the recommended React ref-name rule. - "unicorn/name-replacements": ["error", { replacements: { props: false, ref: false } }], - // React, Mantine and Fetch accept null at their documented call boundaries. - "unicorn/no-null": ["error", { checkArguments: false }], + "unicorn/name-replacements": [ + "error", + { replacements: { props: false, ref: false } }, + ], + // API DTOs, React refs and Mantine use null as part of their contracts. + "unicorn/no-null": "off", + "unicorn/prefer-ternary": ["error", "only-single-line"], }, settings: { - "import-x/resolver-next": [createTypeScriptImportResolver({ project: "tsconfig.json" })], + "import-x/resolver-next": [ + createTypeScriptImportResolver({ project: "tsconfig.json" }), + ], }, }, { @@ -68,18 +141,37 @@ export default defineConfig( languageOptions: { globals: globals.node }, }, { - extends: [tseslint.configs.recommendedTypeChecked, importX.flatConfigs.typescript], + extends: [ + tseslint.configs.recommendedTypeChecked, + importX.flatConfigs.typescript, + ], files: ["**/*.{ts,tsx}"], - languageOptions: { parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname } }, + languageOptions: { + parserOptions: { + projectService: true, + tsconfigRootDir: import.meta.dirname, + }, + }, rules: { // React ignores event handler return values; floating promises are still checked in bodies. - "@typescript-eslint/no-misused-promises": ["error", { checksVoidReturn: { attributes: false } }], + "@typescript-eslint/no-misused-promises": [ + "error", + { checksVoidReturn: { attributes: false } }, + ], "@typescript-eslint/switch-exhaustiveness-check": "error", }, }, { - extends: [react.configs["recommended-type-checked"], hooks.configs.flat.recommended, query.configs["flat/recommended"]], - files: ["src/**/*.{ts,tsx}", "packages/*/src/**/*.{ts,tsx}", ".storybook/preview.tsx"], + extends: [ + react.configs["recommended-type-checked"], + hooks.configs.flat.recommended, + query.configs["flat/recommended"], + ], + files: [ + "src/**/*.{ts,tsx}", + "packages/*/src/**/*.{ts,tsx}", + ".storybook/preview.tsx", + ], languageOptions: { globals: globals.browser }, rules: { "import-x/exports-last": "error", @@ -95,10 +187,16 @@ export default defineConfig( files: ["src/**/*.{ts,tsx}", "packages/*/src/**/*.{ts,tsx}"], ignores: ["**/*.test.{ts,tsx}", "**/*.stories.tsx", "src/test/**"], rules: { - "@typescript-eslint/no-magic-numbers": ["error", { - ignore: [-1, 0, 1, "-1n", "0n", "1n"], ignoreArrayIndexes: true, ignoreDefaultValues: true, - ignoreNumericLiteralTypes: true, ignoreTypeIndexes: true, - }], + "@typescript-eslint/no-magic-numbers": [ + "error", + { + ignore: [-1, 0, 1, "-1n", "0n", "1n"], + ignoreArrayIndexes: true, + ignoreDefaultValues: true, + ignoreNumericLiteralTypes: true, + ignoreTypeIndexes: true, + }, + ], }, }, { @@ -110,51 +208,73 @@ export default defineConfig( }, }, { - extends: [testingLibrary.configs["flat/react"], jestDom.configs["flat/recommended"]], + extends: [ + testingLibrary.configs["flat/react"], + jestDom.configs["flat/recommended"], + ], files: ["**/*.test.tsx"], }, storybook.configs["flat/recommended"], { files: ["**/*.stories.tsx", ".storybook/preview.tsx"], - rules: { "import-x/exports-last": "off", "import-x/no-default-export": "off" }, + rules: { + "import-x/exports-last": "off", + "import-x/no-default-export": "off", + }, }, { - files: [ - "src/**/*.{ts,tsx}", - "packages/*/src/**/*.{ts,tsx}", - ], - ignores: [ - "**/*.test.{ts,tsx}", - "**/*.stories.tsx", - "src/test/**", - ], + files: ["src/**/*.{ts,tsx}", "packages/*/src/**/*.{ts,tsx}"], + ignores: ["**/*.test.{ts,tsx}", "**/*.stories.tsx", "src/test/**"], rules: { "@typescript-eslint/no-unsafe-enum-comparison": "error", "no-restricted-syntax": [ "error", { - message: "Use the owning enum member for machine codes and protocol values.", - selector: "Literal[value=/^(?:(?:INSTRUMENT_ID_TYPE|INSTRUMENT_TYPE|OPERATION_STATE|OPERATION_TYPE|ACCOUNT_STATUS|ACCOUNT_TYPE|CANDLE_INTERVAL|COUPON_TYPE|BANK|INVALID)_[A-Z0-9]+(?:_[A-Z0-9]+)*|[A-Z][A-Z0-9_]*_(?:ERROR|UNAVAILABLE|NOT_FOUND|NOT_CONNECTED|CONFLICT|AMBIGUOUS|REGISTERED)|P[0-9]{4}|UNAUTHORIZED|FORBIDDEN|BAD_REQUEST|NOT_FOUND|UNSUPPORTED_MEDIA_TYPE)$/]:not(TSEnumMember > Literal)", + message: + "Pass a named handler from the ViewModel; prepare prop data before JSX.", + selector: + "JSXAttribute > JSXExpressionContainer :matches(ArrowFunctionExpression, FunctionExpression)", }, { - message: "Use the owning enum member instead of a template machine code.", - selector: "TemplateElement[value.cooked=/^(?:(?:INSTRUMENT_ID_TYPE|INSTRUMENT_TYPE|OPERATION_STATE|OPERATION_TYPE|ACCOUNT_STATUS|ACCOUNT_TYPE|CANDLE_INTERVAL|COUPON_TYPE|BANK|INVALID)_[A-Z0-9]+(?:_[A-Z0-9]+)*|[A-Z][A-Z0-9_]*_(?:ERROR|UNAVAILABLE|NOT_FOUND|NOT_CONNECTED|CONFLICT|AMBIGUOUS|REGISTERED)|P[0-9]{4}|UNAUTHORIZED|FORBIDDEN|BAD_REQUEST|NOT_FOUND|UNSUPPORTED_MEDIA_TYPE)$/]:not(TSEnumMember TemplateElement)", + message: "Name the derived prop value before JSX.", + selector: + "JSXAttribute > JSXExpressionContainer ConditionalExpression", + }, + + { + message: + "Use the owning enum member for machine codes and protocol values.", + selector: + "Literal[value=/^(?:(?:INSTRUMENT_ID_TYPE|INSTRUMENT_TYPE|OPERATION_STATE|OPERATION_TYPE|ACCOUNT_STATUS|ACCOUNT_TYPE|CANDLE_INTERVAL|COUPON_TYPE|BANK|INVALID)_[A-Z0-9]+(?:_[A-Z0-9]+)*|[A-Z][A-Z0-9_]*_(?:ERROR|UNAVAILABLE|NOT_FOUND|NOT_CONNECTED|CONFLICT|AMBIGUOUS|REGISTERED)|P[0-9]{4}|UNAUTHORIZED|FORBIDDEN|BAD_REQUEST|NOT_FOUND|UNSUPPORTED_MEDIA_TYPE)$/]:not(TSEnumMember > Literal)", }, { - message: "Use an enum member instead of an inline code or protocol value.", - selector: "Property:matches([key.name=/^(code|errorCode|idType|instrumentKind)$/], [key.value=/^(code|errorCode|idType|instrumentKind)$/]) > Literal.value[value=type(string)]", + message: + "Use the owning enum member instead of a template machine code.", + selector: + "TemplateElement[value.cooked=/^(?:(?:INSTRUMENT_ID_TYPE|INSTRUMENT_TYPE|OPERATION_STATE|OPERATION_TYPE|ACCOUNT_STATUS|ACCOUNT_TYPE|CANDLE_INTERVAL|COUPON_TYPE|BANK|INVALID)_[A-Z0-9]+(?:_[A-Z0-9]+)*|[A-Z][A-Z0-9_]*_(?:ERROR|UNAVAILABLE|NOT_FOUND|NOT_CONNECTED|CONFLICT|AMBIGUOUS|REGISTERED)|P[0-9]{4}|UNAUTHORIZED|FORBIDDEN|BAD_REQUEST|NOT_FOUND|UNSUPPORTED_MEDIA_TYPE)$/]:not(TSEnumMember TemplateElement)", }, { - message: "Use an enum member instead of constructing a code or protocol value.", - selector: "Property:matches([key.name=/^(code|errorCode|idType|instrumentKind)$/], [key.value=/^(code|errorCode|idType|instrumentKind)$/]) > TemplateLiteral.value", + message: + "Use an enum member instead of an inline code or protocol value.", + selector: + "Property:matches([key.name=/^(code|errorCode|idType|instrumentKind)$/], [key.value=/^(code|errorCode|idType|instrumentKind)$/]) > Literal.value[value=type(string)]", + }, + { + message: + "Use an enum member instead of constructing a code or protocol value.", + selector: + "Property:matches([key.name=/^(code|errorCode|idType|instrumentKind)$/], [key.value=/^(code|errorCode|idType|instrumentKind)$/]) > TemplateLiteral.value", }, { message: "Use a computed enum member as the protocol mapping key.", - selector: "Property[computed=false][key.name=/^(OPERATION_TYPE|ACCOUNT_TYPE)_/]", + selector: + "Property[computed=false][key.name=/^(OPERATION_TYPE|ACCOUNT_TYPE)_/]", }, { - message: "Compare codes with their enum members, not string literals.", - selector: "BinaryExpression:has(> :matches(MemberExpression[property.name=/^(code|errorCode)$/], Identifier[name=/^(code|errorCode)$/])) > Literal[value=type(string)]", + message: + "Compare codes with their enum members, not string literals.", + selector: + "BinaryExpression:has(> :matches(MemberExpression[property.name=/^(code|errorCode)$/], Identifier[name=/^(code|errorCode)$/])) > Literal[value=type(string)]", }, ], }, diff --git a/packages/icons/package.json b/packages/icons/package.json index e3f8c13..17c4c3c 100644 --- a/packages/icons/package.json +++ b/packages/icons/package.json @@ -10,9 +10,12 @@ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" - } + }, + "./styles.css": "./dist/index.css" }, - "sideEffects": false, + "sideEffects": [ + "**/*.css" + ], "scripts": { "build": "vite build && tsc -p tsconfig.json" }, diff --git a/packages/icons/src/Icons.stories.tsx b/packages/icons/src/Icons.stories.tsx index 40bfe20..47a7a0e 100644 --- a/packages/icons/src/Icons.stories.tsx +++ b/packages/icons/src/Icons.stories.tsx @@ -17,6 +17,7 @@ const meta = { } satisfies Meta; export default meta; + type Story = StoryObj; export const Decorative: Story = { @@ -25,9 +26,11 @@ export const Decorative: Story = { + + @@ -39,7 +42,9 @@ export const Meaningful: Story = { render: () => (
+ +
), diff --git a/packages/icons/src/Icons.test.tsx b/packages/icons/src/Icons.test.tsx index 7d52460..c416b5b 100644 --- a/packages/icons/src/Icons.test.tsx +++ b/packages/icons/src/Icons.test.tsx @@ -12,6 +12,7 @@ describe("icon accessibility", () => { , ); + expect(screen.queryByRole("img")).not.toBeInTheDocument(); expect( // eslint-disable-next-line testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish. diff --git a/src/entities/bank-card/ui/BankOperationIcon/BankOperationIcon.module.css b/packages/icons/src/OperationIcon/OperationIcon.module.css similarity index 99% rename from src/entities/bank-card/ui/BankOperationIcon/BankOperationIcon.module.css rename to packages/icons/src/OperationIcon/OperationIcon.module.css index 10e12ad..f986cd6 100644 --- a/src/entities/bank-card/ui/BankOperationIcon/BankOperationIcon.module.css +++ b/packages/icons/src/OperationIcon/OperationIcon.module.css @@ -1,4 +1,5 @@ .icon { + flex-shrink: 0; overflow: visible; & path { diff --git a/packages/icons/src/OperationIcon/OperationIcon.tsx b/packages/icons/src/OperationIcon/OperationIcon.tsx new file mode 100644 index 0000000..1322db5 --- /dev/null +++ b/packages/icons/src/OperationIcon/OperationIcon.tsx @@ -0,0 +1,72 @@ +import type { FC } from "react"; + +import { BasketIcon } from "./svg/BasketIcon"; +import { CarIcon } from "./svg/CarIcon"; +import { CashWithdrawalIcon } from "./svg/CashWithdrawalIcon"; +import { CoffeeIcon } from "./svg/CoffeeIcon"; +import { DepositIcon } from "./svg/DepositIcon"; +import { DiceIcon } from "./svg/DiceIcon"; +import { DownloadIcon } from "./svg/DownloadIcon"; +import { EducationIcon } from "./svg/EducationIcon"; +import { GridIcon } from "./svg/GridIcon"; +import { GrowthIcon } from "./svg/GrowthIcon"; +import { HomeIcon } from "./svg/HomeIcon"; +import { MedicalIcon } from "./svg/MedicalIcon"; +import { MusicIcon } from "./svg/MusicIcon"; +import { RefundIcon } from "./svg/RefundIcon"; +import { RepaymentIcon } from "./svg/RepaymentIcon"; +import { ServerIcon } from "./svg/ServerIcon"; +import { ShieldIcon } from "./svg/ShieldIcon"; +import { ShoppingIcon } from "./svg/ShoppingIcon"; +import { SmokingIcon } from "./svg/SmokingIcon"; +import { SubscriptionsIcon } from "./svg/SubscriptionsIcon"; +import { TaxiIcon } from "./svg/TaxiIcon"; +import { TopupIcon } from "./svg/TopupIcon"; +import { TransferIcon } from "./svg/TransferIcon"; +import { TravelIcon } from "./svg/TravelIcon"; +import { WifiIcon } from "./svg/WifiIcon"; +import { WineIcon } from "./svg/WineIcon"; + +const icons = { + basket: BasketIcon, + car: CarIcon, + cashWithdrawal: CashWithdrawalIcon, + coffee: CoffeeIcon, + deposit: DepositIcon, + dice: DiceIcon, + download: DownloadIcon, + education: EducationIcon, + grid: GridIcon, + growth: GrowthIcon, + home: HomeIcon, + medical: MedicalIcon, + music: MusicIcon, + refund: RefundIcon, + repayment: RepaymentIcon, + server: ServerIcon, + shield: ShieldIcon, + shopping: ShoppingIcon, + smoking: SmokingIcon, + subscriptions: SubscriptionsIcon, + taxi: TaxiIcon, + topup: TopupIcon, + transfer: TransferIcon, + travel: TravelIcon, + wifi: WifiIcon, + wine: WineIcon, +}; + +type OperationIconProps = { + color: string; + variant: keyof typeof icons; +}; + +const OperationIcon: FC = (props) => { + const { color, variant } = props; + // eslint-disable-next-line security/detect-object-injection -- Variant is a closed key of the static icon registry. + const Icon = icons[variant]; + + return ; +}; + +export { OperationIcon, type OperationIconProps }; diff --git a/packages/icons/src/OperationIcon/svg/BasketIcon.tsx b/packages/icons/src/OperationIcon/svg/BasketIcon.tsx new file mode 100644 index 0000000..e476e53 --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/BasketIcon.tsx @@ -0,0 +1,40 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const BasketIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { BasketIcon }; diff --git a/packages/icons/src/OperationIcon/svg/CarIcon.tsx b/packages/icons/src/OperationIcon/svg/CarIcon.tsx new file mode 100644 index 0000000..c71a321 --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/CarIcon.tsx @@ -0,0 +1,40 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const CarIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { CarIcon }; diff --git a/packages/icons/src/OperationIcon/svg/CashWithdrawalIcon.tsx b/packages/icons/src/OperationIcon/svg/CashWithdrawalIcon.tsx new file mode 100644 index 0000000..63b73dc --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/CashWithdrawalIcon.tsx @@ -0,0 +1,38 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const CashWithdrawalIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { CashWithdrawalIcon }; diff --git a/packages/icons/src/OperationIcon/svg/CoffeeIcon.tsx b/packages/icons/src/OperationIcon/svg/CoffeeIcon.tsx new file mode 100644 index 0000000..26dc7c5 --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/CoffeeIcon.tsx @@ -0,0 +1,40 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const CoffeeIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { CoffeeIcon }; diff --git a/packages/icons/src/OperationIcon/svg/DepositIcon.tsx b/packages/icons/src/OperationIcon/svg/DepositIcon.tsx new file mode 100644 index 0000000..c85ae3b --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/DepositIcon.tsx @@ -0,0 +1,38 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const DepositIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { DepositIcon }; diff --git a/packages/icons/src/OperationIcon/svg/DiceIcon.tsx b/packages/icons/src/OperationIcon/svg/DiceIcon.tsx new file mode 100644 index 0000000..0388e9e --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/DiceIcon.tsx @@ -0,0 +1,42 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const DiceIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { DiceIcon }; diff --git a/packages/icons/src/OperationIcon/svg/DownloadIcon.tsx b/packages/icons/src/OperationIcon/svg/DownloadIcon.tsx new file mode 100644 index 0000000..dba47eb --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/DownloadIcon.tsx @@ -0,0 +1,40 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const DownloadIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { DownloadIcon }; diff --git a/packages/icons/src/OperationIcon/svg/EducationIcon.tsx b/packages/icons/src/OperationIcon/svg/EducationIcon.tsx new file mode 100644 index 0000000..b080fa6 --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/EducationIcon.tsx @@ -0,0 +1,36 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const EducationIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { EducationIcon }; diff --git a/packages/icons/src/OperationIcon/svg/GridIcon.tsx b/packages/icons/src/OperationIcon/svg/GridIcon.tsx new file mode 100644 index 0000000..ab3ef21 --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/GridIcon.tsx @@ -0,0 +1,38 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const GridIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { GridIcon }; diff --git a/packages/icons/src/OperationIcon/svg/GrowthIcon.tsx b/packages/icons/src/OperationIcon/svg/GrowthIcon.tsx new file mode 100644 index 0000000..fb2ff72 --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/GrowthIcon.tsx @@ -0,0 +1,36 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const GrowthIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { GrowthIcon }; diff --git a/packages/icons/src/OperationIcon/svg/HomeIcon.tsx b/packages/icons/src/OperationIcon/svg/HomeIcon.tsx new file mode 100644 index 0000000..7ffda51 --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/HomeIcon.tsx @@ -0,0 +1,36 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const HomeIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { HomeIcon }; diff --git a/packages/icons/src/OperationIcon/svg/MedicalIcon.tsx b/packages/icons/src/OperationIcon/svg/MedicalIcon.tsx new file mode 100644 index 0000000..d9df27a --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/MedicalIcon.tsx @@ -0,0 +1,32 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const MedicalIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { MedicalIcon }; diff --git a/packages/icons/src/OperationIcon/svg/MusicIcon.tsx b/packages/icons/src/OperationIcon/svg/MusicIcon.tsx new file mode 100644 index 0000000..c7774f4 --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/MusicIcon.tsx @@ -0,0 +1,36 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const MusicIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { MusicIcon }; diff --git a/packages/icons/src/OperationIcon/svg/RefundIcon.tsx b/packages/icons/src/OperationIcon/svg/RefundIcon.tsx new file mode 100644 index 0000000..882208f --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/RefundIcon.tsx @@ -0,0 +1,34 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const RefundIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { RefundIcon }; diff --git a/packages/icons/src/OperationIcon/svg/RepaymentIcon.tsx b/packages/icons/src/OperationIcon/svg/RepaymentIcon.tsx new file mode 100644 index 0000000..f9ea4d0 --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/RepaymentIcon.tsx @@ -0,0 +1,36 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const RepaymentIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { RepaymentIcon }; diff --git a/packages/icons/src/OperationIcon/svg/ServerIcon.tsx b/packages/icons/src/OperationIcon/svg/ServerIcon.tsx new file mode 100644 index 0000000..de821f4 --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/ServerIcon.tsx @@ -0,0 +1,42 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const ServerIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { ServerIcon }; diff --git a/packages/icons/src/OperationIcon/svg/ShieldIcon.tsx b/packages/icons/src/OperationIcon/svg/ShieldIcon.tsx new file mode 100644 index 0000000..b02a98a --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/ShieldIcon.tsx @@ -0,0 +1,34 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const ShieldIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { ShieldIcon }; diff --git a/packages/icons/src/OperationIcon/svg/ShoppingIcon.tsx b/packages/icons/src/OperationIcon/svg/ShoppingIcon.tsx new file mode 100644 index 0000000..4dd818b --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/ShoppingIcon.tsx @@ -0,0 +1,34 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const ShoppingIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { ShoppingIcon }; diff --git a/packages/icons/src/OperationIcon/svg/SmokingIcon.tsx b/packages/icons/src/OperationIcon/svg/SmokingIcon.tsx new file mode 100644 index 0000000..8e09412 --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/SmokingIcon.tsx @@ -0,0 +1,38 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const SmokingIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { SmokingIcon }; diff --git a/packages/icons/src/OperationIcon/svg/SubscriptionsIcon.tsx b/packages/icons/src/OperationIcon/svg/SubscriptionsIcon.tsx new file mode 100644 index 0000000..87f09f7 --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/SubscriptionsIcon.tsx @@ -0,0 +1,38 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const SubscriptionsIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { SubscriptionsIcon }; diff --git a/packages/icons/src/OperationIcon/svg/TaxiIcon.tsx b/packages/icons/src/OperationIcon/svg/TaxiIcon.tsx new file mode 100644 index 0000000..c72bd19 --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/TaxiIcon.tsx @@ -0,0 +1,44 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const TaxiIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { TaxiIcon }; diff --git a/packages/icons/src/OperationIcon/svg/TopupIcon.tsx b/packages/icons/src/OperationIcon/svg/TopupIcon.tsx new file mode 100644 index 0000000..11328a1 --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/TopupIcon.tsx @@ -0,0 +1,36 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const TopupIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { TopupIcon }; diff --git a/packages/icons/src/OperationIcon/svg/TransferIcon.tsx b/packages/icons/src/OperationIcon/svg/TransferIcon.tsx new file mode 100644 index 0000000..ce41992 --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/TransferIcon.tsx @@ -0,0 +1,34 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const TransferIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { TransferIcon }; diff --git a/packages/icons/src/OperationIcon/svg/TravelIcon.tsx b/packages/icons/src/OperationIcon/svg/TravelIcon.tsx new file mode 100644 index 0000000..4248c2f --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/TravelIcon.tsx @@ -0,0 +1,32 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const TravelIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { TravelIcon }; diff --git a/packages/icons/src/OperationIcon/svg/WifiIcon.tsx b/packages/icons/src/OperationIcon/svg/WifiIcon.tsx new file mode 100644 index 0000000..05b259e --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/WifiIcon.tsx @@ -0,0 +1,38 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const WifiIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { WifiIcon }; diff --git a/packages/icons/src/OperationIcon/svg/WineIcon.tsx b/packages/icons/src/OperationIcon/svg/WineIcon.tsx new file mode 100644 index 0000000..794c404 --- /dev/null +++ b/packages/icons/src/OperationIcon/svg/WineIcon.tsx @@ -0,0 +1,38 @@ +import type { FC } from "react"; + +import type { IconProps } from "../../types"; + +import { bindIconAnimation } from "../../bind-icon-animation"; +import classes from "../OperationIcon.module.css"; + +const WineIcon: FC = (props) => { + const { size = 24, ...svgProps } = props; + + return ( + + ); +}; + +export { WineIcon }; diff --git a/src/assets/react.svg b/packages/icons/src/assets/react.svg similarity index 100% rename from src/assets/react.svg rename to packages/icons/src/assets/react.svg diff --git a/src/assets/vite.svg b/packages/icons/src/assets/vite.svg similarity index 100% rename from src/assets/vite.svg rename to packages/icons/src/assets/vite.svg diff --git a/src/shared/lib/bind-icon-animation.test.tsx b/packages/icons/src/bind-icon-animation.test.tsx similarity index 99% rename from src/shared/lib/bind-icon-animation.test.tsx rename to packages/icons/src/bind-icon-animation.test.tsx index 89a9caa..fde5ddd 100644 --- a/src/shared/lib/bind-icon-animation.test.tsx +++ b/packages/icons/src/bind-icon-animation.test.tsx @@ -9,25 +9,30 @@ it("finishes every delayed part after leaving and does not restart on quick re-e vi.spyOn(globalThis, "matchMedia").mockReturnValue({ matches: true, } as MediaQueryList); + const { container } = render( , ); + // eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- Bind browser animation doubles to the decorative SVG, which has no accessible role. const icon = container.querySelector("svg"); if (!icon) throw new Error("Missing icon"); const target = screen.getByRole("button"); let finishFirst!: () => void; let finishLast!: () => void; + const getAnimations = vi.fn(() => { const first = Promise.withResolvers(); const last = Promise.withResolvers(); finishFirst = first.resolve; finishLast = last.resolve; + return [{ finished: first.promise }, { finished: last.promise }]; }); + Object.defineProperty(icon, "getAnimations", { value: getAnimations }); fireEvent.mouseEnter(target); fireEvent.mouseLeave(target); @@ -53,6 +58,7 @@ it("keeps playing after keyboard blur and releases cancelled animations", async Category , ); + // eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- Bind browser animation doubles to the decorative SVG, which has no accessible role. const icon = container.querySelector("svg"); if (!icon) throw new Error("Missing icon"); diff --git a/src/shared/lib/bind-icon-animation.ts b/packages/icons/src/bind-icon-animation.ts similarity index 99% rename from src/shared/lib/bind-icon-animation.ts rename to packages/icons/src/bind-icon-animation.ts index eb520a5..0f0433d 100644 --- a/src/shared/lib/bind-icon-animation.ts +++ b/packages/icons/src/bind-icon-animation.ts @@ -13,6 +13,7 @@ const bindIconAnimation = (icon: null | SVGSVGElement) => { delete icon.dataset.iconAnimating; } }; + const start = () => { if (Object.hasOwn(icon.dataset, "iconAnimating")) return; icon.dataset.iconAnimating = ""; @@ -27,21 +28,25 @@ const bindIconAnimation = (icon: null | SVGSVGElement) => { release(); }); }; + const enter = () => { if (!matchMedia("(hover: hover)").matches) return; isHovered = true; start(); }; + const leave = () => { isHovered = false; release(); }; + const focus = () => { isFocused = target.matches(":focus-visible") || !!target.querySelector(":focus-visible"); if (isFocused) start(); }; + const blur = (event: FocusEvent) => { if ( event.relatedTarget instanceof Node @@ -51,10 +56,12 @@ const bindIconAnimation = (icon: null | SVGSVGElement) => { isFocused = false; release(); }; + target.addEventListener("mouseenter", enter); target.addEventListener("mouseleave", leave); target.addEventListener("focusin", focus); target.addEventListener("focusout", blur); + return () => { isDisposed = true; target.removeEventListener("mouseenter", enter); diff --git a/packages/icons/src/index.ts b/packages/icons/src/index.ts index 296d458..c1adc6a 100644 --- a/packages/icons/src/index.ts +++ b/packages/icons/src/index.ts @@ -1,4 +1,17 @@ +export { + OperationIcon, + type OperationIconProps, +} from "./OperationIcon/OperationIcon"; export { AddIcon } from "./svg/AddIcon"; +export { BondsIcon } from "./svg/BondsIcon"; +export { CardsIcon } from "./svg/CardsIcon"; +export { CategoriesIcon } from "./svg/CategoriesIcon"; +export { ContactlessIcon } from "./svg/ContactlessIcon"; export { DeleteIcon } from "./svg/DeleteIcon"; export { EditIcon } from "./svg/EditIcon"; +export { PortfolioIcon } from "./svg/PortfolioIcon"; +export { RestoreIcon } from "./svg/RestoreIcon"; +export { SettingsIcon } from "./svg/SettingsIcon"; +export { StocksIcon } from "./svg/StocksIcon"; +export { WalletIcon } from "./svg/WalletIcon"; export type { IconProps } from "./types"; diff --git a/packages/icons/src/navigation.module.css b/packages/icons/src/navigation.module.css new file mode 100644 index 0000000..75f58fa --- /dev/null +++ b/packages/icons/src/navigation.module.css @@ -0,0 +1,179 @@ +.rubles { + pointer-events: none; + color: var(--mantine-color-green-8); + stroke: currentColor; + + & path { + opacity: 0; + --flight-x: -7px; + --flight-rotation: -20deg; + --flight-delay: 0ms; + } + + & path:nth-child(2) { + --flight-x: 0px; + --flight-rotation: 8deg; + --flight-delay: 120ms; + } + + & path:nth-child(3) { + --flight-x: 7px; + --flight-rotation: 24deg; + --flight-delay: 240ms; + } +} + +.portfolioRuble { + stroke: var(--mantine-color-green-8); + opacity: 0; +} + +.stockArrow { + transform-origin: 21px 5px; +} + +.topSlider, +.bottomSlider { + fill: var(--mantine-color-body); +} + +@media (prefers-reduced-motion: no-preference) { + .drawStroke, + .couponLines path { + stroke-dasharray: 1; + } + + .topSlider { + --slider-offset: 3px; + --slider-delay: 0ms; + } + + .bottomSlider { + --slider-offset: -3px; + --slider-delay: 160ms; + } + + .couponLines path:nth-child(2) { + --line-delay: 140ms; + } + + .couponLines path:nth-child(3) { + --line-delay: 280ms; + } + + svg[data-icon-animating] { + .rubles path { + animation: ruble-fly 800ms ease-out var(--flight-delay) both; + } + .portfolioHandle { + animation: handle-lift 1200ms ease-in-out; + } + .portfolioLid { + animation: lid-open 1200ms ease-in-out; + } + .portfolioRuble { + animation: portfolio-ruble-reveal 1200ms ease-in-out; + } + .stockArrow { + animation: arrow-pop 300ms ease-out 400ms both; + } + .couponLines path { + animation: stroke-draw 300ms ease-out var(--line-delay, 0ms) both; + } + .drawStroke { + animation: stroke-draw 450ms ease-out; + } + :is(.topSlider, .bottomSlider) { + animation: slider-slide 650ms ease-in-out var(--slider-delay) both; + } + } +} + +@keyframes ruble-fly { + 0% { + opacity: 0; + transform: translate(0, 4px); + } + 20%, + 50% { + opacity: 1; + } + 100% { + opacity: 0; + transform: translate(var(--flight-x), -10px) rotate(var(--flight-rotation)); + } +} + +@keyframes handle-lift { + 0%, + 100% { + transform: translateY(0); + } + 20% { + transform: translateY(-3px); + } + 40%, + 75% { + transform: translateY(-3px); + } +} + +@keyframes lid-open { + 0%, + 15%, + 100% { + transform: translateY(0); + } + 40%, + 75% { + transform: translateY(-3px); + } +} + +@keyframes portfolio-ruble-reveal { + 0%, + 25%, + 100% { + opacity: 0; + transform: translateY(2px); + } + 40%, + 75% { + opacity: 1; + transform: translateY(0); + } +} + +@keyframes arrow-pop { + 0% { + opacity: 0; + transform: scale(0.7); + } + 60% { + opacity: 1; + transform: scale(1.2); + } + 100% { + opacity: 1; + transform: scale(1); + } +} + +@keyframes stroke-draw { + 0% { + stroke-dashoffset: 1; + } + 100% { + stroke-dashoffset: 0; + } +} + +@keyframes slider-slide { + 0%, + 100% { + transform: translateX(0); + } + 50% { + transform: translateX(var(--slider-offset)); + } +} diff --git a/packages/icons/src/svg/AddIcon.tsx b/packages/icons/src/svg/AddIcon.tsx index fa04cbe..975a562 100644 --- a/packages/icons/src/svg/AddIcon.tsx +++ b/packages/icons/src/svg/AddIcon.tsx @@ -4,6 +4,7 @@ import type { IconProps } from "../types"; const AddIcon: FC = (props) => { const { size = "24", ...svgProps } = props; + return (
- + +
+ {props.valueLabel} + {Boolean(props.actions) && (
{props.actions}
)} diff --git a/packages/ui/src/LoadingSkeleton/LoadingSkeleton.stories.tsx b/packages/ui/src/LoadingSkeleton/LoadingSkeleton.stories.tsx index 561c9e1..e344bd6 100644 --- a/packages/ui/src/LoadingSkeleton/LoadingSkeleton.stories.tsx +++ b/packages/ui/src/LoadingSkeleton/LoadingSkeleton.stories.tsx @@ -23,7 +23,9 @@ const meta = { + + @@ -33,5 +35,7 @@ const meta = { } satisfies Meta; export default meta; + type Story = StoryObj; + export const Initial: Story = { name: "Загрузка области" }; diff --git a/packages/ui/src/StateView/StateView.stories.tsx b/packages/ui/src/StateView/StateView.stories.tsx index 5ab38c3..fc17ced 100644 --- a/packages/ui/src/StateView/StateView.stories.tsx +++ b/packages/ui/src/StateView/StateView.stories.tsx @@ -41,16 +41,17 @@ const meta = { }, render: (arguments_) => { const { onAction, withAction, ...stateProps } = arguments_; + return ( {arguments_.error ? "Повторить локально" : "Выполнить пример"} - )) + ) : undefined } /> @@ -63,6 +64,7 @@ const meta = { export default meta; type Story = StoryObj; + export const Empty: Story = { name: "Пустое состояние" }; export const EmptyWithAction: Story = { args: { withAction: true }, diff --git a/packages/ui/src/StateView/StateView.tsx b/packages/ui/src/StateView/StateView.tsx index a41d0f6..cd059e7 100644 --- a/packages/ui/src/StateView/StateView.tsx +++ b/packages/ui/src/StateView/StateView.tsx @@ -17,7 +17,9 @@ const StateView: FC = (props) => { {title} + {text} + {action} diff --git a/packages/ui/src/theme.ts b/packages/ui/src/theme.ts index 7bdac58..d450d21 100644 --- a/packages/ui/src/theme.ts +++ b/packages/ui/src/theme.ts @@ -1,4 +1,3 @@ -import "./styles.css"; import { colorsTuple, createTheme, @@ -11,8 +10,11 @@ import { } from "@mantine/core"; import designTokens from "@wealthledger/tokens/tokens.json"; +import "./styles.css"; + const { breakpoints, color, radius, shadows, spacing, typography } = designTokens; + const mapValues = (values: Record, convert: (value: T) => U) => Object.fromEntries( Object.entries(values).map(([name, value]) => [name, convert(value)]), diff --git a/scripts/check-image-publication.cjs b/scripts/check-image-publication.cjs index 25788d5..74efa34 100644 --- a/scripts/check-image-publication.cjs +++ b/scripts/check-image-publication.cjs @@ -14,14 +14,20 @@ const { spawnSync } = require("node:child_process"); test("immutable publication resumes exact digest checks after post-push failure", () => { const directory = mkdtempSync(nodePath.join(tmpdir(), "wl-image-retry-")); + const workflow = readFileSync( nodePath.resolve(__dirname, "../.gitea/workflows/image.yml"), "utf8", ); + const block = workflow - .split(" - name: Publish immutable release tag\n run: |\n", 2)[1] + .split( + " - name: Publish immutable release tag\n run: |\n", + 2, + )[1] .split(" - name:", 1)[0] .replaceAll(/^ {10}/gm, ""); + const double = String.raw`#!${process.execPath} const fs = require('node:fs'); const args = process.argv.slice(2).join(' '); @@ -39,6 +45,7 @@ if (args.startsWith('manifest 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"]) { // eslint-disable-next-line security/detect-non-literal-fs-filename -- Path is built from this check’s private mkdtemp directory and fixed filenames. @@ -46,6 +53,7 @@ if (args.startsWith('manifest inspect')) { // eslint-disable-next-line security/detect-non-literal-fs-filename -- Path is built from this check’s private mkdtemp directory and fixed filenames. chmodSync(nodePath.join(directory, name), EXECUTABLE_MODE); } + const run = (extra = {}) => spawnSync("/bin/sh", ["-ec", block], { cwd: directory, @@ -59,6 +67,7 @@ if (args.startsWith('manifest inspect')) { ...extra, }, }); + assert.notEqual(run().status, 0); const retry = run(); assert.equal(retry.status, 0, retry.stdout + retry.stderr); diff --git a/scripts/check-openapi.mjs b/scripts/check-openapi.mjs index a440dfa..d9a9ac5 100644 --- a/scripts/check-openapi.mjs +++ b/scripts/check-openapi.mjs @@ -6,6 +6,7 @@ import nodePath from "node:path"; const temporaryDirectory = await mkdtemp( nodePath.join(tmpdir(), "wealth-ledger-openapi-"), ); + const generatedPath = nodePath.join(temporaryDirectory, "schema.d.ts"); const committedPath = nodePath.resolve("src/shared/api/generated/schema.d.ts"); const cliPath = nodePath.resolve("node_modules/openapi-typescript/bin/cli.js"); @@ -24,6 +25,7 @@ try { // eslint-disable-next-line security/detect-non-literal-fs-filename -- Path is built from this check’s private mkdtemp directory and fixed filenames. readFile(generatedPath, "utf8"), ]); + if (committed !== current) { console.error( "Generated OpenAPI types are stale. Run `npm run openapi:generate` and commit the result.", diff --git a/scripts/check-release.cjs b/scripts/check-release.cjs index f5ed10e..f8814a0 100644 --- a/scripts/check-release.cjs +++ b/scripts/check-release.cjs @@ -2,14 +2,16 @@ const assert = require("node:assert/strict"); const { execFileSync } = require("node:child_process"); const { version } = require("../package.json"); -// eslint-disable-next-line sonarjs/no-os-command-from-path -- Repository checks use the developer/CI Git installation; arguments never invoke a shell. -const git = (...arguments_) => execFileSync("git", arguments_, { encoding: "utf8" }).trim(); + +const git = (...arguments_) => + execFileSync("git", arguments_, { encoding: "utf8" }).trim(); // eslint-disable-line sonarjs/no-os-command-from-path -- Repository checks use the developer/CI Git installation; arguments never invoke a shell. assert.equal( git("status", "--porcelain"), "", "Commit all changes before preparing a release", ); + const tag_ = git( "tag", "--merged", @@ -20,6 +22,7 @@ const tag_ = git( ) .split("\n") .find(tag => /^v\d+\.\d+\.\d+$/.test(tag)); + assert.equal( version, tag_?.slice(1) ?? "0.0.0", diff --git a/scripts/test-eslint.mjs b/scripts/test-eslint.mjs index 36ca2e3..3d383d1 100644 --- a/scripts/test-eslint.mjs +++ b/scripts/test-eslint.mjs @@ -16,11 +16,13 @@ import storybook from "eslint-plugin-storybook"; import testingLibrary from "eslint-plugin-testing-library"; import unicorn from "eslint-plugin-unicorn"; import assert from "node:assert/strict"; +import { globSync } from "node:fs"; import { test } from "node:test"; import tseslint from "typescript-eslint"; test("ESLint enforces the frontend profile and excludes generated artifacts", async () => { const eslint = new ESLint(); + for (const [filePath, code, rule] of [ [ "src/shared/api/problem-details.ts", @@ -110,6 +112,7 @@ test("ESLint enforces the frontend profile and excludes generated artifacts", as rule, ); } + for (const file of [ "src/shared/api/generated/schema.d.ts", "packages/ui/dist/index.js", @@ -117,19 +120,22 @@ test("ESLint enforces the frontend profile and excludes generated artifacts", as "coverage/index.js", ]) assert.equal(await eslint.isPathIgnored(file), true, file); + const story = await eslint.calculateConfigForFile( "src/shared/ui/Button.stories.tsx", ); + assert.equal(story.rules["import-x/no-default-export"][0], 0); assert.ok(story.rules["storybook/default-exports"][0] > 0); assert.equal(story.rules["react-refresh/only-export-components"], undefined); }); -test("all recommended plugin rules remain enabled in their intended scopes", async () => { +test("recommended plugin rules retain the explicit null-contract exception", async () => { const eslint = new ESLint(); const source = "src/shared/api/problem-details.ts"; const component = "packages/ui/src/EntryCard/EntryCard.tsx"; const unit = "packages/ui/src/EntryCard/EntryCard.test.tsx"; + for (const [preset, filePath] of [ [tseslint.configs.recommendedTypeChecked, source], [[importX.flatConfigs.recommended, importX.flatConfigs.typescript], source], @@ -147,15 +153,34 @@ test("all recommended plugin rules remain enabled in their intended scopes", asy [vitest.configs.recommended, unit], [testingLibrary.configs["flat/react"], unit], [jestDom.configs["flat/recommended"], unit], - ...storybook.configs["flat/recommended"].filter(config => config.rules).map(config => [config, config.name.endsWith("main-rules") ? ".storybook/main.ts" : "src/shared/ui/Button.stories.tsx"]), + ...storybook.configs["flat/recommended"] + .filter(config => config.rules) + .map(config => [ + config, + config.name.endsWith("main-rules") + ? ".storybook/main.ts" + : "src/shared/ui/Button.stories.tsx", + ]), ]) { const configs = [preset].flat(); - const expected = Object.assign({}, ...configs.map(config => config.rules)); + + const expected = Object.assign( + {}, + ...configs.map(config => config.rules), + ); + const config = await eslint.calculateConfigForFile(filePath); const actual = new Map(Object.entries(config.rules)); + for (const [rule, setting] of Object.entries(expected)) { const severity = Array.isArray(setting) ? setting[0] : setting; if (severity === "off" || severity === 0 || !rule.includes("/")) continue; + + if (rule === "unicorn/no-null") { + assert.equal(actual.get(rule)?.[0], 0); + continue; + } + assert.ok(actual.get(rule)?.[0] > 0, `${filePath}: ${rule}`); } } @@ -164,10 +189,12 @@ test("all recommended plugin rules remain enabled in their intended scopes", asy test("ESLint formatting is idempotent and preserves TSX generic syntax", async () => { const eslint = new ESLint({ fix: true }); const filePath = "packages/ui/src/EntryCard/EntryCard.tsx"; + const [fixed] = await eslint.lintText( "//identity\nconst identity = (value: T): T => value;\nexport {identity};", { filePath }, ); + assert.equal(fixed.fatalErrorCount, 0); assert.equal(fixed.errorCount, 0); assert.ok(fixed.output); @@ -178,10 +205,12 @@ test("ESLint formatting is idempotent and preserves TSX generic syntax", async ( test("ESLint formatting preserves spaces around JSX text and interpolations", async () => { const eslint = new ESLint({ fix: true }); + const [fixed] = await eslint.lintText( "const Example = () => {\nconst value = 'value';\nreturn Amount: {value} / {value};\n};\nexport { Example };", { filePath: "packages/ui/src/EntryCard/EntryCard.tsx" }, ); + assert.equal(fixed.errorCount, 0); assert.ok(fixed.output?.includes("Amount: {value} / {value}")); }); @@ -190,11 +219,25 @@ test("ESLint formatting preserves spaces around JSX text and interpolations", as test("machine codes require enum members without banning ordinary text or Prisma selects", async () => { const eslint = new ESLint(); const filePath = "src/shared/api/problem-details.ts"; - for (const code of ["export function check(code: string) { return code === \"one-off-code\"; }", "export const result = `MOEX_UNAVAILABLE`;", "export const result = { code: \"one-off-code\" };", "export const result = { \"errorCode\": \"one-off-code\" };", "export const result = { code: `dynamic-${Date.now()}` };", "export const result = \"MOEX_UNAVAILABLE\";", "export const result = [\"INSTRUMENT_ID_TYPE_FIGI\"];", "export const result = { OPERATION_TYPE_COUPON: \"income\" };"]) { + + for (const code of [ + "export function check(code: string) { return code === \"one-off-code\"; }", + "export const result = `MOEX_UNAVAILABLE`;", + "export const result = { code: \"one-off-code\" };", + "export const result = { \"errorCode\": \"one-off-code\" };", + "export const result = { code: `dynamic-${Date.now()}` };", + "export const result = \"MOEX_UNAVAILABLE\";", + "export const result = [\"INSTRUMENT_ID_TYPE_FIGI\"];", + "export const result = { OPERATION_TYPE_COUPON: \"income\" };", + ]) { const [result] = await eslint.lintText(code, { filePath }); assert.equal(result.fatalErrorCount, 0, code); - assert.ok(result.messages.some(({ ruleId }) => ruleId === "no-restricted-syntax"), code); + assert.ok( + result.messages.some(({ ruleId }) => ruleId === "no-restricted-syntax"), + code, + ); } + for (const code of [ "enum Code { Unavailable = \"MOEX_UNAVAILABLE\" } export const result = { code: Code.Unavailable };", "export const select = { code: true, errorCode: true };", @@ -202,10 +245,96 @@ test("machine codes require enum members without banning ordinary text or Prisma ]) { const [result] = await eslint.lintText(code, { filePath }); assert.equal(result.fatalErrorCount, 0, code); - assert.ok(result.messages.every(({ ruleId }) => ruleId !== "no-restricted-syntax"), code); + assert.ok( + result.messages.every(({ ruleId }) => ruleId !== "no-restricted-syntax"), + code, + ); } - const [fixture] = await eslint.lintText("export const result = { code: \"MOEX_UNAVAILABLE\" };", { filePath: "src/shared/api/client.test.ts" }); - assert.ok(fixture.messages.every(({ ruleId }) => ruleId !== "no-restricted-syntax")); - const [comparison] = await eslint.lintText("enum Code { Ready = \"ready\" } export function check(code: Code) { return code === \"ready\"; }", { filePath }); - assert.ok(comparison.messages.some(({ ruleId }) => ruleId === "@typescript-eslint/no-unsafe-enum-comparison")); + + const [fixture] = await eslint.lintText( + "export const result = { code: \"MOEX_UNAVAILABLE\" };", + { filePath: "src/shared/api/client.test.ts" }, + ); + + assert.ok( + fixture.messages.every(({ ruleId }) => ruleId !== "no-restricted-syntax"), + ); + + const [comparison] = await eslint.lintText( + "enum Code { Ready = \"ready\" } export function check(code: Code) { return code === \"ready\"; }", + { filePath }, + ); + + assert.ok( + comparison.messages.some( + ({ ruleId }) => ruleId === "@typescript-eslint/no-unsafe-enum-comparison", + ), + ); +}); + +test("readability enforces syntax without banning VM and schema patterns", async () => { + const eslint = new ESLint(); + const component = "src/entities/bank-card/ui/BankCardForm/BankCardForm.tsx"; + const model = "src/entities/income/api/useIncome.ts"; + + const invalid = [ + [component, "const Example = () => ;", "frontend/readability"], + [component, "const Example = () => + @@ -39,6 +41,7 @@ const renderTitle = (path: string) => + @@ -59,10 +62,13 @@ beforeEach(() => { describe("document titles", () => { it("updates a loading account name and follows account scope and history", async () => { - const { promise: accountsReady, resolve: resolveAccounts } = Promise.withResolvers(); + const { promise: accountsReady, resolve: resolveAccounts } + = Promise.withResolvers(); + server.use( http.get("*/api/v1/brokerage-accounts", async () => { await accountsReady; + return HttpResponse.json(resource([{ id: "a", name: "ИИС" }])); }), ); @@ -102,6 +108,7 @@ describe("document titles", () => { server.use( http.get("*/api/v1/stocks/by-ticker/:ticker", () => { isRequested = true; + return HttpResponse.json({ code: "NOT_FOUND" }, { status: 404 }); }), ); diff --git a/src/app/routes/DocumentTitle/DocumentTitle.tsx b/src/app/routes/DocumentTitle/DocumentTitle.tsx index cb616e5..2c3caa4 100644 --- a/src/app/routes/DocumentTitle/DocumentTitle.tsx +++ b/src/app/routes/DocumentTitle/DocumentTitle.tsx @@ -24,29 +24,36 @@ type AccountDocumentTitleProps = { const AccountDocumentTitle: FC = (props) => { const { t } = useTranslation(); const { data } = useBrokerageAccounts(); + const accountName = props.accountId === "all" ? t("accounts.all") : (data?.find(account => account.id === props.accountId)?.name ?? t("account.title")); + let section = t("portfolio.title"); + switch (props.section ?? "") { case "income": { section = t("income.title"); break; } + case "operations": { section = t("ledger.title"); break; } + case "events": { section = t("events.title"); break; } + default: { break; } } + return ; }; @@ -55,18 +62,21 @@ type InstrumentDocumentTitleProps = { identifier: string }; const BondDocumentTitle: FC = (props) => { const { t } = useTranslation(); const { data } = useBond(props.identifier); + return ; }; const StockDocumentTitle: FC = (props) => { const { t } = useTranslation(); const { data } = useStock(props.identifier); + return ; }; const CardDocumentTitle: FC = (props) => { const { t } = useTranslation(); const { data } = useBankCard(props.identifier); + return ; }; @@ -94,7 +104,10 @@ const ProtectedDocumentTitle: FC = () => { if (cards) return ; if (bonds) return ; if (stocks) return ; - return settings ? : ; + + return settings + ? + : ; }; export { ProtectedDocumentTitle }; diff --git a/src/app/routes/ProtectedLayout.tsx b/src/app/routes/ProtectedLayout.tsx index 821b496..f03ff3b 100644 --- a/src/app/routes/ProtectedLayout.tsx +++ b/src/app/routes/ProtectedLayout.tsx @@ -8,6 +8,7 @@ const ProtectedLayout: FC = () => { return ( <> + } /> ); diff --git a/src/app/routes/RouteErrorBoundary/RouteErrorBoundary.test.tsx b/src/app/routes/RouteErrorBoundary/RouteErrorBoundary.test.tsx index 134afb0..c1c7cd4 100644 --- a/src/app/routes/RouteErrorBoundary/RouteErrorBoundary.test.tsx +++ b/src/app/routes/RouteErrorBoundary/RouteErrorBoundary.test.tsx @@ -8,9 +8,10 @@ import { RouteErrorBoundary } from "./RouteErrorBoundary"; const session = { isAuthenticated: false }; vi.mock("@/features/auth", () => ({ - useAuth: () => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { user: session.isAuthenticated ? {} : null } - /* eslint-enable unicorn/no-null */)), + + useAuth: () => + ({ user: session.isAuthenticated ? {} : null }), + })); const ThrowingRoute: FC = () => { @@ -24,9 +25,7 @@ const HealthyRoute: FC = () => { ? ( "healthy route" ) - : ( - - )} + : }
); }; @@ -39,6 +38,7 @@ const RouteHarness: FC = () => { + @@ -62,10 +62,13 @@ describe("RouteErrorBoundary", () => { async (path) => { session.isAuthenticated = path === "/accounts"; let isFailing = true; + const RecoverableRoute: FC = () => { if (isFailing) throw new Error("temporary failure"); + return
recovered route
; }; + render( @@ -116,10 +119,12 @@ describe("RouteErrorBoundary", () => { expect(reload).toHaveAttribute("href", "/login"); // Cancel browser navigation in JSDOM only after proving React Router did not intercept it. let isIntercepted = true; + const preventNavigation = (event: MouseEvent) => { isIntercepted = event.defaultPrevented; event.preventDefault(); }; + document.addEventListener("click", preventNavigation, { once: true }); fireEvent.click(reload); expect(isIntercepted).toBe(false); diff --git a/src/app/routes/RouteErrorBoundary/RouteErrorBoundary.tsx b/src/app/routes/RouteErrorBoundary/RouteErrorBoundary.tsx index 809c239..bb63f50 100644 --- a/src/app/routes/RouteErrorBoundary/RouteErrorBoundary.tsx +++ b/src/app/routes/RouteErrorBoundary/RouteErrorBoundary.tsx @@ -33,7 +33,11 @@ class Boundary extends Component { } render() { - return this.state.hasError ? : this.props.children; + return this.state.hasError + ? + : ( + this.props.children + ); } } @@ -46,10 +50,13 @@ const RouteErrorFallback: FC = (props) => { return ( {t("routeError.title")} + {t("routeError.text")} + + diff --git a/src/app/routes/RouteFallback.tsx b/src/app/routes/RouteFallback.tsx index d6f4e1d..a2b71cf 100644 --- a/src/app/routes/RouteFallback.tsx +++ b/src/app/routes/RouteFallback.tsx @@ -7,7 +7,10 @@ import { useTranslation } from "react-i18next"; import { RouteTransition } from "./RouteTransition"; type LazyPageProps = PropsWithChildren<{ variant: RouteSkeletonVariant }>; -type RouteSkeletonVariant = "auth" | "content" | "shell"; + +type RouteSkeletonVariant = "auth" + | "content" + | "shell"; const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => { const { variant } = props; @@ -22,8 +25,11 @@ const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => { role="status" > + + + @@ -39,12 +45,16 @@ const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => { > + + + + @@ -54,6 +64,7 @@ const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => { return ( + ); @@ -61,15 +72,14 @@ const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => { const LazyPage: FC = (props) => { const { children, variant } = props; + return ( }> {variant === "shell" ? ( children ) - : ( - {children} - )} + : {children}} ); }; diff --git a/src/app/routes/RouteGuards.tsx b/src/app/routes/RouteGuards.tsx index 3a3cf4f..2d57663 100644 --- a/src/app/routes/RouteGuards.tsx +++ b/src/app/routes/RouteGuards.tsx @@ -11,10 +11,9 @@ const Protected: FC = (props) => { const { ready, user } = useAuth(); const location = useLocation(); if (!ready) return ; + return user - ? ( - <>{children} - ) + ? <>{children} : ( = (props) => { const location = useLocation(); if (!ready) return ; - const requested = (location.state as null | { returnTo?: string })?.returnTo; + + const requested = (location.state as null + | { returnTo?: string })?.returnTo; + const returnTo = typeof requested === "string" && requested.startsWith("/") && !requested.startsWith("//") ? requested : "/accounts"; + return user ? : <>{children}; }; diff --git a/src/app/routes/RouteTransition.tsx b/src/app/routes/RouteTransition.tsx index 84895a9..a7cfd8a 100644 --- a/src/app/routes/RouteTransition.tsx +++ b/src/app/routes/RouteTransition.tsx @@ -11,16 +11,18 @@ const RouteTransition: FC = (props) => { const { pathname } = useLocation(); const reduceMotion = useReducedMotion(); + const transition = { + duration: reduceMotion ? 0 : TRANSITION_DURATION_SECONDS, + ease: "easeOut" as const, + }; + return ( {children} diff --git a/src/app/ui/AppBreadcrumbs/AccountBreadcrumbs.tsx b/src/app/ui/AppBreadcrumbs/AccountBreadcrumbs.tsx index 8a7952d..5879342 100644 --- a/src/app/ui/AppBreadcrumbs/AccountBreadcrumbs.tsx +++ b/src/app/ui/AppBreadcrumbs/AccountBreadcrumbs.tsx @@ -8,19 +8,24 @@ import { BreadcrumbTrail } from "./BreadcrumbTrail"; type AccountBreadcrumbsProps = { accountId: string; - section?: "events" | "income" | "operations"; + section?: "events" + | "income" + | "operations"; }; const AccountBreadcrumbs: FC = (props) => { const { accountId, section } = props; const { data: accounts } = useBrokerageAccounts(); const { t } = useTranslation(); + const accountName = accountId === "all" ? t("accounts.all") : (accounts?.find(account => account.id === accountId)?.name ?? t("breadcrumbs.accountFallback")); + const accountPath = `/accounts/${accountId}`; + const items = [ { label: t("breadcrumbs.accounts"), to: "/accounts" }, section ? { label: accountName, to: accountPath } : { label: accountName }, diff --git a/src/app/ui/AppBreadcrumbs/AccountScopeSwitch/AccountScopeSwitch.tsx b/src/app/ui/AppBreadcrumbs/AccountScopeSwitch/AccountScopeSwitch.tsx new file mode 100644 index 0000000..1ac4153 --- /dev/null +++ b/src/app/ui/AppBreadcrumbs/AccountScopeSwitch/AccountScopeSwitch.tsx @@ -0,0 +1,25 @@ +import type { FC } from "react"; + +import { Select } from "@mantine/core"; + +import { useAccountScopeSwitchVm } from "./AccountScopeSwitch.vm"; + +type AccountScopeSwitchProps = { accountId: string; section?: string }; + +const AccountScopeSwitch: FC = (props) => { + const { accountId, data, onChange, t } = useAccountScopeSwitchVm(props); + + return ( + { - if (!value || value === accountId) return; - const filters = new URLSearchParams(search); - filters.delete("cursor"); - void navigate({ - pathname: ["/accounts", encodeURIComponent(value), section].filter(Boolean).join("/"), - search: filters.toString(), - }); - }} - value={accountId} - w="100%" - /> - ); -}; -export { AccountScopeSwitch }; + const onChange: (value: null | string) => void = (value) => { + if (!value || value === accountId) return; + const filters = new URLSearchParams(search); + filters.delete("cursor"); + void navigate({ + pathname: ["/accounts", encodeURIComponent(value), section] + .filter(Boolean) + .join("/"), + search: filters.toString(), + }); + }; + + return { accountId, data, onChange, t }; +} + +export { useAccountScopeSwitchVm }; diff --git a/src/app/ui/AppBreadcrumbs/AppBreadcrumbs.test.tsx b/src/app/ui/AppBreadcrumbs/AppBreadcrumbs.test.tsx index 0ad4d08..cb82e76 100644 --- a/src/app/ui/AppBreadcrumbs/AppBreadcrumbs.test.tsx +++ b/src/app/ui/AppBreadcrumbs/AppBreadcrumbs.test.tsx @@ -16,6 +16,7 @@ function renderBreadcrumbs( accounts?: { id: string; name: string }[], ) { useBrokerageAccounts.mockReturnValue({ data: accounts }); + return render( @@ -70,6 +71,7 @@ describe("AppBreadcrumbs", () => { "page", ); expect(screen.getByRole("navigation")).toHaveAttribute("data-depth", "3"); + for (const separator of screen.getAllByText("→")) { expect(separator).toHaveAttribute("aria-hidden", "true"); } diff --git a/src/app/ui/AppBreadcrumbs/AppBreadcrumbs.tsx b/src/app/ui/AppBreadcrumbs/AppBreadcrumbs.tsx index 9f7b40b..5f178af 100644 --- a/src/app/ui/AppBreadcrumbs/AppBreadcrumbs.tsx +++ b/src/app/ui/AppBreadcrumbs/AppBreadcrumbs.tsx @@ -5,7 +5,7 @@ import { useTranslation } from "react-i18next"; import { useMatch } from "react-router"; import { AccountBreadcrumbs } from "./AccountBreadcrumbs"; -import { AccountScopeSwitch } from "./AccountScopeSwitch"; +import { AccountScopeSwitch } from "./AccountScopeSwitch/AccountScopeSwitch"; import { BondBreadcrumbs } from "./BondBreadcrumbs"; import { BreadcrumbTrail } from "./BreadcrumbTrail"; import { CardBreadcrumbs } from "./CardBreadcrumbs"; @@ -13,10 +13,12 @@ import { StockBreadcrumbs } from "./StockBreadcrumbs"; const AppBreadcrumbs: FC = () => { const { t } = useTranslation(); + const operations = useMatch({ end: true, path: "/accounts/:accountId/operations", }); + const events = useMatch({ end: true, path: "/accounts/:accountId/events" }); const income = useMatch({ end: true, path: "/accounts/:accountId/income" }); const account = useMatch({ end: true, path: "/accounts/:accountId" }); @@ -37,6 +39,7 @@ const AppBreadcrumbs: FC = () => { accountId={operations.params.accountId ?? ""} section="operations" /> + { accountId={events.params.accountId ?? ""} section="events" /> + { accountId={income.params.accountId ?? ""} section="income" /> + { return ( + ); @@ -80,7 +86,10 @@ const AppBreadcrumbs: FC = () => { if (cards) return ; if (accounts) return ; - return settings ? : undefined; + + return settings + ? + : undefined; }; export { AppBreadcrumbs }; diff --git a/src/app/ui/AppBreadcrumbs/BondBreadcrumbs.tsx b/src/app/ui/AppBreadcrumbs/BondBreadcrumbs.tsx index 6fe89f6..08cb1d2 100644 --- a/src/app/ui/AppBreadcrumbs/BondBreadcrumbs.tsx +++ b/src/app/ui/AppBreadcrumbs/BondBreadcrumbs.tsx @@ -7,9 +7,11 @@ import { useBond } from "@/entities/bond"; import { BreadcrumbTrail } from "./BreadcrumbTrail"; type BondBreadcrumbsProps = { identifier: string }; + const BondBreadcrumbs: FC = (props) => { const { data } = useBond(props.identifier); const { t } = useTranslation(); + return ( = (props) => { const { items } = props; const { t } = useTranslation(); + return ( = (props) => { const { data } = useBankCard(props.identifier); const { t } = useTranslation(); + return ( = (props) => { const { data } = useStock(props.identifier); const { t } = useTranslation(); + return ( = (props) => { const { contentAboveOutlet } = props; const { t } = useTranslation(); const { pathname } = useLocation(); + const items = [ { - icon: ( - <> - - - - - - ), + icon: , iconClassName: classes.portfolioIcon, label: t("navigation.accounts"), to: "/accounts", }, { - icon: ( - <> - - - - - - - - ), + icon: , iconClassName: classes.cardsIcon, label: t("navigation.cards"), to: "/cards", }, { - icon: ( - <> - - - - - ), + icon: , iconClassName: classes.stocksIcon, label: t("navigation.stocks"), to: "/stocks", }, { - icon: ( - <> - - - - - - - - ), + icon: , iconClassName: classes.bondsIcon, label: t("navigation.bonds"), to: "/bonds", }, { - icon: ( - <> - - - - - ), + icon: , iconClassName: classes.settingsIcon, label: t("navigation.settings"), to: "/settings", @@ -105,6 +64,7 @@ const AppShell: FC = (props) => { {t("appName")} + {items.map(item => ( = (props) => { - + {item.icon} )} to={item.to} /> ))} +
{contentAboveOutlet} +
+ ); diff --git a/src/entities/bank-card/api/banking.test.tsx b/src/entities/bank-card/api/banking.test.tsx index f13e8a4..33e87a6 100644 --- a/src/entities/bank-card/api/banking.test.tsx +++ b/src/entities/bank-card/api/banking.test.tsx @@ -19,8 +19,8 @@ import { useBankSummary, } from "./queries"; -const card: BankCard = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { +const card: BankCard + = { archivedAt: null, balance: { currency: "RUB", value: "100" }, bankName: null, @@ -31,8 +31,8 @@ const card: BankCard = (/* eslint-disable unicorn/no-null -- Fixture preserves t openingDate: "2026-09-01", paymentSystem: null, version: 1, - } -/* eslint-enable unicorn/no-null */); + }; + const transfer: CreateBankOperation = { amount: { currency: "RUB", value: "90071992547409.93" }, cardId: "a", @@ -55,6 +55,7 @@ function readHandlers(counts: Map, categoryName = "Food") { http.get("*/api/v1/bank-cards", ({ request }) => { const key = new URL(request.url).pathname + new URL(request.url).search; counts.set(key, (counts.get(key) ?? 0) + 1); + return HttpResponse.json([card]); }), http.get("*/api/v1/bank-cards/*", ({ request }) => { @@ -84,7 +85,10 @@ function readHandlers(counts: Map, categoryName = "Food") { page: 1, total: 0, }); - return url.pathname.includes("/operations/") ? HttpResponse.json({ ...transfer, version: 1 }) : HttpResponse.json({ ...card, id: url.pathname.split("/").at(-1) }); + + return url.pathname.includes("/operations/") + ? HttpResponse.json({ ...transfer, version: 1 }) + : HttpResponse.json({ ...card, id: url.pathname.split("/").at(-1) }); }), ]; } @@ -94,15 +98,18 @@ function useReadModels() { const a = useBankCard("a"); const b = useBankCard("b"); const categories = useBankCategories(); + const history = useBankOperations("a", { limit: 20, month: "2026-09", page: 2, }); + const expenses = useBankExpenses("a", { page: 1 }); const september = useBankSummary("2026-09"); const august = useBankSummary("2026-08", "b"); const original = useBankOperation("original"); + return { mutations: useBankMutations(), reads: [ @@ -134,6 +141,7 @@ describe("banking API", () => { expect(url.searchParams.get("month")).toBe("2026-09"); if (isFail && page === 2) return HttpResponse.json({ code: "FAILED" }, { status: 500 }); + return HttpResponse.json({ hasNext: page === 1, items: [{ ...transfer, id: String(page) }], @@ -142,10 +150,12 @@ describe("banking API", () => { }); }), ); + const { result } = renderHook( () => useBankOperations("a", { limit: "all", month: "2026-09", page: 1 }), { wrapper: createQueryWrapper().wrapper }, ); + await waitFor(() => expect(result.current.isSuccess).toBe(true)); expect(pages).toEqual([1, 2]); expect(result.current.data?.items.map(item => item.id)).toEqual([ @@ -153,10 +163,12 @@ describe("banking API", () => { "2", ]); isFail = true; + const { result: failedResult } = renderHook( () => useBankOperations("a", { limit: "all", month: "2026-09", page: 1 }), { wrapper: createQueryWrapper().wrapper }, ); + await waitFor(() => expect(failedResult.current.isError).toBe(true)); expect(failedResult.current.data).toBeUndefined(); }); @@ -164,15 +176,15 @@ describe("banking API", () => { it("uses session-aware banking endpoints and explicit month/page without T-Bank", async () => { const counts = new Map(); server.use(...readHandlers(counts)); + const { result } = renderHook(useReadModels, { wrapper: createQueryWrapper().wrapper, }); + await waitFor(() => expect(result.current.reads.every(read => read.isSuccess)).toBe(true), ); - expect(counts.keys()).toContain( - "/api/v1/bank-cards?includeArchived=true", - ); + expect(counts.keys()).toContain("/api/v1/bank-cards?includeArchived=true"); expect(counts.keys()).toContain( "/api/v1/bank-cards/a/operations?limit=20&month=2026-09&page=2", ); @@ -184,10 +196,13 @@ describe("banking API", () => { it("replays the exact UUID and large Money string once across shared auth refresh", async () => { let token = "expired"; + const refresh = vi.fn(() => { token = "renewed"; + return Promise.resolve(true); }); + configureAuthClient({ accessToken: () => token, clear: vi.fn(), refresh }); const bodies: unknown[] = []; const headers: (null | string)[] = []; @@ -195,14 +210,17 @@ describe("banking API", () => { http.post("*/api/v1/bank-cards/operations", async ({ request }) => { bodies.push(await request.json()); headers.push(request.headers.get("Authorization")); + return bodies.length === 1 ? HttpResponse.json({ code: "UNAUTHORIZED" }, { status: 401 }) : HttpResponse.json({ ...transfer, version: 1 }); }), ); + const { result } = renderHook(useBankMutations, { wrapper: createQueryWrapper().wrapper, }); + await act(() => result.current.createOperation.mutateAsync(transfer)); expect(bodies).toEqual([transfer, transfer]); expect(headers).toEqual(["Bearer expired", "Bearer renewed"]); @@ -214,14 +232,17 @@ describe("banking API", () => { server.use( http.post("*/api/v1/bank-cards/operations", async ({ request }) => { bodies.push(await request.json()); + return bodies.length === 1 ? HttpResponse.error() : HttpResponse.json({ ...transfer, version: 1 }); }), ); + const { result } = renderHook(useBankMutations, { wrapper: createQueryWrapper().wrapper, }); + await act(async () => { await expect( result.current.createOperation.mutateAsync(transfer), @@ -239,13 +260,16 @@ describe("banking API", () => { server.use( http.post("*/api/v1/bank-cards/operations", async () => { await pending; + return HttpResponse.json({ code: "INTERNAL_ERROR" }, { status: 500 }); }), ); + const { result } = renderHook( () => ({ mutations: useBankMutations(), query: useBankCard("a") }), { wrapper: createQueryWrapper().wrapper }, ); + await waitFor(() => expect(result.current.query.isSuccess).toBe(true)); let saving: Promise; act(() => { @@ -310,10 +334,12 @@ describe("banking API", () => { HttpResponse.json({ code }, { status: 409 }), ), ); + const { result } = renderHook( () => ({ card: useBankCard("a"), mutations: useBankMutations() }), { wrapper: createQueryWrapper().wrapper }, ); + await waitFor(() => expect(result.current.card.data?.version).toBe(1)); await act(async () => { await expect( @@ -337,6 +363,7 @@ describe("banking API", () => { const body = await request.json(); requests.push(body); name = "Groceries"; + return HttpResponse.json({ id: "food", isDefault: true, @@ -348,14 +375,17 @@ describe("banking API", () => { "*/api/v1/bank-cards/operations/original", async ({ request }) => { requests.push(await request.json()); + return HttpResponse.json({ ...transfer, version: 2 }); }, ), http.delete("*/api/v1/bank-cards/operations/original", ({ request }) => { requests.push(new URL(request.url).searchParams.get("version")); + return new HttpResponse(null, { status: 204 }); }), ); + const { result } = renderHook( () => ({ categories: useBankCategories(), @@ -363,6 +393,7 @@ describe("banking API", () => { }), { wrapper: createQueryWrapper().wrapper }, ); + await waitFor(() => expect(result.current.categories.data?.[0].name).toBe("Food"), ); @@ -406,9 +437,11 @@ describe("banking API", () => { ), ); const { queryClient, wrapper } = createQueryWrapper(); + const { rerender, result } = renderHook(() => useBankCard("a"), { wrapper, }); + await waitFor(() => expect(result.current.data?.balance.value).toBe("100")); await apiClient.PUT("/api/v1/tbank-connection", { body: { token: "synthetic" }, diff --git a/src/entities/bank-card/api/mutations.ts b/src/entities/bank-card/api/mutations.ts index cfe0b0d..ea486b1 100644 --- a/src/entities/bank-card/api/mutations.ts +++ b/src/entities/bank-card/api/mutations.ts @@ -1,6 +1,11 @@ import { useMutation, useQueryClient } from "@tanstack/react-query"; -import { apiClient, ApiErrorCode, apiErrorCode, isApiErrorCode } from "@/shared/api"; +import { + apiClient, + ApiErrorCode, + apiErrorCode, + isApiErrorCode, +} from "@/shared/api"; import type { CreateBankCard, @@ -17,21 +22,27 @@ async function mutationData( const { data, error } = await request; // eslint-disable-next-line @typescript-eslint/only-throw-error -- Preserve generated ProblemDetails for apiErrorCode and field-error consumers. if (error) throw error; + return data; } function useBankMutations() { const queryClient = useQueryClient(); + const invalidate = () => queryClient.invalidateQueries({ predicate: ({ queryKey }) => { const [method, path] = queryKey; - return method === "get" + + return ( + method === "get" && typeof path === "string" && (path === "/api/v1/bank-cards" - || path.startsWith("/api/v1/bank-cards/")); + || path.startsWith("/api/v1/bank-cards/")) + ); }, }); + const options = { onError: (error: unknown) => { const errorCode = apiErrorCode(error); @@ -49,11 +60,13 @@ function useBankMutations() { onSuccess: invalidate, retry: false, } as const; + const cardCreation = useMutation({ ...options, mutationFn: (body: CreateBankCard) => mutationData(apiClient.POST("/api/v1/bank-cards", { body })), }); + const updateCard = useMutation({ ...options, mutationFn: ({ body, id }: { body: UpdateBankCard; id: string }) => @@ -64,11 +77,13 @@ function useBankMutations() { }), ), }); + const operationCreation = useMutation({ ...options, mutationFn: (body: CreateBankOperation) => mutationData(apiClient.POST("/api/v1/bank-cards/operations", { body })), }); + const updateOperation = useMutation({ ...options, mutationFn: ({ body, id }: { body: UpdateBankOperation; id: string }) => @@ -79,6 +94,7 @@ function useBankMutations() { }), ), }); + const operationDeletion = useMutation({ ...options, mutationFn: ({ id, version }: { id: string; version: number }) => @@ -88,11 +104,13 @@ function useBankMutations() { }), ), }); + const categoryCreation = useMutation({ ...options, mutationFn: (body: CreateExpenseCategory) => mutationData(apiClient.POST("/api/v1/bank-cards/categories", { body })), }); + const updateCategory = useMutation({ ...options, mutationFn: ({ body, id }: { body: UpdateExpenseCategory; id: string }) => @@ -103,6 +121,7 @@ function useBankMutations() { }), ), }); + return { createCard: cardCreation, createCategory: categoryCreation, diff --git a/src/entities/bank-card/api/queries.ts b/src/entities/bank-card/api/queries.ts index 2a6a427..e97e28a 100644 --- a/src/entities/bank-card/api/queries.ts +++ b/src/entities/bank-card/api/queries.ts @@ -9,24 +9,34 @@ import { moneyCents } from "../model/form-validation"; type BankCard = paths["/api/v1/bank-cards/{id}"]["get"]["responses"][200]["content"]["application/json"]; + type BankOperation = paths["/api/v1/bank-cards/operations/{id}"]["get"]["responses"][200]["content"]["application/json"]; + type BankOperations = paths["/api/v1/bank-cards/{id}/operations"]["get"]["responses"][200]["content"]["application/json"]; + type BankSummary = paths["/api/v1/bank-cards/summary"]["get"]["responses"][200]["content"]["application/json"]; + type CreateBankCard = paths["/api/v1/bank-cards"]["post"]["requestBody"]["content"]["application/json"]; + type CreateBankOperation = paths["/api/v1/bank-cards/operations"]["post"]["requestBody"]["content"]["application/json"]; + type CreateExpenseCategory = paths["/api/v1/bank-cards/categories"]["post"]["requestBody"]["content"]["application/json"]; + type ExpenseCategory = paths["/api/v1/bank-cards/categories"]["get"]["responses"][200]["content"]["application/json"][number]; + type UpdateBankCard = paths["/api/v1/bank-cards/{id}"]["patch"]["requestBody"]["content"]["application/json"]; + type UpdateBankOperation = paths["/api/v1/bank-cards/operations/{id}"]["patch"]["requestBody"]["content"]["application/json"]; + type UpdateExpenseCategory = paths["/api/v1/bank-cards/categories/{id}"]["patch"]["requestBody"]["content"]["application/json"]; @@ -41,12 +51,13 @@ function sortBankSummary(data: BankSummary): BankSummary { if (left === null || right === null) throw new Error("Invalid bank summary amount"); if (left > right) return -1; + return left < right ? 1 : 0; }), }; } -function useBankCard(id: string | undefined) { +function useBankCard(id?: string) { return useAuthenticatedQuery({ ...apiQueryClient.queryOptions("get", "/api/v1/bank-cards/{id}", { params: { path: { id: id ?? "" } }, @@ -83,7 +94,7 @@ function useBankExpenses( }); } -function useBankOperation(id: string | undefined) { +function useBankOperation(id?: string) { return useAuthenticatedQuery({ ...apiQueryClient.queryOptions( "get", @@ -105,6 +116,7 @@ function useBankOperations( }, ) { const isAll = query.limit === "all"; + const parameters = { path: { id: id ?? "" }, query: { @@ -113,11 +125,13 @@ function useBankOperations( page: isAll ? 1 : query.page, }, }; + const options = apiQueryClient.queryOptions( "get", "/api/v1/bank-cards/{id}/operations", { params: parameters }, ); + // eslint-disable-next-line @tanstack/query/exhaustive-deps -- Generated options.queryKey already contains params; retain the shared cache identity. return useAuthenticatedQuery({ enabled: Boolean(id && (query.month || (query.from && query.to))), @@ -126,6 +140,7 @@ function useBankOperations( previousQuery, ) => { const previous = previousQuery?.queryKey[2]?.params; + return !isAll && previousQuery?.queryKey.length === options.queryKey.length && previous?.path?.id === id @@ -138,6 +153,7 @@ function useBankOperations( }, queryFn: async ({ signal }) => { const items: BankOperation[] = []; + for (let page = parameters.query.page; ; page++) { const { data, error } = await apiClient.GET( "/api/v1/bank-cards/{id}/operations", @@ -146,6 +162,7 @@ function useBankOperations( signal, }, ); + // eslint-disable-next-line @typescript-eslint/only-throw-error -- Preserve generated ProblemDetails for apiErrorCode and field-error consumers. if (error) throw error; if (!data) throw new Error("Missing bank operations response"); @@ -154,18 +171,22 @@ function useBankOperations( if (!data.hasNext) return { ...data, hasNext: false, items, page: 1 }; } }, - queryKey: isAll ? ([...options.queryKey, "all"] as const) : options.queryKey, + queryKey: isAll + ? ([...options.queryKey, "all"] as const) + : options.queryKey, }); } function useBankSummary( - period: string | { from: string; to: string }, + period: string + | { from: string; to: string }, cardId?: string, ) { const query = typeof period === "string" ? { cardId, month: period } : { ...period, cardId }; + return useAuthenticatedQuery({ ...apiQueryClient.queryOptions("get", "/api/v1/bank-cards/summary", { params: { query }, diff --git a/src/entities/bank-card/api/summary.test.ts b/src/entities/bank-card/api/summary.test.ts index 76fbe67..2175a8c 100644 --- a/src/entities/bank-card/api/summary.test.ts +++ b/src/entities/bank-card/api/summary.test.ts @@ -28,6 +28,7 @@ it("orders displayed expenses descending, preserving cents, ties and source data net: money("0"), refunds: money("0"), }; + expect(sortBankSummary(data).categories.map(row => row.categoryId)).toEqual( ["3", "1", "2", "5", "4", "0"], ); diff --git a/src/entities/bank-card/index.ts b/src/entities/bank-card/index.ts index a2c908a..ee2aca1 100644 --- a/src/entities/bank-card/index.ts +++ b/src/entities/bank-card/index.ts @@ -10,21 +10,16 @@ export { useBankOperations, useBankSummary, } from "./api/queries"; -export { - bankDateInputValue, - bankDateSchema, - bankMoneyValue, - bankToday, - moneyCents, - positiveMoneySchema, -} from "./model/form-validation"; +export { bankDateInputValue, bankMoneyValue, bankToday, moneyCents } from "./model/form-validation"; +export { bankDateSchema, positiveMoneySchema } from "./model/form.schema"; + +export { bankOperationAppearance } from "./model/operation-appearance"; export { bankOperationKinds } from "./model/operation-kinds"; export { bankPeriod } from "./model/period"; export { BankCardFace } from "./ui/BankCardFace/BankCardFace"; export { BankCardForm } from "./ui/BankCardForm/BankCardForm"; export { BankFeedback } from "./ui/BankFeedback"; -export { BankOperationIcon } from "./ui/BankOperationIcon/BankOperationIcon"; -export { BankPeriodPicker } from "./ui/BankPeriodPicker"; +export { BankPeriodPicker } from "./ui/BankPeriodPicker/BankPeriodPicker"; export { BankSummaryView } from "./ui/BankSummary/BankSummary.view"; export { CategoryManager } from "./ui/CategoryManager/CategoryManager"; export { useBankFormFocus } from "./ui/useBankFormFocus"; diff --git a/src/entities/bank-card/model/bank.ts b/src/entities/bank-card/model/bank.ts new file mode 100644 index 0000000..a015d21 --- /dev/null +++ b/src/entities/bank-card/model/bank.ts @@ -0,0 +1,8 @@ +enum BankName { + AlfaBank = "Альфа-Банк", + Sberbank = "Сбербанк", + TBank = "Т-Банк", + Vtb = "ВТБ", +} + +export { BankName }; diff --git a/src/entities/bank-card/model/category.schema.ts b/src/entities/bank-card/model/category.schema.ts new file mode 100644 index 0000000..f485f91 --- /dev/null +++ b/src/entities/bank-card/model/category.schema.ts @@ -0,0 +1,30 @@ +import { z } from "zod"; + +import { validationMessage } from "@/shared/i18n"; + +import type { ExpenseCategory } from "../api/queries"; +const MAX_CATEGORY_NAME_LENGTH = 80; + +function categorySchema(categories?: ExpenseCategory[], editingId?: string) { + return z.object({ + name: z + .string() + .trim() + .refine( + value => value.length > 0 && value.length <= MAX_CATEGORY_NAME_LENGTH, + { error: validationMessage("bank.validation.category") }, + ) + .refine( + value => + !categories?.some( + c => + c.id !== editingId + && c.name.toLocaleLowerCase("ru-RU") + === value.toLocaleLowerCase("ru-RU"), + ), + { error: validationMessage("bank.validation.duplicate") }, + ), + }); +} + +export { categorySchema }; diff --git a/src/entities/bank-card/model/form-validation.test.ts b/src/entities/bank-card/model/form-validation.test.ts index 3545479..a99a3c5 100644 --- a/src/entities/bank-card/model/form-validation.test.ts +++ b/src/entities/bank-card/model/form-validation.test.ts @@ -1,14 +1,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { - bankCardSchema, - bankDateInputValue, - bankDateSchema, - bankMoneyValue, - bankMonth, - bankToday, - positiveMoneySchema, -} from "./form-validation"; +import { bankDateInputValue, bankMoneyValue, bankMonth, bankToday } from "./form-validation"; +import { bankCardSchema, bankDateSchema, positiveMoneySchema } from "./form.schema"; afterEach(() => vi.useRealTimers()); describe("bank form input", () => { @@ -16,6 +9,7 @@ describe("bank form input", () => { expect(positiveMoneySchema.safeParse("92233720368547758.07").success).toBe( true, ); + for (const invalid of [ "92233720368547758.08", "1.001", @@ -26,7 +20,9 @@ describe("bank form input", () => { ]) { expect(positiveMoneySchema.safeParse(invalid).success).toBe(false); } + expect(bankMoneyValue(" -00010,20 ")).toBe("-10.20"); + const values = { bankName: "", lastFour: "", @@ -34,6 +30,7 @@ describe("bank form input", () => { openingBalance: "-92233720368547758.08", openingDate: "2026-01-01", }; + expect(bankCardSchema.safeParse(values).success).toBe(true); expect( bankCardSchema.safeParse({ @@ -62,6 +59,7 @@ it("converts local date input without accepting impossible or unfinished dates", expect( bankDateSchema.safeParse(bankDateInputValue("29.02.2024")).success, ).toBe(true); + for (const value of ["31.02.2026", "07.08.", ""]) { expect(bankDateSchema.safeParse(bankDateInputValue(value)).success).toBe( false, diff --git a/src/entities/bank-card/model/form-validation.ts b/src/entities/bank-card/model/form-validation.ts index 4a201bc..56f11db 100644 --- a/src/entities/bank-card/model/form-validation.ts +++ b/src/entities/bank-card/model/form-validation.ts @@ -1,28 +1,25 @@ -import { z } from "zod"; - -import { validationMessage } from "@/shared/i18n"; - const DECIMAL_PART_COUNT = 2; const CENTS_PRECISION = 2; -const ISO_DATE_LENGTH = 10; const ISO_MONTH_LENGTH = 7; -const MAX_CARD_NAME_LENGTH = 100; function bankDateInputValue(value: string) { return value.replace(/^(\d{2})\.(\d{2})\.(\d{4})$/, "$3-$2-$1"); } + function bankMoneyValue(value: string) { return value .trim() .replace(",", ".") .replace(/^(-?)0+(?=\d)/, "$1"); } + function bankMonth(value: null | string) { return value && value >= "0001-01" && /^\d{4}-(?:0[1-9]|1[0-2])$/.test(value) ? value : bankToday().slice(0, ISO_MONTH_LENGTH); } + function bankToday() { return new Intl.DateTimeFormat("en-CA", { day: "2-digit", @@ -31,84 +28,20 @@ function bankToday() { year: "numeric", }).format(new Date()); } + function moneyCents(value: string): bigint | null { const normalized = value.trim().replace(",", "."); - if (!/^-?\d+$|^-?\d+\.\d{1,2}$/.test(normalized)) return /* eslint-disable-line unicorn/no-null -- The money parser’s callers distinguish invalid input with null. */ null; - const [whole, fraction = ""] = normalized.replace("-", "").split(".", DECIMAL_PART_COUNT); + if (!/^-?\d+$|^-?\d+\.\d{1,2}$/.test(normalized)) + return null; + + const [whole, fraction = ""] = normalized + .replace("-", "") + .split(".", DECIMAL_PART_COUNT); + return ( BigInt(`${whole}${fraction.padEnd(CENTS_PRECISION, "0")}`) * (normalized.startsWith("-") ? -1n : 1n) ); } -const MIN_BALANCE_KOPECKS = -9_223_372_036_854_775_808n; -const MAX_BALANCE_KOPECKS = 9_223_372_036_854_775_807n; -const moneySchema = z.string().refine( - (value) => { - const cents = moneyCents(value); - return ( - cents !== null - && cents >= MIN_BALANCE_KOPECKS - && cents <= MAX_BALANCE_KOPECKS - ); - }, - { error: validationMessage("bank.validation.money") }, -); -const positiveMoneySchema = moneySchema.refine( - (value) => { - const cents = moneyCents(value); - return cents === null || cents > 0n; - }, - { error: validationMessage("bank.validation.positive") }, -); -const bankDateSchema = z - .string() - .refine( - value => - /^\d{4}-\d{2}-\d{2}$/.test(value) - && value >= "0001-01-01" - && !Number.isNaN(Date.parse(`${value}T00:00:00Z`)) - && new Date(`${value}T00:00:00Z`).toISOString().slice(0, ISO_DATE_LENGTH) === value - && value <= bankToday(), - { error: validationMessage("bank.validation.date") }, - ); -const bankCardSchema = z.object({ - bankName: z - .string() - .trim() - .max( - MAX_CARD_NAME_LENGTH, - validationMessage("bank.validation.bankName")(undefined), - ), - lastFour: z.string().refine(value => !value || /^\d{4}$/.test(value), { - error: validationMessage("bank.validation.lastFour"), - }), - name: z - .string() - .trim() - .min(1, validationMessage("bank.validation.name")(undefined)) - .max( - MAX_CARD_NAME_LENGTH, - validationMessage("bank.validation.name")(undefined), - ), - openingBalance: moneySchema, - openingDate: bankDateSchema, - paymentSystem: z - .enum(["", "mir", "visa", "mastercard"], { - error: validationMessage("bank.validation.paymentSystem"), - }) - .optional(), -}); -type BankCardValues = z.infer; - -export { - bankCardSchema, - type BankCardValues, - bankDateInputValue, - bankDateSchema, - bankMoneyValue, - bankMonth, - bankToday, - moneyCents, - positiveMoneySchema, -}; +export { bankDateInputValue, bankMoneyValue, bankMonth, bankToday, moneyCents }; diff --git a/src/entities/bank-card/model/form.schema.ts b/src/entities/bank-card/model/form.schema.ts new file mode 100644 index 0000000..3d4346b --- /dev/null +++ b/src/entities/bank-card/model/form.schema.ts @@ -0,0 +1,81 @@ +import { z } from "zod"; + +import { validationMessage } from "@/shared/i18n"; + +import { bankToday, moneyCents } from "./form-validation"; +const ISO_DATE_LENGTH = 10; +const MAX_CARD_NAME_LENGTH = 100; +const MIN_BALANCE_KOPECKS = -9_223_372_036_854_775_808n; +const MAX_BALANCE_KOPECKS = 9_223_372_036_854_775_807n; + +const moneySchema = z.string().refine( + (value) => { + const cents = moneyCents(value); + + return ( + cents !== null + && cents >= MIN_BALANCE_KOPECKS + && cents <= MAX_BALANCE_KOPECKS + ); + }, + { error: validationMessage("bank.validation.money") }, +); + +const positiveMoneySchema = moneySchema.refine( + (value) => { + const cents = moneyCents(value); + + return cents === null || cents > 0n; + }, + { error: validationMessage("bank.validation.positive") }, +); + +const bankDateSchema = z + .string() + .refine( + value => + /^\d{4}-\d{2}-\d{2}$/.test(value) + && value >= "0001-01-01" + && !Number.isNaN(Date.parse(`${value}T00:00:00Z`)) + && new Date(`${value}T00:00:00Z`).toISOString().slice(0, ISO_DATE_LENGTH) + === value + && value <= bankToday(), + { error: validationMessage("bank.validation.date") }, + ); + +const bankCardSchema = z.object({ + bankName: z + .string() + .trim() + .max( + MAX_CARD_NAME_LENGTH, + validationMessage("bank.validation.bankName")(undefined), + ), + lastFour: z.string().refine(value => !value || /^\d{4}$/.test(value), { + error: validationMessage("bank.validation.lastFour"), + }), + name: z + .string() + .trim() + .min(1, validationMessage("bank.validation.name")(undefined)) + .max( + MAX_CARD_NAME_LENGTH, + validationMessage("bank.validation.name")(undefined), + ), + openingBalance: moneySchema, + openingDate: bankDateSchema, + paymentSystem: z + .enum(["", "mir", "visa", "mastercard"], { + error: validationMessage("bank.validation.paymentSystem"), + }) + .optional(), +}); + +type BankCardValues = z.infer; + +export { + bankCardSchema, + type BankCardValues, + bankDateSchema, + positiveMoneySchema, +}; diff --git a/src/entities/bank-card/model/operation-appearance.ts b/src/entities/bank-card/model/operation-appearance.ts index e13f17a..177aa02 100644 --- a/src/entities/bank-card/model/operation-appearance.ts +++ b/src/entities/bank-card/model/operation-appearance.ts @@ -1,124 +1,71 @@ +import type { OperationIconProps } from "@wealthledger/icons"; + import type { BankOperation } from "../api/queries"; -type OperationIcon = { animation?: string; color: string; path: string }; +const categoryIcons: { + appearance: OperationIconProps; + name: string; +}[] = [ + { appearance: { color: "grape", variant: "wine" }, name: "Алкоголь" }, + { appearance: { color: "green", variant: "deposit" }, name: "Вклады" }, + { appearance: { color: "orange", variant: "home" }, name: "Жильё" }, + { appearance: { color: "red", variant: "medical" }, name: "Здоровье" }, + { + appearance: { color: "green", variant: "growth" }, + name: "Инвестиции и накопления", + }, + { appearance: { color: "orange", variant: "coffee" }, name: "Кафе" }, + { appearance: { color: "blue", variant: "education" }, name: "Образование" }, + { appearance: { color: "blue", variant: "transfer" }, name: "Переводы" }, + { + appearance: { color: "orange", variant: "repayment" }, + name: "Погашение кредита", + }, + { + appearance: { color: "grape", variant: "subscriptions" }, + name: "Подписки", + }, + { appearance: { color: "grape", variant: "shopping" }, name: "Покупки" }, + { appearance: { color: "green", variant: "basket" }, name: "Продукты" }, + { appearance: { color: "blue", variant: "travel" }, name: "Путешествия" }, + { appearance: { color: "grape", variant: "music" }, name: "Развлечения" }, + { appearance: { color: "blue", variant: "wifi" }, name: "Связь и интернет" }, + { + appearance: { color: "green", variant: "cashWithdrawal" }, + name: "Снятие наличных", + }, + { appearance: { color: "grape", variant: "dice" }, name: "Ставки" }, + { appearance: { color: "green", variant: "shield" }, name: "Страхование" }, + { appearance: { color: "orange", variant: "smoking" }, name: "Табак" }, + { appearance: { color: "yellow", variant: "taxi" }, name: "Такси" }, + { appearance: { color: "blue", variant: "car" }, name: "Транспорт" }, + { + appearance: { color: "grape", variant: "server" }, + name: "Хостинг и ИИ-сервисы", + }, + { + appearance: { color: "blue", variant: "download" }, + name: "Цифровые покупки", + }, +]; -const categoryIcons: Record = { - "алкоголь": { - animation: "wine", - color: "grape", - path: "M7 3h10v5a5 5 0 0 1-10 0V3Z M7 7h10v1a5 5 0 0 1-10 0V7Z M12 13v8 M8 21h8", - }, - "вклады": { - animation: "deposit", - color: "green", - path: "M6 9a6 6 0 1 0 12 0a6 6 0 1 0-12 0 M10.5 12V6h2a1.5 1.5 0 0 1 0 3h-3m0 1.5h3 M4 16c0 4 16 4 16 0 M4 19c0 4 16 4 16 0", - }, - "жилье": { color: "orange", path: "M3 11l9-8 9 8 M5 10v11h14V10 M9 21v-8h6v8" }, - "здоровье": { color: "red", path: "M9 3h6v6h6v6h-6v6H9v-6H3V9h6V3Z" }, - "инвестиции и накопления": { - animation: "growth", - color: "green", - path: "M3 3v18h18 M6 15l5-5 4 3 6-8 M16 5h5v5", - }, - "кафе": { - animation: "coffee", - color: "orange", - path: "M4 8h12v7a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4V8Z M16 9h2a3 3 0 0 1 0 6h-2 M8 6c-2-1 2-2 0-4 M12 6c-2-1 2-2 0-4 M3 22h15", - }, - "образование": { - color: "blue", - path: "M2 8l10-5 10 5-10 5L2 8Z M6 10v7c4 3 8 3 12 0v-7 M22 8v9", - }, - "переводы": { - animation: "transfer", - color: "blue", - path: "M3 7h18l-4-4 M21 17H3l4 4", - }, - "погашение кредита": { - animation: "repayment", - color: "orange", - path: "M3 5h18v14H3V5Z M3 9h18 M10 18v-7h3a2 2 0 0 1 0 4H9m0 1.5h4", - }, - "подписки": { - color: "grape", - path: "M4 10a8 8 0 0 1 13-6l3 3 M20 3v4h-4 M20 14a8 8 0 0 1-13 6l-3-3 M4 21v-4h4", - }, - "покупки": { - color: "grape", - path: "M5 7h14l2 14H3L5 7Z M8 8V6a4 4 0 0 1 8 0v2", - }, - "продукты": { - animation: "basket", - color: "green", - path: "M3 9h18l-2 11H5L3 9Z M8 9l4-6 4 6 M9 13v3 M15 13v3 M10 6a2 2 0 1 0 4 0a2 2 0 1 0-4 0", - }, - "путешествия": { - color: "blue", - path: "M10 3h4v7l7 5v3l-7-3v5l2 1v1l-4-1-4 1v-1l2-1v-5l-7 3v-3l7-5V3Z", - }, - "развлечения": { - color: "grape", - path: "M9 5v14a3 3 0 1 1-3-3h3 M9 5l11-2v14a3 3 0 1 1-3-3h3 M9 9l11-2", - }, - "связь и интернет": { - animation: "wifi", - color: "blue", - path: "M3 7a14 14 0 0 1 18 0 M6 11a9 9 0 0 1 12 0 M9 15a4 4 0 0 1 6 0 M12 19h.01", - }, - "снятие наличных": { - color: "green", - path: "M4 10V3h16v7 M7 7h10v14H7V7Z M7 11h10 M10 16h4", - }, - "ставки": { - color: "grape", - path: "M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2Z M7 7h.01 M17 7h.01 M12 12h.01 M7 17h.01 M17 17h.01", - }, - "страхование": { - color: "green", - path: "M12 2l8 4v6c0 5-8 10-8 10S4 17 4 12V6l8-4Z M8 12l3 3 5-6", - }, - "табак": { - color: "orange", - path: "M3 14h18v5H3v-5Z M16 14v5 M8 10V8c0-2 3-2 3-4V2 M15 10V8c0-2 3-2 3-4", - }, - "такси": { - color: "yellow", - path: "M4 10l2-6h12l2 6 M3 10h18v8H3v-8Z M6 18v3 M18 18v3 M6 14h2 M16 14h2 M10 4V2h4v2", - }, - "транспорт": { - animation: "car", - color: "blue", - path: "M4 16H2v-4l3-1 3-4h6l4 4 4 1v4h-2 M8 16h8 M6 11h12m-6-4v4 M4 16a2 2 0 1 0 4 0a2 2 0 1 0-4 0m2-2v4m-2-2h4 M16 16a2 2 0 1 0 4 0a2 2 0 1 0-4 0m2-2v4m-2-2h4", - }, - "хостинг и ии-сервисы": { - animation: "server", - color: "grape", - path: "M3 3h18v7H3V3Z M3 14h18v7H3v-7Z M7 6.5h.01 M7 17.5h.01 M15 6.5h3 M15 17.5h3", - }, - "цифровые покупки": { - color: "blue", - path: "M3 3h18v13H3V3Z M8 21h8 M12 16v5 M12 6v7 M9 10l3 3 3-3", - }, -}; -const otherIcon: OperationIcon = { - animation: "grid", +const otherIcon: OperationIconProps = { color: "gray", - path: "M4 4h6v6H4V4Z M14 4h6v6h-6V4Z M4 14h6v6H4v-6Z M14 14h6v6h-6v-6Z", + variant: "grid", }; + const operationIcons: Record< Exclude, - OperationIcon + OperationIconProps > = { - refund: { color: "teal", path: "M8 4L3 9l5 5 M3 9h11a7 7 0 0 1 0 14" }, + refund: { color: "teal", variant: "refund" }, topup: { - animation: "topup", color: "green", - path: "M20 8V5H5a2 2 0 0 1 0-4h13v4 M3 3v16a2 2 0 0 0 2 2h15V8H5 M16 12v5m-2.5-2.5h5", + variant: "topup", }, transfer: { - animation: "transfer", color: "blue", - path: "M3 7h18l-4-4 M21 17H3l4 4", + variant: "transfer", }, }; @@ -126,12 +73,21 @@ function bankOperationAppearance( kind: BankOperation["kind"], categoryName?: null | string, ) { - if (kind !== "expense") return /* eslint-disable-line security/detect-object-injection -- Operation kinds are finite; category names are guarded by Object.hasOwn. */ operationIcons[kind]; - const name = categoryName - ?.trim() - .toLocaleLowerCase("ru-RU") - .replaceAll("ё", "е"); - return name && Object.hasOwn(categoryIcons, name) ? /* eslint-disable-line security/detect-object-injection -- Operation kinds are finite; category names are guarded by Object.hasOwn. */ categoryIcons[name] : otherIcon; + if (kind !== "expense") + // eslint-disable-next-line security/detect-object-injection -- Operation kinds are a finite API union. + return operationIcons[kind]; + + const name = normalizeCategoryName(categoryName ?? ""); + + const category = categoryIcons.find( + item => normalizeCategoryName(item.name) === name, + ); + + return category?.appearance ?? otherIcon; +} + +function normalizeCategoryName(name: string) { + return name.trim().toLocaleLowerCase("ru-RU").replaceAll("ё", "е"); } export { bankOperationAppearance }; diff --git a/src/entities/bank-card/model/period.test.ts b/src/entities/bank-card/model/period.test.ts index 343ec53..bb8de22 100644 --- a/src/entities/bank-card/model/period.test.ts +++ b/src/entities/bank-card/model/period.test.ts @@ -17,6 +17,7 @@ it.each([ it("rejects zero year consistently in legacy and explicit periods", () => { vi.useFakeTimers(); vi.setSystemTime(new Date("2026-09-27T10:00:00Z")); + for (const query of ["month=0000-01", "from=0000-01-01&to=0000-01-31"]) { expect(bankPeriod(new URLSearchParams(query))).toEqual({ from: "2026-09-01", diff --git a/src/entities/bank-card/model/period.ts b/src/entities/bank-card/model/period.ts index bd099e9..93cba2b 100644 --- a/src/entities/bank-card/model/period.ts +++ b/src/entities/bank-card/model/period.ts @@ -1,15 +1,16 @@ -import { z } from "zod"; +import { calendarDate } from "@/shared/lib"; import { bankMonth } from "./form-validation"; -const calendarDate = z.iso.date(); const ISO_DATE_LENGTH = 10; + function bankPeriod(parameters: URLSearchParams) { const month = bankMonth(parameters.get("month")); const monthEnd = new Date(`${month}-01T00:00:00Z`); monthEnd.setUTCMonth(monthEnd.getUTCMonth() + 1, 0); const from = parameters.get("from"); const to = parameters.get("to"); + return from && to && calendarDate.safeParse(from).success diff --git a/src/entities/bank-card/ui/BankCardFace/BankCardFace.stories.tsx b/src/entities/bank-card/ui/BankCardFace/BankCardFace.stories.tsx index 99cf1c9..8cdc965 100644 --- a/src/entities/bank-card/ui/BankCardFace/BankCardFace.stories.tsx +++ b/src/entities/bank-card/ui/BankCardFace/BankCardFace.stories.tsx @@ -2,55 +2,62 @@ import type { Meta, StoryObj } from "@storybook/react-vite"; import { SimpleGrid } from "@mantine/core"; +import { BankName } from "../../model/bank"; import { BankCardFace } from "./BankCardFace"; -const meta = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ -{ - args: { - card: { - archivedAt: null, - balance: { currency: "RUB", value: "128450.75" }, - bankName: "Сбербанк", - id: "fictional", - lastFour: "4829", - name: "Для повседневных покупок", - openingBalance: { currency: "RUB", value: "0" }, - openingDate: "2026-01-01", - paymentSystem: "mir", - version: 1, +const meta + = { + args: { + card: { + archivedAt: null, + balance: { currency: "RUB", value: "128450.75" }, + bankName: BankName.Sberbank, + id: "fictional", + lastFour: "4829", + name: "Для повседневных покупок", + openingBalance: { currency: "RUB", value: "0" }, + openingDate: "2026-01-01", + paymentSystem: "mir", + version: 1, + }, }, - }, - component: BankCardFace, - tags: ["autodocs"], - title: "Product/BankCards/CardAppearance", -} -/* eslint-enable unicorn/no-null */) satisfies Meta; + component: BankCardFace, + tags: ["autodocs"], + title: "Product/BankCards/CardAppearance", + } satisfies Meta; + export default meta; + type Story = StoryObj; + export const Banks: Story = { render: arguments_ => ( - {["Сбербанк", "Т-Банк", "Альфа-Банк", "ВТБ", /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null].map( - (bankName, index) => ( - ( + - ), - )} + }} + key={bankName ?? "unknown"} + /> + ))} ), }; -export const MissingDetails: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { + +export const MissingDetails: Story + = { args: { card: { ...meta.args.card, @@ -59,8 +66,8 @@ export const MissingDetails: Story = (/* eslint-disable unicorn/no-null -- Fixtu paymentSystem: null, }, }, - } -/* eslint-enable unicorn/no-null */); + }; + export const LongArchived: Story = { args: { card: { diff --git a/src/entities/bank-card/ui/BankCardFace/BankCardFace.tsx b/src/entities/bank-card/ui/BankCardFace/BankCardFace.tsx index 2788fc2..58d3070 100644 --- a/src/entities/bank-card/ui/BankCardFace/BankCardFace.tsx +++ b/src/entities/bank-card/ui/BankCardFace/BankCardFace.tsx @@ -1,5 +1,6 @@ import type { FC } from "react"; +import { ContactlessIcon } from "@wealthledger/icons"; import { useTranslation } from "react-i18next"; import { formatMoney } from "@/shared/lib"; @@ -9,51 +10,42 @@ import type { BankCard } from "../../api/queries"; import classes from "./BankCardFace.module.css"; type BankCardFaceProps = { card: BankCard }; + const BankCardFace: FC = (props) => { const { card } = props; const { t } = useTranslation(); const bank = card.bankName?.toLocaleLowerCase("ru") ?? ""; const tone = bankTone(bank); + return (
{card.bankName || t("bank.card")} - {card.archivedAt && ( - {t("bank.archived")} - )} + + {card.archivedAt && {t("bank.archived")}}
+ -
+ +
{`•••• •••• •••• ${card.lastFour || "••••"}`}
+
{card.name}
+
{formatMoney(card.balance)}
+ {card.paymentSystem && ( - {card.paymentSystem === "mastercard" && ( -
- )} - large - state={vm.candlesState} - title={t("stock.chart")} - > - {!!(vm.candles) && (( - vm.chartData.length > 0 - ? ( - <> - - new Intl.NumberFormat("ru-RU", { - maximumFractionDigits: 4, - }).format(value)} - withDots={vm.chartData.length === 1} - withGradient - yAxisProps={{ domain: ["auto", "auto"], width: 64 }} - /> - - {t( - props.priceUnit === "percent" - ? "bond.chartNote" - : "stock.chartNote", - )} - - {!!(vm.hasIncompleteCandle) && (( - - {t("stock.incomplete")} - - ))} - {vm.averageLine !== null && (( - - {t("stock.averageLine")} - : - {" "} - {formatMoney(vm.position?.averagePurchasePrice)} - - ))} - - - - {t("stock.priceTable")} - - {t("stock.priceTableHint", { count: vm.chartData.length })} - - - - - - - - {t("stock.date")} - {t("stock.price")} - {t("stock.candle")} - - - - {vm.priceRows.map(candle => ( - - {candle.date} - - {priceLabel(candle.close)} - - - - {t( - candle.isComplete - ? "stock.complete" - : "stock.forming", - )} - - - - ))} - -
-
-
-
-
- - ) - : ( - - {t( - vm.candlesState.partial - ? "investment.partial" - : "stock.noCandles", - )} - - ) - ))} - - ); -}; - -export { InstrumentChart }; diff --git a/src/features/instrument-details/ui/InstrumentChart/InstrumentChart.view.tsx b/src/features/instrument-details/ui/InstrumentChart/InstrumentChart.view.tsx new file mode 100644 index 0000000..7aa826c --- /dev/null +++ b/src/features/instrument-details/ui/InstrumentChart/InstrumentChart.view.tsx @@ -0,0 +1,195 @@ +import type { FC } from "react"; + +import { AreaChart } from "@mantine/charts"; +import { + Accordion, + Badge, + ScrollArea, + SegmentedControl, + Table, + Text, +} from "@mantine/core"; + +import { formatMoney } from "@/shared/lib"; + +import type { InstrumentChartVm } from "../../model/types"; + +import classes from "../InstrumentDetails.module.css"; +import { InstrumentSection } from "../InstrumentSection.view"; +import { useInstrumentChartVm } from "./InstrumentChart.vm"; + +type InstrumentChartProps = { priceUnit?: "percent"; vm: InstrumentChartVm }; + +const InstrumentChart: FC = (props) => { + const { + chartLabel, + formatChartValue, + periodOptions, + priceRows, + referenceLines, + t, + vm, + } = useInstrumentChartVm(props); + + let chartContent; + + if (vm.candles) { + if (vm.chartData.length > 0) { + chartContent = ( + <> + + + + {t( + props.priceUnit === "percent" + ? "bond.chartNote" + : "stock.chartNote", + )} + + + {!!vm.hasIncompleteCandle && ( + + {t("stock.incomplete")} + + )} + + {vm.averageLine !== null && ( + + {t("stock.averageLine")}:{" "} + {formatMoney(vm.position?.averagePurchasePrice)} + + )} + + + + + {t("stock.priceTable")} + + + {t("stock.priceTableHint", { count: vm.chartData.length })} + + + + + + + + + {t("stock.date")} + + {t("stock.price")} + + {t("stock.candle")} + + + + + {priceRows.map((candle) => { + const displayColor = candle.isComplete + ? "gray" + : "blue"; + + return ( + + {candle.date} + + + {candle.price} + + + + + {t( + candle.isComplete + ? "stock.complete" + : "stock.forming", + )} + + + + ); + })} + +
+
+
+
+
+ + ); + } + else { + chartContent = ( + + {t( + vm.candlesState.partial + ? "investment.partial" + : "stock.noCandles", + )} + + ); + } + } + + return ( + + +
+ )} + large + state={vm.candlesState} + title={t("stock.chart")} + > + {chartContent} + + ); +}; + +export { InstrumentChart }; diff --git a/src/features/instrument-details/ui/InstrumentChart/InstrumentChart.vm.ts b/src/features/instrument-details/ui/InstrumentChart/InstrumentChart.vm.ts new file mode 100644 index 0000000..02c6d0c --- /dev/null +++ b/src/features/instrument-details/ui/InstrumentChart/InstrumentChart.vm.ts @@ -0,0 +1,64 @@ +import { useTranslation } from "react-i18next"; + +import { formatChartValue, formatDecimal, formatMoney } from "@/shared/lib"; + +import type { InstrumentChartVm } from "../../model/types"; + +type InstrumentChartProps = { priceUnit?: "percent"; vm: InstrumentChartVm }; + +function useInstrumentChartVm(props: InstrumentChartProps) { + const { vm } = props; + const { t } = useTranslation(); + + const priceRows = vm.priceRows.map((candle) => { + const currency = vm.candles?.currency; + const value = candle.close; + + const amount = currency ? { currency, value } : undefined; + + const price = props.priceUnit === "percent" + ? `${formatDecimal(value)} %` + : formatMoney(amount); + + return { ...candle, price }; + }); + + const periodOptions = ["month", "halfYear", "year", "all"].map(value => ({ + label: t(`stock.periods.${value}`), + value, + })); + + const chartLabel = t( + props.priceUnit === "percent" ? "bond.chartLabel" : "stock.chartLabel", + { + currency: + props.priceUnit === "percent" + ? t("bond.percentOfNominal") + : (vm.candles?.currency ?? ""), + }, + ); + + const referenceLines + = vm.averageLine === null + ? [] + : [ + { + color: "orange.7", + ifOverflow: "extendDomain" as const, + label: t("stock.averageLine"), + y: vm.averageLine, + }, + ]; + + return { + chartLabel, + formatChartValue, + periodOptions, + priceRows, + referenceLines, + t, + vm, + }; +} + +export { useInstrumentChartVm }; diff --git a/src/features/instrument-details/ui/InstrumentEvents.view.tsx b/src/features/instrument-details/ui/InstrumentEvents.view.tsx index df9de31..6d6b75d 100644 --- a/src/features/instrument-details/ui/InstrumentEvents.view.tsx +++ b/src/features/instrument-details/ui/InstrumentEvents.view.tsx @@ -20,25 +20,54 @@ type InstrumentEventsProps = { const InstrumentEvents: FC = (props) => { const { vm } = props; const { t } = useTranslation(); + + const options = [ + "all", + "trades", + props.incomeFilter ?? "dividends", + "other", + ].map(value => ({ + label: + value === (props.incomeFilter ?? "dividends") && props.incomeLabel + ? props.incomeLabel + : t(`stock.filters.${value}`), + value, + })); + + let eventsContent; + + if (vm.eventRows.length > 0) { + eventsContent = ( + + {vm.eventRows.map(event => ( + + ))} + + ); + } + else { + eventsContent = ( + + {t( + vm.operationsState.partial + ? "investment.partial" + : "stock.noOperations", + )} + + ); + } + return ( ({ - label: - value === (props.incomeFilter ?? "dividends") - && props.incomeLabel - ? props.incomeLabel - : t(`stock.filters.${value}`), - value, - }))} + data={options} onChange={vm.setFilter} value={vm.filter} /> @@ -47,32 +76,14 @@ const InstrumentEvents: FC = (props) => { state={vm.operationsState} title={t("stock.history")} > - {!!(vm.operations) && (( + {!!vm.operations && ( <> {props.historyNote ?? t("stock.historyNote")} - {vm.eventRows.length > 0 - ? ( - - {vm.eventRows.map(event => ( - - ))} - - ) - : ( - - {t( - vm.operationsState.partial - ? "investment.partial" - : "stock.noOperations", - )} - - )} + + {eventsContent} + + - ))} + )} ); }; diff --git a/src/features/instrument-details/ui/InstrumentPosition.view.tsx b/src/features/instrument-details/ui/InstrumentPosition.view.tsx index f4abd37..96d5c41 100644 --- a/src/features/instrument-details/ui/InstrumentPosition.view.tsx +++ b/src/features/instrument-details/ui/InstrumentPosition.view.tsx @@ -16,130 +16,144 @@ type InstrumentPositionProps = { returnNote?: string; vm: InstrumentPositionVm; }; + const InstrumentPosition: FC = (props) => { const { vm } = props; const { t } = useTranslation(); if (vm.position && vm.position.accounts.length === 0) return; + + const positionReturnColor = vm.position?.absoluteReturn?.value.startsWith("-") + ? "red.8" + : "green.8"; + return ( - {!!(vm.position) && (( + {!!vm.position && ( - {!!(vm.position.isStale) && (( - {t("portfolio.staleWarning")} - ))} + {!!vm.position.isStale && {t("portfolio.staleWarning")}} +
{props.quantityLabel ?? t("stock.quantity")} + {formatDecimal(vm.position.quantity)}
+
{t("stock.value")} + {formatMoney(vm.position.currentValue)}
+
{t("stock.average")} + {formatMoney(vm.position.averagePurchasePrice)}
+
{t("stock.openReturn")} - + + {formatMoney(vm.position.absoluteReturn)} - {vm.position.returnPercent !== null && (( + + {vm.position.returnPercent !== null && ( - {formatDecimal(vm.position.returnPercent)} - {" "} - % + {formatDecimal(vm.position.returnPercent)} % - ))} + )}
+ {props.returnNote ?? t("stock.openReturnNote")} +
- {vm.position.accounts.map(account => ( -
- {account.account - ? ( - - {account.account.name} - - ) - : ( - {t("stock.portfolio")} - )} -
- - {props.quantityLabel ?? t("stock.quantity")} - - {formatDecimal(account.quantity)} -
-
- - {t("stock.average")} - - {formatMoney(account.averagePurchasePrice)} -
-
- - {t("stock.value")} - - {formatMoney(account.currentValue)} -
-
- - {t("stock.openReturn")} - - - {formatMoney(account.absoluteReturn)} - - {account.returnPercent !== null && (( - - {formatDecimal(account.returnPercent)} - {" "} - % + {vm.position.accounts.map((account) => { + const accountReturnColor = account.absoluteReturn?.value.startsWith("-") + ? "red.8" + : undefined; + + return ( +
+ {account.account + ? ( + + {account.account.name} + + ) + : {t("stock.portfolio")}} + +
+ + {props.quantityLabel ?? t("stock.quantity")} - ))} + + {formatDecimal(account.quantity)} +
+ +
+ + {t("stock.average")} + + + {formatMoney(account.averagePurchasePrice)} +
+ +
+ + {t("stock.value")} + + + {formatMoney(account.currentValue)} +
+ +
+ + {t("stock.openReturn")} + + + + {formatMoney(account.absoluteReturn)} + + + {account.returnPercent !== null && ( + + {formatDecimal(account.returnPercent)} % + + )} +
-
- ))} + ); + })}
+ {t("stock.snapshotAt", { date: formatSnapshotTime(vm.position.observedAt), })} - ))} + )} ); }; diff --git a/src/features/instrument-details/ui/InstrumentSection.view.tsx b/src/features/instrument-details/ui/InstrumentSection.view.tsx index e021b77..9119dd3 100644 --- a/src/features/instrument-details/ui/InstrumentSection.view.tsx +++ b/src/features/instrument-details/ui/InstrumentSection.view.tsx @@ -29,12 +29,46 @@ type InstrumentSectionProps = PropsWithChildren<{ state: SectionState; title: string; }>; + const InstrumentSection: FC = (props) => { const { t } = useTranslation(); - const readError = t(props.state.hasData ? "accounts.refreshError" : "stock.sectionError"); + + const readError = t( + props.state.hasData ? "accounts.refreshError" : "stock.sectionError", + ); + + const sectionClassName = props.embedded + ? classes.embeddedSection + : classes.section; + + const skeletonHeight = props.large + ? CHART_SKELETON_HEIGHT_PX + : SECTION_SKELETON_HEIGHT_PX; + + let sectionContent; + + if (props.state.loading) { + sectionContent = ( + + + + + + + + ); + } + else { + sectionContent = ( + props.children + ); + } + return ( @@ -42,34 +76,35 @@ const InstrumentSection: FC = (props) => { {props.title} + {props.controls} - {!!(props.state.stale) && (( - {t("investment.stale")} - ))} - {!!(props.state.partial) && (( - {t("investment.partial")} - ))} - {!!(props.state.lastSuccessfulAt) && (( + + {!!props.state.stale && {t("investment.stale")}} + + {!!props.state.partial && {t("investment.partial")}} + + {!!props.state.lastSuccessfulAt && ( {t("investment.sourceTime", { date: formatSnapshotTime(props.state.lastSuccessfulAt), })} - ))} - {!!(props.state.refreshing) && (( + )} + + {!!props.state.refreshing && ( {t("accounts.refreshing")} - ))} - {!!(props.state.error) && (( + )} + + {!!props.state.error && ( - {props.state.sourceError - ? t("investment.syncFailed") - : readError} + {props.state.sourceError ? t("investment.syncFailed") : readError} + - ))} - {props.state.loading - ? ( - - - - - - - ) - : ( - props.children - )} + )} + + {sectionContent} ); }; diff --git a/src/features/tbank-connection/model/connection-boundary.ts b/src/features/tbank-connection/model/connection-boundary.ts index 5e23015..a25a7fe 100644 --- a/src/features/tbank-connection/model/connection-boundary.ts +++ b/src/features/tbank-connection/model/connection-boundary.ts @@ -31,6 +31,7 @@ function commitTbankConnectionBoundary( void queryClient.resetQueries({ predicate: ({ queryKey }) => { const [method, path] = queryKey; + return ( method === "get" && typeof path === "string" diff --git a/src/features/tbank-connection/model/screen-sync.test.tsx b/src/features/tbank-connection/model/screen-sync.test.tsx index fec1d07..037298a 100644 --- a/src/features/tbank-connection/model/screen-sync.test.tsx +++ b/src/features/tbank-connection/model/screen-sync.test.tsx @@ -19,11 +19,14 @@ function auth() { refresh: () => Promise.resolve(true), }); } + describe("page-owned screen synchronization", () => { it("ignores a late sync acceptance after the account scope changes", async () => { auth(); - const { promise: blocked, resolve: release } = Promise.withResolvers(); + const { promise: blocked, resolve: release } + = Promise.withResolvers(); + const posted: string[] = []; const polled: string[] = []; server.use( @@ -32,8 +35,10 @@ describe("page-owned screen synchronization", () => { accountId: string; screen: "account"; }; + posted.push(scope.accountId); await blocked; + return HttpResponse.json( { id: scope.accountId, now: "2026-09-25T00:00:00Z", scope }, { status: 202 }, @@ -41,6 +46,7 @@ describe("page-owned screen synchronization", () => { }), http.get("*/api/v1/tbank-sync/:id", ({ params }) => { polled.push(String(params.id)); + return HttpResponse.json({ id: params.id, resources: [], @@ -48,6 +54,7 @@ describe("page-owned screen synchronization", () => { }); }), ); + const { rerender, result } = renderHook( ({ accountId }) => useScreenSync({ accountId, screen: "account" }, []), { @@ -55,6 +62,7 @@ describe("page-owned screen synchronization", () => { wrapper: createQueryWrapper().wrapper, }, ); + let pending!: Promise; act(() => { pending = result.current.refresh(); @@ -79,6 +87,7 @@ describe("page-owned screen synchronization", () => { server.use( http.get("*/api/v1/brokerage-accounts", ({ request }) => { modes.push(new URL(request.url).searchParams.get("sync")); + return isUnavailable ? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 }) : HttpResponse.json( @@ -87,14 +96,17 @@ describe("page-owned screen synchronization", () => { }), http.post("*/api/v1/tbank-sync", () => { posts += 1; + return new HttpResponse(null, { status: 500 }); }), ); const { queryClient, wrapper } = createQueryWrapper(); + const { result } = renderHook( () => { const accounts = useBrokerageAccounts(); const disabled = useStockQuote(""); + return { accounts, disabled, @@ -103,6 +115,7 @@ describe("page-owned screen synchronization", () => { }, { wrapper }, ); + if (cached) { await waitFor(() => // eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch. @@ -111,6 +124,7 @@ describe("page-owned screen synchronization", () => { isUnavailable = true; await act(() => result.current.accounts.refetch()); } + await waitFor(() => expect(result.current.accounts.isError).toBe(true)); isUnavailable = false; await act(() => result.current.sync.retry()); @@ -119,7 +133,13 @@ describe("page-owned screen synchronization", () => { cached ? "3" : "2", ); expect(modes).toEqual( - cached ? [null, /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null, "observe"] : [null, "observe"], + cached + ? [ + null, + null, + "observe", + ] + : [null, "observe"], ); expect(posts).toBe(0); expect(result.current.disabled.data).toBeUndefined(); @@ -141,7 +161,9 @@ describe("page-owned screen synchronization", () => { async (boundary, pending) => { auth(); - const { promise: blocked, resolve: release } = Promise.withResolvers(); + const { promise: blocked, resolve: release } + = Promise.withResolvers(); + let isRecovering = false; let isChanged = false; server.use( @@ -154,18 +176,22 @@ describe("page-owned screen synchronization", () => { : HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 }); isRecovering = true; await blocked; + return HttpResponse.json(resource([], { stateVersion: "old" })); }), ); const { queryClient, wrapper } = createQueryWrapper(); const published: unknown[] = []; + const unsubscribe = queryClient.getQueryCache().subscribe((event) => { if (event.type === "updated" && event.action.type === "success") published.push(event.query.state.data); }); + const { result } = renderHook( () => { const accounts = useBrokerageAccounts(); + return { accounts, sync: useScreenSync({ screen: "accounts" }, [accounts]), @@ -173,6 +199,7 @@ describe("page-owned screen synchronization", () => { }, { wrapper }, ); + await waitFor(() => expect(result.current.accounts.isError).toBe(true)); let recovery!: Promise; act(() => { @@ -182,6 +209,7 @@ describe("page-owned screen synchronization", () => { if (pending) await waitFor(() => expect(isRecovering).toBe(true)); await act(async () => { isChanged = true; + switch (boundary) { case "access": { invalidateResourceAccess(queryClient, "brokerage", { @@ -190,24 +218,29 @@ describe("page-owned screen synchronization", () => { break; } + case "logout": { configureAuthClient(); queryClient.clear(); break; } + case "session": { auth(); queryClient.clear(); break; } - case "connection": { commitTbankConnectionBoundary(queryClient, { - connected: true, - connectedAt: "2026-09-27T00:00:00Z", - }); + + case "connection": { + commitTbankConnectionBoundary(queryClient, { + connected: true, + connectedAt: "2026-09-27T00:00:00Z", + }); } } + release(); await recovery; }); @@ -233,6 +266,7 @@ describe("page-owned screen synchronization", () => { server.use( http.get("*/api/v1/brokerage-accounts", ({ request }) => { modes.push(new URL(request.url).searchParams.get("sync")); + return modes.length === 1 ? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 }) : HttpResponse.json(resource([])); @@ -242,6 +276,7 @@ describe("page-owned screen synchronization", () => { ), http.get("*/api/v1/tbank-sync/:id", () => { polls += 1; + return retryStatus && polls === 1 ? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 }) : HttpResponse.json({ @@ -252,10 +287,12 @@ describe("page-owned screen synchronization", () => { }), ); const { queryClient, wrapper } = createQueryWrapper(); + const { result } = renderHook( () => { const accounts = useBrokerageAccounts(); const disabled = useStockQuote(""); + return { accounts, sync: useScreenSync({ screen: "accounts" }, [accounts, disabled]), @@ -263,9 +300,11 @@ describe("page-owned screen synchronization", () => { }, { wrapper }, ); + await waitFor(() => expect(result.current.accounts.isError).toBe(true)); expect(result.current.accounts.meta).toBeUndefined(); await act(() => result.current.sync.refresh()); + if (retryStatus) { await waitFor(() => // eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch. @@ -273,9 +312,10 @@ describe("page-owned screen synchronization", () => { ); await act(() => result.current.sync.retry()); } + await waitFor(() => expect(result.current.accounts.isSuccess).toBe(true)); expect(result.current.accounts.data).toEqual([]); - // eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response. + expect(modes).toEqual([null, "observe"]); expect( queryClient @@ -290,16 +330,20 @@ describe("page-owned screen synchronization", () => { const bodies: unknown[] = []; let isCompleted = false; let polls = 0; + const meta = () => resource([], { stateVersion: isCompleted ? "2" : "1" }).meta; + server.use( http.get("*/api/v1/brokerage-accounts", ({ request }) => { modes.push(new URL(request.url).searchParams.get("sync")); + return HttpResponse.json(resource([], meta())); }), http.post("*/api/v1/tbank-sync", async ({ request }) => { bodies.push(await request.json()); isCompleted = true; + return HttpResponse.json( { id: "screen", @@ -311,7 +355,8 @@ describe("page-owned screen synchronization", () => { }), http.get("*/api/v1/tbank-sync/:id", () => { polls++; - return HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + + return HttpResponse.json( { errorCode: null, id: "screen", @@ -320,13 +365,15 @@ describe("page-owned screen synchronization", () => { resources: [meta()], scope: { screen: "accounts" }, state: "succeeded", - } - /* eslint-enable unicorn/no-null */)); + }, + ); }), ); + const { result, unmount } = renderHook( () => { const accounts = useBrokerageAccounts(); + return { accounts, sync: useScreenSync({ screen: "accounts" }, [accounts]), @@ -334,6 +381,7 @@ describe("page-owned screen synchronization", () => { }, { wrapper: createQueryWrapper().wrapper }, ); + await waitFor(() => expect(result.current.accounts.data).toEqual([])); await act(async () => { await Promise.all([ @@ -345,13 +393,14 @@ describe("page-owned screen synchronization", () => { expect(result.current.accounts.meta?.stateVersion).toBe("2"), ); expect(bodies).toEqual([{ screen: "accounts" }]); - // eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response. + expect(modes).toEqual([null, "observe"]); vi.useFakeTimers(); + try { await act(() => vi.advanceTimersByTimeAsync(120_000)); expect(polls).toBe(1); - // eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response. + expect(modes).toEqual([null, "observe"]); unmount(); await vi.advanceTimersByTimeAsync(120_000); @@ -365,26 +414,34 @@ describe("page-owned screen synchronization", () => { "publishes completed empty coverage while history runs, then stops on %s", async (boundary) => { vi.useFakeTimers({ toFake: ["Date"] }); + try { auth(); let isCompleted = false; let polls = 0; const modes: (null | string)[] = []; + const snapshot = () => - resource(isCompleted ? [] : /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null, (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + resource( + isCompleted + ? [] + : null, { stateVersion: isCompleted ? "covered" : "initial", sync: { errorCode: null, id: "history", state: "running" }, - } - /* eslint-enable unicorn/no-null */)); + }, + ); + server.use( http.get("*/api/v1/brokerage-accounts", ({ request }) => { modes.push(new URL(request.url).searchParams.get("sync")); + return HttpResponse.json(snapshot()); }), http.get("*/api/v1/tbank-sync/:id", () => { polls++; - return HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + + return HttpResponse.json( { errorCode: null, id: "history", @@ -397,13 +454,15 @@ describe("page-owned screen synchronization", () => { resources: [snapshot().meta], scope: null, state: "running", - } - /* eslint-enable unicorn/no-null */)); + }, + ); }), ); + const { result, unmount } = renderHook( () => { const accounts = useBrokerageAccounts(); + return { accounts, sync: useScreenSync({ screen: "accounts" }, [accounts]), @@ -411,6 +470,7 @@ describe("page-owned screen synchronization", () => { }, { wrapper: createQueryWrapper().wrapper }, ); + await waitFor(() => expect(result.current.accounts.meta?.sync.id).toBe("history"), ); @@ -426,7 +486,7 @@ describe("page-owned screen synchronization", () => { await act(async () => { await new Promise(resolve => setTimeout(resolve, 1100)); }); - // eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response. + expect(modes).toEqual([null, "observe"]); if (boundary === "leave") unmount(); else act(() => configureAuthClient()); @@ -447,20 +507,24 @@ describe("page-owned screen synchronization", () => { server.use( http.get("*/api/v1/brokerage-accounts", () => HttpResponse.json( - resource([], (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + resource( + + [], { sync: { errorCode: null, id: "revoked", state: "running" }, - } - /* eslint-enable unicorn/no-null */)), + }, + ), ), ), http.get("*/api/v1/tbank-sync/:id", () => HttpResponse.json({ code: "INVALID_TBANK_TOKEN" }, { status: 400 }), ), ); + const { result } = renderHook( () => { const accounts = useBrokerageAccounts(); + return { accounts, sync: useScreenSync({ screen: "accounts" }, [accounts]), @@ -468,6 +532,7 @@ describe("page-owned screen synchronization", () => { }, { wrapper: createQueryWrapper().wrapper }, ); + await waitFor(() => expect(result.current.accounts.isError).toBe(true)); expect(result.current.accounts.data).toBeUndefined(); }); @@ -475,7 +540,10 @@ describe("page-owned screen synchronization", () => { auth(); let isObserved = false; const modes: (null | string)[] = []; - const dependency = resource([], (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + + const dependency = resource( + + [], { resourceKey: "operations", stateVersion: isObserved ? "covered" : "initial", @@ -484,24 +552,35 @@ describe("page-owned screen synchronization", () => { id: "dependency", state: isObserved ? "idle" : "running", }, - } - /* eslint-enable unicorn/no-null */)).meta; + }, + ).meta; + server.use( http.get("*/api/v1/brokerage-accounts", ({ request }) => { const mode = new URL(request.url).searchParams.get("sync"); modes.push(mode); if (mode) isObserved = true; + return HttpResponse.json( - resource(isObserved ? [] : /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null, { - dependencies: [ - { ...dependency, stateVersion: isObserved ? "covered" : "initial" }, - ], - resourceKey: "projection", - }), + resource( + isObserved + ? [] + : null, + { + dependencies: [ + { + ...dependency, + stateVersion: isObserved ? "covered" : "initial", + }, + ], + resourceKey: "projection", + }, + ), ); }), http.get("*/api/v1/tbank-sync/:id", () => - HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + + HttpResponse.json( { errorCode: null, id: "dependency", @@ -510,20 +589,23 @@ describe("page-owned screen synchronization", () => { resources: [{ ...dependency, stateVersion: "covered" }], scope: null, state: "succeeded", - } - /* eslint-enable unicorn/no-null */)), + }, + ), ), ); + const { result } = renderHook( () => { const accounts = useBrokerageAccounts(); useScreenSync({ screen: "accounts" }, [accounts]); + return accounts; }, { wrapper: createQueryWrapper().wrapper }, ); + await waitFor(() => expect(result.current.data).toEqual([])); - // eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response. + expect(modes).toEqual([null, "observe"]); }); @@ -536,9 +618,11 @@ describe("page-owned screen synchronization", () => { HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }), ), ); + const { result } = renderHook( () => { const accounts = useBrokerageAccounts(); + return { accounts, sync: useScreenSync({ screen: "accounts" }, [accounts]), @@ -546,6 +630,7 @@ describe("page-owned screen synchronization", () => { }, { wrapper: createQueryWrapper().wrapper }, ); + await waitFor(() => expect(result.current.accounts.data).toEqual([])); await act(() => result.current.sync.refresh()); await waitFor(() => expect(result.current.sync.transportError).toBe(true)); diff --git a/src/features/tbank-connection/model/screen-sync.ts b/src/features/tbank-connection/model/screen-sync.ts index 6bfd0a2..325ce28 100644 --- a/src/features/tbank-connection/model/screen-sync.ts +++ b/src/features/tbank-connection/model/screen-sync.ts @@ -15,15 +15,21 @@ import { type InvestmentScreen, useTbankSync } from "./sync"; type ResourceMeta = paths["/api/v1/tbank-sync/{id}"]["get"]["responses"][200]["content"]["application/json"]["resources"][number]; + type ScreenResource = { meta?: ResourceMeta; observe: (version?: string) => Promise; queryKey: QueryKey; transport: { - fetchStatus: "fetching" | "idle" | "paused"; - status: "error" | "pending" | "success"; + fetchStatus: "fetching" + | "idle" + | "paused"; + status: "error" + | "pending" + | "success"; }; }; + const STATUS_INTERVAL_MS = 1000; function observeResource( @@ -38,27 +44,34 @@ function observeResource( if (observed.get(key) === completedId) return; observed.set(key, completedId); void resource.observe().catch(() => {}); + return; } + const changed = [ resource.meta, ...(resource.meta.dependencies ?? []), ].flatMap((current) => { const notified = latest.get(current.resourceKey); + return notified && notified.stateVersion !== current.stateVersion ? [notified] : []; }); + if (changed.length === 0) return; + const notification = JSON.stringify( changed.map(meta => [meta.resourceKey, meta.stateVersion]), ); - if (observed.get(resource.meta.resourceKey) === notification) - return; + + if (observed.get(resource.meta.resourceKey) === notification) return; observed.set(resource.meta.resourceKey, notification); + const own = changed.find( meta => meta.resourceKey === resource.meta?.resourceKey, ); + void resource.observe(own?.stateVersion).catch(() => {}); } @@ -67,17 +80,24 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) { const client = useQueryClient(); const deniedRef = useRef(new Set()); const scopeKey = JSON.stringify(scope); - const [requested, setRequested] = useState(null); + + const [requested, setRequested] = useState(null); + const requestInFlightRef = useRef(null); const currentScopeRef = useRef(scopeKey); useLayoutEffect(() => { currentScopeRef.current = scopeKey; }, [scopeKey]); - const isCurrentMutation = JSON.stringify(mutation.variables?.body) === scopeKey; + + const isCurrentMutation + = JSON.stringify(mutation.variables?.body) === scopeKey; + const observedRef = useRef(new Map()); + const ids = [ ...new Set([ ...(requested?.scope === scopeKey ? [requested.id] : []), @@ -93,6 +113,7 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) { ), ]), ]; + const statuses = useAuthenticatedQueries( ids.map(id => ({ ...apiQueryClient.queryOptions("get", "/api/v1/tbank-sync/{id}", { @@ -101,12 +122,16 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) { refetchInterval: (query: { state: { data?: { state: string }; error: unknown }; }) => - !(query.state.error || (query.state.data && query.state.data.state !== "running")) && STATUS_INTERVAL_MS, + !( + query.state.error + || (query.state.data && query.state.data.state !== "running") + ) && STATUS_INTERVAL_MS, refetchOnMount: false, refetchOnWindowFocus: false, retry: false, })), ); + useEffect(() => { for (const status of statuses) { if (!status.error || deniedRef.current.has(status.error)) { @@ -117,10 +142,16 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) { if (!isApiErrorCode(apiErrorCode(status.error), ApiErrorCode.NotFound)) invalidateResourceAccess(client, "brokerage", status.error); } + const latest = new Map(); - const orderedStatuses = statuses.toSorted((a, b) => a.dataUpdatedAt - b.dataUpdatedAt); + + const orderedStatuses = statuses.toSorted( + (a, b) => a.dataUpdatedAt - b.dataUpdatedAt, + ); + for (const status of orderedStatuses) { const statusResources = status.data?.resources ?? []; + for (const meta of statusResources) { latest.set(meta.resourceKey, meta); const dependencies = meta.dependencies ?? []; @@ -128,10 +159,18 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) { latest.set(dependency.resourceKey, dependency); } } - const completed = statuses.find(status => requested?.scope === scopeKey - && status.data?.id === requested.id && status.data.state !== "running")?.data; - for (const resource of resources) observeResource(resource, latest, completed?.id, observedRef.current); + + const completed = statuses.find( + status => + requested?.scope === scopeKey + && status.data?.id === requested.id + && status.data.state !== "running", + )?.data; + + for (const resource of resources) + observeResource(resource, latest, completed?.id, observedRef.current); }, [client, statuses, resources, requested, scopeKey]); + const isRefreshing = (isCurrentMutation && mutation.isPending) || statuses.some( @@ -139,15 +178,18 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) { ) || resources.some(({ meta }) => { const status = statuses[ids.indexOf(meta?.sync.id ?? "")]; + return ( !status?.isError && (!status?.data || status.data.state === "running") && (meta?.sync.state === "running" || meta?.sync.state === "queued") ); }); + const refresh = async () => { if (isRefreshing || requestInFlightRef.current === scopeKey) return; requestInFlightRef.current = scopeKey; + try { const accepted = await mutation.mutateAsync({ body: scope }); if ( @@ -162,15 +204,20 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) { */ } finally { - if (requestInFlightRef.current === scopeKey) requestInFlightRef.current = /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null; + if (requestInFlightRef.current === scopeKey) + requestInFlightRef.current + + = null; } }; + // Retry failed HTTP reads without asking the source to import again. // A source failure (or explicit refresh with no read error) still needs a sync. const retry = async () => { const failed = resources.filter( resource => resource.transport.status === "error", ); + const failedStatuses = statuses.filter(status => status.isError); if (failed.length > 0 || failedStatuses.length > 0) { await Promise.allSettled([ @@ -180,6 +227,7 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) { } else await refresh(); }; + return { refresh, refreshing: isRefreshing, diff --git a/src/features/tbank-connection/model/sync.test.tsx b/src/features/tbank-connection/model/sync.test.tsx index 7f90b16..d3ede0a 100644 --- a/src/features/tbank-connection/model/sync.test.tsx +++ b/src/features/tbank-connection/model/sync.test.tsx @@ -25,25 +25,30 @@ describe("sync connection and session boundaries", () => { refresh: () => Promise.resolve(true), }); - const { promise: blocked, resolve: release } = Promise.withResolvers(); + const { promise: blocked, resolve: release } + = Promise.withResolvers(); + const accepted = { id: "work", now: "2026-09-25T12:00:00Z", scope: { screen: "accounts" }, }; + let started = 0; let isChanged = false; server.use( http.post("*/api/v1/tbank-sync", async () => { started += 1; await blocked; + return HttpResponse.json(accepted, { status: 202 }); }), http.get("*/api/v1/tbank-sync/:id", async () => { const now = isChanged ? "2026-09-25T12:01:00Z" : accepted.now; started += 1; await blocked; - return HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + + return HttpResponse.json( { ...accepted, errorCode: null, @@ -51,21 +56,25 @@ describe("sync connection and session boundaries", () => { progress: { completed: 1, discovering: false, total: 1 }, resources: [], state: "succeeded", - } - /* eslint-enable unicorn/no-null */)); + }, + ); }), ); const { queryClient, wrapper } = createQueryWrapper(); const published: string[] = []; + const unsubscribe = queryClient.getQueryCache().subscribe((event) => { - if ((event.query.queryKey as readonly unknown[])[1] - !== "/api/v1/tbank-sync/{id}") { + if ( + (event.query.queryKey as readonly unknown[])[1] + !== "/api/v1/tbank-sync/{id}" + ) { return; } const data = event.query.state.data as undefined | { now?: string }; if (data?.now) published.push(data.now); }); + const { result } = renderHook( () => ({ mutation: useTbankSync(), @@ -73,39 +82,48 @@ describe("sync connection and session boundaries", () => { }), { wrapper }, ); + const screen: InvestmentScreen = { screen: "accounts" }; let mutation!: Promise; act(() => { mutation = result.current.mutation.mutateAsync({ body: screen }); }); + // eslint-disable-next-line vitest/valid-expect -- Attach rejection handling before releasing the request; the assertion is awaited below. const discarded = expect(mutation).rejects.toMatchObject({ name: "AbortError", }); + await waitFor(() => expect(started).toBe(2)); await act(async () => { isChanged = true; + if (boundary === "connection") - commitTbankConnectionBoundary(queryClient, (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + commitTbankConnectionBoundary( + + queryClient, { connected: false, connectedAt: null, - } - /* eslint-enable unicorn/no-null */)); + }, + ); else { generation += 1; queryClient.clear(); } + release(); await blocked; }); await discarded; expect(result.current.mutation.data).toBeUndefined(); + const key = apiQueryClient.queryOptions( "get", "/api/v1/tbank-sync/{id}", { params: { path: { id: "work" } } }, ).queryKey; + // A new request may start after a successful connection boundary; an old result cannot win it. if (boundary === "session") // eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch. diff --git a/src/features/tbank-connection/model/sync.ts b/src/features/tbank-connection/model/sync.ts index 578b213..c53e2f6 100644 --- a/src/features/tbank-connection/model/sync.ts +++ b/src/features/tbank-connection/model/sync.ts @@ -6,11 +6,13 @@ import { type InvestmentScreen = paths["/api/v1/tbank-sync"]["post"]["requestBody"]["content"]["application/json"]; + function useTbankSync() { return apiQueryClient.useMutation("post", "/api/v1/tbank-sync", { retry: false, }); } + function useTbankSyncStatus(id: null | string) { return useAuthenticatedQuery({ ...apiQueryClient.queryOptions("get", "/api/v1/tbank-sync/{id}", { diff --git a/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.test.tsx b/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.test.tsx index 8cd01eb..32492fd 100644 --- a/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.test.tsx +++ b/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.test.tsx @@ -21,26 +21,31 @@ const brokerageAccountsQueryKey = apiQueryClient.queryOptions( "get", "/api/v1/brokerage-accounts", ).queryKey; + const portfolioQueryKey = apiQueryClient.queryOptions( "get", "/api/v1/brokerage-accounts/{accountId}/portfolio", { params: { path: { accountId: "account-1" } } }, ).queryKey; + const operationsQueryKey = apiQueryClient.queryOptions( "get", "/api/v1/brokerage-accounts/{accountId}/operations", { params: { path: { accountId: "account-1" } } }, ).queryKey; + const stockQueryKey = apiQueryClient.queryOptions( "get", "/api/v1/stocks/{uid}/position", { params: { path: { uid: "e6123145-9665-43e0-8413-cd61b8aa9b13" } } }, ).queryKey; + const bondQueryKey = apiQueryClient.queryOptions( "get", "/api/v1/bonds/{uid}/position", { params: { path: { uid: "e6123145-9665-43e0-8413-cd61b8aa9b13" } } }, ).queryKey; + const bankCardsQueryKey = apiQueryClient.queryOptions( "get", "/api/v1/bank-cards", @@ -48,6 +53,7 @@ const bankCardsQueryKey = apiQueryClient.queryOptions( params: { query: { includeArchived: "false" } }, }, ).queryKey; + const unrelatedQueryKey = apiQueryClient.queryOptions( "get", "/api/v1/auth/me", @@ -59,6 +65,7 @@ function renderSection(client: QueryClient) { clear: vi.fn(), refresh: () => Promise.resolve(true), }); + return render( @@ -70,21 +77,22 @@ function renderSection(client: QueryClient) { function seededClient() { const client = createTestQueryClient(); + client.setQueryData(brokerageAccountsQueryKey, [ - (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { - id: "account-1", - name: "Основной счет", - openedOn: null, - type: "BROKERAGE", - } - /* eslint-enable unicorn/no-null */), + { + id: "account-1", + name: "Основной счет", + openedOn: null, + type: "BROKERAGE", + }, + ]); client.setQueryData(portfolioQueryKey, { source: "previous-connection" }); client.setQueryData(stockQueryKey, { source: "previous-connection" }); client.setQueryData(bondQueryKey, { source: "previous-connection" }); client.setQueryData(unrelatedQueryKey, { id: "user-1" }); client.setQueryData(bankCardsQueryKey, [{ id: "bank-card-1" }]); + return client; } @@ -92,18 +100,23 @@ describe("TbankConnectionSection", () => { it("preserves cached status and a draft entered during a delayed failed refetch", async () => { const status = { connected: true, connectedAt: "2026-08-14T00:00:00Z" }; - const { promise: response, resolve: finishRefetch } = Promise.withResolvers(); + const { promise: response, resolve: finishRefetch } + = Promise.withResolvers(); + let reads = 0; server.use( http.get("*/api/v1/tbank-connection", async () => { reads += 1; + if (reads === 1) { await response; + return HttpResponse.json( { code: "TBANK_UNAVAILABLE" }, { status: 503 }, ); } + return HttpResponse.json(status); }), ); @@ -141,11 +154,13 @@ describe("TbankConnectionSection", () => { server.use( http.get("*/api/v1/tbank-connection", () => { reads += 1; + return reads === 1 ? HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }) - : HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { connected: false, connectedAt: null } - /* eslint-enable unicorn/no-null */)); + + : HttpResponse.json( + { connected: false, connectedAt: null }, + ); }), ); renderSection(createTestQueryClient()); @@ -244,19 +259,24 @@ describe("TbankConnectionSection", () => { const client = seededClient(); let isAborted = false; - const { promise: previousResponse, resolve: finishPrevious } = Promise.withResolvers<{ source: string }>(); + + const { promise: previousResponse, resolve: finishPrevious } + = Promise.withResolvers<{ source: string }>(); + const previousRequest = client .query({ queryFn: ({ signal }) => { signal.addEventListener("abort", () => { isAborted = true; }); + return previousResponse; }, queryKey: operationsQueryKey, }) // eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering. .catch(() => {}); + renderSection(client); await screen.findByText("Не подключено"); @@ -302,7 +322,9 @@ describe("TbankConnectionSection", () => { it("keeps DELETE recovery inside the dialog and preserves cache until successful retry", async () => { let deletes = 0; - const { promise: response, resolve: finishDelete } = Promise.withResolvers(); + const { promise: response, resolve: finishDelete } + = Promise.withResolvers(); + server.use( http.get("*/api/v1/tbank-connection", () => HttpResponse.json({ @@ -313,6 +335,7 @@ describe("TbankConnectionSection", () => { http.delete("*/api/v1/tbank-connection", async () => { deletes += 1; if (deletes === 1) await response; + return deletes === 1 ? HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }) : new HttpResponse(null, { status: 204 }); @@ -324,9 +347,11 @@ describe("TbankConnectionSection", () => { fireEvent.click( await screen.findByRole("button", { name: "Удалить подключение" }), ); + const dialog = await screen.findByRole("dialog", { name: "Удалить подключение?", }); + await waitFor(() => // eslint-disable-next-line testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish. expect(dialog.contains(document.activeElement)).toBe(true), diff --git a/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.tsx b/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.tsx index 205fd1b..a0a7eac 100644 --- a/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.tsx +++ b/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.tsx @@ -10,7 +10,10 @@ import { TbankConnectionSectionLoaded } from "./TbankConnectionSectionLoaded"; const TbankConnectionSection: FC = () => { const viewModel = useTbankConnectionViewModel(); if (viewModel.state === "loading") return ; - return viewModel.state === "error" ? : ; + + return viewModel.state === "error" + ? + : ; }; export { TbankConnectionSection }; diff --git a/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.view.test.tsx b/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.view.test.tsx index 2029b30..ec68a16 100644 --- a/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.view.test.tsx +++ b/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.view.test.tsx @@ -10,11 +10,13 @@ import { describe("TbankConnectionSection state views", () => { it("renders loading and retries a status error", () => { const retry = vi.fn(); + const { rerender } = render( , ); + expect(screen.getByRole("status", { name: "Загрузка" })).toHaveAttribute( "aria-busy", "true", diff --git a/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.view.tsx b/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.view.tsx index 9fb619c..67730de 100644 --- a/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.view.tsx +++ b/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.view.tsx @@ -14,6 +14,7 @@ const TbankConnectionLoading: FC = () => { return ( + ); diff --git a/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.vm.ts b/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.vm.ts index aa1a587..9507c0e 100644 --- a/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.vm.ts +++ b/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSection.vm.ts @@ -6,9 +6,13 @@ function useTbankConnectionViewModel() { const status = useAuthenticatedQuery({ ...tbankConnectionQueryOptions(), }); + if (!status.data) { - return status.isPending ? { state: "loading" as const } : { retry: () => status.refetch(), state: "error" as const }; + return status.isPending + ? { state: "loading" as const } + : { retry: () => status.refetch(), state: "error" as const }; } + return { refreshError: status.isError, refreshing: status.isFetching, diff --git a/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSectionLoaded.tsx b/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSectionLoaded.tsx index a84bf72..9749021 100644 --- a/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSectionLoaded.tsx +++ b/src/features/tbank-connection/ui/TbankConnectionSection/TbankConnectionSectionLoaded.tsx @@ -8,19 +8,11 @@ import { Stack, Text, } from "@mantine/core"; -import { useQueryClient } from "@tanstack/react-query"; -import { useEffect, useRef, useState } from "react"; -import { useForm } from "react-hook-form"; -import { useTranslation } from "react-i18next"; -import { ApiErrorCode, apiErrorCode, apiQueryClient, isApiErrorCode } from "@/shared/api"; +import { ApiErrorCode, isApiErrorCode } from "@/shared/api"; -import { - commitTbankConnectionBoundary, - type TbankConnectionStatus, -} from "../../model/connection-boundary"; - -enum ConnectionErrorCode { RequestFailed = "REQUEST_ERROR" } +import { type TbankConnectionStatus } from "../../model/connection-boundary"; +import { useTbankConnectionSectionLoadedVm } from "./TbankConnectionSectionLoaded.vm"; type TbankConnectionSectionLoadedProps = { refreshError: boolean; @@ -32,48 +24,29 @@ type TbankConnectionSectionLoadedProps = { const TbankConnectionSectionLoaded: FC = ( props, ) => { - const { status } = props; - const { t } = useTranslation(); - const queryClient = useQueryClient(); - const [isDeleteOpened, setIsDeleteOpened] = useState(false); - const removalButtonRef = useRef(null); - const [requestError, setRequestError] = useState(null); const { - formState: { errors }, - handleSubmit, + errors, + isConnected, + isDeleteOpened, + isPending, + onCloseDisconnect, + onConfirmDisconnect, + onOpenDisconnect, + onSubmit, register, - reset, - } = useForm<{ token: string }>(); - const update = apiQueryClient.useMutation("put", "/api/v1/tbank-connection", { - onError: error => setRequestError(apiErrorCode(error) ?? ConnectionErrorCode.RequestFailed), - onSuccess: (data) => { - commitTbankConnectionBoundary(queryClient, data); - reset(); - }, - }); - const remove = apiQueryClient.useMutation( - "delete", - "/api/v1/tbank-connection", - { - onSuccess: () => { - commitTbankConnectionBoundary(queryClient, { - connected: false, - connectedAt: /* eslint-disable-line unicorn/no-null -- The disconnected API snapshot requires a null connection timestamp. */ null, - }); - setIsDeleteOpened(false); - }, - }, - ); - const unavailableMessage = isApiErrorCode(requestError, ApiErrorCode.TbankUnavailable) ? "tbank.unavailable" : "tbank.requestError"; - const isPending = update.isPending || remove.isPending; - const isConnected = status.connected; - useEffect(() => { - if (isDeleteOpened && remove.isError) removalButtonRef.current?.focus(); - }, [isDeleteOpened, remove.isError]); + removalButtonRef, + remove, + requestError, + status, + t, + unavailableMessage, + update, + } = useTbankConnectionSectionLoadedVm(props); return ( {t("tbank.title")} + {isConnected ? t("tbank.connected", { @@ -83,18 +56,22 @@ const TbankConnectionSectionLoaded: FC = ( }) : t("tbank.disconnected")} + {t("tbank.hint")} + {props.refreshing && ( {t("tbank.refreshing")} )} + {props.refreshError && ( {t("tbank.refreshError")} + + {isConnected && ( - )} + !isPending && setIsDeleteOpened(false)} + onClose={onCloseDisconnect} opened={isDeleteOpened} title={t("tbank.deleteTitle")} > {t("tbank.deleteText")} - {remove.isError && ( - {t("tbank.requestError")} - )} + + {remove.isError && {t("tbank.requestError")}} + + @@ -55,10 +58,12 @@ describe("Upcoming event date filters", () => { server.use( http.all("*/api/v1/*", ({ request }) => { requests.push(request.url); + return new HttpResponse(null, { status: 503 }); }), ); const queryClient = createTestQueryClient(); + const { result } = renderHook(() => useAccountEventsPageViewModel(), { wrapper: ({ children }) => ( @@ -68,6 +73,7 @@ describe("Upcoming event date filters", () => { ), }); + await new Promise(resolve => setTimeout(resolve, 0)); expect(result.current).toEqual({ state: "loading" }); expect(queryClient.isFetching()).toBe(0); @@ -91,20 +97,23 @@ describe("Upcoming event date filters", () => { server.use( http.get("*/api/v1/brokerage-accounts/all/events", ({ request }) => { requested.push(new URL(request.url).search); + return HttpResponse.json( - resource(null, (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + resource( + null, { sync: { errorCode: "TBANK_UNAVAILABLE", id: null, state: "failed", }, - } - /* eslint-enable unicorn/no-null */)), + }, + ), ); }), http.post("*/api/v1/tbank-sync", async ({ request }) => { syncRequests.push(await request.json()); + return HttpResponse.json( { code: "TBANK_UNAVAILABLE" }, { status: 503 }, @@ -113,6 +122,7 @@ describe("Upcoming event date filters", () => { ); const period = Object.fromEntries(new URLSearchParams(search)); const queryClient = createTestQueryClient(); + const { result } = renderHook( () => useAccountEventsPageViewModel("all"), { @@ -125,6 +135,7 @@ describe("Upcoming event date filters", () => { ), }, ); + await waitFor(() => expect(result.current.state).toBe("error")); expect(requested).toEqual([`?${search}`]); expect(syncRequests).toEqual([]); @@ -153,6 +164,7 @@ describe("Upcoming event date filters", () => { "*/api/v1/brokerage-accounts/:accountId/events", ({ request }) => { searches.push(new URL(request.url).search); + return HttpResponse.json(resource({ events: [] })); }, ), @@ -171,6 +183,7 @@ describe("Upcoming event date filters", () => { initialIndex={0} > + } @@ -182,6 +195,7 @@ describe("Upcoming event date filters", () => { , ); await screen.findByLabelText("Период"); + for (const expected of ["", "", "?from=2099-02-01", "?to=2099-02-28"]) { fireEvent.click( screen.getByRole("button", { name: "History forward" }), @@ -192,6 +206,7 @@ describe("Upcoming event date filters", () => { ); await screen.findByLabelText("Период"); } + fireEvent.click(screen.getByRole("button", { name: "History back" })); await waitFor(() => expect(screen.getByLabelText("URL")).toHaveTextContent( @@ -227,6 +242,7 @@ describe("Upcoming event date filters", () => { initialEntries={[`/accounts/${accountId}/events?from=2099-02-01`]} > + } @@ -258,6 +274,7 @@ describe("Upcoming event date filters", () => { "*/api/v1/brokerage-accounts/:accountId/events", ({ request }) => { searches.push(new URL(request.url).search); + return HttpResponse.json( resource({ accountId, @@ -278,6 +295,7 @@ describe("Upcoming event date filters", () => { ]} > + } @@ -333,6 +351,7 @@ it("retains the previous complete forecast and timestamp when its source refresh clear: vi.fn(), refresh: () => Promise.resolve(true), }); + const events = [ { date: "2026-10-01", @@ -341,16 +360,19 @@ it("retains the previous complete forecast and timestamp when its source refresh type: "coupon", }, ]; + const snapshot = resource( { events, incomeTotalsByCurrency: [{ currency: "RUB", value: "123.45" }] }, { sync: { errorCode: "TBANK_UNAVAILABLE", id: "failed", state: "failed" } }, ); + server.use( http.get("*/api/v1/brokerage-accounts/:accountId/events", () => HttpResponse.json(snapshot), ), ); const queryClient = createTestQueryClient(); + const { result } = renderHook(() => useAccountEventsPageViewModel("all"), { wrapper: ({ children }) => ( @@ -358,6 +380,7 @@ it("retains the previous complete forecast and timestamp when its source refresh ), }); + await waitFor(() => expect(result.current).toMatchObject({ events, diff --git a/src/pages/account-events/ui/AccountEventsPage/AccountEventsPage.test.tsx b/src/pages/account-events/ui/AccountEventsPage/AccountEventsPage.test.tsx index 1532319..3d1025c 100644 --- a/src/pages/account-events/ui/AccountEventsPage/AccountEventsPage.test.tsx +++ b/src/pages/account-events/ui/AccountEventsPage/AccountEventsPage.test.tsx @@ -37,7 +37,8 @@ function renderPage() { describe("AccountEventsPage", () => { beforeEach(() => { refresh.mockClear(); - query.mockReturnValue((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + + query.mockReturnValue( { data: { accountId: "account", @@ -51,8 +52,8 @@ describe("AccountEventsPage", () => { sync: { errorCode: null, id: null, state: "idle" }, }, refetch: vi.fn(), - } - /* eslint-enable unicorn/no-null */) as never); + } as never, + ); }); it("passes the selected route account to the query", () => { @@ -72,7 +73,7 @@ describe("AccountEventsPage", () => { }); it("keeps the loading fallback when no result or account is available", () => { - query.mockReturnValue((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + query.mockReturnValue( { data: undefined, isError: false, @@ -82,8 +83,8 @@ describe("AccountEventsPage", () => { sync: { errorCode: null, id: null, state: "idle" }, }, refetch: vi.fn(), - } - /* eslint-enable unicorn/no-null */) as never); + } as never, + ); renderPage(); expect(query).toHaveBeenCalledWith("", {}); expect(screen.getByRole("status", { name: "Загрузка" })).toHaveAttribute( @@ -93,7 +94,7 @@ describe("AccountEventsPage", () => { }); it("renders events and marks an offer without an amount", () => { - query.mockReturnValue((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + query.mockReturnValue( { data: { accountId: "account", @@ -132,8 +133,8 @@ describe("AccountEventsPage", () => { sync: { errorCode: null, id: null, state: "idle" }, }, refetch: vi.fn(), - } - /* eslint-enable unicorn/no-null */) as never); + } as never, + ); renderPage(); expect(screen.getByText("1 250 ₽")).toBeInTheDocument(); expect(screen.getByText("Сумма неизвестна")).toBeInTheDocument(); @@ -180,7 +181,7 @@ describe("AccountEventsPage", () => { }); it("shows a structural busy state before events are available", () => { - query.mockReturnValue((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + query.mockReturnValue( { data: undefined, isError: false, @@ -190,8 +191,8 @@ describe("AccountEventsPage", () => { sync: { errorCode: null, id: null, state: "idle" }, }, refetch: vi.fn(), - } - /* eslint-enable unicorn/no-null */) as never); + } as never, + ); renderPage(); diff --git a/src/pages/account-events/ui/AccountEventsPage/AccountEventsPage.tsx b/src/pages/account-events/ui/AccountEventsPage/AccountEventsPage.tsx index 247e587..33f0160 100644 --- a/src/pages/account-events/ui/AccountEventsPage/AccountEventsPage.tsx +++ b/src/pages/account-events/ui/AccountEventsPage/AccountEventsPage.tsx @@ -10,7 +10,10 @@ type AccountEventsPageProps = { accountId?: string }; const AccountEventsPage: FC = (props) => { const viewModel = useAccountEventsPageViewModel(props.accountId); if (viewModel.state === "loading") return ; - return viewModel.state === "error" ? : ; + + return viewModel.state === "error" + ? + : ; }; export { AccountEventsPage }; diff --git a/src/pages/account-events/ui/AccountEventsPage/AccountEventsPage.vm.ts b/src/pages/account-events/ui/AccountEventsPage/AccountEventsPage.vm.ts index 0fd1c23..20d0a67 100644 --- a/src/pages/account-events/ui/AccountEventsPage/AccountEventsPage.vm.ts +++ b/src/pages/account-events/ui/AccountEventsPage/AccountEventsPage.vm.ts @@ -1,12 +1,12 @@ import { useEffect, useState } from "react"; import { useParams, useSearchParams } from "react-router"; -import { z } from "zod"; import { type BrokerageEvent, useBrokerageEvents, } from "@/entities/brokerage-event"; import { useScreenSync } from "@/features/tbank-connection"; +import { isValidPeriod } from "@/shared/lib"; type AccountEventsPageViewModel = | { @@ -38,8 +38,15 @@ function useAccountEventsPageViewModel( const urlFrom = searchParameters.get("from"); const urlTo = searchParameters.get("to"); const isValidUrlPeriod = isValidPeriod(urlFrom, urlTo); - const appliedFrom = isValidUrlPeriod ? urlFrom : /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null; - const appliedTo = isValidUrlPeriod ? urlTo : /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null; + + const appliedFrom = isValidUrlPeriod + ? urlFrom + : null; + + const appliedTo = isValidUrlPeriod + ? urlTo + : null; + const [draftFrom, setDraftFrom] = useState(appliedFrom); const [draftTo, setDraftTo] = useState(appliedTo); useEffect(() => { @@ -49,19 +56,23 @@ function useAccountEventsPageViewModel( normalized.delete("to"); setSearchParameters(normalized, { replace: true }); }, [isValidUrlPeriod, searchParameters, setSearchParameters]); + const [previousPeriod, setPreviousPeriod] = useState([ appliedFrom, appliedTo, ]); + if (previousPeriod[0] !== appliedFrom || previousPeriod[1] !== appliedTo) { setPreviousPeriod([appliedFrom, appliedTo]); setDraftFrom(appliedFrom); setDraftTo(appliedTo); } + const events = useBrokerageEvents(accountId, { ...(appliedFrom && { from: appliedFrom }), ...(appliedTo && { to: appliedTo }), }); + const sync = useScreenSync( { accountId, @@ -71,12 +82,15 @@ function useAccountEventsPageViewModel( }, [events], ); + if (events.isLoading) return { state: "loading" }; + const onReset = () => { setDraftFrom(null); setDraftTo(null); setSearchParameters({}); }; + if ((events.isError || events.meta?.sync.state === "failed") && !events.data) return { onReset, @@ -86,6 +100,7 @@ function useAccountEventsPageViewModel( state: "error", }; if (!events.data) return { state: "loading" }; + return { canApply: (draftFrom !== appliedFrom || draftTo !== appliedTo) @@ -115,14 +130,4 @@ function useAccountEventsPageViewModel( }; } -const calendarDate = z.iso.date(); -function isValidPeriod(from: null | string, to: null | string) { - return ( - [from, to].every( - date => date === null || calendarDate.safeParse(date).success, - ) - && (!from || !to || from <= to) - ); -} - export { type AccountEventsPageViewModel, useAccountEventsPageViewModel }; diff --git a/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageEmpty.view.tsx b/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageEmpty.view.tsx index 160df64..990a551 100644 --- a/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageEmpty.view.tsx +++ b/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageEmpty.view.tsx @@ -5,9 +5,8 @@ import { useTranslation } from "react-i18next"; const AccountEventsPageEmpty: FC = () => { const { t } = useTranslation(); - return ( - - ); + + return ; }; export { AccountEventsPageEmpty }; diff --git a/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageError.view.tsx b/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageError.view.tsx index dd0156a..9630812 100644 --- a/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageError.view.tsx +++ b/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageError.view.tsx @@ -8,11 +8,13 @@ type AccountEventsPageErrorProps = { onReset: () => void; retry: () => void }; const AccountEventsPageError: FC = (props) => { const { t } = useTranslation(); + return ( + diff --git a/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageLoaded.view.tsx b/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageLoaded.view.tsx index 0415a3f..8956252 100644 --- a/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageLoaded.view.tsx +++ b/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageLoaded.view.tsx @@ -10,7 +10,6 @@ import { Title, } from "@mantine/core"; import { DatePickerInput } from "@mantine/dates"; -import { useTranslation } from "react-i18next"; import { BrokerageEventCard } from "@/entities/brokerage-event"; import { formatSnapshotTime } from "@/shared/lib"; @@ -18,82 +17,90 @@ import { formatSnapshotTime } from "@/shared/lib"; import type { AccountEventsPageViewModel } from "../AccountEventsPage.vm"; import { AccountEventsPageEmpty } from "./AccountEventsPageEmpty.view"; +import { useAccountEventsPageLoadedVm } from "./AccountEventsPageLoaded.vm"; type AccountEventsPageLoadedProps = Extract< AccountEventsPageViewModel, { state: "loaded" } >; -const AccountEventsPageLoaded: FC = (props) => { - const { t } = useTranslation(); - function renderEvents() { - if (props.events.length > 0) { - return ( - - {props.events.map(event => ( - - ))} - - ); - } - if (props.partial) { - return; - } - return ; +const AccountEventsPageLoadedEvents: FC = ( + props, +) => { + if (props.events.length > 0) { + return ( + + {props.events.map(event => ( + + ))} + + ); } + + if (props.partial) { + return; + } + + return ; +}; + +const AccountEventsPageLoaded: FC = (props) => { + const { onPeriodChange, t } = useAccountEventsPageLoadedVm(props); + return ( - {!!(props.lastSuccessfulAt) && (( + {!!props.lastSuccessfulAt && ( {t("investment.sourceTime", { date: formatSnapshotTime(props.lastSuccessfulAt), })} - ))} + )} + {t("events.title")} + - {!!(props.partial) && (( - {t("investment.partial")} - ))} - {!!(props.refreshing) && (( - - ))} - {!!(props.refreshError) && (( + + {!!props.partial && {t("investment.partial")}} + + {!!props.refreshing && } + + {!!props.refreshError && ( {t( props.sourceError ? "investment.syncFailed" : "accounts.refreshError", )} + - ))} + )} + {t("events.hint")} + { - props.onDraftFromChange(from); - props.onDraftToChange(to); - }} + onChange={onPeriodChange} popoverProps={{ middlewares: { shift: { crossAxis: true } }, returnFocus: true, @@ -103,15 +110,18 @@ const AccountEventsPageLoaded: FC = (props) => { valueFormat="DD.MM.YYYY" /> + + - {renderEvents()} + + ); }; diff --git a/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageLoaded.vm.ts b/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageLoaded.vm.ts new file mode 100644 index 0000000..af03a32 --- /dev/null +++ b/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageLoaded.vm.ts @@ -0,0 +1,24 @@ +import { useTranslation } from "react-i18next"; + +import type { AccountEventsPageViewModel } from "../AccountEventsPage.vm"; + +type AccountEventsPageLoadedProps = Extract< + AccountEventsPageViewModel, + { state: "loaded" } +>; + +function useAccountEventsPageLoadedVm(props: AccountEventsPageLoadedProps) { + const { t } = useTranslation(); + + const onPeriodChange: (value: [null | string, null | string]) => void = ([ + from, + to, + ]) => { + props.onDraftFromChange(from); + props.onDraftToChange(to); + }; + + return { onPeriodChange, t }; +} + +export { useAccountEventsPageLoadedVm }; diff --git a/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageLoading.view.tsx b/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageLoading.view.tsx index a9de6bd..42843cb 100644 --- a/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageLoading.view.tsx +++ b/src/pages/account-events/ui/AccountEventsPage/components/AccountEventsPageLoading.view.tsx @@ -8,21 +8,26 @@ const skeletonRowIds = ["first", "second", "third", "fourth"]; const AccountEventsPageLoading: FC = () => { const { t } = useTranslation(); + return ( + + + + + - {skeletonRowIds.map(id => ( - - ))} + + {skeletonRowIds.map(id => )} ); }; diff --git a/src/pages/account-income/model/income.schema.ts b/src/pages/account-income/model/income.schema.ts new file mode 100644 index 0000000..9d22512 --- /dev/null +++ b/src/pages/account-income/model/income.schema.ts @@ -0,0 +1,31 @@ +import { z } from "zod"; + +import { validationMessage } from "@/shared/i18n"; + +import { moscowDate, parseDraftDate } from "./period"; + +const draftDate = z + .string() + .refine(value => parseDraftDate(value) !== null, { + error: validationMessage("income.validation.date"), + }) + .refine( + (value) => { + const date = parseDraftDate(value); + + return !date || date <= moscowDate(new Date()); + }, + { error: validationMessage("income.validation.future") }, + ); + +const incomeFormSchema = z.object({ from: draftDate, to: draftDate }).refine( + ({ from, to }) => { + const start = parseDraftDate(from); + const end = parseDraftDate(to); + + return !start || !end || start <= end; + }, + { path: ["to"], ...validationMessage("income.validation.period")({}) }, +); + +export { incomeFormSchema }; diff --git a/src/pages/account-income/model/period.ts b/src/pages/account-income/model/period.ts index 110e056..4662a7e 100644 --- a/src/pages/account-income/model/period.ts +++ b/src/pages/account-income/model/period.ts @@ -7,12 +7,14 @@ const datePattern = /^\d{4}-\d{2}-\d{2}$/; function formatDraftDate(value: string): string { const [year, month, day] = value.split("-", DATE_PART_COUNT); + return `${day}.${month}.${year}`; } 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, ISO_DATE_LENGTH) === value @@ -26,19 +28,26 @@ function moscowDate(value: Date): string { timeZone: "Europe/Moscow", year: "numeric", }).formatToParts(value); + const part = (type: string) => parts.find(item => item.type === type)?.value; + return `${part("year")}-${part("month")}-${part("day")}`; } function parseDraftDate(value: string): null | string { - if (!/^\d{2}\.\d{2}\.\d{4}$/.test(value)) return /* eslint-disable-line unicorn/no-null -- Mantine date fields use null for an incomplete or invalid date. */ null; + if (!/^\d{2}\.\d{2}\.\d{4}$/.test(value)) + return null; const [day, month, year] = value.split(".", DATE_PART_COUNT); const date = `${year}-${month}-${day}`; - return isDate(date) ? date : /* eslint-disable-line unicorn/no-null -- Mantine date fields use null for an incomplete or invalid date. */ null; + + return isDate(date) + ? date + : null; } -export { formatDraftDate, +export { + formatDraftDate, type IncomePeriod as IncomeForm, type IncomePeriod, isDate, diff --git a/src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.test.tsx b/src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.test.tsx index fe6240e..614b29d 100644 --- a/src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.test.tsx +++ b/src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.test.tsx @@ -1,6 +1,5 @@ import type { FC } from "react"; -import "dayjs/locale/ru"; import { MantineProvider } from "@mantine/core"; import { DatesProvider } from "@mantine/dates"; import { QueryClientProvider } from "@tanstack/react-query"; @@ -13,6 +12,7 @@ import { waitFor, within, } from "@testing-library/react"; +import "dayjs/locale/ru"; import { http, HttpResponse } from "msw"; import { MemoryRouter, @@ -38,49 +38,48 @@ import { } from "./AccountIncomePage.vm"; import { IncomePayments } from "./components/IncomePayments.view"; -const analytics = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ -{ - accountId: "account-1", - bucketGranularity: "day", - buckets: [ - { - period: { from: "2026-08-01", to: "2026-08-01" }, - totalsByCurrency: [summary("RUB", "10", "2")], +const analytics + = { + accountId: "account-1", + bucketGranularity: "day", + buckets: [ + { + period: { from: "2026-08-01", to: "2026-08-01" }, + totalsByCurrency: [summary("RUB", "10", "2")], + }, + ], + calculatedAt: "2026-08-27T00:00:00Z", + entries: [ + entry(), + { + ...entry(), + id: "dividend-1", + payment: money("RUB", "2"), + type: "OPERATION_TYPE_DIVIDEND", + }, + ], + instruments: [ + { + coupon: money("RUB", "10"), + displayName: "BOND", + dividend: money("RUB", "2"), + figi: "FIGI", + instrumentType: "bond", + instrumentUid: null, + key: "income-group-opaque-v2", + receiptCount: 2, + ticker: "BOND", + total: money("RUB", "12"), + }, + ], + period: { from: "2026-08-01", to: "2026-08-27" }, + previous: { + period: { from: "2026-07-01", to: "2026-07-31" }, + totalsByCurrency: [comparison("RUB")], }, - ], - calculatedAt: "2026-08-27T00:00:00Z", - entries: [ - entry(), - { - ...entry(), - id: "dividend-1", - payment: money("RUB", "2"), - type: "OPERATION_TYPE_DIVIDEND", - }, - ], - instruments: [ - { - coupon: money("RUB", "10"), - displayName: "BOND", - dividend: money("RUB", "2"), - figi: "FIGI", - instrumentType: "bond", - instrumentUid: null, - key: "income-group-opaque-v2", - receiptCount: 2, - ticker: "BOND", - total: money("RUB", "12"), - }, - ], - period: { from: "2026-08-01", to: "2026-08-27" }, - previous: { - period: { from: "2026-07-01", to: "2026-07-31" }, - totalsByCurrency: [comparison("RUB")], - }, - totalsByCurrency: [summary("RUB", "10", "2")], - yearComparison: null, -} -/* eslint-enable unicorn/no-null */) satisfies IncomeAnalytics; + totalsByCurrency: [summary("RUB", "10", "2")], + yearComparison: null, + } satisfies IncomeAnalytics; function comparison(currency: string) { return { @@ -92,26 +91,24 @@ function comparison(currency: string) { } function entry(): IncomeAnalytics["entries"][number] { - return (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { - accruedInterest: null, - category: "income", - commission: null, - description: "Купон", - figi: "FIGI", - id: "coupon-1", - instrumentKey: "income-group-opaque-v2", - instrumentType: "bond", - instrumentUid: null, - logoName: null, - occurredAt: "2026-08-01T12:00:00Z", - payment: money("RUB", "10"), - price: null, - quantity: null, - ticker: "BOND", - type: "OPERATION_TYPE_COUPON", - } - /* eslint-enable unicorn/no-null */); + return { + accruedInterest: null, + category: "income", + commission: null, + description: "Купон", + figi: "FIGI", + id: "coupon-1", + instrumentKey: "income-group-opaque-v2", + instrumentType: "bond", + instrumentUid: null, + logoName: null, + occurredAt: "2026-08-01T12:00:00Z", + payment: money("RUB", "10"), + price: null, + quantity: null, + ticker: "BOND", + type: "OPERATION_TYPE_COUPON", + }; } function money(currency: string, value: string) { @@ -125,6 +122,7 @@ function renderPage(search = "from=2026-08-01&to=2026-08-27") { refresh: () => Promise.resolve(true), }); const queryClient = createTestQueryClient(); + const view = render( @@ -133,11 +131,13 @@ function renderPage(search = "from=2026-08-01&to=2026-08-27") { initialEntries={[`/accounts/account-1/income?${search}`]} > + } path="/accounts/:accountId/income" /> + Events} path="/accounts/:accountId/events" @@ -148,6 +148,7 @@ function renderPage(search = "from=2026-08-01&to=2026-08-27") { , ); + return { ...view, queryClient }; } @@ -171,10 +172,12 @@ describe("AccountIncomePage", () => { server.use( http.all("*/api/v1/*", ({ request }) => { requests.push(request.url); + return new HttpResponse(null, { status: 503 }); }), ); const queryClient = createTestQueryClient(); + const { result } = renderHook(() => useAccountIncomePageViewModel(), { wrapper: ({ children }) => ( @@ -184,6 +187,7 @@ describe("AccountIncomePage", () => { ), }); + await new Promise(resolve => setTimeout(resolve, 0)); expect(result.current).toEqual({ state: "loading" }); expect(queryClient.isFetching()).toBe(0); @@ -198,21 +202,24 @@ describe("AccountIncomePage", () => { "*/api/v1/brokerage-accounts/:accountId/income-analytics", ({ request }) => { requested.push(new URL(request.url).search); + return HttpResponse.json( - resource(null, (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + resource( + null, { sync: { errorCode: "TBANK_UNAVAILABLE", id: null, state: "failed", }, - } - /* eslint-enable unicorn/no-null */)), + }, + ), ); }, ), http.post("*/api/v1/tbank-sync", async ({ request }) => { syncRequests.push(await request.json()); + return HttpResponse.json( { code: "TBANK_UNAVAILABLE" }, { status: 503 }, @@ -243,6 +250,7 @@ describe("AccountIncomePage", () => { "*/api/v1/brokerage-accounts/:accountId/income-analytics", ({ request }) => { requested.push(new URL(request.url).search); + return HttpResponse.json(resource(analytics)); }, ), @@ -255,18 +263,21 @@ describe("AccountIncomePage", () => { it("preserves every repeated-ID payment when an open card updates", async () => { const first = { ...entry(), description: "Выплата A", id: "same-id" }; + const second = { ...entry(), description: "Выплата B", id: "same-id", payment: money("RUB", "-2"), }; + const third = { ...entry(), description: "Выплата C", id: "other-id", payment: money("RUB", "1"), }; + function breakdown(entries: IncomeAnalytics["entries"], total: string) { const display = toIncomeDisplayModel({ ...analytics, @@ -281,19 +292,24 @@ describe("AccountIncomePage", () => { }, ], }); + expect(display).not.toBeNull(); + return ( ); } + const { rerender } = render(breakdown([first, second, third], "9")); const panel = await screen.findByRole("region", { name: "Выплаты" }); + const payments = () => within(panel) .getAllByText(/^Выплата [ABC]$/) .map(element => element.textContent); + expect(payments()).toEqual(["Выплата A", "Выплата B", "Выплата C"]); rerender(breakdown([third, first, second], "9")); @@ -323,6 +339,7 @@ describe("AccountIncomePage", () => { analytics.entries[1], ], }; + server.use( http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () => HttpResponse.json(resource(response)), @@ -409,8 +426,8 @@ describe("AccountIncomePage", () => { }); it("renders the signed drill-down using opaque membership rather than instrument identity", async () => { - const response = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { + const response + = { ...analytics, entries: [ { @@ -436,8 +453,8 @@ describe("AccountIncomePage", () => { total: money("RUB", "8"), }, ], - } - /* eslint-enable unicorn/no-null */); + }; + server.use( http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () => HttpResponse.json(resource(response)), @@ -486,9 +503,11 @@ describe("AccountIncomePage", () => { expect(eventsRequest).not.toHaveBeenCalled(); expect(screen.getByRole("region", { name: "Выплаты" })).toBeInTheDocument(); const year = screen.getByRole("region", { name: "Годом ранее" }); + const selected = within(year).getByRole("region", { name: "01.08.2026 – 27.08.2026", }); + expect( screen.getByRole("region", { name: "01.08.2025 – 27.08.2025" }), ).toBeInTheDocument(); @@ -502,13 +521,17 @@ describe("AccountIncomePage", () => { ).toBeInTheDocument(); expect(screen.queryByText("Сравнения")).not.toBeInTheDocument(); expect(screen.queryByText("RUB", { exact: true })).not.toBeInTheDocument(); + for (const amount of ["10 ₽", "2 ₽", "12 ₽"]) { expect(within(selected).getByText(amount)).toBeInTheDocument(); } + const difference = within(year).getByRole("region", { name: "Разница" }); + for (const amount of ["+9 ₽", "+2 ₽", "+11 ₽"]) { expect(within(difference).getByText(amount)).toBeInTheDocument(); } + expect(within(difference).getByText("+900 %")).toBeInTheDocument(); expect(within(difference).getByText("+1 100 %")).toBeInTheDocument(); expect(within(difference).queryByText("нет базы")).not.toBeInTheDocument(); @@ -523,14 +546,13 @@ describe("AccountIncomePage", () => { const dependencies = [ { ...resource(analytics).meta, role: "selected" as const }, { ...resource(analytics).meta, role: "previous" as const }, - ( - { - ...resource(null).meta, - role: "year" as const, - unavailableReason: "CALENDAR_OR_ACCOUNT_HISTORY", - } - ), + { + ...resource(null).meta, + role: "year" as const, + unavailableReason: "CALENDAR_OR_ACCOUNT_HISTORY", + }, ]; + server.use( http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () => HttpResponse.json(resource(analytics, { dependencies })), @@ -572,16 +594,41 @@ describe("income comparison display", () => { ["1", "3", "+33,3 %"], ["0.01", "0.04", "+25 %"], ["123456789012345678.123456789", "123456789012345678.123456789", "+100 %"], - ["10", "0", /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null], - ["0", "0", /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null], - ["10", "-0.00", /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null], - ["10", "-100", /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null], - ["9".repeat(400), "1", /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null], - ["1", "9".repeat(400), /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null], + [ + "10", + "0", + null, + ], + [ + "0", + "0", + null, + ], + [ + "10", + "-0.00", + null, + ], + [ + "10", + "-100", + null, + ], + [ + "9".repeat(400), + "1", + null, + ], + [ + "1", + "9".repeat(400), + null, + ], ])("formats change %s against base %s", (difference, base, expected) => { const value = comparison("RUB"); value.difference.coupon = money("RUB", difference); value.compared.coupon = money("RUB", base); + const display = toIncomeDisplayModel({ ...analytics, yearComparison: { @@ -589,10 +636,13 @@ describe("income comparison display", () => { totalsByCurrency: [value], }, }); + const result = display?.comparison?.values[0]; - expect(result?.percentages.coupon?.replaceAll("\u{A0}", " ") ?? /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null).toBe( - expected, - ); + expect( + result?.percentages.coupon?.replaceAll("\u{A0}", " ") + + ?? null, + ).toBe(expected); expect(result?.difference.coupon.value).toBe(difference); expect(result?.compared.coupon.value).toBe(base); }); @@ -606,6 +656,7 @@ describe("income comparison display", () => { totalsByCurrency: [comparison("RUB"), comparison("USD")], }, }); + expect(display?.comparison?.selectedPeriod.replaceAll(/\s/g, " ")).toBe( "01.12.2025 – 09.01.2026", ); @@ -622,9 +673,11 @@ describe("income comparison display", () => { const LocationProbe: FC = () => { const location = useLocation(); const navigate = useNavigate(); + return ( <> {location.search} + @@ -639,6 +692,7 @@ function respondWithRequestedPeriod(requests: string[]) { ({ request }) => { const url = new URL(request.url); requests.push(url.search); + return HttpResponse.json( resource({ ...analytics, @@ -753,12 +807,15 @@ describe("income period and snapshot boundary", () => { await screen.findByLabelText("Период"); selectPeriod(); - const { promise: pending, resolve: release } = Promise.withResolvers(); + const { promise: pending, resolve: release } + = Promise.withResolvers(); + server.use( http.get( "*/api/v1/brokerage-accounts/account-1/income-analytics", async () => { await pending; + return new HttpResponse(null, { status: 503 }); }, ), @@ -790,7 +847,8 @@ describe("income period and snapshot boundary", () => { ), ), http.get("*/api/v1/tbank-sync/:id", () => - HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + + HttpResponse.json( { errorCode: null, id: "income", @@ -799,8 +857,8 @@ describe("income period and snapshot boundary", () => { resources: [resource(null, { stateVersion: "2" }).meta], scope: null, state: "succeeded", - } - /* eslint-enable unicorn/no-null */)), + }, + ), ), http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () => HttpResponse.json(resource(analytics, { stateVersion: "2" })), @@ -822,12 +880,15 @@ describe("income period and snapshot boundary", () => { renderPage(); await screen.findByLabelText("Период"); - const { promise: pending, resolve: release } = Promise.withResolvers(); + const { promise: pending, resolve: release } + = Promise.withResolvers(); + server.use( http.get( "*/api/v1/brokerage-accounts/account-1/income-analytics", async () => { await pending; + return HttpResponse.json( resource({ ...analytics, @@ -882,6 +943,7 @@ describe("income period and snapshot boundary", () => { total: money("RUB", "-3"), }, ]; + const display = toIncomeDisplayModel({ ...analytics, entries: instruments.map(instrument => ({ @@ -892,6 +954,7 @@ describe("income period and snapshot boundary", () => { instruments, totalsByCurrency: [summary("RUB", "-5", "0"), summary("USD", "10", "0")], }); + render( @@ -917,8 +980,9 @@ describe("income period and snapshot boundary", () => { it("maps comparison notices by role regardless of dependency order or resource key", () => { const selected = { ...resource(analytics).meta, role: "selected" as const }; - const previous = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { + + const previous + = { ...resource(null).meta, resourceKey: "opaque/year-looking-key", role: "previous" as const, @@ -927,16 +991,15 @@ it("maps comparison notices by role regardless of dependency order or resource k id: null, state: "failed" as const, }, - } - /* eslint-enable unicorn/no-null */); - const year = ( - { - ...resource(null).meta, - resourceKey: "opaque/previous-looking-key", - role: "year" as const, - unavailableReason: "CALENDAR_OR_ACCOUNT_HISTORY", - } - ); + }; + + const year = { + ...resource(null).meta, + resourceKey: "opaque/previous-looking-key", + role: "year" as const, + unavailableReason: "CALENDAR_OR_ACCOUNT_HISTORY", + }; + for (const dependencies of [ [selected, previous, year], [year, selected, previous], @@ -945,6 +1008,7 @@ it("maps comparison notices by role regardless of dependency order or resource k ...resource(analytics).meta, dependencies, }); + expect(display?.previousNotice).toBe("comparisonFailed"); expect(display?.yearNotice).toBe("yearUnavailable"); expect(display?.previousComparison).not.toBeNull(); @@ -957,21 +1021,18 @@ it.each([false, true])( server.use( http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () => HttpResponse.json( + resource( - (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { ...analytics, previous: null, yearComparison: null } - /* eslint-enable unicorn/no-null */), - ( - { - dependencies: legacy - ? [ - resource(null).meta, - resource(null).meta, - resource(null).meta, - ] - : [], - } - ), + { ...analytics, previous: null, yearComparison: null }, + { + dependencies: legacy + ? [ + resource(null).meta, + resource(null).meta, + resource(null).meta, + ] + : [], + }, ), ), ), @@ -992,20 +1053,20 @@ it.each([false, true])( it("shows selected income before comparison coverage without inventing a zero baseline", async () => { const dependencies = (["year", "selected", "previous"] as const).map( - role => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { + + role => + ({ ...resource(role === "selected" ? analytics : null).meta, role, - } - /* eslint-enable unicorn/no-null */)), + }), ); + server.use( http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () => HttpResponse.json( + resource( - (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { ...analytics, previous: null, yearComparison: null } - /* eslint-enable unicorn/no-null */), + { ...analytics, previous: null, yearComparison: null }, { dependencies }, ), ), @@ -1031,20 +1092,26 @@ it("shows selected income before comparison coverage without inventing a zero ba it("keeps complete previous comparison while year source failed without inventing its amounts", async () => { const dependencies = [ - { ...resource(analytics).meta, role: "previous" as const }, - (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { - ...resource(null).meta, - role: "year" as const, - sync: { - errorCode: "TBANK_UNAVAILABLE", - id: null, - state: "failed" as const, - }, - } - /* eslint-enable unicorn/no-null */), - { ...resource(analytics).meta, role: "selected" as const }, + { + ...resource(analytics).meta, + role: "previous" as const, + + }, + { + ...resource(null).meta, + role: "year" as const, + sync: { + errorCode: "TBANK_UNAVAILABLE", + id: null, + state: "failed" as const, + }, + }, + { + ...resource(analytics).meta, + role: "selected" as const, + }, ]; + server.use( http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () => HttpResponse.json(resource(analytics, { dependencies })), diff --git a/src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.tsx b/src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.tsx index bdbfab6..d9217bb 100644 --- a/src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.tsx +++ b/src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.tsx @@ -10,7 +10,10 @@ type AccountIncomePageProps = { accountId?: string }; const AccountIncomePage: FC = (props) => { const viewModel = useAccountIncomePageViewModel(props.accountId); if (viewModel.state === "loading") return ; - return viewModel.state === "error" ? : ; + + return viewModel.state === "error" + ? + : ; }; export { AccountIncomePage }; diff --git a/src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.vm.ts b/src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.vm.ts index ef00e28..ab419df 100644 --- a/src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.vm.ts +++ b/src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.vm.ts @@ -2,13 +2,12 @@ import { zodResolver } from "@hookform/resolvers/zod"; import { useEffect, useMemo, useState } from "react"; import { useForm } from "react-hook-form"; import { useParams, useSearchParams } from "react-router"; -import { z } from "zod"; import { type IncomeAnalytics, useIncomeAnalytics } from "@/entities/income"; import { useScreenSync } from "@/features/tbank-connection"; -import { validationMessage } from "@/shared/i18n"; import { formatDate } from "@/shared/lib"; +import { incomeFormSchema } from "../../model/income.schema"; import { formatDraftDate, type IncomeForm, @@ -43,6 +42,7 @@ type AccountIncomePageViewModel state: "error"; } | { state: "loading" }; + type ComparisonNotice = | "comparisonFailed" | "comparisonPending" @@ -50,15 +50,18 @@ type ComparisonNotice | "yearUnavailable"; type IncomeDisplayModel = { - comparison: null | { - comparedPeriod: string; - selectedPeriod: string; - values: (NonNullable< - IncomeAnalytics["yearComparison"] - >["totalsByCurrency"][number] & { - percentages: Record<"coupon" | "dividend" | "total", null | string>; - })[]; - }; + comparison: null + | { + comparedPeriod: string; + selectedPeriod: string; + values: (NonNullable< + IncomeAnalytics["yearComparison"] + >["totalsByCurrency"][number] & { + percentages: Record<"coupon" + | "dividend" + | "total", null | string>; + })[]; + }; entries: { key: string; operation: IncomeAnalytics["entries"][number] }[]; previousComparison: IncomeDisplayModel["comparison"]; previousNotice: ComparisonNotice; @@ -67,33 +70,13 @@ type IncomeDisplayModel = { type IncomeMeta = ReturnType["meta"]; -const draftDate = z - .string() - .refine(value => parseDraftDate(value) !== null, { - error: validationMessage("income.validation.date"), - }) - .refine( - (value) => { - const date = parseDraftDate(value); - return !date || date <= moscowDate(new Date()); - }, - { error: validationMessage("income.validation.future") }, - ); -const incomeFormSchema = z.object({ from: draftDate, to: draftDate }).refine( - ({ from, to }) => { - const start = parseDraftDate(from); - const end = parseDraftDate(to); - return !start || !end || start <= end; - }, - { path: ["to"], ...validationMessage("income.validation.period")({}) }, -); - const useAccountIncomePageViewModel = ( scopeId?: string, ): AccountIncomePageViewModel => { const { accountId: routeAccountId } = useParams(); const accountId = scopeId ?? routeAccountId ?? ""; const [searchParameters, setSearchParameters] = useSearchParams(); + const requested = useMemo( () => ({ from: searchParameters.get("from") ?? "", @@ -101,31 +84,39 @@ const useAccountIncomePageViewModel = ( }), [searchParameters], ); + const period = useMemo( () => (isValidPeriod(requested) ? requested : defaultPeriod()), [requested], ); + const form = useForm({ defaultValues: draftPeriod(period), resolver: zodResolver(incomeFormSchema), }); + const [resetRevision, setResetRevision] = useState(0); const analytics = useIncomeAnalytics(accountId, period); + const sync = useScreenSync( { accountId, from: period.from, screen: "income", to: period.to }, [analytics], ); useEffect(() => { - if (!isValidPeriod(requested)) setSearchParameters(period, { replace: true }); + if (!isValidPeriod(requested)) + setSearchParameters(period, { replace: true }); }, [period, requested, setSearchParameters]); useEffect(() => { form.reset(draftPeriod(period)); }, [form, period]); if (analytics.isLoading || !analytics.data) { - return analytics.isError || analytics.meta?.sync.state === "failed" ? { period, retry: sync.retry, state: "error" } : { state: "loading" }; + return analytics.isError || analytics.meta?.sync.state === "failed" + ? { period, retry: sync.retry, state: "error" } + : { state: "loading" }; } + const display = toIncomeDisplayModel(analytics.data, analytics.meta); if (!display) return { @@ -133,11 +124,13 @@ const useAccountIncomePageViewModel = ( retry: () => analytics.observe(), state: "error", }; + const onSubmit = (values: IncomeForm) => { const from = parseDraftDate(values.from); const to = parseDraftDate(values.to); if (from && to) setSearchParameters({ from, to }); }; + const onReset = () => { const next = defaultPeriod(); form.reset(draftPeriod(next)); @@ -145,6 +138,7 @@ const useAccountIncomePageViewModel = ( setResetRevision(revision => revision + 1); setSearchParameters(next, { replace: true }); }; + return { analytics: analytics.data, display, @@ -166,7 +160,9 @@ function comparisonDisplay( period: IncomePeriod, comparison: IncomeAnalytics["yearComparison"], ): IncomeDisplayModel["comparison"] { - if (!comparison) return /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null; + if (!comparison) + return null; + return { comparedPeriod: formatComparisonPeriod(comparison.period), selectedPeriod: formatComparisonPeriod(period), @@ -192,11 +188,11 @@ function comparisonDisplay( function comparisonNotice( dependency: - | NonNullable["dependencies"]>[number] - | undefined, + NonNullable["dependencies"]>[number] | undefined, unavailable: "previousUnavailable" | "yearUnavailable", ): ComparisonNotice { if (!dependency || dependency.unavailableReason) return unavailable; + return dependency.sync.state === "failed" ? "comparisonFailed" : "comparisonPending"; @@ -204,6 +200,7 @@ function comparisonNotice( function defaultPeriod(): IncomePeriod { const today = moscowDate(new Date()); + return { from: `${today.slice(0, ISO_MONTH_LENGTH)}-01`, to: today }; } @@ -221,9 +218,12 @@ function formatIncomeChange( ): null | string { // Display-only ratio; server-provided Money values remain exact decimal strings. const base = Number(compared); - if (!Number.isFinite(base) || base <= 0) return /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null; + if (!Number.isFinite(base) || base <= 0) + return null; const ratio = Number(difference) / base; - if (!Number.isFinite(ratio)) return /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null; + if (!Number.isFinite(ratio)) + return null; + return new Intl.NumberFormat("ru-RU", { maximumFractionDigits: 1, signDisplay: "exceptZero", @@ -236,6 +236,7 @@ function isValidPeriod(period: IncomePeriod): period is IncomePeriod { const from = new Date(`${period.from}T00:00:00Z`); const to = new Date(`${period.to}T00:00:00Z`); const today = new Date(`${moscowDate(new Date())}T00:00:00Z`); + return ( from.toISOString().slice(0, ISO_DATE_LENGTH) === period.from && to.toISOString().slice(0, ISO_DATE_LENGTH) === period.to @@ -256,9 +257,11 @@ function toIncomeDisplayModel( receiptCount: number; } >(); + const currencies = new Set( analytics.totalsByCurrency.map(({ currency }) => currency), ); + for (const instrument of analytics.instruments) { if ( typeof instrument.key !== "string" @@ -266,7 +269,7 @@ function toIncomeDisplayModel( || instruments.has(instrument.key) || !currencies.has(instrument.total.currency) ) - // eslint-disable-next-line unicorn/no-null -- Preserve the existing nullable validation/ref contract. + return null; instruments.set(instrument.key, { currency: instrument.total.currency, @@ -274,15 +277,15 @@ function toIncomeDisplayModel( receiptCount: instrument.receiptCount, }); } + const entries: IncomeDisplayModel["entries"] = []; const occurrences = new Map(); + for (const entry of analytics.entries) { if (typeof entry.instrumentKey !== "string" || !entry.instrumentKey.trim()) - // eslint-disable-next-line unicorn/no-null -- Preserve the existing nullable validation/ref contract. return null; const instrument = instruments.get(entry.instrumentKey); if (!instrument || entry.payment?.currency !== instrument.currency) - // eslint-disable-next-line unicorn/no-null -- Preserve the existing nullable validation/ref contract. return null; const occurrenceKey = JSON.stringify([entry.instrumentKey, entry.id]); const occurrence = occurrences.get(occurrenceKey) ?? 0; @@ -298,12 +301,15 @@ function toIncomeDisplayModel( operation: entry, }); } + for (const instrument of instruments.values()) { - if (instrument.includedCount !== instrument.receiptCount) return /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null; + if (instrument.includedCount !== instrument.receiptCount) + return null; } const previous = meta?.dependencies?.find(({ role }) => role === "previous"); const year = meta?.dependencies?.find(({ role }) => role === "year"); + return { comparison: comparisonDisplay(analytics.period, analytics.yearComparison), entries, diff --git a/src/pages/account-income/ui/AccountIncomePage/components/AccountIncomePageError.view.tsx b/src/pages/account-income/ui/AccountIncomePage/components/AccountIncomePageError.view.tsx index 51ad1a6..e4603ea 100644 --- a/src/pages/account-income/ui/AccountIncomePage/components/AccountIncomePageError.view.tsx +++ b/src/pages/account-income/ui/AccountIncomePage/components/AccountIncomePageError.view.tsx @@ -10,6 +10,7 @@ type ErrorProps = Extract; const AccountIncomePageError: FC = (props) => { const { t } = useTranslation(); + return ( {t("income.retry")}} diff --git a/src/pages/account-income/ui/AccountIncomePage/components/AccountIncomePageLoaded.view.tsx b/src/pages/account-income/ui/AccountIncomePage/components/AccountIncomePageLoaded.view.tsx index cb5cfcd..91d91d1 100644 --- a/src/pages/account-income/ui/AccountIncomePage/components/AccountIncomePageLoaded.view.tsx +++ b/src/pages/account-income/ui/AccountIncomePage/components/AccountIncomePageLoaded.view.tsx @@ -25,45 +25,42 @@ import { IncomeSummary } from "./IncomeSummary.view"; type LoadedProps = Extract; -const AccountIncomePageLoaded: FC = (props) => { - const { - analytics, - display, - form, - onReset, - onSubmit, - refreshError, - refreshing, - retry, - } = props; +const AccountIncomePageLoadedSummary: FC = (props) => { const { t } = useTranslation(); - function renderSummary() { - if (props.partial) { - return {t("investment.partial")}; - } - if (analytics.totalsByCurrency.length > 0) { - return ; - } - return ( - - ); + + const { analytics } = props; + + if (props.partial) { + return {t("investment.partial")}; } + + return analytics.totalsByCurrency.length > 0 + ? + : ; +}; + +const AccountIncomePageLoaded: FC = (props) => { + const { display, form, onReset, onSubmit, refreshError, refreshing, retry } + = props; + + const { t } = useTranslation(); + return ( - {!!(props.lastSuccessfulAt) && (( + {!!props.lastSuccessfulAt && ( {t("investment.sourceTime", { date: formatSnapshotTime(props.lastSuccessfulAt), })} - ))} + )} + {t("income.title")} + + = (props) => { onSubmit={form.handleSubmit(onSubmit)} /> - {!!(refreshing) && (( + + {!!refreshing && ( + {t("income.refreshing")} - ))} - {!!(refreshError) && (( + )} + + {!!refreshError && ( @@ -87,24 +87,30 @@ const AccountIncomePageLoaded: FC = (props) => { : "income.refreshError", )} + - ))} - {renderSummary()} + )} + + + {t("income.taxBoundary")} + + + ); diff --git a/src/pages/account-income/ui/AccountIncomePage/components/AccountIncomePageLoading.view.tsx b/src/pages/account-income/ui/AccountIncomePage/components/AccountIncomePageLoading.view.tsx index b51136c..235d38d 100644 --- a/src/pages/account-income/ui/AccountIncomePage/components/AccountIncomePageLoading.view.tsx +++ b/src/pages/account-income/ui/AccountIncomePage/components/AccountIncomePageLoading.view.tsx @@ -8,24 +8,34 @@ import classes from "../AccountIncomePage.module.css"; const AccountIncomePageLoading: FC = () => { const { t } = useTranslation(); + return ( + +
+
+
+ + + + +
diff --git a/src/pages/account-income/ui/AccountIncomePage/components/IncomeComparisons.view.tsx b/src/pages/account-income/ui/AccountIncomePage/components/IncomeComparisons.view.tsx index 9acf384..2cd9f14 100644 --- a/src/pages/account-income/ui/AccountIncomePage/components/IncomeComparisons.view.tsx +++ b/src/pages/account-income/ui/AccountIncomePage/components/IncomeComparisons.view.tsx @@ -12,12 +12,16 @@ import classes from "../AccountIncomePage.module.css"; type ComparisonProps = NonNullable & { title: string; }; + type ComparisonValuesProps = { - kind: "compared" | "difference" | "selected"; + kind: "compared" + | "difference" + | "selected"; label: string; percentages?: ComparisonProps["values"][number]["percentages"]; values: ComparisonProps["values"][number]["selected"]; }; + type IncomeComparisonsProps = { comparison: IncomeDisplayModel["comparison"]; notice: string; @@ -28,10 +32,9 @@ const IncomeComparisons: FC = (props) => { return ( {props.title} + {props.comparison - ? ( - - ) + ? : ( @@ -45,6 +48,7 @@ const IncomeComparisons: FC = (props) => { const Comparison: FC = (props) => { const { t } = useTranslation(); + return (
@@ -61,11 +65,13 @@ const Comparison: FC = (props) => { label={props.selectedPeriod} values={value.selected} /> + + = (props) => {
))} - {props.values.length === 0 && (( + + {props.values.length === 0 && ( {t("income.comparisonEmpty")} - ))} + )} ); @@ -87,46 +94,59 @@ const Comparison: FC = (props) => { const ComparisonValues: FC = (props) => { const { t } = useTranslation(); + + const data_tone + = props.kind === "difference" + ? differenceTone(props.values.total.value) + : undefined; + return (
{props.label} +
{(["total", "coupon", "dividend"] as const).map((key) => { - const money = /* eslint-disable-line security/detect-object-injection -- This lookup uses a fixed typed key set, not an arbitrary external property name. */ props.values[key]; - const percentage = /* eslint-disable-line security/detect-object-injection -- This lookup uses a fixed typed key set, not an arbitrary external property name. */ props.percentages?.[key]; + const money + // eslint-disable-next-line security/detect-object-injection -- This lookup uses a fixed typed key set, not an arbitrary external property name. + = props.values[key]; + + const percentage + // eslint-disable-next-line security/detect-object-injection -- This lookup uses a fixed typed key set, not an arbitrary external property name. + = props.percentages?.[key]; + const tone = props.kind === "difference" ? differenceTone(money.value) : undefined; + + const appearanceClass + = key === "total" + ? classes.comparisonTotal + : classes.comparisonDetail; + return ( -
+
{t(`income.${key}`)}
+
{tone === "positive" ? "+" : ""} + {formatMoney(money)} - {!!(percentage) && (( + + {!!percentage && ( {percentage} - ))} + )}
); @@ -136,8 +156,11 @@ const ComparisonValues: FC = (props) => { ); }; -function differenceTone(value: string): "negative" | "neutral" | "positive" { +function differenceTone(value: string): "negative" + | "neutral" + | "positive" { if (!/[1-9]/.test(value)) return "neutral"; + return value.startsWith("-") ? "negative" : "positive"; } diff --git a/src/pages/account-income/ui/AccountIncomePage/components/IncomePayments.view.tsx b/src/pages/account-income/ui/AccountIncomePage/components/IncomePayments.view.tsx index cf418ed..fd85150 100644 --- a/src/pages/account-income/ui/AccountIncomePage/components/IncomePayments.view.tsx +++ b/src/pages/account-income/ui/AccountIncomePage/components/IncomePayments.view.tsx @@ -10,13 +10,16 @@ import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm"; import classes from "../AccountIncomePage.module.css"; type IncomePaymentsProps = { entries: LoadedProps["display"]["entries"] }; + type LoadedProps = Extract; const IncomePayments: FC = (props) => { const { t } = useTranslation(); + return ( {t("income.payments")} + {props.entries.map(({ key, operation }) => (
  • diff --git a/src/pages/account-income/ui/AccountIncomePage/components/IncomePeriodForm/IncomePeriodForm.stories.tsx b/src/pages/account-income/ui/AccountIncomePage/components/IncomePeriodForm/IncomePeriodForm.stories.tsx index 8109871..94b849a 100644 --- a/src/pages/account-income/ui/AccountIncomePage/components/IncomePeriodForm/IncomePeriodForm.stories.tsx +++ b/src/pages/account-income/ui/AccountIncomePage/components/IncomePeriodForm/IncomePeriodForm.stories.tsx @@ -8,6 +8,7 @@ import type { IncomeForm } from "../../../../model/period"; import { IncomePeriodForm } from "./IncomePeriodForm.view"; const period = { from: "01.08.2026", to: "27.08.2026" }; + const errors = { to: { message: "Синтетическая ошибка периода", type: "manual" }, }; @@ -19,8 +20,13 @@ const PeriodExample: FC = (props) => { defaultValues: period, errors: props.invalid ? errors : undefined, }); + const { isSubmitSuccessful } = useFormState({ control: methods.control }); - const submitted = isSubmitSuccessful ? methods.getValues() : /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null; + + const submitted = isSubmitSuccessful + ? methods.getValues() + : null; + return ( = (props) => { }} onSubmit={methods.handleSubmit(() => {})} /> + {submitted ? `Применено: ${submitted.from} – ${submitted.to}` @@ -54,7 +61,9 @@ const meta = { } satisfies Meta; export default meta; + type Story = StoryObj; + export const Default: Story = {}; export const ValidationError: Story = { render: () => , diff --git a/src/pages/account-income/ui/AccountIncomePage/components/IncomePeriodForm/IncomePeriodForm.view.tsx b/src/pages/account-income/ui/AccountIncomePage/components/IncomePeriodForm/IncomePeriodForm.view.tsx index 61d9953..a02faa5 100644 --- a/src/pages/account-income/ui/AccountIncomePage/components/IncomePeriodForm/IncomePeriodForm.view.tsx +++ b/src/pages/account-income/ui/AccountIncomePage/components/IncomePeriodForm/IncomePeriodForm.view.tsx @@ -2,17 +2,9 @@ import type { FC, SubmitEventHandler } from "react"; import { Button, Paper, Stack, Text } from "@mantine/core"; import { DatePickerInput } from "@mantine/dates"; -import { useState } from "react"; -import { useController, useFormContext, useWatch } from "react-hook-form"; -import { useTranslation } from "react-i18next"; -import { - formatDraftDate, - type IncomeForm, - moscowDate, - parseDraftDate, -} from "../../../../model/period"; import classes from "../../AccountIncomePage.module.css"; +import { useIncomePeriodFormVm } from "./IncomePeriodForm.vm"; type IncomePeriodFormProps = { onReset: () => void; @@ -20,23 +12,20 @@ type IncomePeriodFormProps = { }; const IncomePeriodForm: FC = (props) => { - const { t } = useTranslation(); const { - control, - formState: { isSubmitting }, - } = useFormContext(); - const { - field: { onBlur: onFromBlur, onChange: onFromChange, ref: fromRef }, - fieldState: { error: fromError }, - } = useController({ control, name: "from" }); - const { - field: { onBlur: onToBlur, onChange: onToChange }, - fieldState: { error: toError }, - } = useController({ control, name: "to" }); - const [from, to] = useWatch({ control, name: ["from", "to"] }); - const [today, setToday] = useState(() => moscowDate(new Date())); - const start = parseDraftDate(from); - const end = parseDraftDate(to); + end, + fromError, + fromRef, + isSubmitting, + onBlur2, + onPeriodChange, + popoverProps, + start, + t, + today, + toError, + } = useIncomePeriodFormVm(); + return ( = (props) => { > {t("income.period")} +
    = (props) => { error={fromError?.message ?? toError?.message} label={t("income.period")} maxDate={today} - onBlur={() => { - onFromBlur(); - onToBlur(); - }} - onChange={([from, to]) => { - onFromChange(from ? formatDraftDate(from) : ""); - onToChange(to ? formatDraftDate(to) : ""); - }} - popoverProps={{ - middlewares: { shift: { crossAxis: true } }, - onOpen: () => setToday(moscowDate(new Date())), - returnFocus: true, - }} + onBlur={onBlur2} + onChange={onPeriodChange} + popoverProps={popoverProps} ref={fromRef} type="range" value={[start, end]} valueFormat="DD.MM.YYYY" />
    +
    + + @@ -225,6 +227,7 @@ describe("AccountOperationsPage", () => { "*/api/v1/brokerage-accounts/:accountId/operations", ({ request }) => { searches.push(new URL(request.url).searchParams); + return HttpResponse.json( resource({ hasNext: true, @@ -249,6 +252,7 @@ describe("AccountOperationsPage", () => { initialIndex={0} > + } @@ -262,6 +266,7 @@ describe("AccountOperationsPage", () => { await screen.findByLabelText("Период"); expect(searches[0].get("from")).toBeNull(); expect(searches[0].get("to")).toBeNull(); + for (const expected of [ "?categories=trade", "?categories=trade", @@ -276,6 +281,7 @@ describe("AccountOperationsPage", () => { ); await screen.findByLabelText("Период"); } + expect(searches.at(-1)?.get("from")).toBe("2026-02-01T00:00:00.000Z"); expect(searches.at(-1)?.get("to")).toBeNull(); fireEvent.click(screen.getByRole("button", { name: "Далее" })); @@ -313,9 +319,10 @@ describe("AccountOperationsPage", () => { new URL(request.url).searchParams.has("from") ? HttpResponse.json({ code: "VALIDATION_ERROR" }, { status: 400 }) : HttpResponse.json( - resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { hasNext: false, items: [], nextCursor: null } - /* eslint-enable unicorn/no-null */)), + + resource( + { hasNext: false, items: [], nextCursor: null }, + ), ), ), ); @@ -328,6 +335,7 @@ describe("AccountOperationsPage", () => { ]} > + } @@ -354,16 +362,18 @@ describe("AccountOperationsPage", () => { ({ request }) => { const url = new URL(request.url); searches.push(url.search); + return HttpResponse.json( - resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + + resource( { accountId: "account-1", hasNext: !url.searchParams.get("cursor"), items: [operation], nextCursor: url.searchParams.get("cursor") ? null : "next-1", observedAt: "2026-08-14T00:00:00Z", - } - /* eslint-enable unicorn/no-null */)), + }, + ), ); }, ), @@ -394,16 +404,18 @@ describe("AccountOperationsPage", () => { ({ request }) => { const url = new URL(request.url); searches.push(url.search); + return HttpResponse.json( - resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + + resource( { accountId: "account-1", hasNext: false, items: [operation], nextCursor: null, observedAt: "2026-08-14T00:00:00Z", - } - /* eslint-enable unicorn/no-null */)), + }, + ), ); }, ), @@ -431,16 +443,18 @@ describe("AccountOperationsPage", () => { ({ request }) => { const url = new URL(request.url); searches.push(url.search); + return HttpResponse.json( - resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + + resource( { accountId: "account-1", hasNext: false, items: [operation], nextCursor: null, observedAt: "2026-08-14T00:00:00Z", - } - /* eslint-enable unicorn/no-null */)), + }, + ), ); }, ), @@ -484,17 +498,24 @@ it("keeps UTC operation boundaries in GET and source sync requests", async () => "*/api/v1/brokerage-accounts/:accountId/operations", ({ request }) => { requested.push(Object.fromEntries(new URL(request.url).searchParams)); + return HttpResponse.json( - resource(null, (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + resource( + null, { - sync: { errorCode: "TBANK_UNAVAILABLE", id: null, state: "failed" }, - } - /* eslint-enable unicorn/no-null */)), + sync: { + errorCode: "TBANK_UNAVAILABLE", + id: null, + state: "failed", + }, + }, + ), ); }, ), http.post("*/api/v1/tbank-sync", async ({ request }) => { syncRequests.push(await request.json()); + return HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }); }), ); @@ -529,15 +550,14 @@ it("does not label incomplete empty operations as a confirmed empty period", asy server.use( http.get("*/api/v1/brokerage-accounts/:accountId/operations", () => HttpResponse.json( + resource( - (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { - accountId: "account-1", - hasNext: false, - items: [], - nextCursor: null, - } - /* eslint-enable unicorn/no-null */), + { + accountId: "account-1", + hasNext: false, + items: [], + nextCursor: null, + }, { availability: "partial" }, ), ), @@ -562,6 +582,7 @@ it("recovers an invalid cursor at the first page without clearing applied filter { code: "INVALID_OPERATIONS_CURSOR" }, { status: 400 }, ); + return HttpResponse.json( resource({ hasNext: true, diff --git a/src/pages/account-operations/ui/AccountOperationsPage/AccountOperationsPage.tsx b/src/pages/account-operations/ui/AccountOperationsPage/AccountOperationsPage.tsx index 1ed7045..b001e41 100644 --- a/src/pages/account-operations/ui/AccountOperationsPage/AccountOperationsPage.tsx +++ b/src/pages/account-operations/ui/AccountOperationsPage/AccountOperationsPage.tsx @@ -14,7 +14,9 @@ const AccountOperationsPage: FC = (props) => { return ; } - return viewModel.state === "error" ? : ; + return viewModel.state === "error" + ? + : ; }; export { AccountOperationsPage }; diff --git a/src/pages/account-operations/ui/AccountOperationsPage/AccountOperationsPage.vm.ts b/src/pages/account-operations/ui/AccountOperationsPage/AccountOperationsPage.vm.ts index dd7b799..ed1676b 100644 --- a/src/pages/account-operations/ui/AccountOperationsPage/AccountOperationsPage.vm.ts +++ b/src/pages/account-operations/ui/AccountOperationsPage/AccountOperationsPage.vm.ts @@ -1,7 +1,6 @@ import { useQueryClient } from "@tanstack/react-query"; import { useEffect, useState } from "react"; import { useParams, useSearchParams } from "react-router"; -import { z } from "zod"; import { type BrokerageOperation, @@ -12,6 +11,7 @@ import { } from "@/entities/broker-operation"; import { useScreenSync } from "@/features/tbank-connection"; import { ApiErrorCode, apiErrorCode, isApiErrorCode } from "@/shared/api"; +import { isValidPeriod } from "@/shared/lib"; type AccountOperationsPageViewModel = | { @@ -51,30 +51,44 @@ const useAccountOperationsPageVm = ( const urlFrom = searchParameters.get("from"); const urlTo = searchParameters.get("to"); const isValidUrlPeriod = isValidPeriod(urlFrom, urlTo); - const appliedFrom = isValidUrlPeriod ? urlFrom : /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null; - const appliedTo = isValidUrlPeriod ? urlTo : /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null; + + const appliedFrom = isValidUrlPeriod + ? urlFrom + : null; + + const appliedTo = isValidUrlPeriod + ? urlTo + : null; + const appliedCategories = operationCategories.filter(category => (searchParameters.get("categories") ?? "").split(",").includes(category), ); + const [draftFrom, setDraftFrom] = useState(appliedFrom); const [draftTo, setDraftTo] = useState(appliedTo); + const [draftCategories, setDraftCategories] = useState(appliedCategories); + const scopeKey = JSON.stringify([ accountId, urlFrom, urlTo, appliedCategories, ]); + const [pagination, setPagination] = useState<{ cursors: string[]; scopeKey: string; }>({ cursors: [], scopeKey }); + const cursors = pagination.scopeKey === scopeKey ? pagination.cursors : []; const cursor = cursors.at(-1); + if (pagination.scopeKey !== scopeKey) { setPagination({ cursors: [], scopeKey }); } + useEffect(() => { if (isValidUrlPeriod) return; const normalized = new URLSearchParams(searchParameters); @@ -83,38 +97,52 @@ const useAccountOperationsPageVm = ( setSearchParameters(normalized, { replace: true }); }, [isValidUrlPeriod, searchParameters, setSearchParameters]); const [previousSearch, setPreviousSearch] = useState(searchParameters); + if (previousSearch !== searchParameters) { setPreviousSearch(searchParameters); setDraftFrom(appliedFrom); setDraftTo(appliedTo); setDraftCategories( operationCategories.filter(category => - (searchParameters.get("categories") ?? "").split(",").includes(category), + (searchParameters.get("categories") ?? "") + .split(",") + .includes(category), ), ); } + const firstPageQuery = { from: dateStart(appliedFrom), to: dateEnd(appliedTo), - ...((appliedCategories.length > 0) && { categories: appliedCategories }), + ...(appliedCategories.length > 0 && { categories: appliedCategories }), limit: 100, }; + const operations = useBrokerageOperations(accountId, { ...firstPageQuery, ...(cursor && { cursor }), }); + const sync = useScreenSync( { accountId, screen: "operations", ...firstPageQuery }, [operations], ); + if (operations.isLoading) return { state: "loading" }; + const resetQueryKey = brokerageOperationsQueryOptions(accountId, { limit: 100, }).queryKey; const resetCursors = () => setPagination({ cursors: [], scopeKey }); + const retry = () => { - if (isApiErrorCode(apiErrorCode(operations.error), ApiErrorCode.InvalidOperationsCursor)) { + if ( + isApiErrorCode( + apiErrorCode(operations.error), + ApiErrorCode.InvalidOperationsCursor, + ) + ) { void queryClient.invalidateQueries({ exact: true, queryKey: brokerageOperationsQueryOptions(accountId, firstPageQuery) @@ -124,6 +152,7 @@ const useAccountOperationsPageVm = ( } else void sync.retry(); }; + const onReset = () => { setDraftFrom(null); setDraftTo(null); @@ -136,7 +165,10 @@ const useAccountOperationsPageVm = ( if ( (operations.isError || operations.meta?.sync.state === "failed") && (!operations.data - || isApiErrorCode(apiErrorCode(operations.error), ApiErrorCode.InvalidOperationsCursor)) + || isApiErrorCode( + apiErrorCode(operations.error), + ApiErrorCode.InvalidOperationsCursor, + )) ) return { onReset, retry, state: "error" }; if (!operations.data) return { state: "loading" }; @@ -164,7 +196,9 @@ const useAccountOperationsPageVm = ( setSearchParameters({ ...(draftFrom && { from: draftFrom }), ...(draftTo && { to: draftTo }), - ...((draftCategories.length > 0) && { categories: draftCategories.join(",") }), + ...(draftCategories.length > 0 && { + categories: draftCategories.join(","), + }), }); resetCursors(); }, @@ -187,7 +221,6 @@ const useAccountOperationsPageVm = ( }; }; -const calendarDate = z.iso.date(); function dateEnd(value: null | string) { return value ? `${value}T23:59:59.999Z` : undefined; } @@ -200,13 +233,4 @@ function isSameCategories(a: OperationCategory[], b: OperationCategory[]) { return a.length === b.length && a.every(value => b.includes(value)); } -function isValidPeriod(from: null | string, to: null | string) { - return ( - [from, to].every( - date => date === null || calendarDate.safeParse(date).success, - ) - && (!from || !to || from <= to) - ); -} - export { type AccountOperationsPageViewModel, useAccountOperationsPageVm }; diff --git a/src/pages/account-operations/ui/AccountOperationsPage/components/AccountOperationsPageError.view.tsx b/src/pages/account-operations/ui/AccountOperationsPage/components/AccountOperationsPageError.view.tsx index 3a8e4cb..fd1fdf6 100644 --- a/src/pages/account-operations/ui/AccountOperationsPage/components/AccountOperationsPageError.view.tsx +++ b/src/pages/account-operations/ui/AccountOperationsPage/components/AccountOperationsPageError.view.tsx @@ -22,6 +22,7 @@ const AccountOperationsPageError: FC = ( action={( + diff --git a/src/pages/account-operations/ui/AccountOperationsPage/components/AccountOperationsPageLoaded.view.tsx b/src/pages/account-operations/ui/AccountOperationsPage/components/AccountOperationsPageLoaded.view.tsx index 84d7fa1..c981e79 100644 --- a/src/pages/account-operations/ui/AccountOperationsPage/components/AccountOperationsPageLoaded.view.tsx +++ b/src/pages/account-operations/ui/AccountOperationsPage/components/AccountOperationsPageLoaded.view.tsx @@ -1,4 +1,4 @@ -import type { FC, ReactNode } from "react"; +import type { FC } from "react"; import { Alert, @@ -14,120 +14,108 @@ import { DatePickerInput } from "@mantine/dates"; import { StateView } from "@wealthledger/ui"; import { useTranslation } from "react-i18next"; -import { - LedgerEntryRow, - operationCategories, - type OperationCategory, -} from "@/entities/broker-operation"; +import { LedgerEntryRow } from "@/entities/broker-operation"; import { formatSnapshotTime } from "@/shared/lib"; import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm"; +import { useAccountOperationsPageLoadedVm } from "./AccountOperationsPageLoaded.vm"; + type AccountOperationsPageLoadedProps = Extract< AccountOperationsPageViewModel, { state: "loaded" } >; -const operationCategorySet = new Set(operationCategories); +const AccountOperationsPageLoadedOperations: FC< + AccountOperationsPageLoadedProps +> = (props) => { // eslint-disable-line sonarjs/function-return-type -- React renders elements and lists. + const { t } = useTranslation(); -function fromMultiSelectValue(value: string[]) { - return value.filter((item): item is OperationCategory => - operationCategorySet.has(item), - ); -} + const { items } = props; + + if (items.length > 0) { + return items.map(operation => ( + + )); + } + + if (props.partial) { + return; + } + + return ; +}; const AccountOperationsPageLoaded: FC = ( props, ) => { const { canApply, + categoryData, draftCategories, draftFrom, draftTo, hasNext, hasPrevious, - items, onApply, - onDraftCategoriesChange, - onDraftFromChange, - onDraftToChange, + onCategoriesChange, onNext, + onPeriodChange, onPrevious, onReset, - } = props; - const { t } = useTranslation(); + t, + } = useAccountOperationsPageLoadedVm(props); - const categoryData = operationCategories.map(category => ({ - label: t(`ledger.category.${category}`), - value: category, - })); - - // eslint-disable-next-line sonarjs/function-return-type -- ReactNode deliberately includes lists, elements and empty output. - function renderOperations(): ReactNode { - if (items.length > 0) { - return items.map(operation => ( - - )); - } - if (props.partial) { - return; - } - return ( - - ); - } return ( - {!!(props.lastSuccessfulAt) && (( + {!!props.lastSuccessfulAt && ( {t("investment.sourceTime", { date: formatSnapshotTime(props.lastSuccessfulAt), })} - ))} + )} + {t("ledger.title")} + - {!!(props.partial) && (( - {t("investment.partial")} - ))} - {!!(props.historyLoading) && ({t("investment.history")})} - {!!(props.refreshing) && (( - - ))} - {!!(props.refreshError) && (( + + {!!props.partial && {t("investment.partial")}} + + {!!props.historyLoading && {t("investment.history")}} + + {!!props.refreshing && } + + {!!props.refreshError && ( {t( props.sourceError ? "investment.syncFailed" : "accounts.refreshError", )} + - ))} + )} + { - onDraftFromChange(from); - onDraftToChange(to); - }} + onChange={onPeriodChange} popoverProps={{ middlewares: { shift: { crossAxis: true } }, returnFocus: true, @@ -137,35 +125,40 @@ const AccountOperationsPageLoaded: FC = ( valueFormat="DD.MM.YYYY" /> + - onDraftCategoriesChange(fromMultiSelectValue(value))} + onChange={onCategoriesChange} placeholder={t("ledger.categoriesPlaceholder")} value={draftCategories} /> + + - {renderOperations()} - {!!(hasNext || hasPrevious) && (( + + + + {!!(hasNext || hasPrevious) && ( + - ))} + )} ); }; diff --git a/src/pages/account-operations/ui/AccountOperationsPage/components/AccountOperationsPageLoaded.vm.ts b/src/pages/account-operations/ui/AccountOperationsPage/components/AccountOperationsPageLoaded.vm.ts new file mode 100644 index 0000000..5ee01cc --- /dev/null +++ b/src/pages/account-operations/ui/AccountOperationsPage/components/AccountOperationsPageLoaded.vm.ts @@ -0,0 +1,78 @@ +import { useTranslation } from "react-i18next"; + +import { + operationCategories, + type OperationCategory, +} from "@/entities/broker-operation"; + +import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm"; + +type AccountOperationsPageLoadedProps = Extract< + AccountOperationsPageViewModel, + { state: "loaded" } +>; + +const operationCategorySet = new Set(operationCategories); + +function fromMultiSelectValue(value: string[]) { + return value.filter((item): item is OperationCategory => + operationCategorySet.has(item), + ); +} + +function useAccountOperationsPageLoadedVm( + props: AccountOperationsPageLoadedProps, +) { + const { + canApply, + draftCategories, + draftFrom, + draftTo, + hasNext, + hasPrevious, + onApply, + onDraftCategoriesChange, + onDraftFromChange, + onDraftToChange, + onNext, + onPrevious, + onReset, + } = props; + + const { t } = useTranslation(); + + const categoryData = operationCategories.map(category => ({ + label: t(`ledger.category.${category}`), + value: category, + })); + + const onPeriodChange: (value: [null | string, null | string]) => void = ([ + from, + to, + ]) => { + onDraftFromChange(from); + onDraftToChange(to); + }; + + const onCategoriesChange: (value: string[]) => void = value => + onDraftCategoriesChange(fromMultiSelectValue(value)); + + return { + canApply, + categoryData, + draftCategories, + draftFrom, + draftTo, + hasNext, + hasPrevious, + onApply, + onCategoriesChange, + onNext, + onPeriodChange, + onPrevious, + onReset, + t, + }; +} + +export { useAccountOperationsPageLoadedVm }; diff --git a/src/pages/account-operations/ui/AccountOperationsPage/components/AccountOperationsPageLoading.view.tsx b/src/pages/account-operations/ui/AccountOperationsPage/components/AccountOperationsPageLoading.view.tsx index fbbcc98..cacaf1d 100644 --- a/src/pages/account-operations/ui/AccountOperationsPage/components/AccountOperationsPageLoading.view.tsx +++ b/src/pages/account-operations/ui/AccountOperationsPage/components/AccountOperationsPageLoading.view.tsx @@ -12,19 +12,23 @@ const AccountOperationsPageLoading: FC = () => { return ( + + + + + + - {skeletonRowIds.map(id => ( - - ))} + {skeletonRowIds.map(id => )} ); diff --git a/src/pages/account/ui/AccountPage/AccountPage.test.tsx b/src/pages/account/ui/AccountPage/AccountPage.test.tsx index ab19dbf..7bb0fe7 100644 --- a/src/pages/account/ui/AccountPage/AccountPage.test.tsx +++ b/src/pages/account/ui/AccountPage/AccountPage.test.tsx @@ -41,6 +41,7 @@ function configureTestAuth() { function renderAccountRoute(queryClient: QueryClient) { configureTestAuth(); + return render( @@ -56,6 +57,7 @@ function renderAccountRoute(queryClient: QueryClient) { function renderPage(ui: React.ReactNode) { const queryClient = createTestQueryClient(); + return render( @@ -65,8 +67,8 @@ function renderPage(ui: React.ReactNode) { ); } -const portfolio: Portfolio = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { +const portfolio: Portfolio + = { cashBalances: [{ currency: "USD", value: "0.5" }], isStale: true, lastSuccessfulAt: "2026-08-13T10:00:00Z", @@ -98,8 +100,7 @@ const portfolio: Portfolio = (/* eslint-disable unicorn/no-null -- Fixture prese ], structure: { currencies: [], unvaluedCategories: [] }, totalsByCurrency: [{ currency: "RUB", value: "1234.5" }], - } -/* eslint-enable unicorn/no-null */); + }; const emptyRecentOperations: AccountPageRecentOperations = { state: "empty", @@ -141,16 +142,17 @@ describe("AccountPage states", () => { const slug = type === "STOCK" ? "SBERP" : "SU26238RMFS4"; const uid = "c190ff1f-1447-4227-b543-316332699ca5"; const requests = vi.fn(); - const position = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { + + const position + = { ...portfolio.positions[0], displayName: hasMetadata ? "Сбербанк привилегированные" : "FIGI-2", instrumentUid: uid, logoName: hasMetadata ? "vtoraya.png" : null, ticker: hasMetadata ? slug : null, type, - } - /* eslint-enable unicorn/no-null */); + }; + server.use( http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () => HttpResponse.json( @@ -168,6 +170,7 @@ describe("AccountPage states", () => { ), http.get(`*/api/v1/${collection}/:uid`, () => { requests(); + return HttpResponse.json( resource({ instrumentUid: uid, @@ -186,6 +189,7 @@ describe("AccountPage states", () => { const links = screen.getAllByRole("link", { name: position.displayName, }); + expect(links).toHaveLength(2); for (const link of links) expect(link).toHaveAttribute( @@ -234,6 +238,7 @@ describe("AccountPage states", () => { ), http.get("*/api/v1/stocks/:uid", () => { requests(); + return scenario === "unavailable" ? HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }) : HttpResponse.json(resource({ instrumentUid: uid, slug: uid })); @@ -286,15 +291,12 @@ describe("AccountPage states", () => { }, ); - it.each(["TBANK_UNAVAILABLE", "UNKNOWN"])( - "allows retry for %s", - (code) => { - const retry = vi.fn(); - renderPage(); - fireEvent.click(screen.getByRole("button", { name: "Повторить" })); - expect(retry).toHaveBeenCalledOnce(); - }, - ); + it.each(["TBANK_UNAVAILABLE", "UNKNOWN"])("allows retry for %s", (code) => { + const retry = vi.fn(); + renderPage(); + fireEvent.click(screen.getByRole("button", { name: "Повторить" })); + expect(retry).toHaveBeenCalledOnce(); + }); it("shows supplied cash separately without adding currency instruments or recalculating totals", () => { renderPage( @@ -320,9 +322,11 @@ describe("AccountPage states", () => { })} />, ); + const balances = within( screen.getByRole("region", { name: "Денежные остатки" }), ); + expect( balances.getAllByRole("definition").map(node => node.textContent), ).toEqual(["234,500000000000000001 ₽", "-0,5 $", "3,00 XYZ"]); @@ -376,6 +380,7 @@ describe("AccountPage states", () => { structure: { currencies: [], unvaluedCategories: [] }, totalsByCurrency, }; + server.use( http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () => HttpResponse.json(resource(snapshot)), @@ -447,9 +452,11 @@ describe("AccountPage states", () => { expect( screen.getByRole("button", { name: "Облигации" }), ).toBeInTheDocument(); + const positions = screen .getAllByText(/Вторая|Первая/) .map(element => element.textContent); + expect(positions).toEqual(["Вторая", "Первая"]); expect(screen.getByText("10 ₽")).toBeInTheDocument(); expect(screen.getByText("-1 ₽")).toBeInTheDocument(); @@ -470,7 +477,7 @@ describe("AccountPage states", () => { it("renders stock cards with logo fallback and signed unlabeled return", () => { renderPage( { type: "STOCK", }, ], - } - /* eslint-enable unicorn/no-null */))} + }, + )} />, ); expect(screen.getByText("А")).toBeInTheDocument(); @@ -513,7 +520,7 @@ describe("AccountPage states", () => { it("groups stock supporting metrics into quiet single lines", () => { renderPage( { type: "STOCK", }, ], - } - /* eslint-enable unicorn/no-null */))} + }, + )} />, ); @@ -546,7 +553,7 @@ describe("AccountPage states", () => { it("uses the ticker only for stock cards and otherwise keeps the ISIN", () => { renderPage( { type: "BOND", }, ], - } - /* eslint-enable unicorn/no-null */))} + }, + )} />, ); @@ -604,7 +611,7 @@ describe("AccountPage states", () => { it("renders bond cards with logo, fallback, and signed unlabeled return like stocks", () => { renderPage( { type: "BOND", }, ], - } - /* eslint-enable unicorn/no-null */))} + }, + )} />, ); expect(screen.getByRole("img", { name: "Долг" })).toHaveAttribute( @@ -653,7 +660,7 @@ describe("AccountPage states", () => { it("renders bond cards in expanded layout with bond-specific classes", () => { renderPage( { type: "BOND", }, ], - } - /* eslint-enable unicorn/no-null */))} + }, + )} />, ); expect(screen.getByText("О")).toBeInTheDocument(); @@ -684,7 +691,7 @@ describe("AccountPage states", () => { it("keeps other-position cards compact with labeled return and no logo", () => { renderPage( { type: "FUND", }, ], - } - /* eslint-enable unicorn/no-null */))} + }, + )} />, ); expect(screen.getByText("Доход: -5 ₽")).toBeInTheDocument(); @@ -713,15 +720,14 @@ describe("AccountPage states", () => { renderPage( , ); expect( @@ -750,31 +756,30 @@ describe("AccountPage states", () => { renderPage( , ); @@ -783,8 +788,8 @@ describe("AccountPage states", () => { }); it("keeps future events ordered with calendar dates and projected rather than posted amounts", () => { - const event: BrokerageEvent = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { + const event: BrokerageEvent + = { date: "2026-09-10", dateKind: "event", displayName: "Облигация", @@ -795,52 +800,53 @@ describe("AccountPage states", () => { projectedAmount: { currency: "RUB", value: "850.50" }, ticker: "DEMO", type: "coupon", - } - /* eslint-enable unicorn/no-null */); + }; + renderPage( , ); const section = screen.getByRole("region", { name: "Будущие события" }); const content = within(section); const text = section.textContent ?? ""; + const titles = [ "Купон · Облигация", "Дивиденд · Акция", "Погашение · Облигация", "Оферта · Облигация", ]; + for (const title of titles) expect(content.getByText(title)).toBeVisible(); expect(titles.map(title => text.indexOf(title))).toEqual( titles.map(title => text.indexOf(title)).toSorted((a, b) => a - b), @@ -870,13 +876,16 @@ describe("AccountPage states", () => { recentEvents={{ state, to: "/accounts/account-1/events" }} />, ); + const content = within( screen.getByRole("region", { name: "Будущие события" }), ); + if (state === "loading") { const skeleton = content.getByRole("status", { name: "Загрузка будущих событий", }); + // eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch. expect(skeleton).toHaveAttribute("aria-busy", "true"); // eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch. @@ -888,6 +897,7 @@ describe("AccountPage states", () => { content.getByText("На ближайшие 30 дней событий не найдено."), ).toBeVisible(); } + expect( content.getByRole("link", { name: "Открыть будущие события" }), ).toHaveAttribute("href", "/accounts/account-1/events"); @@ -914,8 +924,8 @@ describe("AccountPage states", () => { it.each([503])( "preserves totals and UTC snapshot through refresh error %i, retry and success", async (status) => { - const initialPortfolio: Portfolio = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { + const initialPortfolio: Portfolio + = { ...portfolio, structure: { currencies: [ @@ -928,8 +938,8 @@ describe("AccountPage states", () => { ], unvaluedCategories: [{ count: 1, type: "STOCK" }], }, - } - /* eslint-enable unicorn/no-null */); + }; + let requestCount = 0; let resolveRetry: ((response: Response) => void) | undefined; server.use( @@ -944,7 +954,8 @@ describe("AccountPage states", () => { ), ), http.get("*/api/v1/tbank-sync/:id", () => - HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + + HttpResponse.json( { errorCode: null, id: "overview", @@ -956,8 +967,8 @@ describe("AccountPage states", () => { ], scope: { accountId: "account-1", screen: "account" }, state: "succeeded", - } - /* eslint-enable unicorn/no-null */)), + }, + ), ), http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () => { requestCount += 1; @@ -965,11 +976,14 @@ describe("AccountPage states", () => { return HttpResponse.json( resource(initialPortfolio, { resourceKey: "portfolio" }), ); + if (requestCount === 3) { const deferred = Promise.withResolvers(); resolveRetry = deferred.resolve; + return deferred.promise; } + return HttpResponse.json( { code: status === 404 ? "NOT_FOUND" : "TBANK_UNAVAILABLE" }, { status }, @@ -980,9 +994,11 @@ describe("AccountPage states", () => { renderAccountRoute(queryClient); await screen.findByText("Вторая"); + const structure = screen.getByRole("region", { name: "Структура портфеля", }); + expect(structure).toHaveTextContent("10 ₽"); const snapshotText = screen.getByText(/Данные получены/).textContent; expect(snapshotText).toContain("10:00"); @@ -1057,9 +1073,11 @@ describe("AccountPage states", () => { http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () => { requestCount += 1; if (requestCount === 1) return HttpResponse.json(resource(portfolio)); + { const deferred = Promise.withResolvers(); resolveRefresh = deferred.resolve; + return deferred.promise; } }), diff --git a/src/pages/account/ui/AccountPage/AccountPage.tsx b/src/pages/account/ui/AccountPage/AccountPage.tsx index 6a9f1b4..4512daf 100644 --- a/src/pages/account/ui/AccountPage/AccountPage.tsx +++ b/src/pages/account/ui/AccountPage/AccountPage.tsx @@ -26,6 +26,7 @@ const AccountPage: FC = (props) => { sourceError={viewModel.sourceError} /> ); + return ( = props => ( @@ -87,6 +87,7 @@ function createWrapper() { ); + return Wrapper; } @@ -97,7 +98,8 @@ function mockLoadedAccountPage() { ), http.get("*/api/v1/brokerage-accounts/:accountId/operations", () => HttpResponse.json( - resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + + resource( { accountId: "account-1", hasNext: false, @@ -121,8 +123,8 @@ function mockLoadedAccountPage() { ], nextCursor: null, observedAt: "2026-08-13T10:00:00Z", - } - /* eslint-enable unicorn/no-null */)), + }, + ), ), ), http.get("*/api/v1/brokerage-accounts/:accountId/events", () => @@ -130,18 +132,21 @@ function mockLoadedAccountPage() { resource({ accountId: "account-1", calculatedAt: "2026-08-13T10:00:00Z", - events: Array.from({ length: 6 }, (_, index) => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { - date: `2026-09-${String(index + 1).padStart(2, "0")}`, - dateKind: "event", - displayName: `Купон ${index}`, - figi: `FIGI-EVENT-${index}`, - instrumentUid: null, - projectedAmount: { currency: "RUB", value: String(index + 1) }, - ticker: `BND${index}`, - type: "coupon", - } - /* eslint-enable unicorn/no-null */))), + events: Array.from( + { length: 6 }, + + (_, index) => + ({ + date: `2026-09-${String(index + 1).padStart(2, "0")}`, + dateKind: "event", + displayName: `Купон ${index}`, + figi: `FIGI-EVENT-${index}`, + instrumentUid: null, + projectedAmount: { currency: "RUB", value: String(index + 1) }, + ticker: `BND${index}`, + type: "coupon", + }), + ), }), ), ), @@ -158,6 +163,7 @@ describe("useAccountPageViewModel", () => { "DIGITAL_FINANCIAL_ASSET", "FUND", ] as const; + const snapshot: Portfolio = { ...portfolio, cashBalances: [{ currency: "RUB", value: "1000" }], @@ -169,19 +175,22 @@ describe("useAccountPageViewModel", () => { figi: "FIGI-CURRENCY", type: "CURRENCY", }, - ...otherTypes.map(type => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { - ...portfolio.positions[2], - currentValue: - type === "OPTION" ? { currency: "RUB", value: "50" } : null, - figi: `FIGI-${type}-NEXT`, - type, - } - /* eslint-enable unicorn/no-null */))), + ...otherTypes.map( + + type => + ({ + ...portfolio.positions[2], + currentValue: + type === "OPTION" ? { currency: "RUB", value: "50" } : null, + figi: `FIGI-${type}-NEXT`, + type, + }), + ), ], structure: { currencies: [], unvaluedCategories: [] }, totalsByCurrency: [{ currency: "RUB", value: "1250" }], }; + const original = structuredClone(snapshot); const sections = toAccountPagePositionSections(snapshot); @@ -210,10 +219,12 @@ describe("useAccountPageViewModel", () => { }); await waitFor(() => expect(result.current.state).toBe("loaded")); + const loaded = result.current as Extract< typeof result.current, { state: "loaded" } >; + expect( loaded.positionSections.map(({ groups, kind }) => ({ kind, @@ -231,35 +242,32 @@ describe("useAccountPageViewModel", () => { shareText: "66,7 %", }, ], + + }, + { + kind: "bonds", + positions: [ + { + displayName: "Облигация", + logoSrc: null, + returnText: "-5 ₽", + returnTone: "negative", + shareText: "33,3 %", + }, + ], + }, + { + kind: "other", + positions: [ + { + displayName: "Фонд", + logoSrc: null, + returnText: null, + returnTone: undefined, + shareText: null, + }, + ], }, - (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { - kind: "bonds", - positions: [ - { - displayName: "Облигация", - logoSrc: null, - returnText: "-5 ₽", - returnTone: "negative", - shareText: "33,3 %", - }, - ], - } - /* eslint-enable unicorn/no-null */), - (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { - kind: "other", - positions: [ - { - displayName: "Фонд", - logoSrc: null, - returnText: null, - returnTone: undefined, - shareText: null, - }, - ], - } - /* eslint-enable unicorn/no-null */), ]); }); @@ -276,10 +284,12 @@ describe("useAccountPageViewModel", () => { (result.current as { recentEvents?: { state: string } }).recentEvents, )?.toMatchObject({ state: "loaded" }), ); + const loaded = result.current as Extract< typeof result.current, { state: "loaded" } >; + expect(loaded.recentOperations).toMatchObject({ items: [{ description: "Покупка акции", id: "operation-1" }], state: "loaded", @@ -335,10 +345,9 @@ it("keeps overview sections independent when their source data is incomplete", a ), http.get("*/api/v1/brokerage-accounts/:accountId/operations", () => HttpResponse.json( + resource( - (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { hasNext: false, items: [], nextCursor: null } - /* eslint-enable unicorn/no-null */), + { hasNext: false, items: [], nextCursor: null }, { availability: "partial" }, ), ), @@ -352,9 +361,11 @@ it("keeps overview sections independent when their source data is incomplete", a ), ), ); + const { result } = renderHook(() => useAccountPageViewModel(), { wrapper: createWrapper(), }); + await waitFor(() => expect(result.current.state).toBe("loaded")); await waitFor(() => expect(result.current).toMatchObject({ @@ -367,14 +378,15 @@ it("keeps overview sections independent when their source data is incomplete", a it("refreshes every overview section through one account descriptor and observational reads", async () => { configureTestAuth(); - const sections: Record = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { + + const sections: Record + = { "events": { events: [], incomeTotalsByCurrency: [] }, "income-summary": { totalsByCurrency: [] }, "operations": { hasNext: false, items: [], nextCursor: null }, portfolio, - } - /* eslint-enable unicorn/no-null */); + }; + const observed: string[] = []; const scopes: unknown[] = []; let version = "1"; @@ -385,6 +397,7 @@ it("refreshes every overview section through one account descriptor and observat ({ request }) => { if (new URL(request.url).searchParams.get("sync") === "observe") observed.push(path); + return HttpResponse.json( resource(data, { resourceKey: path, stateVersion: version }), ); @@ -394,6 +407,7 @@ it("refreshes every overview section through one account descriptor and observat http.post("*/api/v1/tbank-sync", async ({ request }) => { scopes.push(await request.json()); version = "2"; + return HttpResponse.json( { id: "overview", @@ -404,7 +418,8 @@ it("refreshes every overview section through one account descriptor and observat ); }), http.get("*/api/v1/tbank-sync/:id", () => - HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ + + HttpResponse.json( { errorCode: null, id: "overview", @@ -416,13 +431,15 @@ it("refreshes every overview section through one account descriptor and observat ), scope: null, state: "succeeded", - } - /* eslint-enable unicorn/no-null */)), + }, + ), ), ); + const { result } = renderHook(() => useAccountPageViewModel(), { wrapper: createWrapper(), }); + await waitFor(() => expect(result.current).toMatchObject({ incomeSummary: { state: "empty" }, diff --git a/src/pages/account/ui/AccountPage/AccountPage.vm.ts b/src/pages/account/ui/AccountPage/AccountPage.vm.ts index 8bfa236..32868b7 100644 --- a/src/pages/account/ui/AccountPage/AccountPage.vm.ts +++ b/src/pages/account/ui/AccountPage/AccountPage.vm.ts @@ -33,6 +33,7 @@ type AccountPageContent = { retry: () => Promise | undefined; sourceError?: boolean; }; + type AccountPageEmptyViewModel = AccountPageContent & { state: "empty"; }; @@ -47,7 +48,9 @@ type AccountPageIncomeSummary to: string; } | { retry: () => Promise | undefined; state: "error"; to: string } - | { state: "empty" | "loading" | "partial"; to: string }; + | { state: "empty" + | "loading" + | "partial"; to: string; }; type AccountPageLoadedViewModel = AccountPageContent & { portfolio: Portfolio; @@ -85,7 +88,9 @@ type AccountPageRecentOperations to: string; } | { - state: "empty" | "error" | "loading"; + state: "empty" + | "error" + | "loading"; to: string; }; @@ -97,23 +102,31 @@ type AccountPageViewModel | { code?: string; retry: () => Promise | undefined; state: "error" } | { state: "loading" }; -type PositionSectionKind = "bonds" | "other" | "stocks"; +type PositionSectionKind = "bonds" + | "other" + | "stocks"; function groupPositions( positions: AccountPagePosition[], ): AccountPagePositionGroup[] { const groups = new Map(); + for (const [index, position] of positions.entries()) { const identity = positionIdentity(position); const rowKey = JSON.stringify(["row", position.account?.id, index]); + const key = identity && position.account ? JSON.stringify([position.type, ...identity]) : rowKey; + const group = groups.get(key); + if ( group - && group.positions.every(item => item.account?.id !== position.account?.id) + && group.positions.every( + item => item.account?.id !== position.account?.id, + ) ) { group.positions.push(position); } @@ -122,21 +135,26 @@ function groupPositions( groups.set(uniqueKey, { key: uniqueKey, positions: [position] }); } } + // eslint-disable-next-line unicorn/prefer-iterator-to-array -- Production targets ES2023; Iterator helpers require a newer browser baseline. return [...groups.values()]; } function positionIdentity(position: AccountPagePosition) { - if (position.instrumentUid?.trim()) return ["uid", position.instrumentUid.trim()]; + if (position.instrumentUid?.trim()) + return ["uid", position.instrumentUid.trim()]; if (position.figi?.trim()) return ["figi", position.figi.trim()]; + return position.isin?.trim() ? ["isin", position.isin.trim()] : undefined; } function toAccountPagePositionSections( portfolio: Portfolio, - instrumentDetails: Map = new Map(), + instrumentDetails: Map = new Map(), ): AccountPagePositionSection[] { const denominators = new Map(); + for (const position of portfolio.positions) { if (!position.currentValue) continue; const currency = position.currentValue.currency; @@ -145,14 +163,17 @@ function toAccountPagePositionSections( (denominators.get(currency) ?? 0) + Number(position.currentValue.value), ); } + const stocks = toSection( "stocks", portfolio, denominators, instrumentDetails, ); + const bonds = toSection("bonds", portfolio, denominators, instrumentDetails); const other = toSection("other", portfolio, denominators, instrumentDetails); + return [stocks, bonds, other].filter(section => section.groups.length > 0); } @@ -167,6 +188,7 @@ function toIncomeSummary( if (!income.data && (income.isError || income.meta?.sync.state === "failed")) return { retry: () => income.refetch(), state: "error", to }; if (!income.data?.totalsByCurrency.length) return { state: "empty", to }; + return { lastSuccessfulAt: income.meta?.lastSuccessfulAt, refreshError: income.isError || income.meta?.sync.state === "failed", @@ -181,32 +203,40 @@ function toPosition( position: Portfolio["positions"][number], denominators: Map, kind: PositionSectionKind, - instrumentSlug: string | undefined, + instrumentSlug?: string, ): AccountPagePosition { const isExpanded = kind !== "other"; + const returnValue = position.absoluteReturn ? Number(position.absoluteReturn.value) - : /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null; + : null; + let returnTone: AccountPageReturnTone | undefined; - if (returnValue !== null && returnValue !== 0) returnTone = returnValue > 0 ? "positive" : "negative"; - const returnPrefix = isExpanded && returnValue !== null && returnValue > 0 ? "+" : ""; + if (returnValue !== null && returnValue !== 0) + returnTone = returnValue > 0 ? "positive" : "negative"; + + const returnPrefix + = isExpanded && returnValue !== null && returnValue > 0 ? "+" : ""; + return { ...position, instrumentTo: (kind === "stocks" || kind === "bonds") && position.instrumentUid ? `/${kind}/${encodeURIComponent(instrumentSlug ?? position.instrumentUid)}` : undefined, - logoSrc: isExpanded ? instrumentLogoUrl(position.logoName) : /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null, + logoSrc: isExpanded + ? instrumentLogoUrl(position.logoName) + : null, returnText: position.absoluteReturn ? `${returnPrefix}${formatMoney(position.absoluteReturn)}` - : /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null, + : null, returnTone, shareText: position.currentValue?.currency ? formatShare(position.currentValue, { currency: position.currentValue.currency, value: String(denominators.get(position.currentValue.currency) ?? 0), }) - : /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null, + : null, }; } @@ -227,6 +257,7 @@ function toRecentEvents( return { state: "error", to }; const items = events.data?.events.slice(0, RECENT_EVENTS_LIMIT) ?? []; if (items.length === 0) return { state: "empty", to }; + return { items, lastSuccessfulAt: events.meta?.lastSuccessfulAt, @@ -256,6 +287,7 @@ function toRecentOperations( ) return { state: "error", to }; if (!operations.data?.items.length) return { state: "empty", to }; + return { items: operations.data.items, lastSuccessfulAt: operations.meta?.lastSuccessfulAt, @@ -271,20 +303,20 @@ function toSection( kind: PositionSectionKind, portfolio: Portfolio, denominators: Map, - instrumentDetails: Map, + instrumentDetails: Map, ): AccountPagePositionSection { return { groups: groupPositions( portfolio.positions .filter((position) => { if (kind === "stocks") return position.type === "STOCK"; + return kind === "bonds" ? position.type === "BOND" - : ( - position.type !== "STOCK" - && position.type !== "BOND" - && position.type !== "CURRENCY" - ); + : position.type !== "STOCK" + && position.type !== "BOND" + && position.type !== "CURRENCY"; }) .map(position => toPosition( @@ -303,6 +335,7 @@ function useAccountPageViewModel(scopeId?: string): AccountPageViewModel { const { accountId: routeAccountId } = useParams(); const accountId = scopeId ?? routeAccountId; const portfolio = usePortfolio(accountId); + const stocks = useStocks( portfolio.data?.positions.flatMap(position => position.type === "STOCK" && position.instrumentUid @@ -310,13 +343,17 @@ function useAccountPageViewModel(scopeId?: string): AccountPageViewModel { : [], ) ?? [], ); + const instrumentDetails = stocks; + const operations = useBrokerageOperations(accountId, { limit: 5, }); + const events = useBrokerageEvents(accountId); const income = useIncomeSummary(accountId); const accounts = useBrokerageAccounts(); + const sync = useScreenSync({ accountId, screen: "account" }, [ accounts, portfolio, @@ -332,12 +369,15 @@ function useAccountPageViewModel(scopeId?: string): AccountPageViewModel { retry: sync.retry, state: "error" as const, }; + return { state: "loading" as const }; } + const account = accounts.data?.find(item => item.id === accountId); const recentOperations = toRecentOperations(accountId, operations); const recentEvents = toRecentEvents(accountId, events); const incomeSummary = toIncomeSummary(accountId, income); + const refresh = { partial: portfolio.meta?.availability === "partial", refreshError: portfolio.isError || sync.transportError || sync.sourceError, @@ -345,6 +385,7 @@ function useAccountPageViewModel(scopeId?: string): AccountPageViewModel { retry: sync.retry, sourceError: sync.sourceError, }; + if ( portfolio.meta?.availability === "complete" && portfolio.data.positions.length === 0 @@ -359,6 +400,7 @@ function useAccountPageViewModel(scopeId?: string): AccountPageViewModel { state: "empty" as const, ...refresh, }; + return { account, accountId, diff --git a/src/pages/account/ui/AccountPage/components/AccountHeading.view.tsx b/src/pages/account/ui/AccountPage/components/AccountHeading.view.tsx index 3cc11ea..b2f42b6 100644 --- a/src/pages/account/ui/AccountPage/components/AccountHeading.view.tsx +++ b/src/pages/account/ui/AccountPage/components/AccountHeading.view.tsx @@ -27,7 +27,12 @@ const AccountHeading: FC = (props) => { ? t("accounts.all") : (account?.name ?? t("portfolio.title"))} - {description && {description}} + + {description && ( + + {description} + + )} ); }; diff --git a/src/pages/account/ui/AccountPage/components/AccountPageEmpty.view.tsx b/src/pages/account/ui/AccountPage/components/AccountPageEmpty.view.tsx index c3c83a2..bcea919 100644 --- a/src/pages/account/ui/AccountPage/components/AccountPageEmpty.view.tsx +++ b/src/pages/account/ui/AccountPage/components/AccountPageEmpty.view.tsx @@ -34,29 +34,35 @@ type AccountPageEmptyProps = { const AccountPageEmpty: FC = (props) => { const { t } = useTranslation(); + + const text = t( + props.accountId === "all" + ? "portfolio.allEmptyText" + : "portfolio.emptyText", + ); + return ( + - + + + + + - {!!(props.incomeSummary) && ()} + + {!!props.incomeSummary && } ); }; diff --git a/src/pages/account/ui/AccountPage/components/AccountPageError.view.tsx b/src/pages/account/ui/AccountPage/components/AccountPageError.view.tsx index b216637..9cda789 100644 --- a/src/pages/account/ui/AccountPage/components/AccountPageError.view.tsx +++ b/src/pages/account/ui/AccountPage/components/AccountPageError.view.tsx @@ -25,7 +25,10 @@ const AccountPageError: FC = (props) => { title={t("portfolio.accountUnavailableTitle")} /> ); - if (isApiErrorCode(code, ApiErrorCode.TbankNotConnected) || isApiErrorCode(code, ApiErrorCode.InvalidTbankToken)) + if ( + isApiErrorCode(code, ApiErrorCode.TbankNotConnected) + || isApiErrorCode(code, ApiErrorCode.InvalidTbankToken) + ) return ( = (props) => { title={t("accounts.unavailableTitle")} /> ); + return ( {t("accounts.retry")}} diff --git a/src/pages/account/ui/AccountPage/components/AccountPageLoaded.view.tsx b/src/pages/account/ui/AccountPage/components/AccountPageLoaded.view.tsx index f085fca..8ee2a43 100644 --- a/src/pages/account/ui/AccountPage/components/AccountPageLoaded.view.tsx +++ b/src/pages/account/ui/AccountPage/components/AccountPageLoaded.view.tsx @@ -42,18 +42,28 @@ type AccountPageLoadedProps = { const AccountPageLoaded: FC = (props) => { const { t } = useTranslation(); + + const defaultValue = [ + ...props.positionSections.map(section => section.kind), + "cash", + "recentOperations", + "recentEvents", + "incomeSummary", + ]; + return ( + - {!!(props.portfolio.isStale) && (( - {t("portfolio.staleWarning")} - ))} + + {!!props.portfolio.isStale && {t("portfolio.staleWarning")}} + {t( props.accountId === "all" @@ -64,19 +74,18 @@ const AccountPageLoaded: FC = (props) => { }, )} + {props.partial - ? ( - {t("investment.partial")} - ) - : ( - - )} - {!(props.partial) && (( + ? {t("investment.partial")} + : } + + {!props.partial && ( - ))} + )} + = (props) => { label: classes.accordionLabel, panel: classes.accordionPanel, }} - defaultValue={[ - ...props.positionSections.map(section => section.kind), - "cash", - "recentOperations", - "recentEvents", - "incomeSummary", - ]} + defaultValue={defaultValue} multiple > {props.positionSections.map(section => ( @@ -98,35 +101,44 @@ const AccountPageLoaded: FC = (props) => { {t(positionSectionTitleKey(section.kind))} + ))} + {t("portfolio.cashBalances")} + + {t("ledger.recentTitle")} + + {t("events.recentTitle")} + + {t("income.summaryTitle")} + - {!!(props.incomeSummary) && (( + {!!props.incomeSummary && ( - ))} + )} @@ -136,6 +148,7 @@ const AccountPageLoaded: FC = (props) => { function positionSectionTitleKey(kind: AccountPagePositionSection["kind"]) { if (kind === "stocks") return "portfolio.stocks"; + return kind === "bonds" ? "portfolio.bonds" : "portfolio.otherPositions"; } diff --git a/src/pages/account/ui/AccountPage/components/AccountPageLoading/AccountPageLoading.stories.tsx b/src/pages/account/ui/AccountPage/components/AccountPageLoading/AccountPageLoading.stories.tsx index ab07983..fd03792 100644 --- a/src/pages/account/ui/AccountPage/components/AccountPageLoading/AccountPageLoading.stories.tsx +++ b/src/pages/account/ui/AccountPage/components/AccountPageLoading/AccountPageLoading.stories.tsx @@ -19,4 +19,5 @@ const meta = { export default meta; type Story = StoryObj; + export const InitialLoading: Story = { name: "Начальная загрузка счёта" }; diff --git a/src/pages/account/ui/AccountPage/components/AccountPageLoading/AccountPageLoading.view.tsx b/src/pages/account/ui/AccountPage/components/AccountPageLoading/AccountPageLoading.view.tsx index 8f96f4d..acf5c80 100644 --- a/src/pages/account/ui/AccountPage/components/AccountPageLoading/AccountPageLoading.view.tsx +++ b/src/pages/account/ui/AccountPage/components/AccountPageLoading/AccountPageLoading.view.tsx @@ -8,9 +8,11 @@ import classes from "../../AccountPage.module.css"; const AccountPageLoading: FC = () => { const { t } = useTranslation(); + return ( + + - {["first", "second", "third"].map(placeholder => ( - - ))} + + {["first", "second", "third"].map(placeholder => )} ); }; diff --git a/src/pages/account/ui/AccountPage/components/CurrencyCards/CurrencyCards.test.tsx b/src/pages/account/ui/AccountPage/components/CurrencyCards/CurrencyCards.test.tsx index 39482af..2f08143 100644 --- a/src/pages/account/ui/AccountPage/components/CurrencyCards/CurrencyCards.test.tsx +++ b/src/pages/account/ui/AccountPage/components/CurrencyCards/CurrencyCards.test.tsx @@ -15,11 +15,13 @@ describe("CurrencyCards currency presentation", () => { { currency: "CAD", value: "4.00" }, { currency: "XYZ", value: "5.00" }, ].slice(0, count); + const { container } = render( , ); + expect( screen.queryAllByRole("definition").map(node => node.textContent), ).toEqual( diff --git a/src/pages/account/ui/AccountPage/components/CurrencyCards/CurrencyCards.view.tsx b/src/pages/account/ui/AccountPage/components/CurrencyCards/CurrencyCards.view.tsx index 2e2536d..ccf0f00 100644 --- a/src/pages/account/ui/AccountPage/components/CurrencyCards/CurrencyCards.view.tsx +++ b/src/pages/account/ui/AccountPage/components/CurrencyCards/CurrencyCards.view.tsx @@ -16,8 +16,9 @@ type CurrencyCardsProps = { }; const CurrencyCards: FC = (props) => { - const { amounts } = props; const { t } = useTranslation(); + const { amounts } = props; + const currencies: Record = { EUR: { name: t("portfolio.currencies.EUR"), symbol: "€" }, RUB: { name: t("portfolio.currencies.RUB"), symbol: "₽" }, @@ -28,6 +29,7 @@ const CurrencyCards: FC = (props) => { {amounts.map((money) => { const amount = formatDecimal(money.value); + return ( = (props) => { + {currencies[money.currency]?.name ?? money.currency} + {amount.startsWith("-") ? ( @@ -51,13 +55,13 @@ const CurrencyCards: FC = (props) => { {amount.slice(0, SIGN_PREFIX_LENGTH)} + {amount.slice(SIGN_PREFIX_LENGTH)} ) : ( amount - )} - {" "} + )}{" "} {currencies[money.currency]?.symbol ?? money.currency} diff --git a/src/pages/account/ui/AccountPage/components/IncomeSummary.view.tsx b/src/pages/account/ui/AccountPage/components/IncomeSummary.view.tsx index c73cf1c..9f4af99 100644 --- a/src/pages/account/ui/AccountPage/components/IncomeSummary.view.tsx +++ b/src/pages/account/ui/AccountPage/components/IncomeSummary.view.tsx @@ -50,42 +50,38 @@ const IncomeSummary: FC = (props) => { return ( {t("income.summaryEmpty")} + ); + return ( - {!!(props.lastSuccessfulAt) && (( + {!!props.lastSuccessfulAt && ( {t("investment.sourceTime", { date: formatSnapshotTime(props.lastSuccessfulAt), })} - ))} - {!!(props.stale) && ({t("investment.stale")})} - {!!(props.refreshError) && (( - {t("income.refreshError")} - ))} + )} + + {!!props.stale && {t("investment.stale")}} + + {!!props.refreshError && {t("income.refreshError")}} + {props.summary.totalsByCurrency.map(total => ( {formatMoney(total.total)} + - {t("income.coupon")} - : - {" "} - {formatMoney(total.coupon)} - {" "} - · - {" "} - {t("income.dividend")} - : - {" "} - {formatMoney(total.dividend)} + {t("income.coupon")}: {formatMoney(total.coupon)} ·{" "} + {t("income.dividend")}: {formatMoney(total.dividend)} ))} + diff --git a/src/pages/account/ui/AccountPage/components/PortfolioRefreshState/PortfolioRefreshState.stories.tsx b/src/pages/account/ui/AccountPage/components/PortfolioRefreshState/PortfolioRefreshState.stories.tsx index 95af73c..212a8e8 100644 --- a/src/pages/account/ui/AccountPage/components/PortfolioRefreshState/PortfolioRefreshState.stories.tsx +++ b/src/pages/account/ui/AccountPage/components/PortfolioRefreshState/PortfolioRefreshState.stories.tsx @@ -30,6 +30,7 @@ const meta = { { currency: "USD", value: "320" }, ]} /> + ), @@ -40,6 +41,7 @@ const meta = { export default meta; type Story = StoryObj; + export const Idle: Story = { name: "Сохранённые данные" }; export const Refreshing: Story = { args: { refreshing: true }, diff --git a/src/pages/account/ui/AccountPage/components/PortfolioRefreshState/PortfolioRefreshState.view.tsx b/src/pages/account/ui/AccountPage/components/PortfolioRefreshState/PortfolioRefreshState.view.tsx index 89eab6f..1507457 100644 --- a/src/pages/account/ui/AccountPage/components/PortfolioRefreshState/PortfolioRefreshState.view.tsx +++ b/src/pages/account/ui/AccountPage/components/PortfolioRefreshState/PortfolioRefreshState.view.tsx @@ -24,15 +24,18 @@ const PortfolioRefreshState: FC = (props) => { > {t(refreshError ? "accounts.retry" : "investment.refresh")} - {!!(refreshing) && (( + + {!!refreshing && ( + {t("portfolio.refreshing")} - ))} - {!!(refreshError) && (( + )} + + {!!refreshError && ( @@ -44,7 +47,7 @@ const PortfolioRefreshState: FC = (props) => { - ))} + )} ); }; diff --git a/src/pages/account/ui/AccountPage/components/PortfolioStructure/PortfolioStructure.stories.tsx b/src/pages/account/ui/AccountPage/components/PortfolioStructure/PortfolioStructure.stories.tsx index 6d83480..38900e5 100644 --- a/src/pages/account/ui/AccountPage/components/PortfolioStructure/PortfolioStructure.stories.tsx +++ b/src/pages/account/ui/AccountPage/components/PortfolioStructure/PortfolioStructure.stories.tsx @@ -15,6 +15,7 @@ const rub: Portfolio["structure"]["currencies"][number] = { hasNegativeValues: false, totalValue: "1250000", }; + const meta = { args: { structure: { currencies: [rub], unvaluedCategories: [] } }, component: PortfolioStructure, @@ -31,7 +32,9 @@ const meta = { } satisfies Meta; export default meta; + type Story = StoryObj; + export const Regular: Story = {}; export const MultipleCurrencies: Story = { args: { @@ -77,12 +80,14 @@ export const Incomplete: Story = { currencies: [ { ...rub, - categories: rub.categories.map(row => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { - ...row, - sharePercent: null, - } - /* eslint-enable unicorn/no-null */))), + categories: rub.categories.map( + + row => + ({ + ...row, + sharePercent: null, + }), + ), }, ], unvaluedCategories: [{ count: 2, type: "STOCK" }], @@ -103,13 +108,15 @@ export const Negative: Story = { currencies: [ { ...rub, - categories: rub.categories.map(row => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { - ...row, - sharePercent: null, - value: row.type === "OTHER" ? "25000" : row.value, - } - /* eslint-enable unicorn/no-null */))), + categories: rub.categories.map( + + row => + ({ + ...row, + sharePercent: null, + value: row.type === "OTHER" ? "25000" : row.value, + }), + ), hasNegativeValues: true, totalValue: "1150000", }, diff --git a/src/pages/account/ui/AccountPage/components/PortfolioStructure/PortfolioStructure.test.tsx b/src/pages/account/ui/AccountPage/components/PortfolioStructure/PortfolioStructure.test.tsx index 6551b9f..0f41c4f 100644 --- a/src/pages/account/ui/AccountPage/components/PortfolioStructure/PortfolioStructure.test.tsx +++ b/src/pages/account/ui/AccountPage/components/PortfolioStructure/PortfolioStructure.test.tsx @@ -17,6 +17,7 @@ const rub: Portfolio["structure"]["currencies"][number] = { hasNegativeValues: false, totalValue: "100", }; + const ui = (structure: null | Portfolio["structure"] | undefined) => ( @@ -24,7 +25,10 @@ const ui = (structure: null | Portfolio["structure"] | undefined) => ( ); describe("portfolio structure", () => { - it.each([undefined, /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null])( + it.each([ + undefined, + null, + ])( "keeps an older snapshot without structure available (%s) and recovers on refresh", (structure) => { const view = render(ui(structure)); @@ -68,12 +72,14 @@ describe("portfolio structure", () => { currencies: [ { ...rub, - categories: rub.categories.map(row => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { - ...row, - sharePercent: null, - } - /* eslint-enable unicorn/no-null */))), + categories: rub.categories.map( + + row => + ({ + ...row, + sharePercent: null, + }), + ), }, ], unvaluedCategories: [ @@ -97,13 +103,15 @@ describe("portfolio structure", () => { currencies: [ { ...rub, - categories: rub.categories.map(row => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { - ...row, - sharePercent: null, - value: row.type === "STOCK" ? "-60" : row.value, - } - /* eslint-enable unicorn/no-null */))), + categories: rub.categories.map( + + row => + ({ + ...row, + sharePercent: null, + value: row.type === "STOCK" ? "-60" : row.value, + }), + ), hasNegativeValues: true, }, ], @@ -123,6 +131,7 @@ describe("portfolio structure", () => { const view = render( ui({ currencies: [], unvaluedCategories: [{ count: 1, type: "BOND" }] }), ); + expect(screen.getByText("Облигации: без оценки — 1")).toBeInTheDocument(); expect(screen.queryByRole("list")).not.toBeInTheDocument(); view.rerender(ui({ currencies: [], unvaluedCategories: [] })); diff --git a/src/pages/account/ui/AccountPage/components/PortfolioStructure/PortfolioStructure.tsx b/src/pages/account/ui/AccountPage/components/PortfolioStructure/PortfolioStructure.tsx index bcd3372..1f175a5 100644 --- a/src/pages/account/ui/AccountPage/components/PortfolioStructure/PortfolioStructure.tsx +++ b/src/pages/account/ui/AccountPage/components/PortfolioStructure/PortfolioStructure.tsx @@ -1,80 +1,15 @@ -import { type FC, useState } from "react"; -import { useTranslation } from "react-i18next"; - -import type { Portfolio } from "@/entities/portfolio"; - -import { formatMoney } from "@/shared/lib"; +import type { FC } from "react"; import { PortfolioStructureView } from "./PortfolioStructure.view"; - -const MIN_VISIBLE_SHARE_PERCENT = 0.01; - -// A cached snapshot or an older running server can predate this response field. -type PortfolioStructureProps = { structure?: null | Portfolio["structure"] }; - -const categoryPresentation = { - BOND: { color: "grape.6", label: "portfolio.bonds" }, - CASH: { color: "green.6", label: "portfolio.structure.cash" }, - OTHER: { color: "orange.6", label: "portfolio.structure.other" }, - STOCK: { color: "blue.6", label: "portfolio.stocks" }, -} as const; +import { + type PortfolioStructureProps, + usePortfolioStructureVm, +} from "./PortfolioStructure.vm"; const PortfolioStructure: FC = (props) => { - const { structure } = props; - const { t } = useTranslation(); - const [currency, setCurrency] = useState(null); - const selected - = structure?.currencies.find(item => item.currency === currency) - ?? structure?.currencies[0]; - const isIncomplete = (structure?.unvaluedCategories.length ?? 0) > 0; - const rows = selected - ? selected.categories.map((category) => { - const presentation = categoryPresentation[category.type]; - const percentage - = category.sharePercent === null ? /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null : Number(category.sharePercent); - const unknown = structure?.unvaluedCategories.some( - item => item.type === category.type, - ); - const amount = formatMoney({ - currency: selected.currency, - value: category.value, - }); - let displayedAmount = amount; - if (unknown) displayedAmount = category.value === "0" ? t("portfolio.structure.unvalued") : t("portfolio.structure.knownAmount", { amount }); - let share = t("portfolio.structure.shareUnavailable"); - if (percentage !== null) share = percentage > 0 && percentage < MIN_VISIBLE_SHARE_PERCENT - ? t("portfolio.structure.smallShare") - : `${new Intl.NumberFormat("ru-RU", { maximumFractionDigits: 2 }).format(percentage)} %`; - return { - amount: displayedAmount, - color: presentation.color, - name: t(presentation.label), - share, - value: percentage ?? 0, - }; - }) - : []; - const chartData = rows.filter(row => row.value > 0); - return ( - item.currency) ?? []} - currency={selected?.currency ?? /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null} - incomplete={isIncomplete} - negative={selected?.hasNegativeValues ?? false} - onCurrencyChange={setCurrency} - rows={rows} - unavailable={!structure} - unvalued={ - structure?.unvaluedCategories.map(category => - t("portfolio.structure.unvaluedCategory", { - category: t(categoryPresentation[category.type].label), - count: category.count, - }), - ) ?? [] - } - /> - ); + const vm = usePortfolioStructureVm(props); + + return ; }; export { PortfolioStructure }; diff --git a/src/pages/account/ui/AccountPage/components/PortfolioStructure/PortfolioStructure.view.tsx b/src/pages/account/ui/AccountPage/components/PortfolioStructure/PortfolioStructure.view.tsx index 468791e..e48ce17 100644 --- a/src/pages/account/ui/AccountPage/components/PortfolioStructure/PortfolioStructure.view.tsx +++ b/src/pages/account/ui/AccountPage/components/PortfolioStructure/PortfolioStructure.view.tsx @@ -16,6 +16,13 @@ type PortfolioStructureViewProps = { unavailable: boolean; unvalued: string[]; }; + +type PortfolioTooltipProps = { + active?: boolean; + payload?: { name?: number | string }[]; + rows: StructureRow[]; +}; + type StructureRow = { amount: string; color: string; @@ -24,9 +31,28 @@ type StructureRow = { value: number; }; +const PortfolioTooltip: FC = (props) => { + const row = props.rows.find(item => item.name === props.payload?.[0]?.name); + if (!row || !props.active) return; + + return ( + + {row.name} + + {row.amount} · {row.share} + + ); +}; + const PortfolioStructureView: FC = (props) => { const { t } = useTranslation(); const titleId = useId(); + const appearanceClass = `${classes.content} ${props.chartData.length > 0 ? classes.layout : ""}`; + + const tooltipProps = { + content: , + }; + return ( = (props) => { {t("portfolio.structure.title")} - {(props.currencies.length > 1) && (( + + {props.currencies.length > 1 && ( = (props) => { w={180} /> + = (props) => { gap="lg" key={`${vm.period.from}-${vm.period.to}-${vm.pageSize}-${vm.history.data?.page ?? "loading"}`} > - {renderHistory()} + + {vm.history.isError && ( {t(vm.rows ? "bank.refreshError" : "bank.error")} - + + )} + {vm.history.data && vm.pageSize !== "all" && ( = (props) => { > ({ - "aria-label": t( - control === "previous" ? "bank.previous" : "bank.next", - ), - })} - getItemProps={page => ({ - "aria-label": t("bank.page", { page }), - })} - onChange={(page) => { - if (paginationRef.current) - pendingPageRef.current = { - page, - scope, - top: paginationRef.current.getBoundingClientRect().top, - }; - vm.setPage(page); - }} + getControlProps={getControlProps} + getItemProps={getItemProps} + onChange={onPageChange} siblings={0} total={vm.totalPages} value={vm.page} diff --git a/src/pages/card/ui/CardPage/CardPage.vm.ts b/src/pages/card/ui/CardPage/CardPage.vm.ts index 9b9a0db..45c20a3 100644 --- a/src/pages/card/ui/CardPage/CardPage.vm.ts +++ b/src/pages/card/ui/CardPage/CardPage.vm.ts @@ -17,6 +17,7 @@ import { formatDate, formatMoney } from "@/shared/lib"; const PAGE_SIZES = new Set(["5", "10", "20", "50", "100", "all"]); type CardPageVm = ReturnType; + function useCardPageVm() { const { cardId } = useParams(); const [parameters, setParameters] = useSearchParams(); @@ -25,32 +26,46 @@ function useCardPageVm() { const requestedSize = parameters.get("limit") ?? "10"; const pageSize = PAGE_SIZES.has(requestedSize) ? requestedSize : "10"; const rawPage = Number(parameters.get("page") ?? 1); + const page = pageSize !== "all" && Number.isSafeInteger(rawPage) && rawPage > 0 ? rawPage : 1; + const card = useBankCard(cardId); const { updateCard } = useBankMutations(); const [archiveError, setArchiveError] = useState(); const cards = useBankCards(true); + const history = useBankOperations(cardId, { ...period, limit: pageSize === "all" ? "all" : Number(pageSize), page, }); + const summary = useBankSummary(period, cardId); const [editingCard, setEditingCard] = useState(false); - const [operation, setOperation] = useState<"new" | BankOperation | null>( + + const [operation, setOperation] = useState<"new" + | BankOperation + | null>( null, ); + const [deleting, setDeleting] = useState(null); + const rows = history.data?.items.map((item) => { const isOutgoing = item.kind === "expense" || (item.kind === "transfer" && item.cardId === cardId); + const otherCardId = isOutgoing ? item.targetCardId : item.cardId; let title = t(`bank.kinds.${item.kind}`); - if (item.kind === "transfer") title = t(isOutgoing ? "bank.transferTo" : "bank.transferFrom", { name: isOutgoing ? item.targetCardName : item.cardName }); + if (item.kind === "transfer") + title = t(isOutgoing ? "bank.transferTo" : "bank.transferFrom", { + name: isOutgoing ? item.targetCardName : item.cardName, + }); + return { color: isOutgoing ? "red" : "green", editable: @@ -64,24 +79,34 @@ function useCardPageVm() { metadata: [formatDate(item.date), item.categoryName, item.description] .filter(Boolean) .join(" · "), + onDelete: () => setDeleting(item), + onEdit: () => setOperation(item), otherCard: item.kind === "transfer" ? otherCardId - : /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null, + : null, title, tone: isOutgoing ? ("negative" as const) : ("positive" as const), value: `${isOutgoing ? "−" : "+"}${formatMoney(item.amount)}`, }; }); + return { archiveError, archivePending: updateCard.isPending, card, cards, + closeDeletion: () => setDeleting(null), + closeEditing: () => setEditingCard(false), + closeOperation: () => setOperation(null), deleting, + editableOperation: operation === "new" ? undefined : (operation ?? undefined), editingCard, history, - notFound: isApiErrorCode(apiErrorCode(card.error), ApiErrorCode.BankNotFound), + notFound: isApiErrorCode( + apiErrorCode(card.error), + ApiErrorCode.BankNotFound, + ), operation, page, pageSize, @@ -104,6 +129,7 @@ function useCardPageVm() { toggleArchive: async () => { if (!card.data) return; setArchiveError(undefined); + try { await updateCard.mutateAsync({ body: { archived: !card.data.archivedAt, version: card.data.version }, diff --git a/src/pages/card/ui/CardPage/CardPagePresentation.vm.ts b/src/pages/card/ui/CardPage/CardPagePresentation.vm.ts new file mode 100644 index 0000000..ee1b7ad --- /dev/null +++ b/src/pages/card/ui/CardPage/CardPagePresentation.vm.ts @@ -0,0 +1,97 @@ +import type { ComponentProps } from "react"; + +import { Pagination } from "@mantine/core"; +import { useLayoutEffect, useRef } from "react"; +import { useTranslation } from "react-i18next"; + +import type { CardPageVm } from "./CardPage.vm"; + +function useCardPagePresentationVm(vm: CardPageVm) { + const { t } = useTranslation(); + const card = vm.card.data; + const paginationRef = useRef(null); + + const pendingPageRef = useRef(null); + + const scope = `${card?.id}-${vm.period.from}-${vm.period.to}-${vm.pageSize}`; + useLayoutEffect(() => { + const pending = pendingPageRef.current; + if (!pending) return; + + if (pending.scope !== scope || vm.history.isError) { + pendingPageRef.current + + = null; + + return; + } + + if (vm.history.isPlaceholderData || vm.history.data?.page !== pending.page) + return; + const pagination = paginationRef.current; + + if (pagination) { + const delta = pagination.getBoundingClientRect().top - pending.top; + if (delta) window.scrollBy({ behavior: "instant", top: delta }); + } + + pendingPageRef.current = null; + }, [ + scope, + vm.history.data, + vm.history.isPlaceholderData, + vm.history.isError, + ]); + const onEditCard = () => vm.setEditingCard(true); + const archiveActionLabel = t(card?.archivedAt ? "bank.restore" : "bank.archive"); + const onToggleArchive = () => void vm.toggleArchive(); + const retryCard = () => void vm.card.refetch(); + const retryCards = () => void vm.cards.refetch(); + const retrySummary = () => void vm.summary.refetch(); + const onAddOperation = () => vm.setOperation("new"); + const retryHistory = () => void vm.history.refetch(); + + const getControlProps: ComponentProps< + typeof Pagination + >["getControlProps"] = control => ({ + "aria-label": t(control === "previous" ? "bank.previous" : "bank.next"), + }); + + const getItemProps: ComponentProps["getItemProps"] = page => ({ + "aria-label": t("bank.page", { page }), + }); + + const onPageChange: ComponentProps["onChange"] = (page) => { + if (paginationRef.current) + pendingPageRef.current = { + page, + scope, + top: paginationRef.current.getBoundingClientRect().top, + }; + vm.setPage(page); + }; + + return { + archiveActionLabel, + card, + getControlProps, + getItemProps, + onAddOperation, + onEditCard, + onPageChange, + onToggleArchive, + paginationRef, + retryCard, + retryCards, + retryHistory, + retrySummary, + t, + }; +} + +export { useCardPagePresentationVm }; diff --git a/src/pages/card/ui/DeleteOperation/DeleteOperation.test.tsx b/src/pages/card/ui/DeleteOperation/DeleteOperation.test.tsx index dcc2f1e..406da07 100644 --- a/src/pages/card/ui/DeleteOperation/DeleteOperation.test.tsx +++ b/src/pages/card/ui/DeleteOperation/DeleteOperation.test.tsx @@ -12,8 +12,8 @@ import { server } from "@/test/server"; import { DeleteOperation } from "./DeleteOperation"; -const transfer: BankOperation = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { +const transfer: BankOperation + = { amount: { currency: "RUB", value: "100" }, availableRefund: null, cardId: "a", @@ -29,8 +29,8 @@ const transfer: BankOperation = (/* eslint-disable unicorn/no-null -- Fixture pr targetCardId: "b", targetCardName: "Запасная", version: 1, - } -/* eslint-enable unicorn/no-null */); + }; + describe("DeleteOperation", () => { it("names both sides and requires a deliberate fresh version after conflict", async () => { configureAuthClient({ @@ -46,6 +46,7 @@ describe("DeleteOperation", () => { http.delete("*/api/v1/bank-cards/operations/transfer", ({ request }) => { const version = new URL(request.url).searchParams.get("version") ?? ""; versions.push(version); + return version === "1" ? HttpResponse.json( { code: "BANK_VERSION_CONFLICT" }, diff --git a/src/pages/card/ui/DeleteOperation/DeleteOperation.tsx b/src/pages/card/ui/DeleteOperation/DeleteOperation.tsx index ab9c8d4..8350214 100644 --- a/src/pages/card/ui/DeleteOperation/DeleteOperation.tsx +++ b/src/pages/card/ui/DeleteOperation/DeleteOperation.tsx @@ -1,36 +1,34 @@ import { Button, Group, Modal, Stack, Text } from "@mantine/core"; -import { type FC, useState } from "react"; -import { useTranslation } from "react-i18next"; +import { type FC } from "react"; -import { - BankFeedback, - type BankOperation, - useBankFormFocus, - useBankMutations, - useBankOperation, -} from "@/entities/bank-card"; +import { BankFeedback, type BankOperation } from "@/entities/bank-card"; import { formatDate, formatMoney } from "@/shared/lib"; +import { useDeleteOperationVm } from "./DeleteOperation.vm"; + type DeleteOperationProps = { onClose: () => void; operation: BankOperation }; + const DeleteOperation: FC = (props) => { - useBankFormFocus(); - const [opened, setOpened] = useState(true); - const { t } = useTranslation(); - const [record, setRecord] = useState(props.operation); - const [latest, setLatest] = useState(); - const [error, setError] = useState(); - const query = useBankOperation(record.id); - const { deleteOperation: operationDeletion } = useBankMutations(); - const isPending - = !opened - || operationDeletion.isPending - || (query.isFetching && Boolean(error)); + const { + error, + isPending, + latest, + onAdoptVersion, + onCancel, + onDelete, + onReloadRecord, + onRequestClose, + opened, + record, + t, + } = useDeleteOperationVm(props); + return ( !isPending && setOpened(false)} + onClose={onRequestClose} onExitTransitionEnd={props.onClose} opened={opened} title={t("bank.deleteTitle")} @@ -49,22 +47,21 @@ const DeleteOperation: FC = (props) => { kind: t(`bank.kinds.${record.kind}`), })} - {!!(error) && (( + + {!!error && ( <> + - ))} + )} + {latest && ( <> @@ -72,44 +69,23 @@ const DeleteOperation: FC = (props) => { details: `${formatDate(latest.date)} · ${formatMoney(latest.amount)} · ${latest.description ?? ""}`, })} + )} + - - diff --git a/src/pages/card/ui/DeleteOperation/DeleteOperation.vm.ts b/src/pages/card/ui/DeleteOperation/DeleteOperation.vm.ts new file mode 100644 index 0000000..ff76f02 --- /dev/null +++ b/src/pages/card/ui/DeleteOperation/DeleteOperation.vm.ts @@ -0,0 +1,75 @@ +import { useState } from "react"; +import { useTranslation } from "react-i18next"; + +import { + type BankOperation, + useBankFormFocus, + useBankMutations, + useBankOperation, +} from "@/entities/bank-card"; + +type DeleteOperationProps = { onClose: () => void; operation: BankOperation }; + +function useDeleteOperationVm(props: DeleteOperationProps) { + useBankFormFocus(); + const [opened, setOpened] = useState(true); + const { t } = useTranslation(); + const [record, setRecord] = useState(props.operation); + const [latest, setLatest] = useState(); + const [error, setError] = useState(); + const query = useBankOperation(record.id); + const { deleteOperation: operationDeletion } = useBankMutations(); + + const isPending + = !opened + || operationDeletion.isPending + || (query.isFetching && Boolean(error)); + + const onRequestClose = () => !isPending && setOpened(false); + + const onReloadRecord = async () => { + const result = await query.refetch(); + if (result.data && !result.error) setLatest(result.data); + else setError(result.error); + }; + + const onAdoptVersion = () => { + if (!latest) return; + setRecord(latest); + setLatest(undefined); + setError(undefined); + }; + + const onDelete = async () => { + setError(undefined); + + try { + await operationDeletion.mutateAsync({ + id: record.id, + version: record.version, + }); + setOpened(false); + } + catch (error_) { + setError(error_); + } + }; + + const onCancel = () => setOpened(false); + + return { + error, + isPending, + latest, + onAdoptVersion, + onCancel, + onDelete, + onReloadRecord, + onRequestClose, + opened, + record, + t, + }; +} + +export { useDeleteOperationVm }; diff --git a/src/pages/card/ui/OperationForm/OperationFields.vm.ts b/src/pages/card/ui/OperationForm/OperationFields.vm.ts new file mode 100644 index 0000000..53cc5dd --- /dev/null +++ b/src/pages/card/ui/OperationForm/OperationFields.vm.ts @@ -0,0 +1,99 @@ +import type { ComponentProps } from "react"; + +import { DateInput } from "@mantine/dates"; +import { useController, useFormContext } from "react-hook-form"; +import { useTranslation } from "react-i18next"; + +import type { OperationValues } from "./OperationForm.types"; + +type Choice = { label: string; value: string }; + +type OperationFieldsProps = { + cards: Choice[]; + categories: Choice[]; + dateInputValue: (value: string) => string; + defaultCategory: string; + editing: boolean; + kind: OperationValues["kind"]; + kinds: Choice[]; + maxDate: () => string; + refundCardId: string; + targets: Choice[]; + validDate: (value: string) => boolean; +}; + +function useOperationFieldsVm(props: OperationFieldsProps) { + const { t } = useTranslation(); + + const { + control, + formState: { errors, isSubmitting }, + register, + setValue, + } = useFormContext(); + + const { field: kindField } = useController({ control, name: "kind" }); + const { field: cardIdField } = useController({ control, name: "cardId" }); + + const { field: targetCardIdField } = useController({ + control, + name: "targetCardId", + }); + + const { field: dateField } = useController({ control, name: "date" }); + + const { field: categoryIdField } = useController({ + control, + name: "categoryId", + }); + + const onKindChange: (value: null | string) => void = (value) => { + kindField.onChange(value ?? "expense"); + if (value === "refund") setValue("cardId", props.refundCardId); + }; + + const sourceCardLabel = t( + props.kind === "transfer" ? "bank.source" : "bank.operationCard", + ); + + const dateParser: ComponentProps["dateParser"] = value => + props.validDate(props.dateInputValue(value)) + ? props.dateInputValue(value) + : null; + + const onDateBlur: ComponentProps["onBlur"] = (event) => { + dateField.onChange(props.dateInputValue(event.currentTarget.value)); + dateField.onBlur(); + }; + + const onDateChange: (value: null | string) => void = value => + dateField.onChange(value ?? ""); + + const onDateInput: ComponentProps["onInput"] = event => + dateField.onChange(props.dateInputValue(event.currentTarget.value)); + + const dateValue = props.validDate(dateField.value) + ? dateField.value + : undefined; + + return { + cardIdField, + categoryIdField, + dateField, + dateParser, + dateValue, + errors, + isSubmitting, + kindField, + onDateBlur, + onDateChange, + onDateInput, + onKindChange, + register, + sourceCardLabel, + t, + targetCardIdField, + }; +} + +export { useOperationFieldsVm }; diff --git a/src/pages/card/ui/OperationForm/OperationForm.schema.ts b/src/pages/card/ui/OperationForm/OperationForm.schema.ts new file mode 100644 index 0000000..7173642 --- /dev/null +++ b/src/pages/card/ui/OperationForm/OperationForm.schema.ts @@ -0,0 +1,131 @@ +import { z } from "zod"; + +import { + type BankCard, + bankDateSchema, + type BankOperation, + bankOperationKinds, + moneyCents, + positiveMoneySchema, +} from "@/entities/bank-card"; +import { validationMessage } from "@/shared/i18n"; + +import type { OperationValues } from "./OperationForm.types"; + +// ZodIssueCode is deprecated; this is the custom refinement code accepted by Zod. +enum FormIssueCode { + Custom = "custom", +} + +type SchemaInputs = { + cards: BankCard[]; + categories?: { id: string; isDefault: boolean }[]; + expense?: BankOperation; + limit?: BankOperation["availableRefund"]; + submittedValues?: OperationValues; +}; + +const MAX_DESCRIPTION_LENGTH = 500; + +const operationSchema = z.object({ + amount: positiveMoneySchema, + cardId: z.string(), + categoryId: z.string(), + date: bankDateSchema, + description: z + .string() + .max( + MAX_DESCRIPTION_LENGTH, + validationMessage("bank.validation.description")(undefined), + ), + kind: z.enum(bankOperationKinds), + originalExpenseId: z.string(), + targetCardId: z.string(), +}); + +function createOperationSchema({ + cards, + categories, + expense, + limit, + submittedValues, +}: SchemaInputs) { + return operationSchema.superRefine((values, context) => { + // Repeated intent reaches server idempotency even after its source changed. + if ( + submittedValues + && JSON.stringify(values) === JSON.stringify(submittedValues) + ) + return; + const source = cards.find(c => c.id === values.cardId); + const target = cards.find(c => c.id === values.targetCardId); + if (!source || source.archivedAt) + context.addIssue({ + code: FormIssueCode.Custom, + path: ["cardId"], + ...validationMessage("bank.validation.required")(undefined), + }); + if ( + values.kind === "transfer" + && (!target || target.archivedAt || target.id === values.cardId) + ) + context.addIssue({ + code: FormIssueCode.Custom, + path: ["targetCardId"], + ...validationMessage("bank.validation.destination")(undefined), + }); + if ( + (source && values.date < source.openingDate) + || (target && values.kind === "transfer" && values.date < target.openingDate) + ) + context.addIssue({ + code: FormIssueCode.Custom, + path: ["date"], + ...validationMessage("bank.validation.start")(undefined), + }); + if (values.kind === "refund") + validateRefund(values, context, expense, limit); + if ( + values.kind === "expense" + && !categories?.some( + c => + c.id + === (values.categoryId || categories?.find(c => c.isDefault)?.id), + ) + ) + context.addIssue({ + code: FormIssueCode.Custom, + path: ["categoryId"], + ...validationMessage("bank.validation.required")(undefined), + }); + }); +} + +function validateRefund( + values: OperationValues, + context: z.RefinementCtx, + expense: BankOperation | undefined, + limit?: BankOperation["availableRefund"], +) { + if (!expense || expense.cardId !== values.cardId) + context.addIssue({ + code: FormIssueCode.Custom, + path: ["originalExpenseId"], + ...validationMessage("bank.validation.required")(undefined), + }); + if (expense && values.date < expense.date) + context.addIssue({ + code: FormIssueCode.Custom, + path: ["date"], + ...validationMessage("bank.validation.start")(undefined), + }); + const amount = moneyCents(values.amount); + if (limit && amount !== null && amount > (moneyCents(limit.value) ?? 0n)) + context.addIssue({ + code: FormIssueCode.Custom, + path: ["amount"], + ...validationMessage("bank.validation.refund")(undefined), + }); +} + +export { createOperationSchema }; diff --git a/src/pages/card/ui/OperationForm/OperationForm.stories.tsx b/src/pages/card/ui/OperationForm/OperationForm.stories.tsx index 8ecbfea..78d57d9 100644 --- a/src/pages/card/ui/OperationForm/OperationForm.stories.tsx +++ b/src/pages/card/ui/OperationForm/OperationForm.stories.tsx @@ -9,9 +9,11 @@ import type { OperationValues } from "./OperationForm.types"; import { OperationFormView } from "./OperationForm.view"; type ExampleProps = { conflict?: boolean; pending?: boolean }; + const OperationExample: FC = (props) => { const [opened, setOpened] = useState(true); const [action, setAction] = useState(""); + const methods = useForm({ defaultValues: { amount: "500", @@ -24,7 +26,9 @@ const OperationExample: FC = (props) => { targetCardId: "", }, }); + const kind = useWatch({ control: methods.control, name: "kind" }); + return ( = (props) => { validDate: value => value === "2026-08-01", }} latest={ - (props.conflict) - ? ({ + props.conflict + ? { details: "Учебная версия", onAdopt: () => setAction("Локальное принятие версии"), version: 2, - }) + } : undefined } loadingExpenses={false} @@ -69,7 +73,7 @@ const OperationExample: FC = (props) => { onNext={() => {}} onPrevious={() => {}} onReload={ - (props.conflict) ? () => setAction("Локальный reload") : undefined + props.conflict ? () => setAction("Локальный reload") : undefined } onSubmit={(event) => { event.preventDefault(); @@ -92,10 +96,12 @@ const OperationExample: FC = (props) => { saveDisabled={false} sourcePage={1} /> + {action} ); }; + const meta = { component: OperationExample, parameters: { @@ -109,8 +115,11 @@ const meta = { tags: ["autodocs"], title: "Product/OperationForm", } satisfies Meta; + export default meta; + type Story = StoryObj; + export const Refund: Story = {}; export const Pending: Story = { args: { pending: true } }; export const Conflict: Story = { args: { conflict: true } }; diff --git a/src/pages/card/ui/OperationForm/OperationForm.test.tsx b/src/pages/card/ui/OperationForm/OperationForm.test.tsx index 332ac9f..1729b71 100644 --- a/src/pages/card/ui/OperationForm/OperationForm.test.tsx +++ b/src/pages/card/ui/OperationForm/OperationForm.test.tsx @@ -19,8 +19,9 @@ import { server } from "@/test/server"; import { OperationForm } from "./OperationForm"; const money = (value: string) => ({ currency: "RUB", value }); -const card: BankCard = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { + +const card: BankCard + = { archivedAt: null, balance: money("0"), bankName: null, @@ -31,12 +32,13 @@ const card: BankCard = (/* eslint-disable unicorn/no-null -- Fixture preserves t openingDate: "2026-01-01", paymentSystem: null, version: 1, - } -/* eslint-enable unicorn/no-null */); + }; + async function select(label: RegExp, value: RegExp | string) { fireEvent.click(screen.getByRole("combobox", { name: label })); fireEvent.click(await screen.findByRole("option", { name: value })); } + function setup(operation?: BankOperation) { configureAuthClient({ accessToken: () => "test", @@ -72,16 +74,21 @@ function setup(operation?: BankOperation) { , ); + return close; } + describe("OperationForm", () => { it("blocks closing and editing while save is pending, then closes after success", async () => { - const { promise: response, resolve: finish } = Promise.withResolvers(); + const { promise: response, resolve: finish } + = Promise.withResolvers(); + const received = vi.fn(); server.use( http.post("*/api/v1/bank-cards/operations", async () => { received(); await response; + return HttpResponse.json({}, { status: 201 }); }), ); @@ -96,6 +103,7 @@ describe("OperationForm", () => { }); fireEvent.click(screen.getByRole("button", { name: "Сохранить" })); await waitFor(() => expect(received).toHaveBeenCalledOnce()); + try { expect(screen.getByLabelText(/Сумма/)).toBeDisabled(); expect(screen.getByRole("button", { name: "Закрыть" })).toBeDisabled(); @@ -107,6 +115,7 @@ describe("OperationForm", () => { finally { finish(); } + await waitFor(() => expect(close).toHaveBeenCalledOnce()); }); @@ -126,6 +135,7 @@ describe("OperationForm", () => { server.use( http.post("*/api/v1/bank-cards/operations", async ({ request }) => { body = await request.json(); + return HttpResponse.json({}, { status: 201 }); }), ); @@ -155,6 +165,7 @@ describe("OperationForm", () => { server.use( http.post("*/api/v1/bank-cards/operations", async ({ request }) => { bodies.push(await request.json()); + return bodies.length === 1 ? HttpResponse.error() : HttpResponse.json({}, { status: 201 }); @@ -195,6 +206,7 @@ describe("OperationForm", () => { server.use( http.post("*/api/v1/bank-cards/operations", async ({ request }) => { body = await request.json(); + return HttpResponse.json({}, { status: 201 }); }), ); @@ -214,8 +226,8 @@ describe("OperationForm", () => { expect(body).not.toHaveProperty("categoryId"); }); it("finds a previous-month purchase across pages, checks remaining refund and retains the complete-refund intent", async () => { - const purchase: BankOperation = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { + const purchase: BankOperation + = { amount: money("500"), availableRefund: money("500"), cardId: "a", @@ -231,8 +243,8 @@ describe("OperationForm", () => { targetCardId: null, targetCardName: null, version: 1, - } - /* eslint-enable unicorn/no-null */); + }; + server.use( http.get("*/api/v1/bank-cards/a/expenses", ({ request }) => { return HttpResponse.json({ @@ -270,6 +282,7 @@ describe("OperationForm", () => { http.post("*/api/v1/bank-cards/operations", async ({ request }) => { bodies.push(await request.json()); purchase.availableRefund = money("0"); + return bodies.length === 1 ? HttpResponse.error() : HttpResponse.json({}, { status: 201 }); @@ -295,8 +308,8 @@ describe("OperationForm", () => { }); }); it("edits a full refund with its own amount excluded from the limit and immutable purchase", async () => { - const refund: BankOperation = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { + const refund: BankOperation + = { amount: money("500"), availableRefund: money("500"), cardId: "a", @@ -312,8 +325,8 @@ describe("OperationForm", () => { targetCardId: null, targetCardName: null, version: 2, - } - /* eslint-enable unicorn/no-null */); + }; + const purchase = { ...refund, availableRefund: money("0"), @@ -321,6 +334,7 @@ describe("OperationForm", () => { id: "purchase", kind: "expense", }; + server.use( http.get("*/api/v1/bank-cards/a/expenses", () => HttpResponse.json({ @@ -354,6 +368,7 @@ describe("OperationForm", () => { "*/api/v1/bank-cards/operations/refund", async ({ request }) => { body = await request.json(); + return HttpResponse.json(refund); }, ), @@ -372,8 +387,8 @@ describe("OperationForm", () => { }); it("keeps edit draft and stale version until explicit adoption after conflict", async () => { - const operation: BankOperation = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */ - { + const operation: BankOperation + = { amount: money("100"), availableRefund: money("100"), cardId: "a", @@ -389,8 +404,8 @@ describe("OperationForm", () => { targetCardId: null, targetCardName: null, version: 1, - } - /* eslint-enable unicorn/no-null */); + }; + let readVersion = 1; const bodies: Record[] = []; server.use( @@ -407,6 +422,7 @@ describe("OperationForm", () => { const body = (await request.json()) as Record; bodies.push(body); readVersion = 2; + return body.version === 1 ? HttpResponse.json( { code: "BANK_VERSION_CONFLICT" }, @@ -465,6 +481,7 @@ describe("OperationForm", () => { server.use( http.post("*/api/v1/bank-cards/categories", () => { isCreated = true; + return HttpResponse.json( { id: "new", isDefault: false, name: "кафе", version: 1 }, { status: 201 }, @@ -498,6 +515,7 @@ describe("OperationForm", () => { server.use( http.post("*/api/v1/bank-cards/operations", async ({ request }) => { body = await request.json(); + return HttpResponse.json({}, { status: 201 }); }), ); diff --git a/src/pages/card/ui/OperationForm/OperationForm.tsx b/src/pages/card/ui/OperationForm/OperationForm.tsx index 251e6c2..dd68158 100644 --- a/src/pages/card/ui/OperationForm/OperationForm.tsx +++ b/src/pages/card/ui/OperationForm/OperationForm.tsx @@ -11,6 +11,8 @@ import { useOperationFormVm } from "./OperationForm.vm"; const OperationForm: FC = (props) => { const vm = useOperationFormVm(props); + const feedback = vm.error ? : undefined; + return ( <> @@ -25,7 +27,7 @@ const OperationForm: FC = (props) => { /> ) } - feedback={(vm.error) ? () : undefined} + feedback={feedback} refundFeedback={( <> {vm.expensesError && ( @@ -34,8 +36,7 @@ const OperationForm: FC = (props) => { loadingError retry={vm.retryExpenses} /> - )} - {" "} + )}{" "} {vm.sourceError && ( = (props) => { )} /> + {vm.categoriesOpen && ( boolean; }; + const OperationFields: FC = (props) => { - const { t } = useTranslation(); const { - control, - formState: { errors, isSubmitting }, + cardIdField, + categoryIdField, + dateField, + dateParser, + dateValue, + errors, + isSubmitting, + kindField, + onDateBlur, + onDateChange, + onDateInput, + onKindChange, register, - setValue, - } = useFormContext(); + sourceCardLabel, + t, + targetCardIdField, + } = useOperationFieldsVm(props); + return ( - ( - - ( - + {props.kind === "transfer" && ( - ( - )} + = (props) => { {...register("amount")} error={errors.amount?.message} /> - ( - - props.validDate(props.dateInputValue(value)) - ? props.dateInputValue(value) - : /* eslint-disable-line unicorn/no-null -- Mantine represents an empty controlled field as null. */ null} - error={errors.date?.message} - fixOnBlur={false} - label={t("bank.date")} - maxDate={props.maxDate()} - onBlur={(event) => { - field.onChange(props.dateInputValue(event.currentTarget.value)); - field.onBlur(); - }} - onChange={value => field.onChange(value ?? "")} - onInput={event => - field.onChange(props.dateInputValue(event.currentTarget.value))} - popoverProps={{ - middlewares: { shift: { crossAxis: true } }, - withinPortal: false, - }} - required - value={(props.validDate(field.value)) ? (field.value) : undefined} - valueFormat="DD.MM.YYYY" - /> - )} + + + {props.kind === "expense" && ( - ( - )} +