10 Commits
Author SHA1 Message Date
ksv741 b34c1c860a chore(release): 0.4.0
Frontend image / publish (push) Successful in 6m44s
Conventional commits / commits (pull_request) Successful in 27s
Frontend security / security (pull_request) Successful in 10s
Frontend verify / verify (pull_request) Successful in 5m46s
Frontend security / security (push) Successful in 10s
Frontend verify / verify (push) Successful in 6m57s
2026-09-26 22:10:01 +03:00
ksv741 a005e8b13b chore: synchronize develop before release
Conventional commits / commits (pull_request) Successful in 27s
Frontend security / security (pull_request) Successful in 10s
Frontend verify / verify (pull_request) Successful in 6m6s
Frontend security / security (push) Successful in 10s
Frontend verify / verify (push) Successful in 7m5s
2026-09-26 21:30:58 +03:00
ksv741 4e5f564fa1 feat: show persisted investment data and sync state
Consume the provided resource-envelope API snapshot. Preserve financial snapshots during
refresh, observe synchronization without importing, and fence late responses across
account and connection changes.
2026-09-26 21:22:49 +03:00
codex-bot cd09ec698c refactor: colocate frontend component files (#35)
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Successful in 6m53s
2026-09-23 08:49:01 +03:00
ksv741 b987fd8e78 refactor: colocate frontend component files
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Successful in 5m10s
Conventional commits / commits (pull_request) Successful in 25s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 5m10s
2026-09-23 08:34:58 +03:00
ksv741 85fcfe3d07 refactor: establish local frontend workspace boundaries
Conventional commits / commits (pull_request) Successful in 24s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 5m18s
Frontend security / security (push) Successful in 10s
Frontend verify / verify (push) Successful in 6m45s
OpenSpec change: evolve-frontend-stack
2026-09-22 22:11:02 +03:00
ksv741 c86be7bf73 fix(ui): improve financial text contrast
TD-010: use readable semantic text colors on financial surfaces while preserving signs
and state meanings.
2026-09-21 21:10:10 +03:00
ksv741 6a87379813 fix(ci): resume verification of immutable release images
TD-009: retry verification of an existing digest without republishing. Paired backend
workflow fix: 82eccc3.
2026-09-21 21:09:53 +03:00
ksv741 db184c8cae fix(api): update validation and conflict response contract
TD-003 and TD-005: explicitly deliver OpenAPI and generated types from backend commit 1667991.
2026-09-21 21:09:41 +03:00
ksv741 a209d71589 fix(auth): isolate session races and financial caches
TD-001 and TD-002: serialize cookie writes, ignore stale responses and reset financial
queries on identity changes. Backend cookie lifecycle regression: ec5780d.
2026-09-21 21:09:23 +03:00
229 changed files with 4889 additions and 1554 deletions
+2 -2
View File
@@ -76,8 +76,8 @@ Add/Edit/Delete; restore/category SVG остаются локальными.
## Примеры ## Примеры
- Общая busy-область: существующий [LoadingSkeleton](../packages/ui/src/LoadingSkeleton.tsx), а не domain widget в shared. - Общая busy-область: существующий [LoadingSkeleton](../packages/ui/src/LoadingSkeleton/LoadingSkeleton.tsx), а не domain widget в shared.
- Account-income state views: [страница](../src/pages/account-income/ui/AccountIncomePage.tsx) и её flat `components/*.view.tsx`; новый page-local filter остаётся здесь. - Account-income state views: [страница](../src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.tsx) и её `components/`; новый page-local filter остаётся здесь. Комплекты файлов группируются по [UI convention](conventions/ui.md#размещение-файлов-компонента).
- Portfolio query: [entity public API](../src/entities/portfolio/index.ts); новая UI-сводка с бизнес-смыслом не становится shared только из-за нескольких экранов. - Portfolio query: [entity public API](../src/entities/portfolio/index.ts); новая UI-сводка с бизнес-смыслом не становится shared только из-за нескольких экранов.
## Проверка ## Проверка
+1 -1
View File
@@ -26,7 +26,7 @@ Stories не достигают application API, auth, VM и query providers д
контракт: keyboard activation, доступность действия, local callback. Не повторяй контракт: keyboard activation, доступность действия, local callback. Не повторяй
RTL suite и не тестируй внутренности Mantine. Существующий RTL suite и не тестируй внутренности Mantine. Существующий
[Button](../../src/shared/ui/Button.stories.tsx) показывает themed control [Button](../../src/shared/ui/Button.stories.tsx) показывает themed control
без production wrapper; [LoadingSkeleton](../../packages/ui/src/LoadingSkeleton.stories.tsx) без production wrapper; [LoadingSkeleton](../../packages/ui/src/LoadingSkeleton/LoadingSkeleton.stories.tsx)
— значимые busy states. — значимые busy states.
`npm run typecheck`, `npm run deps:storybook`, `npm run build:catalog` проверяют `npm run typecheck`, `npm run deps:storybook`, `npm run build:catalog` проверяют
+1 -1
View File
@@ -45,7 +45,7 @@ Finance: loading/error/empty/loaded, cached snapshot при refetch failure, ret
отсутствие старых данных после session/connection switch. ErrorBoundary: test-only отсутствие старых данных после session/connection switch. ErrorBoundary: test-only
throwing route, безопасная ссылка и reset после navigation. throwing route, безопасная ссылка и reset после navigation.
Примеры: [AuthForm test](../../src/features/auth/ui/AuthForm.test.tsx), Примеры: [AuthForm test](../../src/features/auth/ui/AuthForm/AuthForm.test.tsx),
[client test](../../src/shared/api/client.test.ts), [client test](../../src/shared/api/client.test.ts),
[usePortfolio test](../../src/entities/portfolio/api/usePortfolio.test.tsx). [usePortfolio test](../../src/entities/portfolio/api/usePortfolio.test.tsx).
Не копируй fixtures/сценарии целиком, если задача затрагивает один исход. Не копируй fixtures/сценарии целиком, если задача затрагивает один исход.
+29 -6
View File
@@ -12,7 +12,7 @@ Mantine component и общую тему. Для выпадающего выбо
Семантический HTML для структуры страницы остаётся уместным. Семантический HTML для структуры страницы остаётся уместным.
Icons ищи у существующего owner (например, Icons ищи у существующего owner (например,
[BankOperationIcon](../../src/entities/bank-card/ui/BankOperationIcon.tsx)); [BankOperationIcon](../../src/entities/bank-card/ui/BankOperationIcon/BankOperationIcon.tsx));
статичные Add/Edit/Delete доступны в `@wealthledger/icons`. Их SVG декоративны статичные Add/Edit/Delete доступны в `@wealthledger/icons`. Их SVG декоративны
по умолчанию; имя action принадлежит кнопке. Standalone meaningful icon получает по умолчанию; имя action принадлежит кнопке. Standalone meaningful icon получает
`aria-hidden={false}`, `role="img"` и доступное имя. Category/kind mappings `aria-hidden={false}`, `role="img"` и доступное имя. Category/kind mappings
@@ -56,11 +56,34 @@ retry callbacks, domain grouping и derived presentation data. View получа
image fallback) и formatter одного переданного значения. Группировка/доли image fallback) и formatter одного переданного значения. Группировка/доли
коллекции готовятся в VM. Перенос fetch во view ради меньшего container нарушает границу. коллекции готовятся в VM. Перенос fetch во view ради меньшего container нарушает границу.
Отдельный state/section с самостоятельной responsibility выноси в flat Отдельный state/section с самостоятельной responsibility выноси в
`components/*.view.tsx`. Небольшой tightly-coupled renderer оставляй рядом. `components/` своего component. Небольшой tightly-coupled renderer оставляй
Не создавай folder/barrel/test/CSS для каждого view и не дроби по line count. рядом; размер файла сам по себе не требует разделения.
Пример: [AccountIncomePage](../../src/pages/account-income/ui/AccountIncomePage.tsx) Пример: [AccountIncomePage](../../src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.tsx)
и [его VM](../../src/pages/account-income/ui/AccountIncomePage.vm.ts). и [его VM](../../src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.vm.ts).
## Размещение файлов компонента
Правило действует в `src` и `packages`: компонент с сопутствующими файлами
(view, VM, types, CSS, tests, stories) размещай в папке `Component/`.
Сохраняй полные имена файлов: `Component.tsx`, `Component.view.tsx`,
`Component.test.tsx`. Создавай только нужные файлы; одиночный компонент
оставляй непосредственно в `ui`, `components` или source-каталоге пакета.
Внутренние части принадлежат папке родителя; для набора state/section views
используй её `components/`. Внутри него действует то же правило: отдельная
папка объединяет комплект файлов, одиночный view остаётся файлом.
Стили и хуки нескольких соседних компонентов остаются у ближайшего общего
владельца; не копируй их и не прячь внутрь одного потребителя.
Папка компонента не создаёт новую FSD-границу. Публичные exports остаются в
существующем `index.ts` slice/segment или entry пакета; внутри используй
прямые относительные imports без дополнительных barrels на каждый компонент.
При переносе обновляй imports, ссылки документации и проверки, зависящие от пути.
Пример: [BankCardForm](../../src/entities/bank-card/ui/BankCardForm/BankCardForm.tsx)
лежит рядом со своим view, тестом и story; общий `BankForms.module.css`
остаётся в `bank-card/ui`.
## Формы ## Формы
+1 -1
View File
@@ -9,7 +9,7 @@ module.exports = {
severity: "error", severity: "error",
from: { path: "\\.stories\\.tsx$|^\\.storybook/preview\\.tsx$" }, from: { path: "\\.stories\\.tsx$|^\\.storybook/preview\\.tsx$" },
to: { to: {
path: "^src/(shared/api|features/auth|app/routes|app/ui)/|^src/(entities|features)/[^/]+/api/|\\.vm\\.ts$|^src/pages/[^/]+/ui/[^/]+Page\\.tsx$|node_modules/(@tanstack/react-query|openapi-fetch|openapi-react-query)/", path: "^src/(shared/api|features/auth|app/routes|app/ui)/|^src/(entities|features)/[^/]+/api/|\\.vm\\.ts$|^src/pages/[^/]+/ui/.*Page\\.tsx$|node_modules/(@tanstack/react-query|openapi-fetch|openapi-react-query)/",
reachable: true, reachable: true,
}, },
}, },
+18
View File
@@ -1,5 +1,23 @@
# Changelog # Changelog
## [0.4.0](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.3.0...v0.4.0) (2026-09-26)
### Features
* show persisted investment data and sync state ([4e5f564](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/4e5f564fa1d583013fb3e7febdb3baa9737446b4))
### Bug Fixes
* **api:** update validation and conflict response contract ([db184c8](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/db184c8caec01609e8a3df3b16097ce634e5eff0))
* **auth:** isolate session races and financial caches ([a209d71](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/a209d715892862bb6d48084df0c84a10b8d56bf1))
* **ci:** resume verification of immutable release images ([6a87379](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/6a87379813ba1d4002779b23b2a65446b4d10258))
* **ui:** improve financial text contrast ([c86be7b](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/c86be7bf73d0141e0606d259ada6453c0d8e3dec))
### Refactoring
* colocate frontend component files ([b987fd8](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/b987fd8e780963dfe1dde0c714232697a52e0475))
* establish local frontend workspace boundaries ([85fcfe3](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/85fcfe3d073f80e759dafb14281c9462c1d7410d))
## [0.3.0](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.2.3...v0.3.0) (2026-09-20) ## [0.3.0](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.2.3...v0.3.0) (2026-09-20)
### Features ### Features
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "wealth-ledger-frontend", "name": "wealth-ledger-frontend",
"version": "0.3.0", "version": "0.4.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "wealth-ledger-frontend", "name": "wealth-ledger-frontend",
"version": "0.3.0", "version": "0.4.0",
"workspaces": [ "workspaces": [
"packages/*" "packages/*"
], ],
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "wealth-ledger-frontend", "name": "wealth-ledger-frontend",
"private": true, "private": true,
"version": "0.3.0", "version": "0.4.0",
"type": "module", "type": "module",
"engines": { "engines": {
"node": "24.21.0" "node": "24.21.0"
@@ -1,7 +1,7 @@
import { MantineProvider } from "@mantine/core"; import { MantineProvider } from "@mantine/core";
import { render, screen } from "@testing-library/react"; import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { LoadingSkeleton } from "./LoadingSkeleton"; import { LoadingSkeleton } from "../LoadingSkeleton/LoadingSkeleton";
import { StateView } from "./StateView"; import { StateView } from "./StateView";
describe("StateView", () => { describe("StateView", () => {
+3 -3
View File
@@ -1,3 +1,3 @@
export { EntryCard } from "./EntryCard"; export { EntryCard } from "./EntryCard/EntryCard";
export { LoadingSkeleton } from "./LoadingSkeleton"; export { LoadingSkeleton } from "./LoadingSkeleton/LoadingSkeleton";
export { StateView } from "./StateView"; export { StateView } from "./StateView/StateView";
@@ -16,6 +16,7 @@ import type { IncomeAnalytics } from "@/entities/income";
import type { Portfolio } from "@/entities/portfolio"; import type { Portfolio } from "@/entities/portfolio";
import { AuthProvider } from "@/features/auth"; import { AuthProvider } from "@/features/auth";
import { createTestQueryClient } from "@/test/query"; import { createTestQueryClient } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server"; import { server } from "@/test/server";
import { AppRoutes } from "./AppRoutes"; import { AppRoutes } from "./AppRoutes";
@@ -132,6 +133,7 @@ beforeEach(() => {
), ),
http.get("*/api/v1/brokerage-accounts", () => http.get("*/api/v1/brokerage-accounts", () =>
HttpResponse.json( HttpResponse.json(
resource(
accounts.map((account) => ({ accounts.map((account) => ({
...account, ...account,
type: "BROKERAGE", type: "BROKERAGE",
@@ -140,13 +142,15 @@ beforeEach(() => {
})), })),
), ),
), ),
),
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () => http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
HttpResponse.json(portfolio), HttpResponse.json(resource(portfolio)),
), ),
http.get( http.get(
"*/api/v1/brokerage-accounts/:accountId/operations", "*/api/v1/brokerage-accounts/:accountId/operations",
({ params }) => ({ params }) =>
HttpResponse.json({ HttpResponse.json(
resource({
accountId: params.accountId, accountId: params.accountId,
items, items,
hasNext: false, hasNext: false,
@@ -154,11 +158,13 @@ beforeEach(() => {
observedAt: receipt.occurredAt, observedAt: receipt.occurredAt,
}), }),
), ),
),
http.get("*/api/v1/brokerage-accounts/:accountId/income-analytics", () => http.get("*/api/v1/brokerage-accounts/:accountId/income-analytics", () =>
HttpResponse.json(analytics), HttpResponse.json(resource(analytics)),
), ),
http.get("*/api/v1/brokerage-accounts/:accountId/events", () => http.get("*/api/v1/brokerage-accounts/:accountId/events", () =>
HttpResponse.json({ HttpResponse.json(
resource({
accountId: "all", accountId: "all",
calculatedAt: receipt.occurredAt, calculatedAt: receipt.occurredAt,
incomeTotalsByCurrency: [], incomeTotalsByCurrency: [],
@@ -177,6 +183,7 @@ beforeEach(() => {
})), })),
}), }),
), ),
),
); );
}); });
@@ -224,7 +231,8 @@ describe("All accounts routes", () => {
({ request, params }) => { ({ request, params }) => {
const url = new URL(request.url); const url = new URL(request.url);
requests.push(url); requests.push(url);
return HttpResponse.json({ return HttpResponse.json(
resource({
accountId: params.accountId, accountId: params.accountId,
items: [ items: [
{ {
@@ -237,7 +245,8 @@ describe("All accounts routes", () => {
hasNext: !url.searchParams.has("cursor"), hasNext: !url.searchParams.has("cursor"),
nextCursor: url.searchParams.has("cursor") ? null : "next", nextCursor: url.searchParams.has("cursor") ? null : "next",
observedAt: receipt.occurredAt, observedAt: receipt.occurredAt,
}); }),
);
}, },
), ),
); );
@@ -274,7 +283,8 @@ describe("All accounts routes", () => {
{ code: "INVALID_OPERATIONS_CURSOR" }, { code: "INVALID_OPERATIONS_CURSOR" },
{ status: 400 }, { status: 400 },
) )
: HttpResponse.json({ : HttpResponse.json(
resource({
accountId: "all", accountId: "all",
items, items,
hasNext: true, hasNext: true,
@@ -282,6 +292,7 @@ describe("All accounts routes", () => {
observedAt: receipt.occurredAt, observedAt: receipt.occurredAt,
}), }),
), ),
),
); );
renderPage("/accounts/all/operations?from=2026-08-01&to=2026-08-31"); renderPage("/accounts/all/operations?from=2026-08-01&to=2026-08-31");
await screen.findAllByText("Выплата купона"); await screen.findAllByText("Выплата купона");
@@ -1,8 +1,8 @@
import type { FC } from "react"; import type { FC } from "react";
import { lazy } from "react"; import { lazy } from "react";
import { Navigate, Route, Routes } from "react-router"; import { Navigate, Route, Routes } from "react-router";
import { LazyPage } from "./RouteFallback"; import { LazyPage } from "../RouteFallback";
import { Protected, Public } from "./RouteGuards"; import { Protected, Public } from "../RouteGuards";
const CardPage = lazy(async () => { const CardPage = lazy(async () => {
const { CardPage } = await import("@/pages/card"); const { CardPage } = await import("@/pages/card");
@@ -65,7 +65,7 @@ const SettingsPage = lazy(async () => {
return { default: SettingsPage }; return { default: SettingsPage };
}); });
const ProtectedLayout = lazy(async () => { const ProtectedLayout = lazy(async () => {
const { ProtectedLayout } = await import("./ProtectedLayout"); const { ProtectedLayout } = await import("../ProtectedLayout");
return { default: ProtectedLayout }; return { default: ProtectedLayout };
}); });
@@ -12,6 +12,7 @@ import { MemoryRouter, useNavigate } from "react-router";
import { beforeEach, describe, expect, it } from "vitest"; import { beforeEach, describe, expect, it } from "vitest";
import { AuthProvider } from "@/features/auth"; import { AuthProvider } from "@/features/auth";
import { createTestQueryClient } from "@/test/query"; import { createTestQueryClient } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server"; import { server } from "@/test/server";
import { ProtectedDocumentTitle } from "./DocumentTitle"; import { ProtectedDocumentTitle } from "./DocumentTitle";
@@ -62,7 +63,7 @@ describe("document titles", () => {
server.use( server.use(
http.get("*/api/v1/brokerage-accounts", async () => { http.get("*/api/v1/brokerage-accounts", async () => {
await accountsReady; await accountsReady;
return HttpResponse.json([{ id: "a", name: "ИИС" }]); return HttpResponse.json(resource([{ id: "a", name: "ИИС" }]));
}), }),
); );
renderTitle("/accounts/a/income?from=2026-01-01&to=2026-08-31"); renderTitle("/accounts/a/income?from=2026-01-01&to=2026-08-31");
@@ -85,7 +86,7 @@ describe("document titles", () => {
async (kind, id, fallback, name) => { async (kind, id, fallback, name) => {
server.use( server.use(
http.get(`*/api/v1/${kind}/by-ticker/:ticker`, () => http.get(`*/api/v1/${kind}/by-ticker/:ticker`, () =>
HttpResponse.json({ name }), HttpResponse.json(resource({ name })),
), ),
); );
renderTitle(`/${kind}/${id}`); renderTitle(`/${kind}/${id}`);
+1 -1
View File
@@ -1,6 +1,6 @@
import type { FC } from "react"; import type { FC } from "react";
import { AppBreadcrumbs, AppShell } from "@/app/ui"; import { AppBreadcrumbs, AppShell } from "@/app/ui";
import { ProtectedDocumentTitle } from "./DocumentTitle"; import { ProtectedDocumentTitle } from "./DocumentTitle/DocumentTitle";
const ProtectedLayout: FC = () => { const ProtectedLayout: FC = () => {
return ( return (
+2 -2
View File
@@ -1,2 +1,2 @@
export { AppRoutes } from "./AppRoutes"; export { AppRoutes } from "./AppRoutes/AppRoutes";
export { RouteErrorBoundary } from "./RouteErrorBoundary"; export { RouteErrorBoundary } from "./RouteErrorBoundary/RouteErrorBoundary";
+2 -2
View File
@@ -1,2 +1,2 @@
export { AppBreadcrumbs } from "./AppBreadcrumbs"; export { AppBreadcrumbs } from "./AppBreadcrumbs/AppBreadcrumbs";
export { AppShell } from "./AppShell"; export { AppShell } from "./AppShell/AppShell";
+5 -5
View File
@@ -20,11 +20,11 @@ export {
} from "./model/form-validation"; } from "./model/form-validation";
export { bankOperationKinds } from "./model/operation-kinds"; export { bankOperationKinds } from "./model/operation-kinds";
export { bankPeriod } from "./model/period"; export { bankPeriod } from "./model/period";
export { BankCardFace } from "./ui/BankCardFace"; export { BankCardFace } from "./ui/BankCardFace/BankCardFace";
export { BankCardForm } from "./ui/BankCardForm"; export { BankCardForm } from "./ui/BankCardForm/BankCardForm";
export { BankFeedback } from "./ui/BankFeedback"; export { BankFeedback } from "./ui/BankFeedback";
export { BankOperationIcon } from "./ui/BankOperationIcon"; export { BankOperationIcon } from "./ui/BankOperationIcon/BankOperationIcon";
export { BankPeriodPicker } from "./ui/BankPeriodPicker"; export { BankPeriodPicker } from "./ui/BankPeriodPicker";
export { BankSummaryView } from "./ui/BankSummary.view"; export { BankSummaryView } from "./ui/BankSummary/BankSummary.view";
export { CategoryManager } from "./ui/CategoryManager"; export { CategoryManager } from "./ui/CategoryManager/CategoryManager";
export { useBankFormFocus } from "./ui/useBankFormFocus"; export { useBankFormFocus } from "./ui/useBankFormFocus";
@@ -1,7 +1,7 @@
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { formatMoney } from "@/shared/lib"; import { formatMoney } from "@/shared/lib";
import type { BankCard } from "../api/queries"; import type { BankCard } from "../../api/queries";
import classes from "./BankCardFace.module.css"; import classes from "./BankCardFace.module.css";
type BankCardFaceProps = { card: BankCard }; type BankCardFaceProps = { card: BankCard };
@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from "@storybook/react-vite"; import type { Meta, StoryObj } from "@storybook/react-vite";
import { FormProvider, useForm } from "react-hook-form"; import { FormProvider, useForm } from "react-hook-form";
import type { BankCardValues } from "../model/form-validation"; import type { BankCardValues } from "../../model/form-validation";
import { BankCardFields } from "./BankCardForm.view"; import { BankCardFields } from "./BankCardForm.view";
const meta = { const meta = {
@@ -6,7 +6,7 @@ import { describe, expect, it, vi } from "vitest";
import { configureAuthClient } from "@/shared/api"; import { configureAuthClient } from "@/shared/api";
import { createTestQueryClient } from "@/test/query"; import { createTestQueryClient } from "@/test/query";
import { server } from "@/test/server"; import { server } from "@/test/server";
import type { BankCard } from "../api/queries"; import type { BankCard } from "../../api/queries";
import { BankCardForm } from "./BankCardForm"; import { BankCardForm } from "./BankCardForm";
const card: BankCard = { const card: BankCard = {
@@ -4,18 +4,18 @@ import { type FC, useState } from "react";
import { FormProvider, useForm } from "react-hook-form"; import { FormProvider, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { formatDate } from "@/shared/lib"; import { formatDate } from "@/shared/lib";
import { useBankMutations } from "../api/mutations"; import { useBankMutations } from "../../api/mutations";
import { type BankCard, useBankCard } from "../api/queries"; import { type BankCard, useBankCard } from "../../api/queries";
import { import {
type BankCardValues, type BankCardValues,
bankCardSchema, bankCardSchema,
bankMoneyValue, bankMoneyValue,
bankToday, bankToday,
} from "../model/form-validation"; } from "../../model/form-validation";
import { BankFeedback } from "../BankFeedback";
import classes from "../BankForms.module.css";
import { useBankFormFocus } from "../useBankFormFocus";
import { BankCardFields } from "./BankCardForm.view"; import { BankCardFields } from "./BankCardForm.view";
import { BankFeedback } from "./BankFeedback";
import classes from "./BankForms.module.css";
import { useBankFormFocus } from "./useBankFormFocus";
type BankCardFormProps = { card?: BankCard; onClose: () => void }; type BankCardFormProps = { card?: BankCard; onClose: () => void };
const BankCardForm: FC<BankCardFormProps> = (props) => { const BankCardForm: FC<BankCardFormProps> = (props) => {
@@ -8,7 +8,7 @@ import {
bankDateInputValue, bankDateInputValue,
bankDateSchema, bankDateSchema,
bankToday, bankToday,
} from "../model/form-validation"; } from "../../model/form-validation";
type BankCardFieldsProps = { archived: boolean }; type BankCardFieldsProps = { archived: boolean };
const BankCardFields: FC<BankCardFieldsProps> = (props) => { const BankCardFields: FC<BankCardFieldsProps> = (props) => {
@@ -1,8 +1,8 @@
import type { FC } from "react"; import type { FC } from "react";
import { bindIconAnimation } from "@/shared/lib"; import { bindIconAnimation } from "@/shared/lib";
import type { BankOperation } from "../api/queries"; import type { BankOperation } from "../../api/queries";
import { bankOperationAppearance } from "../model/operation-appearance"; import { bankOperationAppearance } from "../../model/operation-appearance";
import classes from "./BankOperationIcon.module.css"; import classes from "./BankOperationIcon.module.css";
type BankOperationIconProps = { type BankOperationIconProps = {
@@ -3,8 +3,8 @@ import { LoadingSkeleton } from "@wealthledger/ui";
import type { CSSProperties, FC } from "react"; import type { CSSProperties, FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { formatMoney } from "@/shared/lib"; import { formatMoney } from "@/shared/lib";
import type { BankSummary } from "../api/queries"; import type { BankSummary } from "../../api/queries";
import { BankOperationIcon } from "./BankOperationIcon"; import { BankOperationIcon } from "../BankOperationIcon/BankOperationIcon";
import classes from "./BankSummary.module.css"; import classes from "./BankSummary.module.css";
type BankSummaryViewProps = { type BankSummaryViewProps = {
@@ -18,12 +18,12 @@ import {
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { z } from "zod"; import { z } from "zod";
import { validationMessage } from "@/shared/i18n"; import { validationMessage } from "@/shared/i18n";
import { useBankMutations } from "../api/mutations"; import { useBankMutations } from "../../api/mutations";
import { type ExpenseCategory, useBankCategories } from "../api/queries"; import { type ExpenseCategory, useBankCategories } from "../../api/queries";
import { BankFeedback } from "./BankFeedback"; import { BankFeedback } from "../BankFeedback";
import classes from "./BankForms.module.css"; import classes from "../BankForms.module.css";
import { BankOperationIcon } from "./BankOperationIcon"; import { BankOperationIcon } from "../BankOperationIcon/BankOperationIcon";
import { useBankFormFocus } from "./useBankFormFocus"; import { useBankFormFocus } from "../useBankFormFocus";
const MAX_CATEGORY_NAME_LENGTH = 80; const MAX_CATEGORY_NAME_LENGTH = 80;
+11 -13
View File
@@ -1,8 +1,4 @@
import { import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
apiQueryClient,
type paths,
useAuthenticatedQuery,
} from "@/shared/api";
type BondPeriod = NonNullable< type BondPeriod = NonNullable<
NonNullable< NonNullable<
@@ -13,7 +9,7 @@ type BondPeriod = NonNullable<
const BOND_STALE_TIME_MS = 30_000; const BOND_STALE_TIME_MS = 30_000;
function useBondSearch(query: string) { function useBondSearch(query: string) {
return useAuthenticatedQuery({ return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bonds", { ...apiQueryClient.queryOptions("get", "/api/v1/bonds", {
params: { query: { query } }, params: { query: { query } },
}), }),
@@ -36,11 +32,11 @@ function useBond(identifier: string) {
identifier, identifier,
); );
const byUid = useAuthenticatedQuery({ const byUid = useResourceQuery({
...bondQueryOptions(identifier), ...bondQueryOptions(identifier),
enabled: Boolean(identifier) && isUid, enabled: Boolean(identifier) && isUid,
}); });
const byTicker = useAuthenticatedQuery({ const byTicker = useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bonds/by-ticker/{ticker}", { ...apiQueryClient.queryOptions("get", "/api/v1/bonds/by-ticker/{ticker}", {
params: { path: { ticker: identifier } }, params: { path: { ticker: identifier } },
}), }),
@@ -50,7 +46,7 @@ function useBond(identifier: string) {
return isUid ? byUid : byTicker; return isUid ? byUid : byTicker;
} }
function useBondMetrics(uid: string) { function useBondMetrics(uid: string) {
return useAuthenticatedQuery({ return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/metrics", { ...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/metrics", {
params: { path: { uid } }, params: { path: { uid } },
}), }),
@@ -59,7 +55,7 @@ function useBondMetrics(uid: string) {
}); });
} }
function useBondQuote(uid: string) { function useBondQuote(uid: string) {
return useAuthenticatedQuery({ return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/quote", { ...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/quote", {
params: { path: { uid } }, params: { path: { uid } },
}), }),
@@ -68,7 +64,7 @@ function useBondQuote(uid: string) {
}); });
} }
function useBondCandles(uid: string, period: BondPeriod) { function useBondCandles(uid: string, period: BondPeriod) {
return useAuthenticatedQuery({ return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/candles", { ...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/candles", {
params: { path: { uid }, query: { period } }, params: { path: { uid }, query: { period } },
}), }),
@@ -77,7 +73,8 @@ function useBondCandles(uid: string, period: BondPeriod) {
}); });
} }
function useBondPosition(uid: string) { function useBondPosition(uid: string) {
return useAuthenticatedQuery({ return useResourceQuery({
meta: { accessGroup: "brokerage" },
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/position", { ...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/position", {
params: { path: { uid } }, params: { path: { uid } },
}), }),
@@ -86,7 +83,8 @@ function useBondPosition(uid: string) {
}); });
} }
function useBondCoupons(uid: string) { function useBondCoupons(uid: string) {
return useAuthenticatedQuery({ return useResourceQuery({
meta: { accessGroup: "brokerage" },
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/coupons", { ...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/coupons", {
params: { path: { uid } }, params: { path: { uid } },
}), }),
@@ -1,16 +1,14 @@
import { import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
apiQueryClient,
type paths,
useAuthenticatedQuery,
} from "@/shared/api";
type OperationsEndpoint = type OperationsEndpoint =
paths["/api/v1/brokerage-accounts/{accountId}/operations"]["get"]; paths["/api/v1/brokerage-accounts/{accountId}/operations"]["get"];
type BrokerageOperation = type BrokerageOperation = NonNullable<
OperationsEndpoint["responses"][200]["content"]["application/json"]["items"][number]; OperationsEndpoint["responses"][200]["content"]["application/json"]["data"]
type BrokerageOperationsQuery = NonNullable< >["items"][number];
OperationsEndpoint["parameters"]["query"] type BrokerageOperationsQuery = Omit<
NonNullable<OperationsEndpoint["parameters"]["query"]>,
"sync"
>; >;
type OperationCategory = BrokerageOperation["category"]; type OperationCategory = BrokerageOperation["category"];
@@ -56,7 +54,8 @@ function useBrokerageOperations(
accountId: string | undefined, accountId: string | undefined,
query: BrokerageOperationsQuery = {}, query: BrokerageOperationsQuery = {},
) { ) {
return useAuthenticatedQuery({ return useResourceQuery({
meta: { accessGroup: "brokerage" },
...brokerageOperationsQueryOptions(accountId, query), ...brokerageOperationsQueryOptions(accountId, query),
enabled: Boolean(accountId), enabled: Boolean(accountId),
staleTime: 30_000, staleTime: 30_000,
@@ -3,6 +3,7 @@ import { HttpResponse, http } from "msw";
import { describe, expect, it, vi } from "vitest"; import { describe, expect, it, vi } from "vitest";
import { configureAuthClient } from "@/shared/api"; import { configureAuthClient } from "@/shared/api";
import { createQueryWrapper } from "@/test/query"; import { createQueryWrapper } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server"; import { server } from "@/test/server";
import { useBrokerageAccounts } from "./useBrokerageAccounts"; import { useBrokerageAccounts } from "./useBrokerageAccounts";
@@ -15,7 +16,8 @@ describe("useBrokerageAccounts", () => {
}); });
server.use( server.use(
http.get("*/api/v1/brokerage-accounts", () => http.get("*/api/v1/brokerage-accounts", () =>
HttpResponse.json([ HttpResponse.json(
resource([
{ {
id: "account-1", id: "account-1",
name: "Основной", name: "Основной",
@@ -24,6 +26,7 @@ describe("useBrokerageAccounts", () => {
}, },
]), ]),
), ),
),
); );
const { result } = renderHook(() => useBrokerageAccounts(), { const { result } = renderHook(() => useBrokerageAccounts(), {
@@ -52,14 +55,16 @@ describe("useBrokerageAccounts", () => {
http.get("*/api/v1/brokerage-accounts", () => { http.get("*/api/v1/brokerage-accounts", () => {
calls += 1; calls += 1;
return calls === 1 return calls === 1
? HttpResponse.json([ ? HttpResponse.json(
resource([
{ {
id: "account-1", id: "account-1",
name: "Основной", name: "Основной",
type: "BROKERAGE", type: "BROKERAGE",
openedOn: "2024-08-13", openedOn: "2024-08-13",
}, },
]) ]),
)
: HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }); : HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 });
}), }),
); );
@@ -1,19 +1,17 @@
import { import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
apiQueryClient,
type paths,
useAuthenticatedQuery,
} from "@/shared/api";
const brokerageAccountsQueryOptions = () => const brokerageAccountsQueryOptions = () =>
apiQueryClient.queryOptions("get", "/api/v1/brokerage-accounts"); apiQueryClient.queryOptions("get", "/api/v1/brokerage-accounts");
const brokerageAccountsQueryKey = brokerageAccountsQueryOptions().queryKey; const brokerageAccountsQueryKey = brokerageAccountsQueryOptions().queryKey;
type BrokerageAccount = type BrokerageAccount = NonNullable<
paths["/api/v1/brokerage-accounts"]["get"]["responses"][200]["content"]["application/json"][number]; paths["/api/v1/brokerage-accounts"]["get"]["responses"][200]["content"]["application/json"]["data"]
>[number];
function useBrokerageAccounts() { function useBrokerageAccounts() {
return useAuthenticatedQuery({ return useResourceQuery({
meta: { accessGroup: "brokerage" },
...brokerageAccountsQueryOptions(), ...brokerageAccountsQueryOptions(),
staleTime: 60_000, staleTime: 60_000,
}); });
+1 -1
View File
@@ -8,4 +8,4 @@ export {
type BrokerageAccountCard, type BrokerageAccountCard,
brokerageAccountCards, brokerageAccountCards,
} from "./model/display"; } from "./model/display";
export { BrokerageAccountList } from "./ui/BrokerageAccountList"; export { BrokerageAccountList } from "./ui/BrokerageAccountList/BrokerageAccountList";
@@ -1,10 +1,18 @@
import type { BrokerageAccount } from "../api/useBrokerageAccounts"; import type {
BrokerageAccount,
useBrokerageAccounts,
} from "../api/useBrokerageAccounts";
type Money = NonNullable< type Money = NonNullable<
BrokerageAccount["portfolioSummary"] BrokerageAccount["portfolioSummary"]
>["totalsByCurrency"][number]; >["totalsByCurrency"][number];
type BrokerageAccountCard = { type BrokerageAccountCard = {
source?: NonNullable<
ReturnType<typeof useBrokerageAccounts>["meta"]
>["dependencies"] extends (infer T)[] | undefined
? T
: never;
account: BrokerageAccount; account: BrokerageAccount;
positionCounts: { stocks: number; bonds: number } | null; positionCounts: { stocks: number; bonds: number } | null;
summary: summary:
@@ -19,11 +27,19 @@ function accountTypeKey(type: BrokerageAccount["type"]) {
function brokerageAccountCards( function brokerageAccountCards(
accounts: BrokerageAccount[], accounts: BrokerageAccount[],
dependencies: NonNullable<
ReturnType<typeof useBrokerageAccounts>["meta"]
>["dependencies"] = [],
): BrokerageAccountCard[] { ): BrokerageAccountCard[] {
return accounts.map((account) => { return accounts.map((account) => {
const source = dependencies.find(
(item) =>
item.resourceKey === `portfolio/${encodeURIComponent(account.id)}`,
);
const summary = account.portfolioSummary; const summary = account.portfolioSummary;
if (!summary) if (!summary)
return { return {
source,
account, account,
positionCounts: null, positionCounts: null,
summary: { state: "unavailable" }, summary: { state: "unavailable" },
@@ -33,8 +49,9 @@ function brokerageAccountCards(
bonds: summary.bondPositionCount, bonds: summary.bondPositionCount,
}; };
if (!summary.totalsByCurrency.length) if (!summary.totalsByCurrency.length)
return { account, positionCounts, summary: { state: "empty" } }; return { source, account, positionCounts, summary: { state: "empty" } };
return { return {
source,
account, account,
positionCounts, positionCounts,
summary: { summary: {
@@ -1,7 +1,7 @@
import type { Meta, StoryObj } from "@storybook/react-vite"; import type { Meta, StoryObj } from "@storybook/react-vite";
import { MemoryRouter } from "react-router"; import { MemoryRouter } from "react-router";
import type { BrokerageAccount } from "../api/useBrokerageAccounts"; import type { BrokerageAccount } from "../../api/useBrokerageAccounts";
import { brokerageAccountCards } from "../model/display"; import { brokerageAccountCards } from "../../model/display";
import { BrokerageAccountList } from "./BrokerageAccountList"; import { BrokerageAccountList } from "./BrokerageAccountList";
const syntheticAccount = { const syntheticAccount = {
@@ -185,3 +185,44 @@ export const LargeValues: Story = {
]), ]),
}, },
}; };
export const IndependentFreshness: Story = {
name: "Независимая свежесть и ошибка сводок",
args: {
accounts: brokerageAccountCards(
[
syntheticAccount,
{
...syntheticAccount,
id: "waiting",
name: "Новый счёт",
portfolioSummary: null,
},
],
[
{
resourceKey: "portfolio/storybook-account",
dataRevision: "1",
stateVersion: "failed",
availability: "complete",
freshness: "stale",
lastSuccessfulAt: "2026-09-24T10:30:00Z",
sync: {
id: "failed",
state: "failed",
errorCode: "TBANK_UNAVAILABLE",
},
},
{
resourceKey: "portfolio/waiting",
dataRevision: "0",
stateVersion: "waiting",
availability: "missing",
freshness: "unknown",
lastSuccessfulAt: null,
sync: { id: "waiting", state: "running", errorCode: null },
},
],
),
},
};
@@ -2,7 +2,8 @@ import { MantineProvider } from "@mantine/core";
import { render, screen, within } from "@testing-library/react"; import { render, screen, within } from "@testing-library/react";
import { MemoryRouter } from "react-router"; import { MemoryRouter } from "react-router";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { brokerageAccountCards } from "../model/display"; import { resource } from "@/test/resource";
import { brokerageAccountCards } from "../../model/display";
import { BrokerageAccountList } from "./BrokerageAccountList"; import { BrokerageAccountList } from "./BrokerageAccountList";
describe("BrokerageAccountList", () => { describe("BrokerageAccountList", () => {
@@ -84,3 +85,42 @@ describe("BrokerageAccountList", () => {
).not.toBeInTheDocument(); ).not.toBeInTheDocument();
}); });
}); });
it("shows portfolio summary freshness independently for each account", () => {
const accounts = brokerageAccountCards(
["fresh", "stale"].map((id) => ({
id,
name: id,
type: "BROKERAGE" as const,
openedOn: null,
portfolioSummary: {
stockPositionCount: 1,
bondPositionCount: 0,
totalsByCurrency: [{ currency: "RUB", value: "10" }],
},
})),
[
resource(null, { resourceKey: "portfolio/fresh", freshness: "fresh" })
.meta,
resource(null, { resourceKey: "portfolio/stale", freshness: "stale" })
.meta,
],
);
render(
<MantineProvider>
<MemoryRouter>
<BrokerageAccountList accounts={accounts} />
</MemoryRouter>
</MantineProvider>,
);
expect(
within(screen.getByRole("link", { name: /stale/ })).getByText(
"Данные требуют обновления",
),
).toBeVisible();
expect(
within(screen.getByRole("link", { name: /fresh/ })).queryByText(
"Данные требуют обновления",
),
).not.toBeInTheDocument();
});
@@ -2,9 +2,9 @@ import { Card, Group, SimpleGrid, Stack, Text } from "@mantine/core";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Link } from "react-router"; import { Link } from "react-router";
import { formatDate, formatMoney } from "@/shared/lib"; import { formatDate, formatMoney, formatSnapshotTime } from "@/shared/lib";
import type { BrokerageAccountCard } from "../model/display"; import type { BrokerageAccountCard } from "../../model/display";
import { accountTypeKey } from "../model/display"; import { accountTypeKey } from "../../model/display";
import classes from "./BrokerageAccountList.module.css"; import classes from "./BrokerageAccountList.module.css";
type BrokerageAccountListProps = { accounts: BrokerageAccountCard[] }; type BrokerageAccountListProps = { accounts: BrokerageAccountCard[] };
@@ -52,8 +52,8 @@ const BrokerageAccountList: FC<BrokerageAccountListProps> = (props) => {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
<SimpleGrid className={classes.list} cols={{ base: 1, lg: 2 }} spacing="lg"> <SimpleGrid className={classes.list} cols={1} spacing="lg">
{accounts.map(({ account, summary, positionCounts }) => ( {accounts.map(({ account, summary, positionCounts, source }) => (
<Card <Card
component={Link} component={Link}
to={`/accounts/${account.id}`} to={`/accounts/${account.id}`}
@@ -92,6 +92,25 @@ const BrokerageAccountList: FC<BrokerageAccountListProps> = (props) => {
{t("accounts.currentValue")} {t("accounts.currentValue")}
</Text> </Text>
<BrokerageAccountSummary summary={summary} /> <BrokerageAccountSummary summary={summary} />
{source?.lastSuccessfulAt ? (
<Text size="xs" c="dimmed">
{t("investment.sourceTime", {
date: formatSnapshotTime(source.lastSuccessfulAt),
})}
</Text>
) : null}
{source?.sync.state === "running" ||
source?.sync.state === "queued" ? (
<Text size="xs" role="status">
{t("accounts.refreshing")}
</Text>
) : null}
{source?.sync.state === "failed" ? (
<Text size="xs">{t("accounts.refreshError")}</Text>
) : null}
{source?.freshness === "stale" ? (
<Text size="xs">{t("investment.stale")}</Text>
) : null}
</Stack> </Stack>
{positionCounts ? ( {positionCounts ? (
<dl className={classes.positions}> <dl className={classes.positions}>
@@ -3,6 +3,7 @@ import { HttpResponse, http } from "msw";
import { describe, expect, it, vi } from "vitest"; import { describe, expect, it, vi } from "vitest";
import { configureAuthClient } from "@/shared/api"; import { configureAuthClient } from "@/shared/api";
import { createQueryWrapper } from "@/test/query"; import { createQueryWrapper } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server"; import { server } from "@/test/server";
import { useBrokerageEvents } from "./useBrokerageEvents"; import { useBrokerageEvents } from "./useBrokerageEvents";
@@ -31,7 +32,8 @@ describe("useBrokerageEvents", () => {
}); });
server.use( server.use(
http.get("*/api/v1/brokerage-accounts/account-1/events", () => http.get("*/api/v1/brokerage-accounts/account-1/events", () =>
HttpResponse.json({ HttpResponse.json(
resource({
accountId: "account-1", accountId: "account-1",
calculatedAt: "2026-08-14T00:00:00Z", calculatedAt: "2026-08-14T00:00:00Z",
events: [ events: [
@@ -49,6 +51,7 @@ describe("useBrokerageEvents", () => {
], ],
}), }),
), ),
),
); );
const { result } = renderHook(() => useBrokerageEvents("account-1"), { const { result } = renderHook(() => useBrokerageEvents("account-1"), {
@@ -1,19 +1,17 @@
import { import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
apiQueryClient,
type paths,
useAuthenticatedQuery,
} from "@/shared/api";
type EventsEndpoint = type EventsEndpoint =
paths["/api/v1/brokerage-accounts/{accountId}/events"]["get"]; paths["/api/v1/brokerage-accounts/{accountId}/events"]["get"];
type BrokerageEvent = type BrokerageEvent = NonNullable<
EventsEndpoint["responses"][200]["content"]["application/json"]["events"][number]; EventsEndpoint["responses"][200]["content"]["application/json"]["data"]
>["events"][number];
function useBrokerageEvents( function useBrokerageEvents(
accountId: string | undefined, accountId: string | undefined,
query: EventsEndpoint["parameters"]["query"] = {}, query: Omit<NonNullable<EventsEndpoint["parameters"]["query"]>, "sync"> = {},
) { ) {
return useAuthenticatedQuery({ return useResourceQuery({
meta: { accessGroup: "brokerage" },
...apiQueryClient.queryOptions( ...apiQueryClient.queryOptions(
"get", "get",
"/api/v1/brokerage-accounts/{accountId}/events", "/api/v1/brokerage-accounts/{accountId}/events",
+1 -1
View File
@@ -6,4 +6,4 @@ export { BrokerageEventCard } from "./ui/BrokerageEventCard";
export { export {
BrokerageEventsPreview, BrokerageEventsPreview,
type BrokerageEventsPreviewState, type BrokerageEventsPreviewState,
} from "./ui/BrokerageEventsPreview"; } from "./ui/BrokerageEventsPreview/BrokerageEventsPreview";
@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from "@storybook/react-vite"; import type { Meta, StoryObj } from "@storybook/react-vite";
import { MemoryRouter } from "react-router"; import { MemoryRouter } from "react-router";
import type { BrokerageEvent } from "../api/useBrokerageEvents"; import type { BrokerageEvent } from "../../api/useBrokerageEvents";
import { BrokerageEventsPreview } from "./BrokerageEventsPreview"; import { BrokerageEventsPreview } from "./BrokerageEventsPreview";
const syntheticEvent = { const syntheticEvent = {
@@ -3,8 +3,9 @@ import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Link } from "react-router"; import { Link } from "react-router";
import type { BrokerageEvent } from "../api/useBrokerageEvents"; import { formatSnapshotTime } from "@/shared/lib";
import { BrokerageEventCard } from "./BrokerageEventCard"; import type { BrokerageEvent } from "../../api/useBrokerageEvents";
import { BrokerageEventCard } from "../BrokerageEventCard";
type BrokerageEventsPreviewProps = { type BrokerageEventsPreviewProps = {
events: BrokerageEventsPreviewState; events: BrokerageEventsPreviewState;
@@ -12,7 +13,14 @@ type BrokerageEventsPreviewProps = {
type BrokerageEventsPreviewState = type BrokerageEventsPreviewState =
| { state: "loading" | "error" | "empty"; to: string } | { state: "loading" | "error" | "empty"; to: string }
| { state: "loaded"; to: string; items: BrokerageEvent[] }; | {
state: "loaded" | "partial";
to: string;
lastSuccessfulAt?: string | null;
stale?: boolean;
refreshError?: boolean;
items: BrokerageEvent[];
};
const BrokerageEventsPreview: FC<BrokerageEventsPreviewProps> = (props) => { const BrokerageEventsPreview: FC<BrokerageEventsPreviewProps> = (props) => {
const { events } = props; const { events } = props;
@@ -20,6 +28,21 @@ const BrokerageEventsPreview: FC<BrokerageEventsPreviewProps> = (props) => {
return ( return (
<Stack gap="sm"> <Stack gap="sm">
{events.state === "loaded" ? (
<>
{events.lastSuccessfulAt ? (
<Text size="xs" c="dimmed">
{t("investment.sourceTime", {
date: formatSnapshotTime(events.lastSuccessfulAt),
})}
</Text>
) : null}
{events.stale ? <Text size="xs">{t("investment.stale")}</Text> : null}
{events.refreshError ? (
<Text role="status">{t("accounts.refreshError")}</Text>
) : null}
</>
) : null}
{events.state === "loading" ? ( {events.state === "loading" ? (
<LoadingSkeleton label={t("events.recentLoading")}> <LoadingSkeleton label={t("events.recentLoading")}>
{[0, 1, 2].map((index) => ( {[0, 1, 2].map((index) => (
@@ -33,7 +56,10 @@ const BrokerageEventsPreview: FC<BrokerageEventsPreviewProps> = (props) => {
{events.state === "empty" ? ( {events.state === "empty" ? (
<Text c="dimmed">{t("events.recentEmpty")}</Text> <Text c="dimmed">{t("events.recentEmpty")}</Text>
) : null} ) : null}
{events.state === "loaded" {events.state === "partial" ? (
<Text role="status">{t("investment.partial")}</Text>
) : null}
{events.state === "loaded" || events.state === "partial"
? events.items.map((event) => ( ? events.items.map((event) => (
<BrokerageEventCard <BrokerageEventCard
key={JSON.stringify([ key={JSON.stringify([
+11 -11
View File
@@ -1,16 +1,15 @@
import { import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
apiQueryClient,
type paths,
useAuthenticatedQuery,
} from "@/shared/api";
type IncomeSummary = type IncomeSummary = NonNullable<
paths["/api/v1/brokerage-accounts/{accountId}/income-summary"]["get"]["responses"][200]["content"]["application/json"]; paths["/api/v1/brokerage-accounts/{accountId}/income-summary"]["get"]["responses"][200]["content"]["application/json"]["data"]
type IncomeAnalytics = >;
paths["/api/v1/brokerage-accounts/{accountId}/income-analytics"]["get"]["responses"][200]["content"]["application/json"]; type IncomeAnalytics = NonNullable<
paths["/api/v1/brokerage-accounts/{accountId}/income-analytics"]["get"]["responses"][200]["content"]["application/json"]["data"]
>;
function useIncomeSummary(accountId: string | undefined) { function useIncomeSummary(accountId: string | undefined) {
return useAuthenticatedQuery({ return useResourceQuery({
meta: { accessGroup: "brokerage" },
...apiQueryClient.queryOptions( ...apiQueryClient.queryOptions(
"get", "get",
"/api/v1/brokerage-accounts/{accountId}/income-summary", "/api/v1/brokerage-accounts/{accountId}/income-summary",
@@ -25,7 +24,8 @@ function useIncomeAnalytics(
accountId: string | undefined, accountId: string | undefined,
period: { from: string; to: string }, period: { from: string; to: string },
) { ) {
return useAuthenticatedQuery({ return useResourceQuery({
meta: { accessGroup: "brokerage" },
...apiQueryClient.queryOptions( ...apiQueryClient.queryOptions(
"get", "get",
"/api/v1/brokerage-accounts/{accountId}/income-analytics", "/api/v1/brokerage-accounts/{accountId}/income-analytics",
@@ -0,0 +1,144 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { describe, expect, it, vi } from "vitest";
import { apiClient, configureAuthClient } from "@/shared/api";
import { createQueryWrapper } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server";
import {
type Portfolio,
portfolioQueryOptions,
usePortfolio,
} from "./usePortfolio";
const snapshot: Portfolio = {
positions: [],
totalsByCurrency: [{ currency: "RUB", value: "123.000000001" }],
cashBalances: [],
structure: { currencies: [], unvaluedCategories: [] },
lastSuccessfulAt: "2026-08-14T00:00:00Z",
isStale: false,
};
function auth() {
configureAuthClient({
accessToken: () => "synthetic",
refresh: async () => true,
clear: vi.fn(),
});
}
describe("persistent resource query lifecycle", () => {
it("observes into the canonical cache and rejects an old notified state before accepting the current one", async () => {
auth();
const modes: (string | null)[] = [];
let observations = 0;
server.use(
http.get(
"*/api/v1/brokerage-accounts/:accountId/portfolio",
({ request }) => {
const mode = new URL(request.url).searchParams.get("sync");
modes.push(mode);
if (mode) observations += 1;
return HttpResponse.json(
resource(snapshot, {
stateVersion: observations > 1 ? "new" : "old",
}),
);
},
),
);
const { wrapper, queryClient } = createQueryWrapper();
const { result } = renderHook(() => usePortfolio("a"), { wrapper });
await waitFor(() => expect(result.current.isSuccess).toBe(true));
await act(() => result.current.observe("new"));
await waitFor(() => expect(result.current.meta?.stateVersion).toBe("new"));
expect(modes).toEqual([null, "observe", "observe"]);
expect(queryClient.getQueryCache().getAll()).toHaveLength(1);
expect(
queryClient.getQueryData(portfolioQueryOptions("a").queryKey),
).toMatchObject({ meta: { stateVersion: "new" }, data: snapshot });
});
it("does not convert missing or failed source data to empty financial success", async () => {
auth();
server.use(
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
HttpResponse.json(
resource(null, {
sync: {
id: "work",
state: "failed",
errorCode: "TBANK_UNAVAILABLE",
},
}),
),
),
);
const { result } = renderHook(() => usePortfolio("a"), {
wrapper: createQueryWrapper().wrapper,
});
await waitFor(() => expect(result.current.meta?.sync.state).toBe("failed"));
expect(result.current.data).toBeUndefined();
expect(result.current.isSuccess).toBe(false);
expect(result.current.meta?.availability).toBe("missing");
});
it("rejects a late ordinary response when an observe response for that resource arrived first", async () => {
auth();
let release!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
server.use(
http.get(
"*/api/v1/brokerage-accounts/:accountId/portfolio",
async ({ request }) => {
if (!new URL(request.url).searchParams.has("sync")) await blocked;
return HttpResponse.json(resource(snapshot));
},
),
);
const old = apiClient.GET(
"/api/v1/brokerage-accounts/{accountId}/portfolio",
{ params: { path: { accountId: "a" } } },
);
const rejected = expect(old).rejects.toMatchObject({ name: "AbortError" });
await apiClient.GET("/api/v1/brokerage-accounts/{accountId}/portfolio", {
params: { path: { accountId: "a" }, query: { sync: "observe" } },
});
release();
await rejected;
});
it("clears private snapshots on confirmed access loss and fences another pending success", async () => {
auth();
let denied = false;
let release!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
server.use(
http.get(
"*/api/v1/brokerage-accounts/:accountId/portfolio",
async ({ params }) => {
if (params.accountId === "b") await blocked;
if (params.accountId === "a" && denied)
return HttpResponse.json({ code: "NOT_FOUND" }, { status: 404 });
return HttpResponse.json(resource(snapshot));
},
),
);
const { wrapper } = createQueryWrapper();
const { result } = renderHook(
() => ({ a: usePortfolio("a"), b: usePortfolio("b") }),
{ wrapper },
);
await waitFor(() => expect(result.current.a.data).toEqual(snapshot));
denied = true;
await act(() => result.current.a.refetch());
await waitFor(() => expect(result.current.a.data).toBeUndefined());
await act(async () => {
release();
await blocked;
});
expect(result.current.b.data).toBeUndefined();
expect(result.current.a.isError).toBe(true);
});
});
@@ -1,9 +1,9 @@
import { renderHook, waitFor } from "@testing-library/react"; import { renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw"; import { HttpResponse, http } from "msw";
import { describe, expect, it, vi } from "vitest"; import { describe, expect, it, vi } from "vitest";
import { configureAuthClient } from "@/shared/api"; import { configureAuthClient } from "@/shared/api";
import { createQueryWrapper } from "@/test/query"; import { createQueryWrapper } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server"; import { server } from "@/test/server";
import { usePortfolio } from "./usePortfolio"; import { usePortfolio } from "./usePortfolio";
@@ -33,14 +33,16 @@ describe("usePortfolio", () => {
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () => { http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () => {
calls += 1; calls += 1;
return calls === 1 return calls === 1
? HttpResponse.json({ ? HttpResponse.json(
resource({
lastSuccessfulAt: "2026-08-14T00:00:00Z", lastSuccessfulAt: "2026-08-14T00:00:00Z",
isStale: false, isStale: false,
totalsByCurrency: [], totalsByCurrency: [],
positions: [], positions: [],
structure: { currencies: [], unvaluedCategories: [] }, structure: { currencies: [], unvaluedCategories: [] },
cashBalances: [], cashBalances: [],
}) }),
)
: HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }); : HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 });
}), }),
); );
+6 -8
View File
@@ -1,15 +1,12 @@
import { import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
apiQueryClient,
type paths,
useAuthenticatedQuery,
} from "@/shared/api";
const portfolioQueryPolicy = { const portfolioQueryPolicy = {
staleTime: 30_000, staleTime: 30_000,
} as const; } as const;
type Portfolio = type Portfolio = NonNullable<
paths["/api/v1/brokerage-accounts/{accountId}/portfolio"]["get"]["responses"][200]["content"]["application/json"]; paths["/api/v1/brokerage-accounts/{accountId}/portfolio"]["get"]["responses"][200]["content"]["application/json"]["data"]
>;
function portfolioQueryOptions(accountId: string | undefined) { function portfolioQueryOptions(accountId: string | undefined) {
return apiQueryClient.queryOptions( return apiQueryClient.queryOptions(
@@ -20,7 +17,8 @@ function portfolioQueryOptions(accountId: string | undefined) {
} }
function usePortfolio(accountId: string | undefined) { function usePortfolio(accountId: string | undefined) {
return useAuthenticatedQuery({ return useResourceQuery({
meta: { accessGroup: "brokerage" },
...portfolioQueryOptions(accountId), ...portfolioQueryOptions(accountId),
enabled: Boolean(accountId), enabled: Boolean(accountId),
...portfolioQueryPolicy, ...portfolioQueryPolicy,
+16 -10
View File
@@ -1,8 +1,9 @@
import { import {
apiQueryClient, apiQueryClient,
type paths, type paths,
unwrapResourceResult,
useAuthenticatedQueries, useAuthenticatedQueries,
useAuthenticatedQuery, useResourceQuery,
} from "@/shared/api"; } from "@/shared/api";
type StockPeriod = NonNullable< type StockPeriod = NonNullable<
@@ -14,7 +15,7 @@ type StockPeriod = NonNullable<
const STOCK_STALE_TIME_MS = 30_000; const STOCK_STALE_TIME_MS = 30_000;
function useStockSearch(query: string) { function useStockSearch(query: string) {
return useAuthenticatedQuery({ return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/stocks", { ...apiQueryClient.queryOptions("get", "/api/v1/stocks", {
params: { query: { query } }, params: { query: { query } },
}), }),
@@ -35,7 +36,10 @@ function useStocks(uids: string[]) {
const uniqueUids = [...new Set(uids)]; const uniqueUids = [...new Set(uids)];
const queries = useAuthenticatedQueries(uniqueUids.map(stockQueryOptions)); const queries = useAuthenticatedQueries(uniqueUids.map(stockQueryOptions));
return new Map( return new Map(
queries.map((query, index) => [uniqueUids[index], query.data]), queries.map((query, index) => [
uniqueUids[index],
unwrapResourceResult(query).data,
]),
); );
} }
@@ -45,11 +49,11 @@ function useStock(identifier: string) {
identifier, identifier,
); );
const byUid = useAuthenticatedQuery({ const byUid = useResourceQuery({
...stockQueryOptions(identifier), ...stockQueryOptions(identifier),
enabled: Boolean(identifier) && isUid, enabled: Boolean(identifier) && isUid,
}); });
const byTicker = useAuthenticatedQuery({ const byTicker = useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/stocks/by-ticker/{ticker}", { ...apiQueryClient.queryOptions("get", "/api/v1/stocks/by-ticker/{ticker}", {
params: { path: { ticker: identifier } }, params: { path: { ticker: identifier } },
}), }),
@@ -59,7 +63,7 @@ function useStock(identifier: string) {
return isUid ? byUid : byTicker; return isUid ? byUid : byTicker;
} }
function useStockQuote(uid: string) { function useStockQuote(uid: string) {
return useAuthenticatedQuery({ return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/quote", { ...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/quote", {
params: { path: { uid } }, params: { path: { uid } },
}), }),
@@ -68,7 +72,7 @@ function useStockQuote(uid: string) {
}); });
} }
function useStockCandles(uid: string, period: StockPeriod) { function useStockCandles(uid: string, period: StockPeriod) {
return useAuthenticatedQuery({ return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/candles", { ...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/candles", {
params: { path: { uid }, query: { period } }, params: { path: { uid }, query: { period } },
}), }),
@@ -77,7 +81,8 @@ function useStockCandles(uid: string, period: StockPeriod) {
}); });
} }
function useStockPosition(uid: string) { function useStockPosition(uid: string) {
return useAuthenticatedQuery({ return useResourceQuery({
meta: { accessGroup: "brokerage" },
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/position", { ...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/position", {
params: { path: { uid } }, params: { path: { uid } },
}), }),
@@ -86,7 +91,7 @@ function useStockPosition(uid: string) {
}); });
} }
function useStockCompany(uid: string) { function useStockCompany(uid: string) {
return useAuthenticatedQuery({ return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/company", { ...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/company", {
params: { path: { uid } }, params: { path: { uid } },
}), }),
@@ -95,7 +100,8 @@ function useStockCompany(uid: string) {
}); });
} }
function useStockDividends(uid: string) { function useStockDividends(uid: string) {
return useAuthenticatedQuery({ return useResourceQuery({
meta: { accessGroup: "brokerage" },
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/dividends", { ...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/dividends", {
params: { path: { uid } }, params: { path: { uid } },
}), }),
+1 -1
View File
@@ -1,4 +1,4 @@
export { AuthProvider, useAuth } from "./model/auth"; export { AuthProvider, useAuth } from "./model/auth";
export { AuthPageLayout } from "./ui/AuthPageLayout"; export { AuthPageLayout } from "./ui/AuthPageLayout/AuthPageLayout";
export { LoginForm } from "./ui/LoginForm"; export { LoginForm } from "./ui/LoginForm";
export { RegisterForm } from "./ui/RegisterForm"; export { RegisterForm } from "./ui/RegisterForm";
+2 -1
View File
@@ -5,6 +5,7 @@ import type { FC, PropsWithChildren } from "react";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { apiClient, apiQueryClient, useAuthenticatedQuery } from "@/shared/api"; import { apiClient, apiQueryClient, useAuthenticatedQuery } from "@/shared/api";
import { createTestQueryClient } from "@/test/query"; import { createTestQueryClient } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server"; import { server } from "@/test/server";
import { AuthProvider, useAuth } from "./auth"; import { AuthProvider, useAuth } from "./auth";
@@ -24,7 +25,7 @@ describe("AuthProvider", () => {
), ),
http.get("*/api/v1/brokerage-accounts", ({ request }) => { http.get("*/api/v1/brokerage-accounts", ({ request }) => {
authorization = request.headers.get("Authorization"); authorization = request.headers.get("Authorization");
return HttpResponse.json([]); return HttpResponse.json(resource([]));
}), }),
); );
const queryClient = createTestQueryClient(); const queryClient = createTestQueryClient();
+1 -1
View File
@@ -143,8 +143,8 @@ const AuthProvider: FC<PropsWithChildren> = (props) => {
refresh, refresh,
clear: clearSession, clear: clearSession,
}); });
return () => configureAuthClient(null);
}); });
useEffect(() => () => configureAuthClient(null), []);
return ( return (
<AuthContext <AuthContext
@@ -9,7 +9,7 @@ import {
type AuthFormValues, type AuthFormValues,
loginSchema, loginSchema,
registerSchema, registerSchema,
} from "../model/validation"; } from "../../model/validation";
import classes from "./AuthForm.module.css"; import classes from "./AuthForm.module.css";
type AuthFormProps = { type AuthFormProps = {
+1 -1
View File
@@ -1,7 +1,7 @@
import type { FC } from "react"; import type { FC } from "react";
import { useLocation, useNavigate } from "react-router"; import { useLocation, useNavigate } from "react-router";
import { useAuth } from "../model/auth"; import { useAuth } from "../model/auth";
import { AuthForm } from "./AuthForm"; import { AuthForm } from "./AuthForm/AuthForm";
const LoginForm: FC = () => { const LoginForm: FC = () => {
const { login } = useAuth(); const { login } = useAuth();
+1 -1
View File
@@ -1,7 +1,7 @@
import type { FC } from "react"; import type { FC } from "react";
import { useLocation, useNavigate } from "react-router"; import { useLocation, useNavigate } from "react-router";
import { useAuth } from "../model/auth"; import { useAuth } from "../model/auth";
import { AuthForm } from "./AuthForm"; import { AuthForm } from "./AuthForm/AuthForm";
const RegisterForm: FC = () => { const RegisterForm: FC = () => {
const { register } = useAuth(); const { register } = useAuth();
@@ -0,0 +1,59 @@
import { describe, expect, it, vi } from "vitest";
import { resource } from "@/test/resource";
import { section } from "./section";
describe("instrument source and transport presentation", () => {
it.each(["missing", "partial", "complete"] as const)(
"keeps %s separate from successful transport",
(availability) => {
const data = availability === "missing" ? undefined : { rows: [] };
const state = section({
data,
meta: resource(data, { availability }).meta,
isError: false,
isFetching: false,
refetch: vi.fn(),
});
expect(state.loading).toBe(availability === "missing");
expect(state.partial).toBe(availability === "partial");
expect(state.hasData).toBe(availability !== "missing");
},
);
it("preserves a full fresh source and timestamp when force fails, while offering scoped retry", () => {
const retry = vi.fn();
const refetch = vi.fn();
const meta = resource([], {
sync: { id: "work", state: "failed", errorCode: "TBANK_UNAVAILABLE" },
}).meta;
const state = section(
{ data: [], meta, isError: false, isFetching: false, refetch },
retry,
);
expect(state).toMatchObject({
hasData: true,
loading: false,
error: true,
refreshing: false,
lastSuccessfulAt: meta.lastSuccessfulAt,
});
state.retry();
expect(retry).toHaveBeenCalledOnce();
expect(refetch).not.toHaveBeenCalled();
});
it("shows source failure without a false loading or empty result", () => {
const state = section({
data: undefined,
meta: resource(null, {
sync: { id: "work", state: "failed", errorCode: "TBANK_UNAVAILABLE" },
}).meta,
isError: false,
isFetching: false,
refetch: vi.fn(),
});
expect(state).toMatchObject({
hasData: false,
loading: false,
error: true,
});
});
});
@@ -1,23 +1,44 @@
import type { paths } from "@/shared/api";
type Meta =
paths["/api/v1/tbank-sync/{id}"]["get"]["responses"][200]["content"]["application/json"]["resources"][number];
type SectionState = { type SectionState = {
stale?: boolean;
sourceError?: boolean;
partial?: boolean;
lastSuccessfulAt?: string | null;
hasData: boolean; hasData: boolean;
loading: boolean; loading: boolean;
error: boolean; error: boolean;
refreshing: boolean; refreshing: boolean;
retry: () => void; retry: () => void;
}; };
function section(query: { function section(
query: {
data: unknown; data: unknown;
meta?: Meta;
isError: boolean; isError: boolean;
isFetching: boolean; isFetching: boolean;
refetch: () => unknown; refetch: () => unknown;
}): SectionState { },
retry?: () => unknown,
): SectionState {
const error = query.isError || query.meta?.sync.state === "failed";
return { return {
stale: query.meta?.freshness === "stale",
sourceError: query.meta?.sync.state === "failed",
partial: query.meta?.availability === "partial",
lastSuccessfulAt: query.meta?.lastSuccessfulAt,
hasData: Boolean(query.data), hasData: Boolean(query.data),
loading: !query.data && !query.isError, loading: !query.data && !error,
error: query.isError, error,
refreshing: Boolean(query.data) && query.isFetching, refreshing:
Boolean(query.data) &&
(query.isFetching ||
query.meta?.sync.state === "running" ||
query.meta?.sync.state === "queued"),
retry: () => { retry: () => {
void query.refetch(); void (retry ?? query.refetch)();
}, },
}; };
} }
@@ -2,10 +2,12 @@ import type { BrokerageOperation } from "@/entities/broker-operation";
import type { paths } from "@/shared/api"; import type { paths } from "@/shared/api";
import type { SectionState } from "./section"; import type { SectionState } from "./section";
type Position = type Position = NonNullable<
paths["/api/v1/stocks/{uid}/position"]["get"]["responses"][200]["content"]["application/json"]; paths["/api/v1/stocks/{uid}/position"]["get"]["responses"][200]["content"]["application/json"]["data"]
type Candles = >;
paths["/api/v1/stocks/{uid}/candles"]["get"]["responses"][200]["content"]["application/json"]; type Candles = NonNullable<
paths["/api/v1/stocks/{uid}/candles"]["get"]["responses"][200]["content"]["application/json"]["data"]
>;
type ChartRow = Candles["candles"][number] & { date: string; price: number }; type ChartRow = Candles["candles"][number] & { date: string; price: number };
type InstrumentPositionVm = { type InstrumentPositionVm = {
position?: Position; position?: Position;
@@ -177,7 +177,13 @@ const InstrumentChart: FC<InstrumentChartProps> = (props) => {
</Accordion> </Accordion>
</> </>
) : ( ) : (
<Text c="dimmed">{t("stock.noCandles")}</Text> <Text c="dimmed">
{t(
vm.candlesState.partial
? "investment.partial"
: "stock.noCandles",
)}
</Text>
) )
) : null} ) : null}
</InstrumentSection> </InstrumentSection>
@@ -60,7 +60,11 @@ const InstrumentEvents: FC<InstrumentEventsProps> = (props) => {
</Stack> </Stack>
) : ( ) : (
<Text c="dimmed" py="lg"> <Text c="dimmed" py="lg">
{t("stock.noOperations")} {t(
vm.operationsState.partial
? "investment.partial"
: "stock.noOperations",
)}
</Text> </Text>
)} )}
<Group justify="space-between" mt="md"> <Group justify="space-between" mt="md">
@@ -11,6 +11,7 @@ import {
import { LoadingSkeleton } from "@wealthledger/ui"; import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC, PropsWithChildren, ReactNode } from "react"; import type { FC, PropsWithChildren, ReactNode } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { formatSnapshotTime } from "@/shared/lib";
import type { SectionState } from "../model/section"; import type { SectionState } from "../model/section";
import classes from "./InstrumentDetails.module.css"; import classes from "./InstrumentDetails.module.css";
@@ -38,20 +39,40 @@ const InstrumentSection: FC<InstrumentSectionProps> = (props) => {
</Title> </Title>
{props.controls} {props.controls}
</Group> </Group>
{props.state.stale ? (
<Text size="xs">{t("investment.stale")}</Text>
) : null}
{props.state.partial ? (
<Text role="status">{t("investment.partial")}</Text>
) : null}
{props.state.lastSuccessfulAt ? (
<Text size="xs" c="dimmed">
{t("investment.sourceTime", {
date: formatSnapshotTime(props.state.lastSuccessfulAt),
})}
</Text>
) : null}
{props.state.refreshing ? ( {props.state.refreshing ? (
<Text role="status" size="xs" c="dimmed"> <Text role="status" size="xs" c="dimmed">
{t("accounts.refreshing")} {t("accounts.refreshing")}
</Text> </Text>
) : null} ) : null}
{props.state.error ? ( {props.state.error ? (
<Alert color="orange" mb="sm" role="alert"> <Alert color="orange" mb="sm" role="status" aria-live="polite">
<Group justify="space-between"> <Group justify="space-between">
<Text size="sm"> <Text size="sm">
{props.state.hasData {props.state.sourceError
? t("investment.syncFailed")
: props.state.hasData
? t("accounts.refreshError") ? t("accounts.refreshError")
: t("stock.sectionError")} : t("stock.sectionError")}
</Text> </Text>
<Button size="xs" variant="default" onClick={props.state.retry}> <Button
size="xs"
variant="default"
onClick={props.state.retry}
disabled={props.state.refreshing}
>
{t("accounts.retry")} {t("accounts.retry")}
</Button> </Button>
</Group> </Group>
+7 -1
View File
@@ -1 +1,7 @@
export { TbankConnectionSection } from "./ui/TbankConnectionSection"; export { useScreenSync } from "./model/screen-sync";
export {
type InvestmentScreen,
useTbankSync,
useTbankSyncStatus,
} from "./model/sync";
export { TbankConnectionSection } from "./ui/TbankConnectionSection/TbankConnectionSection";
@@ -1,5 +1,9 @@
import type { QueryClient } from "@tanstack/react-query"; import type { QueryClient } from "@tanstack/react-query";
import { apiQueryClient, type paths } from "@/shared/api"; import {
apiQueryClient,
invalidateApiRequests,
type paths,
} from "@/shared/api";
type TbankConnectionStatus = type TbankConnectionStatus =
paths["/api/v1/tbank-connection"]["get"]["responses"][200]["content"]["application/json"]; paths["/api/v1/tbank-connection"]["get"]["responses"][200]["content"]["application/json"];
@@ -15,6 +19,13 @@ function commitTbankConnectionBoundary(
queryClient: QueryClient, queryClient: QueryClient,
status: TbankConnectionStatus, status: TbankConnectionStatus,
) { ) {
invalidateApiRequests(
(path) =>
path.startsWith("/api/v1/brokerage-accounts") ||
path.startsWith("/api/v1/stocks") ||
path.startsWith("/api/v1/bonds") ||
path.startsWith("/api/v1/tbank-sync"),
);
queryClient.setQueryData(tbankConnectionQueryKey, status); queryClient.setQueryData(tbankConnectionQueryKey, status);
void queryClient.resetQueries({ void queryClient.resetQueries({
predicate: ({ queryKey }) => { predicate: ({ queryKey }) => {
@@ -22,7 +33,8 @@ function commitTbankConnectionBoundary(
return ( return (
method === "get" && method === "get" &&
typeof path === "string" && typeof path === "string" &&
(path === "/api/v1/bonds" || (path.startsWith("/api/v1/tbank-sync") ||
path === "/api/v1/bonds" ||
path.startsWith("/api/v1/bonds/") || path.startsWith("/api/v1/bonds/") ||
path === "/api/v1/stocks" || path === "/api/v1/stocks" ||
path.startsWith("/api/v1/stocks/") || path.startsWith("/api/v1/stocks/") ||
@@ -0,0 +1,268 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { describe, expect, it, vi } from "vitest";
import { useBrokerageAccounts } from "@/entities/brokerage-account";
import { configureAuthClient } from "@/shared/api";
import { createQueryWrapper } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server";
import { useScreenSync } from "../index";
function auth() {
configureAuthClient({
accessToken: () => "synthetic",
refresh: async () => true,
clear: vi.fn(),
});
}
describe("page-owned screen synchronization", () => {
it("posts only its scope once and observes completion without importing again", async () => {
auth();
const modes: (string | null)[] = [];
const bodies: unknown[] = [];
let completed = false;
let polls = 0;
const meta = () =>
resource([], { stateVersion: completed ? "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());
completed = true;
return HttpResponse.json(
{
id: "screen",
scope: { screen: "accounts" },
now: "2026-09-25T00:00:00Z",
},
{ status: 202 },
);
}),
http.get("*/api/v1/tbank-sync/:id", () => {
polls++;
return HttpResponse.json({
id: "screen",
scope: { screen: "accounts" },
now: "2026-09-25T00:00:00Z",
state: "succeeded",
errorCode: null,
progress: { total: 1, completed: 1, discovering: false },
resources: [meta()],
});
}),
);
const { result, unmount } = renderHook(
() => {
const accounts = useBrokerageAccounts();
return {
accounts,
sync: useScreenSync({ screen: "accounts" }, [accounts]),
};
},
{ wrapper: createQueryWrapper().wrapper },
);
await waitFor(() => expect(result.current.accounts.data).toEqual([]));
await act(async () => {
await Promise.all([
result.current.sync.refresh(),
result.current.sync.refresh(),
]);
});
await waitFor(() =>
expect(result.current.accounts.meta?.stateVersion).toBe("2"),
);
expect(bodies).toEqual([{ screen: "accounts" }]);
expect(modes).toEqual([null, "observe"]);
vi.useFakeTimers();
try {
await act(() => vi.advanceTimersByTimeAsync(120000));
expect(polls).toBe(1);
expect(modes).toEqual([null, "observe"]);
unmount();
await vi.advanceTimersByTimeAsync(120000);
expect(polls).toBe(1);
} finally {
vi.useRealTimers();
}
});
it.each(["leave", "logout"])(
"publishes completed empty coverage while history runs, then stops on %s",
async (boundary) => {
vi.useFakeTimers({ toFake: ["Date"] });
try {
auth();
let completed = false;
let polls = 0;
const modes: (string | null)[] = [];
const snapshot = () =>
resource(completed ? [] : null, {
stateVersion: completed ? "covered" : "initial",
sync: { id: "history", state: "running", errorCode: 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({
id: "history",
scope: null,
now: "2026-09-25T00:00:00Z",
state: "running",
errorCode: null,
progress: {
total: 2,
completed: completed ? 1 : 0,
discovering: true,
},
resources: [snapshot().meta],
});
}),
);
const { result, unmount } = renderHook(
() => {
const accounts = useBrokerageAccounts();
return {
accounts,
sync: useScreenSync({ screen: "accounts" }, [accounts]),
};
},
{ wrapper: createQueryWrapper().wrapper },
);
await waitFor(() =>
expect(result.current.accounts.meta?.sync.id).toBe("history"),
);
await waitFor(() => expect(polls).toBeGreaterThan(0));
expect(result.current.sync.refreshing).toBe(true);
expect(result.current.accounts.data).toBeUndefined();
completed = true;
vi.setSystemTime(Date.now() + 61000);
await waitFor(() => expect(result.current.accounts.data).toEqual([]), {
timeout: 3000,
});
expect(result.current.sync.refreshing).toBe(true);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 1100));
});
expect(modes).toEqual([null, "observe"]);
if (boundary === "leave") unmount();
else await act(() => configureAuthClient(null));
const stopped = polls;
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 1100));
});
expect(polls).toBe(stopped);
} finally {
vi.useRealTimers();
}
},
);
it("clears private snapshots when status confirms access loss", async () => {
auth();
server.use(
http.get("*/api/v1/brokerage-accounts", () =>
HttpResponse.json(
resource([], {
sync: { id: "revoked", state: "running", errorCode: 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]),
};
},
{ wrapper: createQueryWrapper().wrapper },
);
await waitFor(() => expect(result.current.accounts.isError).toBe(true));
expect(result.current.accounts.data).toBeUndefined();
});
it("observes a projection when only its dependency reports new coverage", async () => {
auth();
let observed = false;
const modes: (string | null)[] = [];
const dependency = resource([], {
resourceKey: "operations",
stateVersion: observed ? "covered" : "initial",
sync: {
id: "dependency",
state: observed ? "idle" : "running",
errorCode: null,
},
}).meta;
server.use(
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
const mode = new URL(request.url).searchParams.get("sync");
modes.push(mode);
if (mode) observed = true;
return HttpResponse.json(
resource(observed ? [] : null, {
resourceKey: "projection",
dependencies: [
{ ...dependency, stateVersion: observed ? "covered" : "initial" },
],
}),
);
}),
http.get("*/api/v1/tbank-sync/:id", () =>
HttpResponse.json({
id: "dependency",
scope: null,
now: "2026-09-25T00:00:00Z",
state: "succeeded",
errorCode: null,
progress: { total: 1, completed: 1, discovering: false },
resources: [{ ...dependency, stateVersion: "covered" }],
}),
),
);
const { result } = renderHook(
() => {
const accounts = useBrokerageAccounts();
useScreenSync({ screen: "accounts" }, [accounts]);
return accounts;
},
{ wrapper: createQueryWrapper().wrapper },
);
await waitFor(() => expect(result.current.data).toEqual([]));
expect(modes).toEqual([null, "observe"]);
});
it("preserves a fresh snapshot and timestamp after a failed force", async () => {
auth();
const saved = resource([], { lastSuccessfulAt: "2026-09-25T01:00:00Z" });
server.use(
http.get("*/api/v1/brokerage-accounts", () => HttpResponse.json(saved)),
http.post("*/api/v1/tbank-sync", () =>
HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }),
),
);
const { result } = renderHook(
() => {
const accounts = useBrokerageAccounts();
return {
accounts,
sync: useScreenSync({ screen: "accounts" }, [accounts]),
};
},
{ 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));
expect(result.current.accounts.meta).toEqual(saved.meta);
});
});
@@ -0,0 +1,148 @@
import { useQueryClient } from "@tanstack/react-query";
import { useEffect, useRef, useState } from "react";
import {
apiErrorCode,
apiQueryClient,
invalidateResourceAccess,
type paths,
useAuthenticatedQueries,
} from "@/shared/api";
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<unknown>;
};
const STATUS_INTERVAL_MS = 1000;
function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
const mutation = useTbankSync();
const client = useQueryClient();
const denied = useRef(new Set<unknown>());
const scopeKey = JSON.stringify(scope);
const [requested, setRequested] = useState<{
scope: string;
id: string;
} | null>(null);
const requestInFlight = useRef<string | null>(null);
const currentScope = useRef(scopeKey);
currentScope.current = scopeKey;
const currentMutation = JSON.stringify(mutation.variables?.body) === scopeKey;
const observed = useRef(new Map<string, string>());
const ids = [
...new Set([
...(requested?.scope === scopeKey ? [requested.id] : []),
...resources
.flatMap(({ meta }) =>
meta ? [meta, ...(meta.dependencies ?? [])] : [],
)
.flatMap((meta) =>
meta?.sync.id &&
(meta.sync.state === "running" || meta.sync.state === "queued")
? [meta.sync.id]
: [],
),
]),
];
const statuses = useAuthenticatedQueries(
ids.map((id) => ({
...apiQueryClient.queryOptions("get", "/api/v1/tbank-sync/{id}", {
params: { path: { id } },
}),
retry: false,
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchInterval: (query: {
state: { error: unknown; data?: { state: string } };
}) =>
query.state.error ||
(query.state.data && query.state.data.state !== "running")
? false
: STATUS_INTERVAL_MS,
})),
);
useEffect(() => {
for (const status of statuses) {
if (status.error && !denied.current.has(status.error)) {
denied.current.add(status.error);
if (apiErrorCode(status.error) !== "NOT_FOUND")
invalidateResourceAccess(client, "brokerage", status.error);
}
}
const latest = new Map<string, ResourceMeta>();
for (const status of [...statuses].sort(
(a, b) => a.dataUpdatedAt - b.dataUpdatedAt,
))
for (const meta of status.data?.resources ?? []) {
latest.set(meta.resourceKey, meta);
for (const dependency of meta.dependencies ?? [])
latest.set(dependency.resourceKey, dependency);
}
for (const resource of resources) {
if (!resource.meta) continue;
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) continue;
const notification = JSON.stringify(
changed.map((meta) => [meta.resourceKey, meta.stateVersion]),
);
if (observed.current.get(resource.meta.resourceKey) === notification)
continue;
observed.current.set(resource.meta.resourceKey, notification);
const own = changed.find(
(meta) => meta.resourceKey === resource.meta?.resourceKey,
);
void resource.observe(own?.stateVersion).catch(() => undefined);
}
}, [client, statuses, resources]);
const refreshing =
(currentMutation && mutation.isPending) ||
statuses.some(
(status) => !status.isError && status.data?.state === "running",
) ||
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 (requestInFlight.current === scopeKey || refreshing) return;
requestInFlight.current = scopeKey;
try {
const accepted = await mutation.mutateAsync({ body: scope });
if (
currentScope.current === scopeKey &&
requestInFlight.current === scopeKey
)
setRequested({ scope: scopeKey, id: accepted.id });
} catch {
/* The mutation retains the transport error for presentation. */
} finally {
if (requestInFlight.current === scopeKey) requestInFlight.current = null;
}
};
return {
refresh,
refreshing,
transportError:
(currentMutation && mutation.isError) ||
statuses.some((status) => status.isError),
sourceError:
statuses.some((status) => status.data?.state === "failed") ||
resources.some(({ meta }) => meta?.sync.state === "failed"),
};
}
export { useScreenSync };
@@ -0,0 +1,114 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { describe, expect, it, vi } from "vitest";
import { apiQueryClient, configureAuthClient } from "@/shared/api";
import { createQueryWrapper } from "@/test/query";
import { server } from "@/test/server";
import {
type InvestmentScreen,
useTbankSync,
useTbankSyncStatus,
} from "../index";
import { commitTbankConnectionBoundary } from "./connection-boundary";
describe("sync connection and session boundaries", () => {
it.each(["connection", "session"])(
"discards pending status and mutation after %s changes",
async (boundary) => {
let generation = 0;
configureAuthClient({
generation: () => generation,
accessToken: () => "synthetic",
refresh: async () => true,
clear: vi.fn(),
});
let release!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
const accepted = {
id: "work",
scope: { screen: "accounts" },
now: "2026-09-25T12:00:00Z",
};
let started = 0;
let changed = 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 = changed ? "2026-09-25T12:01:00Z" : accepted.now;
started += 1;
await blocked;
return HttpResponse.json({
...accepted,
now,
state: "succeeded",
errorCode: null,
progress: { total: 1, completed: 1, discovering: false },
resources: [],
});
}),
);
const { wrapper, queryClient } = createQueryWrapper();
const published: string[] = [];
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
if (event.query.queryKey[1] === "/api/v1/tbank-sync/{id}") {
const data = event.query.state.data as { now?: string } | undefined;
if (data?.now) published.push(data.now);
}
});
const { result } = renderHook(
() => ({
mutation: useTbankSync(),
status: useTbankSyncStatus("work"),
}),
{ wrapper },
);
const screen: InvestmentScreen = { screen: "accounts" };
let mutation!: Promise<unknown>;
act(() => {
mutation = result.current.mutation.mutateAsync({ body: screen });
});
const discarded = expect(mutation).rejects.toMatchObject({
name: "AbortError",
});
await waitFor(() => expect(started).toBe(2));
await act(async () => {
changed = true;
if (boundary === "connection")
commitTbankConnectionBoundary(queryClient, {
connected: false,
connectedAt: 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")
expect(queryClient.getQueryData(key)).toBeUndefined();
else
await waitFor(() =>
expect(queryClient.getQueryData(key)).toMatchObject({
now: "2026-09-25T12:01:00Z",
}),
);
expect(published).not.toContain(accepted.now);
unsubscribe();
},
);
});
@@ -0,0 +1,24 @@
import {
apiQueryClient,
type paths,
useAuthenticatedQuery,
} from "@/shared/api";
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: string | null) {
return useAuthenticatedQuery({
...apiQueryClient.queryOptions("get", "/api/v1/tbank-sync/{id}", {
params: { path: { id: id ?? "" } },
}),
enabled: Boolean(id),
retry: false,
});
}
export { type InvestmentScreen, useTbankSync, useTbankSyncStatus };

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