Compare commits
5
Commits
85fcfe3d07
..
v0.4.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b34c1c860a | ||
|
|
a005e8b13b | ||
|
|
4e5f564fa1 | ||
|
|
cd09ec698c | ||
|
|
b987fd8e78 |
+2
-2
@@ -76,8 +76,8 @@ Add/Edit/Delete; restore/category SVG остаются локальными.
|
||||
|
||||
## Примеры
|
||||
|
||||
- Общая busy-область: существующий [LoadingSkeleton](../packages/ui/src/LoadingSkeleton.tsx), а не domain widget в shared.
|
||||
- Account-income state views: [страница](../src/pages/account-income/ui/AccountIncomePage.tsx) и её flat `components/*.view.tsx`; новый page-local filter остаётся здесь.
|
||||
- Общая busy-область: существующий [LoadingSkeleton](../packages/ui/src/LoadingSkeleton/LoadingSkeleton.tsx), а не domain widget в shared.
|
||||
- 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 только из-за нескольких экранов.
|
||||
|
||||
## Проверка
|
||||
|
||||
@@ -26,7 +26,7 @@ Stories не достигают application API, auth, VM и query providers д
|
||||
контракт: keyboard activation, доступность действия, local callback. Не повторяй
|
||||
RTL suite и не тестируй внутренности Mantine. Существующий
|
||||
[Button](../../src/shared/ui/Button.stories.tsx) показывает themed control
|
||||
без production wrapper; [LoadingSkeleton](../../packages/ui/src/LoadingSkeleton.stories.tsx)
|
||||
без production wrapper; [LoadingSkeleton](../../packages/ui/src/LoadingSkeleton/LoadingSkeleton.stories.tsx)
|
||||
— значимые busy states.
|
||||
|
||||
`npm run typecheck`, `npm run deps:storybook`, `npm run build:catalog` проверяют
|
||||
|
||||
@@ -45,7 +45,7 @@ Finance: loading/error/empty/loaded, cached snapshot при refetch failure, ret
|
||||
отсутствие старых данных после session/connection switch. ErrorBoundary: test-only
|
||||
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),
|
||||
[usePortfolio test](../../src/entities/portfolio/api/usePortfolio.test.tsx).
|
||||
Не копируй fixtures/сценарии целиком, если задача затрагивает один исход.
|
||||
|
||||
+29
-6
@@ -12,7 +12,7 @@ Mantine component и общую тему. Для выпадающего выбо
|
||||
Семантический HTML для структуры страницы остаётся уместным.
|
||||
|
||||
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 декоративны
|
||||
по умолчанию; имя action принадлежит кнопке. Standalone meaningful icon получает
|
||||
`aria-hidden={false}`, `role="img"` и доступное имя. Category/kind mappings
|
||||
@@ -56,11 +56,34 @@ retry callbacks, domain grouping и derived presentation data. View получа
|
||||
image fallback) и formatter одного переданного значения. Группировка/доли
|
||||
коллекции готовятся в VM. Перенос fetch во view ради меньшего container нарушает границу.
|
||||
|
||||
Отдельный state/section с самостоятельной responsibility выноси в flat
|
||||
`components/*.view.tsx`. Небольшой tightly-coupled renderer оставляй рядом.
|
||||
Не создавай folder/barrel/test/CSS для каждого view и не дроби по line count.
|
||||
Пример: [AccountIncomePage](../../src/pages/account-income/ui/AccountIncomePage.tsx)
|
||||
и [его VM](../../src/pages/account-income/ui/AccountIncomePage.vm.ts).
|
||||
Отдельный state/section с самостоятельной responsibility выноси в
|
||||
`components/` своего component. Небольшой tightly-coupled renderer оставляй
|
||||
рядом; размер файла сам по себе не требует разделения.
|
||||
Пример: [AccountIncomePage](../../src/pages/account-income/ui/AccountIncomePage/AccountIncomePage.tsx)
|
||||
и [его 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`.
|
||||
|
||||
## Формы
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ module.exports = {
|
||||
severity: "error",
|
||||
from: { path: "\\.stories\\.tsx$|^\\.storybook/preview\\.tsx$" },
|
||||
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,
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,5 +1,23 @@
|
||||
# Changelog
|
||||
|
||||
## [0.4.0](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.3.0...v0.4.0) (2026-09-26)
|
||||
|
||||
### Features
|
||||
|
||||
* show persisted investment data and sync state ([4e5f564](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/4e5f564fa1d583013fb3e7febdb3baa9737446b4))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **api:** update validation and conflict response contract ([db184c8](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/db184c8caec01609e8a3df3b16097ce634e5eff0))
|
||||
* **auth:** isolate session races and financial caches ([a209d71](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/a209d715892862bb6d48084df0c84a10b8d56bf1))
|
||||
* **ci:** resume verification of immutable release images ([6a87379](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/6a87379813ba1d4002779b23b2a65446b4d10258))
|
||||
* **ui:** improve financial text contrast ([c86be7b](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/c86be7bf73d0141e0606d259ada6453c0d8e3dec))
|
||||
|
||||
### Refactoring
|
||||
|
||||
* colocate frontend component files ([b987fd8](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/b987fd8e780963dfe1dde0c714232697a52e0475))
|
||||
* establish local frontend workspace boundaries ([85fcfe3](https://git.personal.ksv741.ru/WealthLedger/frontend/commit/85fcfe3d073f80e759dafb14281c9462c1d7410d))
|
||||
|
||||
## [0.3.0](https://git.personal.ksv741.ru/WealthLedger/frontend/compare/v0.2.3...v0.3.0) (2026-09-20)
|
||||
|
||||
### Features
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "wealth-ledger-frontend",
|
||||
"version": "0.3.0",
|
||||
"version": "0.4.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "wealth-ledger-frontend",
|
||||
"version": "0.3.0",
|
||||
"version": "0.4.0",
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "wealth-ledger-frontend",
|
||||
"private": true,
|
||||
"version": "0.3.0",
|
||||
"version": "0.4.0",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": "24.21.0"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { LoadingSkeleton } from "./LoadingSkeleton";
|
||||
import { LoadingSkeleton } from "../LoadingSkeleton/LoadingSkeleton";
|
||||
import { StateView } from "./StateView";
|
||||
|
||||
describe("StateView", () => {
|
||||
@@ -1,3 +1,3 @@
|
||||
export { EntryCard } from "./EntryCard";
|
||||
export { LoadingSkeleton } from "./LoadingSkeleton";
|
||||
export { StateView } from "./StateView";
|
||||
export { EntryCard } from "./EntryCard/EntryCard";
|
||||
export { LoadingSkeleton } from "./LoadingSkeleton/LoadingSkeleton";
|
||||
export { StateView } from "./StateView/StateView";
|
||||
|
||||
+65
-54
@@ -16,6 +16,7 @@ import type { IncomeAnalytics } from "@/entities/income";
|
||||
import type { Portfolio } from "@/entities/portfolio";
|
||||
import { AuthProvider } from "@/features/auth";
|
||||
import { createTestQueryClient } from "@/test/query";
|
||||
import { resource } from "@/test/resource";
|
||||
import { server } from "@/test/server";
|
||||
import { AppRoutes } from "./AppRoutes";
|
||||
|
||||
@@ -132,50 +133,56 @@ beforeEach(() => {
|
||||
),
|
||||
http.get("*/api/v1/brokerage-accounts", () =>
|
||||
HttpResponse.json(
|
||||
accounts.map((account) => ({
|
||||
...account,
|
||||
type: "BROKERAGE",
|
||||
openedOn: null,
|
||||
portfolioSummary: null,
|
||||
})),
|
||||
resource(
|
||||
accounts.map((account) => ({
|
||||
...account,
|
||||
type: "BROKERAGE",
|
||||
openedOn: null,
|
||||
portfolioSummary: null,
|
||||
})),
|
||||
),
|
||||
),
|
||||
),
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
|
||||
HttpResponse.json(portfolio),
|
||||
HttpResponse.json(resource(portfolio)),
|
||||
),
|
||||
http.get(
|
||||
"*/api/v1/brokerage-accounts/:accountId/operations",
|
||||
({ params }) =>
|
||||
HttpResponse.json({
|
||||
accountId: params.accountId,
|
||||
items,
|
||||
hasNext: false,
|
||||
nextCursor: null,
|
||||
observedAt: receipt.occurredAt,
|
||||
}),
|
||||
HttpResponse.json(
|
||||
resource({
|
||||
accountId: params.accountId,
|
||||
items,
|
||||
hasNext: false,
|
||||
nextCursor: null,
|
||||
observedAt: receipt.occurredAt,
|
||||
}),
|
||||
),
|
||||
),
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/income-analytics", () =>
|
||||
HttpResponse.json(analytics),
|
||||
HttpResponse.json(resource(analytics)),
|
||||
),
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/events", () =>
|
||||
HttpResponse.json({
|
||||
accountId: "all",
|
||||
calculatedAt: receipt.occurredAt,
|
||||
incomeTotalsByCurrency: [],
|
||||
events: accounts.map((account) => ({
|
||||
account,
|
||||
type: "coupon",
|
||||
date: "2026-09-15",
|
||||
dateKind: "event",
|
||||
figi: null,
|
||||
instrumentUid: null,
|
||||
ticker: "BOND",
|
||||
displayName: "Облигация",
|
||||
isin: null,
|
||||
logoName: null,
|
||||
projectedAmount: { currency: "RUB", value: "2" },
|
||||
})),
|
||||
}),
|
||||
HttpResponse.json(
|
||||
resource({
|
||||
accountId: "all",
|
||||
calculatedAt: receipt.occurredAt,
|
||||
incomeTotalsByCurrency: [],
|
||||
events: accounts.map((account) => ({
|
||||
account,
|
||||
type: "coupon",
|
||||
date: "2026-09-15",
|
||||
dateKind: "event",
|
||||
figi: null,
|
||||
instrumentUid: null,
|
||||
ticker: "BOND",
|
||||
displayName: "Облигация",
|
||||
isin: null,
|
||||
logoName: null,
|
||||
projectedAmount: { currency: "RUB", value: "2" },
|
||||
})),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -224,20 +231,22 @@ describe("All accounts routes", () => {
|
||||
({ request, params }) => {
|
||||
const url = new URL(request.url);
|
||||
requests.push(url);
|
||||
return HttpResponse.json({
|
||||
accountId: params.accountId,
|
||||
items: [
|
||||
{
|
||||
...receipt,
|
||||
description: url.searchParams.has("cursor")
|
||||
? "Вторая страница"
|
||||
: "Первая страница",
|
||||
},
|
||||
],
|
||||
hasNext: !url.searchParams.has("cursor"),
|
||||
nextCursor: url.searchParams.has("cursor") ? null : "next",
|
||||
observedAt: receipt.occurredAt,
|
||||
});
|
||||
return HttpResponse.json(
|
||||
resource({
|
||||
accountId: params.accountId,
|
||||
items: [
|
||||
{
|
||||
...receipt,
|
||||
description: url.searchParams.has("cursor")
|
||||
? "Вторая страница"
|
||||
: "Первая страница",
|
||||
},
|
||||
],
|
||||
hasNext: !url.searchParams.has("cursor"),
|
||||
nextCursor: url.searchParams.has("cursor") ? null : "next",
|
||||
observedAt: receipt.occurredAt,
|
||||
}),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -274,13 +283,15 @@ describe("All accounts routes", () => {
|
||||
{ code: "INVALID_OPERATIONS_CURSOR" },
|
||||
{ status: 400 },
|
||||
)
|
||||
: HttpResponse.json({
|
||||
accountId: "all",
|
||||
items,
|
||||
hasNext: true,
|
||||
nextCursor: "expired",
|
||||
observedAt: receipt.occurredAt,
|
||||
}),
|
||||
: HttpResponse.json(
|
||||
resource({
|
||||
accountId: "all",
|
||||
items,
|
||||
hasNext: true,
|
||||
nextCursor: "expired",
|
||||
observedAt: receipt.occurredAt,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
renderPage("/accounts/all/operations?from=2026-08-01&to=2026-08-31");
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { FC } from "react";
|
||||
import { lazy } from "react";
|
||||
import { Navigate, Route, Routes } from "react-router";
|
||||
import { LazyPage } from "./RouteFallback";
|
||||
import { Protected, Public } from "./RouteGuards";
|
||||
import { LazyPage } from "../RouteFallback";
|
||||
import { Protected, Public } from "../RouteGuards";
|
||||
|
||||
const CardPage = lazy(async () => {
|
||||
const { CardPage } = await import("@/pages/card");
|
||||
@@ -65,7 +65,7 @@ const SettingsPage = lazy(async () => {
|
||||
return { default: SettingsPage };
|
||||
});
|
||||
const ProtectedLayout = lazy(async () => {
|
||||
const { ProtectedLayout } = await import("./ProtectedLayout");
|
||||
const { ProtectedLayout } = await import("../ProtectedLayout");
|
||||
return { default: ProtectedLayout };
|
||||
});
|
||||
|
||||
+3
-2
@@ -12,6 +12,7 @@ import { MemoryRouter, useNavigate } from "react-router";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { AuthProvider } from "@/features/auth";
|
||||
import { createTestQueryClient } from "@/test/query";
|
||||
import { resource } from "@/test/resource";
|
||||
import { server } from "@/test/server";
|
||||
import { ProtectedDocumentTitle } from "./DocumentTitle";
|
||||
|
||||
@@ -62,7 +63,7 @@ describe("document titles", () => {
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", async () => {
|
||||
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");
|
||||
@@ -85,7 +86,7 @@ describe("document titles", () => {
|
||||
async (kind, id, fallback, name) => {
|
||||
server.use(
|
||||
http.get(`*/api/v1/${kind}/by-ticker/:ticker`, () =>
|
||||
HttpResponse.json({ name }),
|
||||
HttpResponse.json(resource({ name })),
|
||||
),
|
||||
);
|
||||
renderTitle(`/${kind}/${id}`);
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { FC } from "react";
|
||||
import { AppBreadcrumbs, AppShell } from "@/app/ui";
|
||||
import { ProtectedDocumentTitle } from "./DocumentTitle";
|
||||
import { ProtectedDocumentTitle } from "./DocumentTitle/DocumentTitle";
|
||||
|
||||
const ProtectedLayout: FC = () => {
|
||||
return (
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export { AppRoutes } from "./AppRoutes";
|
||||
export { RouteErrorBoundary } from "./RouteErrorBoundary";
|
||||
export { AppRoutes } from "./AppRoutes/AppRoutes";
|
||||
export { RouteErrorBoundary } from "./RouteErrorBoundary/RouteErrorBoundary";
|
||||
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
export { AppBreadcrumbs } from "./AppBreadcrumbs";
|
||||
export { AppShell } from "./AppShell";
|
||||
export { AppBreadcrumbs } from "./AppBreadcrumbs/AppBreadcrumbs";
|
||||
export { AppShell } from "./AppShell/AppShell";
|
||||
|
||||
@@ -20,11 +20,11 @@ export {
|
||||
} from "./model/form-validation";
|
||||
export { bankOperationKinds } from "./model/operation-kinds";
|
||||
export { bankPeriod } from "./model/period";
|
||||
export { BankCardFace } from "./ui/BankCardFace";
|
||||
export { BankCardForm } from "./ui/BankCardForm";
|
||||
export { BankCardFace } from "./ui/BankCardFace/BankCardFace";
|
||||
export { BankCardForm } from "./ui/BankCardForm/BankCardForm";
|
||||
export { BankFeedback } from "./ui/BankFeedback";
|
||||
export { BankOperationIcon } from "./ui/BankOperationIcon";
|
||||
export { BankOperationIcon } from "./ui/BankOperationIcon/BankOperationIcon";
|
||||
export { BankPeriodPicker } from "./ui/BankPeriodPicker";
|
||||
export { BankSummaryView } from "./ui/BankSummary.view";
|
||||
export { CategoryManager } from "./ui/CategoryManager";
|
||||
export { BankSummaryView } from "./ui/BankSummary/BankSummary.view";
|
||||
export { CategoryManager } from "./ui/CategoryManager/CategoryManager";
|
||||
export { useBankFormFocus } from "./ui/useBankFormFocus";
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import type { FC } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { formatMoney } from "@/shared/lib";
|
||||
import type { BankCard } from "../api/queries";
|
||||
import type { BankCard } from "../../api/queries";
|
||||
import classes from "./BankCardFace.module.css";
|
||||
|
||||
type BankCardFaceProps = { card: BankCard };
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
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";
|
||||
|
||||
const meta = {
|
||||
+1
-1
@@ -6,7 +6,7 @@ import { describe, expect, it, vi } from "vitest";
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createTestQueryClient } from "@/test/query";
|
||||
import { server } from "@/test/server";
|
||||
import type { BankCard } from "../api/queries";
|
||||
import type { BankCard } from "../../api/queries";
|
||||
import { BankCardForm } from "./BankCardForm";
|
||||
|
||||
const card: BankCard = {
|
||||
+6
-6
@@ -4,18 +4,18 @@ import { type FC, useState } from "react";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { formatDate } from "@/shared/lib";
|
||||
import { useBankMutations } from "../api/mutations";
|
||||
import { type BankCard, useBankCard } from "../api/queries";
|
||||
import { useBankMutations } from "../../api/mutations";
|
||||
import { type BankCard, useBankCard } from "../../api/queries";
|
||||
import {
|
||||
type BankCardValues,
|
||||
bankCardSchema,
|
||||
bankMoneyValue,
|
||||
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 { BankFeedback } from "./BankFeedback";
|
||||
import classes from "./BankForms.module.css";
|
||||
import { useBankFormFocus } from "./useBankFormFocus";
|
||||
|
||||
type BankCardFormProps = { card?: BankCard; onClose: () => void };
|
||||
const BankCardForm: FC<BankCardFormProps> = (props) => {
|
||||
+1
-1
@@ -8,7 +8,7 @@ import {
|
||||
bankDateInputValue,
|
||||
bankDateSchema,
|
||||
bankToday,
|
||||
} from "../model/form-validation";
|
||||
} from "../../model/form-validation";
|
||||
|
||||
type BankCardFieldsProps = { archived: boolean };
|
||||
const BankCardFields: FC<BankCardFieldsProps> = (props) => {
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
import type { FC } from "react";
|
||||
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";
|
||||
|
||||
type BankOperationIconProps = {
|
||||
+2
-2
@@ -3,8 +3,8 @@ import { LoadingSkeleton } from "@wealthledger/ui";
|
||||
import type { CSSProperties, FC } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { formatMoney } from "@/shared/lib";
|
||||
import type { BankSummary } from "../api/queries";
|
||||
import { BankOperationIcon } from "./BankOperationIcon";
|
||||
import type { BankSummary } from "../../api/queries";
|
||||
import { BankOperationIcon } from "../BankOperationIcon/BankOperationIcon";
|
||||
import classes from "./BankSummary.module.css";
|
||||
|
||||
type BankSummaryViewProps = {
|
||||
+6
-6
@@ -18,12 +18,12 @@ import {
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { z } from "zod";
|
||||
import { validationMessage } from "@/shared/i18n";
|
||||
import { useBankMutations } from "../api/mutations";
|
||||
import { type ExpenseCategory, useBankCategories } from "../api/queries";
|
||||
import { BankFeedback } from "./BankFeedback";
|
||||
import classes from "./BankForms.module.css";
|
||||
import { BankOperationIcon } from "./BankOperationIcon";
|
||||
import { useBankFormFocus } from "./useBankFormFocus";
|
||||
import { useBankMutations } from "../../api/mutations";
|
||||
import { type ExpenseCategory, useBankCategories } from "../../api/queries";
|
||||
import { BankFeedback } from "../BankFeedback";
|
||||
import classes from "../BankForms.module.css";
|
||||
import { BankOperationIcon } from "../BankOperationIcon/BankOperationIcon";
|
||||
import { useBankFormFocus } from "../useBankFormFocus";
|
||||
|
||||
const MAX_CATEGORY_NAME_LENGTH = 80;
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
apiQueryClient,
|
||||
type paths,
|
||||
useAuthenticatedQuery,
|
||||
} from "@/shared/api";
|
||||
import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
|
||||
|
||||
type BondPeriod = NonNullable<
|
||||
NonNullable<
|
||||
@@ -13,7 +9,7 @@ type BondPeriod = NonNullable<
|
||||
const BOND_STALE_TIME_MS = 30_000;
|
||||
|
||||
function useBondSearch(query: string) {
|
||||
return useAuthenticatedQuery({
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds", {
|
||||
params: { query: { query } },
|
||||
}),
|
||||
@@ -36,11 +32,11 @@ function useBond(identifier: string) {
|
||||
identifier,
|
||||
);
|
||||
|
||||
const byUid = useAuthenticatedQuery({
|
||||
const byUid = useResourceQuery({
|
||||
...bondQueryOptions(identifier),
|
||||
enabled: Boolean(identifier) && isUid,
|
||||
});
|
||||
const byTicker = useAuthenticatedQuery({
|
||||
const byTicker = useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/by-ticker/{ticker}", {
|
||||
params: { path: { ticker: identifier } },
|
||||
}),
|
||||
@@ -50,7 +46,7 @@ function useBond(identifier: string) {
|
||||
return isUid ? byUid : byTicker;
|
||||
}
|
||||
function useBondMetrics(uid: string) {
|
||||
return useAuthenticatedQuery({
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/metrics", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
@@ -59,7 +55,7 @@ function useBondMetrics(uid: string) {
|
||||
});
|
||||
}
|
||||
function useBondQuote(uid: string) {
|
||||
return useAuthenticatedQuery({
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/quote", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
@@ -68,7 +64,7 @@ function useBondQuote(uid: string) {
|
||||
});
|
||||
}
|
||||
function useBondCandles(uid: string, period: BondPeriod) {
|
||||
return useAuthenticatedQuery({
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/candles", {
|
||||
params: { path: { uid }, query: { period } },
|
||||
}),
|
||||
@@ -77,7 +73,8 @@ function useBondCandles(uid: string, period: BondPeriod) {
|
||||
});
|
||||
}
|
||||
function useBondPosition(uid: string) {
|
||||
return useAuthenticatedQuery({
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/position", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
@@ -86,7 +83,8 @@ function useBondPosition(uid: string) {
|
||||
});
|
||||
}
|
||||
function useBondCoupons(uid: string) {
|
||||
return useAuthenticatedQuery({
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/coupons", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
import {
|
||||
apiQueryClient,
|
||||
type paths,
|
||||
useAuthenticatedQuery,
|
||||
} from "@/shared/api";
|
||||
import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
|
||||
|
||||
type OperationsEndpoint =
|
||||
paths["/api/v1/brokerage-accounts/{accountId}/operations"]["get"];
|
||||
|
||||
type BrokerageOperation =
|
||||
OperationsEndpoint["responses"][200]["content"]["application/json"]["items"][number];
|
||||
type BrokerageOperationsQuery = NonNullable<
|
||||
OperationsEndpoint["parameters"]["query"]
|
||||
type BrokerageOperation = NonNullable<
|
||||
OperationsEndpoint["responses"][200]["content"]["application/json"]["data"]
|
||||
>["items"][number];
|
||||
type BrokerageOperationsQuery = Omit<
|
||||
NonNullable<OperationsEndpoint["parameters"]["query"]>,
|
||||
"sync"
|
||||
>;
|
||||
type OperationCategory = BrokerageOperation["category"];
|
||||
|
||||
@@ -56,7 +54,8 @@ function useBrokerageOperations(
|
||||
accountId: string | undefined,
|
||||
query: BrokerageOperationsQuery = {},
|
||||
) {
|
||||
return useAuthenticatedQuery({
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...brokerageOperationsQueryOptions(accountId, query),
|
||||
enabled: Boolean(accountId),
|
||||
staleTime: 30_000,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { HttpResponse, http } from "msw";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createQueryWrapper } from "@/test/query";
|
||||
import { resource } from "@/test/resource";
|
||||
import { server } from "@/test/server";
|
||||
import { useBrokerageAccounts } from "./useBrokerageAccounts";
|
||||
|
||||
@@ -15,14 +16,16 @@ describe("useBrokerageAccounts", () => {
|
||||
});
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", () =>
|
||||
HttpResponse.json([
|
||||
{
|
||||
id: "account-1",
|
||||
name: "Основной",
|
||||
type: "BROKERAGE",
|
||||
openedOn: "2024-08-13",
|
||||
},
|
||||
]),
|
||||
HttpResponse.json(
|
||||
resource([
|
||||
{
|
||||
id: "account-1",
|
||||
name: "Основной",
|
||||
type: "BROKERAGE",
|
||||
openedOn: "2024-08-13",
|
||||
},
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -52,14 +55,16 @@ describe("useBrokerageAccounts", () => {
|
||||
http.get("*/api/v1/brokerage-accounts", () => {
|
||||
calls += 1;
|
||||
return calls === 1
|
||||
? HttpResponse.json([
|
||||
{
|
||||
id: "account-1",
|
||||
name: "Основной",
|
||||
type: "BROKERAGE",
|
||||
openedOn: "2024-08-13",
|
||||
},
|
||||
])
|
||||
? HttpResponse.json(
|
||||
resource([
|
||||
{
|
||||
id: "account-1",
|
||||
name: "Основной",
|
||||
type: "BROKERAGE",
|
||||
openedOn: "2024-08-13",
|
||||
},
|
||||
]),
|
||||
)
|
||||
: HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 });
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
import {
|
||||
apiQueryClient,
|
||||
type paths,
|
||||
useAuthenticatedQuery,
|
||||
} from "@/shared/api";
|
||||
import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
|
||||
|
||||
const brokerageAccountsQueryOptions = () =>
|
||||
apiQueryClient.queryOptions("get", "/api/v1/brokerage-accounts");
|
||||
|
||||
const brokerageAccountsQueryKey = brokerageAccountsQueryOptions().queryKey;
|
||||
|
||||
type BrokerageAccount =
|
||||
paths["/api/v1/brokerage-accounts"]["get"]["responses"][200]["content"]["application/json"][number];
|
||||
type BrokerageAccount = NonNullable<
|
||||
paths["/api/v1/brokerage-accounts"]["get"]["responses"][200]["content"]["application/json"]["data"]
|
||||
>[number];
|
||||
|
||||
function useBrokerageAccounts() {
|
||||
return useAuthenticatedQuery({
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...brokerageAccountsQueryOptions(),
|
||||
staleTime: 60_000,
|
||||
});
|
||||
|
||||
@@ -8,4 +8,4 @@ export {
|
||||
type BrokerageAccountCard,
|
||||
brokerageAccountCards,
|
||||
} 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<
|
||||
BrokerageAccount["portfolioSummary"]
|
||||
>["totalsByCurrency"][number];
|
||||
|
||||
type BrokerageAccountCard = {
|
||||
source?: NonNullable<
|
||||
ReturnType<typeof useBrokerageAccounts>["meta"]
|
||||
>["dependencies"] extends (infer T)[] | undefined
|
||||
? T
|
||||
: never;
|
||||
account: BrokerageAccount;
|
||||
positionCounts: { stocks: number; bonds: number } | null;
|
||||
summary:
|
||||
@@ -19,11 +27,19 @@ function accountTypeKey(type: BrokerageAccount["type"]) {
|
||||
|
||||
function brokerageAccountCards(
|
||||
accounts: BrokerageAccount[],
|
||||
dependencies: NonNullable<
|
||||
ReturnType<typeof useBrokerageAccounts>["meta"]
|
||||
>["dependencies"] = [],
|
||||
): BrokerageAccountCard[] {
|
||||
return accounts.map((account) => {
|
||||
const source = dependencies.find(
|
||||
(item) =>
|
||||
item.resourceKey === `portfolio/${encodeURIComponent(account.id)}`,
|
||||
);
|
||||
const summary = account.portfolioSummary;
|
||||
if (!summary)
|
||||
return {
|
||||
source,
|
||||
account,
|
||||
positionCounts: null,
|
||||
summary: { state: "unavailable" },
|
||||
@@ -33,8 +49,9 @@ function brokerageAccountCards(
|
||||
bonds: summary.bondPositionCount,
|
||||
};
|
||||
if (!summary.totalsByCurrency.length)
|
||||
return { account, positionCounts, summary: { state: "empty" } };
|
||||
return { source, account, positionCounts, summary: { state: "empty" } };
|
||||
return {
|
||||
source,
|
||||
account,
|
||||
positionCounts,
|
||||
summary: {
|
||||
|
||||
+43
-2
@@ -1,7 +1,7 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import type { BrokerageAccount } from "../api/useBrokerageAccounts";
|
||||
import { brokerageAccountCards } from "../model/display";
|
||||
import type { BrokerageAccount } from "../../api/useBrokerageAccounts";
|
||||
import { brokerageAccountCards } from "../../model/display";
|
||||
import { BrokerageAccountList } from "./BrokerageAccountList";
|
||||
|
||||
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 },
|
||||
},
|
||||
],
|
||||
),
|
||||
},
|
||||
};
|
||||
+41
-1
@@ -2,7 +2,8 @@ import { MantineProvider } from "@mantine/core";
|
||||
import { render, screen, within } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router";
|
||||
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";
|
||||
|
||||
describe("BrokerageAccountList", () => {
|
||||
@@ -84,3 +85,42 @@ describe("BrokerageAccountList", () => {
|
||||
).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();
|
||||
});
|
||||
+24
-5
@@ -2,9 +2,9 @@ import { Card, Group, SimpleGrid, Stack, Text } from "@mantine/core";
|
||||
import type { FC } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
import { formatDate, formatMoney } from "@/shared/lib";
|
||||
import type { BrokerageAccountCard } from "../model/display";
|
||||
import { accountTypeKey } from "../model/display";
|
||||
import { formatDate, formatMoney, formatSnapshotTime } from "@/shared/lib";
|
||||
import type { BrokerageAccountCard } from "../../model/display";
|
||||
import { accountTypeKey } from "../../model/display";
|
||||
import classes from "./BrokerageAccountList.module.css";
|
||||
|
||||
type BrokerageAccountListProps = { accounts: BrokerageAccountCard[] };
|
||||
@@ -52,8 +52,8 @@ const BrokerageAccountList: FC<BrokerageAccountListProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<SimpleGrid className={classes.list} cols={{ base: 1, lg: 2 }} spacing="lg">
|
||||
{accounts.map(({ account, summary, positionCounts }) => (
|
||||
<SimpleGrid className={classes.list} cols={1} spacing="lg">
|
||||
{accounts.map(({ account, summary, positionCounts, source }) => (
|
||||
<Card
|
||||
component={Link}
|
||||
to={`/accounts/${account.id}`}
|
||||
@@ -92,6 +92,25 @@ const BrokerageAccountList: FC<BrokerageAccountListProps> = (props) => {
|
||||
{t("accounts.currentValue")}
|
||||
</Text>
|
||||
<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>
|
||||
{positionCounts ? (
|
||||
<dl className={classes.positions}>
|
||||
@@ -3,6 +3,7 @@ import { HttpResponse, http } from "msw";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createQueryWrapper } from "@/test/query";
|
||||
import { resource } from "@/test/resource";
|
||||
import { server } from "@/test/server";
|
||||
import { useBrokerageEvents } from "./useBrokerageEvents";
|
||||
|
||||
@@ -31,23 +32,25 @@ describe("useBrokerageEvents", () => {
|
||||
});
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts/account-1/events", () =>
|
||||
HttpResponse.json({
|
||||
accountId: "account-1",
|
||||
calculatedAt: "2026-08-14T00:00:00Z",
|
||||
events: [
|
||||
{
|
||||
type: "dividend",
|
||||
date: "2026-09-01",
|
||||
dateKind: "registry",
|
||||
figi: "figi-1",
|
||||
instrumentUid: null,
|
||||
ticker: "SBER",
|
||||
displayName: "Сбер",
|
||||
logoName: "sber3.png",
|
||||
projectedAmount: { currency: "RUB", value: "12.34" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
HttpResponse.json(
|
||||
resource({
|
||||
accountId: "account-1",
|
||||
calculatedAt: "2026-08-14T00:00:00Z",
|
||||
events: [
|
||||
{
|
||||
type: "dividend",
|
||||
date: "2026-09-01",
|
||||
dateKind: "registry",
|
||||
figi: "figi-1",
|
||||
instrumentUid: null,
|
||||
ticker: "SBER",
|
||||
displayName: "Сбер",
|
||||
logoName: "sber3.png",
|
||||
projectedAmount: { currency: "RUB", value: "12.34" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
import {
|
||||
apiQueryClient,
|
||||
type paths,
|
||||
useAuthenticatedQuery,
|
||||
} from "@/shared/api";
|
||||
import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
|
||||
|
||||
type EventsEndpoint =
|
||||
paths["/api/v1/brokerage-accounts/{accountId}/events"]["get"];
|
||||
type BrokerageEvent =
|
||||
EventsEndpoint["responses"][200]["content"]["application/json"]["events"][number];
|
||||
type BrokerageEvent = NonNullable<
|
||||
EventsEndpoint["responses"][200]["content"]["application/json"]["data"]
|
||||
>["events"][number];
|
||||
|
||||
function useBrokerageEvents(
|
||||
accountId: string | undefined,
|
||||
query: EventsEndpoint["parameters"]["query"] = {},
|
||||
query: Omit<NonNullable<EventsEndpoint["parameters"]["query"]>, "sync"> = {},
|
||||
) {
|
||||
return useAuthenticatedQuery({
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/brokerage-accounts/{accountId}/events",
|
||||
|
||||
@@ -6,4 +6,4 @@ export { BrokerageEventCard } from "./ui/BrokerageEventCard";
|
||||
export {
|
||||
BrokerageEventsPreview,
|
||||
type BrokerageEventsPreviewState,
|
||||
} from "./ui/BrokerageEventsPreview";
|
||||
} from "./ui/BrokerageEventsPreview/BrokerageEventsPreview";
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import type { BrokerageEvent } from "../api/useBrokerageEvents";
|
||||
import type { BrokerageEvent } from "../../api/useBrokerageEvents";
|
||||
import { BrokerageEventsPreview } from "./BrokerageEventsPreview";
|
||||
|
||||
const syntheticEvent = {
|
||||
+30
-4
@@ -3,8 +3,9 @@ import { LoadingSkeleton } from "@wealthledger/ui";
|
||||
import type { FC } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
import type { BrokerageEvent } from "../api/useBrokerageEvents";
|
||||
import { BrokerageEventCard } from "./BrokerageEventCard";
|
||||
import { formatSnapshotTime } from "@/shared/lib";
|
||||
import type { BrokerageEvent } from "../../api/useBrokerageEvents";
|
||||
import { BrokerageEventCard } from "../BrokerageEventCard";
|
||||
|
||||
type BrokerageEventsPreviewProps = {
|
||||
events: BrokerageEventsPreviewState;
|
||||
@@ -12,7 +13,14 @@ type BrokerageEventsPreviewProps = {
|
||||
|
||||
type BrokerageEventsPreviewState =
|
||||
| { 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 { events } = props;
|
||||
@@ -20,6 +28,21 @@ const BrokerageEventsPreview: FC<BrokerageEventsPreviewProps> = (props) => {
|
||||
|
||||
return (
|
||||
<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" ? (
|
||||
<LoadingSkeleton label={t("events.recentLoading")}>
|
||||
{[0, 1, 2].map((index) => (
|
||||
@@ -33,7 +56,10 @@ const BrokerageEventsPreview: FC<BrokerageEventsPreviewProps> = (props) => {
|
||||
{events.state === "empty" ? (
|
||||
<Text c="dimmed">{t("events.recentEmpty")}</Text>
|
||||
) : 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) => (
|
||||
<BrokerageEventCard
|
||||
key={JSON.stringify([
|
||||
@@ -1,16 +1,15 @@
|
||||
import {
|
||||
apiQueryClient,
|
||||
type paths,
|
||||
useAuthenticatedQuery,
|
||||
} from "@/shared/api";
|
||||
import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
|
||||
|
||||
type IncomeSummary =
|
||||
paths["/api/v1/brokerage-accounts/{accountId}/income-summary"]["get"]["responses"][200]["content"]["application/json"];
|
||||
type IncomeAnalytics =
|
||||
paths["/api/v1/brokerage-accounts/{accountId}/income-analytics"]["get"]["responses"][200]["content"]["application/json"];
|
||||
type IncomeSummary = NonNullable<
|
||||
paths["/api/v1/brokerage-accounts/{accountId}/income-summary"]["get"]["responses"][200]["content"]["application/json"]["data"]
|
||||
>;
|
||||
type IncomeAnalytics = NonNullable<
|
||||
paths["/api/v1/brokerage-accounts/{accountId}/income-analytics"]["get"]["responses"][200]["content"]["application/json"]["data"]
|
||||
>;
|
||||
|
||||
function useIncomeSummary(accountId: string | undefined) {
|
||||
return useAuthenticatedQuery({
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/brokerage-accounts/{accountId}/income-summary",
|
||||
@@ -25,7 +24,8 @@ function useIncomeAnalytics(
|
||||
accountId: string | undefined,
|
||||
period: { from: string; to: string },
|
||||
) {
|
||||
return useAuthenticatedQuery({
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/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 { HttpResponse, http } from "msw";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createQueryWrapper } from "@/test/query";
|
||||
import { resource } from "@/test/resource";
|
||||
import { server } from "@/test/server";
|
||||
import { usePortfolio } from "./usePortfolio";
|
||||
|
||||
@@ -33,14 +33,16 @@ describe("usePortfolio", () => {
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () => {
|
||||
calls += 1;
|
||||
return calls === 1
|
||||
? HttpResponse.json({
|
||||
lastSuccessfulAt: "2026-08-14T00:00:00Z",
|
||||
isStale: false,
|
||||
totalsByCurrency: [],
|
||||
positions: [],
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
cashBalances: [],
|
||||
})
|
||||
? HttpResponse.json(
|
||||
resource({
|
||||
lastSuccessfulAt: "2026-08-14T00:00:00Z",
|
||||
isStale: false,
|
||||
totalsByCurrency: [],
|
||||
positions: [],
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
cashBalances: [],
|
||||
}),
|
||||
)
|
||||
: HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 });
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import {
|
||||
apiQueryClient,
|
||||
type paths,
|
||||
useAuthenticatedQuery,
|
||||
} from "@/shared/api";
|
||||
import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
|
||||
|
||||
const portfolioQueryPolicy = {
|
||||
staleTime: 30_000,
|
||||
} as const;
|
||||
|
||||
type Portfolio =
|
||||
paths["/api/v1/brokerage-accounts/{accountId}/portfolio"]["get"]["responses"][200]["content"]["application/json"];
|
||||
type Portfolio = NonNullable<
|
||||
paths["/api/v1/brokerage-accounts/{accountId}/portfolio"]["get"]["responses"][200]["content"]["application/json"]["data"]
|
||||
>;
|
||||
|
||||
function portfolioQueryOptions(accountId: string | undefined) {
|
||||
return apiQueryClient.queryOptions(
|
||||
@@ -20,7 +17,8 @@ function portfolioQueryOptions(accountId: string | undefined) {
|
||||
}
|
||||
|
||||
function usePortfolio(accountId: string | undefined) {
|
||||
return useAuthenticatedQuery({
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...portfolioQueryOptions(accountId),
|
||||
enabled: Boolean(accountId),
|
||||
...portfolioQueryPolicy,
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import {
|
||||
apiQueryClient,
|
||||
type paths,
|
||||
unwrapResourceResult,
|
||||
useAuthenticatedQueries,
|
||||
useAuthenticatedQuery,
|
||||
useResourceQuery,
|
||||
} from "@/shared/api";
|
||||
|
||||
type StockPeriod = NonNullable<
|
||||
@@ -14,7 +15,7 @@ type StockPeriod = NonNullable<
|
||||
const STOCK_STALE_TIME_MS = 30_000;
|
||||
|
||||
function useStockSearch(query: string) {
|
||||
return useAuthenticatedQuery({
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks", {
|
||||
params: { query: { query } },
|
||||
}),
|
||||
@@ -35,7 +36,10 @@ function useStocks(uids: string[]) {
|
||||
const uniqueUids = [...new Set(uids)];
|
||||
const queries = useAuthenticatedQueries(uniqueUids.map(stockQueryOptions));
|
||||
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,
|
||||
);
|
||||
|
||||
const byUid = useAuthenticatedQuery({
|
||||
const byUid = useResourceQuery({
|
||||
...stockQueryOptions(identifier),
|
||||
enabled: Boolean(identifier) && isUid,
|
||||
});
|
||||
const byTicker = useAuthenticatedQuery({
|
||||
const byTicker = useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/by-ticker/{ticker}", {
|
||||
params: { path: { ticker: identifier } },
|
||||
}),
|
||||
@@ -59,7 +63,7 @@ function useStock(identifier: string) {
|
||||
return isUid ? byUid : byTicker;
|
||||
}
|
||||
function useStockQuote(uid: string) {
|
||||
return useAuthenticatedQuery({
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/quote", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
@@ -68,7 +72,7 @@ function useStockQuote(uid: string) {
|
||||
});
|
||||
}
|
||||
function useStockCandles(uid: string, period: StockPeriod) {
|
||||
return useAuthenticatedQuery({
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/candles", {
|
||||
params: { path: { uid }, query: { period } },
|
||||
}),
|
||||
@@ -77,7 +81,8 @@ function useStockCandles(uid: string, period: StockPeriod) {
|
||||
});
|
||||
}
|
||||
function useStockPosition(uid: string) {
|
||||
return useAuthenticatedQuery({
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/position", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
@@ -86,7 +91,7 @@ function useStockPosition(uid: string) {
|
||||
});
|
||||
}
|
||||
function useStockCompany(uid: string) {
|
||||
return useAuthenticatedQuery({
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/company", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
@@ -95,7 +100,8 @@ function useStockCompany(uid: string) {
|
||||
});
|
||||
}
|
||||
function useStockDividends(uid: string) {
|
||||
return useAuthenticatedQuery({
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/dividends", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export { AuthProvider, useAuth } from "./model/auth";
|
||||
export { AuthPageLayout } from "./ui/AuthPageLayout";
|
||||
export { AuthPageLayout } from "./ui/AuthPageLayout/AuthPageLayout";
|
||||
export { LoginForm } from "./ui/LoginForm";
|
||||
export { RegisterForm } from "./ui/RegisterForm";
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { FC, PropsWithChildren } from "react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { apiClient, apiQueryClient, useAuthenticatedQuery } from "@/shared/api";
|
||||
import { createTestQueryClient } from "@/test/query";
|
||||
import { resource } from "@/test/resource";
|
||||
import { server } from "@/test/server";
|
||||
import { AuthProvider, useAuth } from "./auth";
|
||||
|
||||
@@ -24,7 +25,7 @@ describe("AuthProvider", () => {
|
||||
),
|
||||
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
||||
authorization = request.headers.get("Authorization");
|
||||
return HttpResponse.json([]);
|
||||
return HttpResponse.json(resource([]));
|
||||
}),
|
||||
);
|
||||
const queryClient = createTestQueryClient();
|
||||
|
||||
@@ -143,8 +143,8 @@ const AuthProvider: FC<PropsWithChildren> = (props) => {
|
||||
refresh,
|
||||
clear: clearSession,
|
||||
});
|
||||
return () => configureAuthClient(null);
|
||||
});
|
||||
useEffect(() => () => configureAuthClient(null), []);
|
||||
|
||||
return (
|
||||
<AuthContext
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
type AuthFormValues,
|
||||
loginSchema,
|
||||
registerSchema,
|
||||
} from "../model/validation";
|
||||
} from "../../model/validation";
|
||||
import classes from "./AuthForm.module.css";
|
||||
|
||||
type AuthFormProps = {
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { FC } from "react";
|
||||
import { useLocation, useNavigate } from "react-router";
|
||||
import { useAuth } from "../model/auth";
|
||||
import { AuthForm } from "./AuthForm";
|
||||
import { AuthForm } from "./AuthForm/AuthForm";
|
||||
|
||||
const LoginForm: FC = () => {
|
||||
const { login } = useAuth();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { FC } from "react";
|
||||
import { useLocation, useNavigate } from "react-router";
|
||||
import { useAuth } from "../model/auth";
|
||||
import { AuthForm } from "./AuthForm";
|
||||
import { AuthForm } from "./AuthForm/AuthForm";
|
||||
|
||||
const RegisterForm: FC = () => {
|
||||
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 = {
|
||||
stale?: boolean;
|
||||
sourceError?: boolean;
|
||||
partial?: boolean;
|
||||
lastSuccessfulAt?: string | null;
|
||||
hasData: boolean;
|
||||
loading: boolean;
|
||||
error: boolean;
|
||||
refreshing: boolean;
|
||||
retry: () => void;
|
||||
};
|
||||
function section(query: {
|
||||
data: unknown;
|
||||
isError: boolean;
|
||||
isFetching: boolean;
|
||||
refetch: () => unknown;
|
||||
}): SectionState {
|
||||
function section(
|
||||
query: {
|
||||
data: unknown;
|
||||
meta?: Meta;
|
||||
isError: boolean;
|
||||
isFetching: boolean;
|
||||
refetch: () => unknown;
|
||||
},
|
||||
retry?: () => unknown,
|
||||
): SectionState {
|
||||
const error = query.isError || query.meta?.sync.state === "failed";
|
||||
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),
|
||||
loading: !query.data && !query.isError,
|
||||
error: query.isError,
|
||||
refreshing: Boolean(query.data) && query.isFetching,
|
||||
loading: !query.data && !error,
|
||||
error,
|
||||
refreshing:
|
||||
Boolean(query.data) &&
|
||||
(query.isFetching ||
|
||||
query.meta?.sync.state === "running" ||
|
||||
query.meta?.sync.state === "queued"),
|
||||
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 { SectionState } from "./section";
|
||||
|
||||
type Position =
|
||||
paths["/api/v1/stocks/{uid}/position"]["get"]["responses"][200]["content"]["application/json"];
|
||||
type Candles =
|
||||
paths["/api/v1/stocks/{uid}/candles"]["get"]["responses"][200]["content"]["application/json"];
|
||||
type Position = NonNullable<
|
||||
paths["/api/v1/stocks/{uid}/position"]["get"]["responses"][200]["content"]["application/json"]["data"]
|
||||
>;
|
||||
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 InstrumentPositionVm = {
|
||||
position?: Position;
|
||||
|
||||
@@ -177,7 +177,13 @@ const InstrumentChart: FC<InstrumentChartProps> = (props) => {
|
||||
</Accordion>
|
||||
</>
|
||||
) : (
|
||||
<Text c="dimmed">{t("stock.noCandles")}</Text>
|
||||
<Text c="dimmed">
|
||||
{t(
|
||||
vm.candlesState.partial
|
||||
? "investment.partial"
|
||||
: "stock.noCandles",
|
||||
)}
|
||||
</Text>
|
||||
)
|
||||
) : null}
|
||||
</InstrumentSection>
|
||||
|
||||
@@ -60,7 +60,11 @@ const InstrumentEvents: FC<InstrumentEventsProps> = (props) => {
|
||||
</Stack>
|
||||
) : (
|
||||
<Text c="dimmed" py="lg">
|
||||
{t("stock.noOperations")}
|
||||
{t(
|
||||
vm.operationsState.partial
|
||||
? "investment.partial"
|
||||
: "stock.noOperations",
|
||||
)}
|
||||
</Text>
|
||||
)}
|
||||
<Group justify="space-between" mt="md">
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||
import type { FC, PropsWithChildren, ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { formatSnapshotTime } from "@/shared/lib";
|
||||
import type { SectionState } from "../model/section";
|
||||
import classes from "./InstrumentDetails.module.css";
|
||||
|
||||
@@ -38,20 +39,40 @@ const InstrumentSection: FC<InstrumentSectionProps> = (props) => {
|
||||
</Title>
|
||||
{props.controls}
|
||||
</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 ? (
|
||||
<Text role="status" size="xs" c="dimmed">
|
||||
{t("accounts.refreshing")}
|
||||
</Text>
|
||||
) : null}
|
||||
{props.state.error ? (
|
||||
<Alert color="orange" mb="sm" role="alert">
|
||||
<Alert color="orange" mb="sm" role="status" aria-live="polite">
|
||||
<Group justify="space-between">
|
||||
<Text size="sm">
|
||||
{props.state.hasData
|
||||
? t("accounts.refreshError")
|
||||
: t("stock.sectionError")}
|
||||
{props.state.sourceError
|
||||
? t("investment.syncFailed")
|
||||
: props.state.hasData
|
||||
? t("accounts.refreshError")
|
||||
: t("stock.sectionError")}
|
||||
</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")}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
@@ -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 { apiQueryClient, type paths } from "@/shared/api";
|
||||
import {
|
||||
apiQueryClient,
|
||||
invalidateApiRequests,
|
||||
type paths,
|
||||
} from "@/shared/api";
|
||||
|
||||
type TbankConnectionStatus =
|
||||
paths["/api/v1/tbank-connection"]["get"]["responses"][200]["content"]["application/json"];
|
||||
@@ -15,6 +19,13 @@ function commitTbankConnectionBoundary(
|
||||
queryClient: QueryClient,
|
||||
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);
|
||||
void queryClient.resetQueries({
|
||||
predicate: ({ queryKey }) => {
|
||||
@@ -22,7 +33,8 @@ function commitTbankConnectionBoundary(
|
||||
return (
|
||||
method === "get" &&
|
||||
typeof path === "string" &&
|
||||
(path === "/api/v1/bonds" ||
|
||||
(path.startsWith("/api/v1/tbank-sync") ||
|
||||
path === "/api/v1/bonds" ||
|
||||
path.startsWith("/api/v1/bonds/") ||
|
||||
path === "/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
Reference in New Issue
Block a user