chore: finish frontend ESLint migration #18

Enable every plugin recommended preset and replace Biome with ESLint formatting.

Preserve API contracts and JSX whitespace; verify source, tests, builds and tooling.
This commit is contained in:
2026-09-28 16:36:40 +03:00
committed by ksv741
parent 57630102e4
commit 72d7835227
253 changed files with 10059 additions and 8864 deletions
+137 -119
View File
@@ -1,3 +1,5 @@
import type { FC } from "react";
import { MantineProvider } from "@mantine/core";
import { QueryClientProvider } from "@tanstack/react-query";
import {
@@ -7,96 +9,104 @@ import {
screen,
waitFor,
} from "@testing-library/react";
import { HttpResponse, http } from "msw";
import type { FC } from "react";
import { http, HttpResponse } from "msw";
import { MemoryRouter, useLocation } from "react-router";
import { beforeEach, describe, expect, it } from "vitest";
import type { BrokerageOperation } from "@/entities/broker-operation";
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";
const accounts = [
{ id: "a", name: "Основной" },
{ id: "b", name: "ИИС" },
];
const position: Portfolio["positions"][number] = {
figi: "SBER",
displayName: "Сбербанк",
type: "STOCK",
quantity: "2",
currentValue: { currency: "RUB", value: "600" },
absoluteReturn: null,
averagePurchasePrice: null,
isin: null,
ticker: "SBER",
logoName: null,
};
const position: Portfolio["positions"][number] = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
absoluteReturn: null,
averagePurchasePrice: null,
currentValue: { currency: "RUB", value: "600" },
displayName: "Сбербанк",
figi: "SBER",
isin: null,
logoName: null,
quantity: "2",
ticker: "SBER",
type: "STOCK",
}
/* eslint-enable unicorn/no-null */);
const portfolio: Portfolio = {
lastSuccessfulAt: "2026-08-15T12:00:00Z",
isStale: false,
totalsByCurrency: [{ currency: "RUB", value: "1200" }],
structure: { currencies: [], unvaluedCategories: [] },
cashBalances: [],
positions: accounts.map((account) => ({ ...position, account })),
isStale: false,
lastSuccessfulAt: "2026-08-15T12:00:00Z",
positions: accounts.map(account => ({ ...position, account })),
structure: { currencies: [], unvaluedCategories: [] },
totalsByCurrency: [{ currency: "RUB", value: "1200" }],
};
const receipt: BrokerageOperation = {
id: "same",
occurredAt: "2026-08-15T12:00:00Z",
type: "OPERATION_TYPE_COUPON",
category: "income",
description: "Выплата купона",
figi: null,
instrumentUid: null,
ticker: "BOND",
instrumentType: "bond",
logoName: null,
payment: { currency: "RUB", value: "1" },
quantity: null,
price: null,
accruedInterest: null,
commission: null,
};
const items = accounts.map((account) => ({ ...receipt, account }));
const analytics: IncomeAnalytics = {
accountId: "all",
period: { from: "2026-08-01", to: "2026-08-31" },
calculatedAt: "2026-09-01T12:00:00Z",
totalsByCurrency: [
{
currency: "RUB",
coupon: { currency: "RUB", value: "2" },
dividend: { currency: "RUB", value: "0" },
total: { currency: "RUB", value: "2" },
const receipt: BrokerageOperation = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
accruedInterest: null,
category: "income",
commission: null,
description: "Выплата купона",
figi: null,
id: "same",
instrumentType: "bond",
instrumentUid: null,
logoName: null,
occurredAt: "2026-08-15T12:00:00Z",
payment: { currency: "RUB", value: "1" },
price: null,
quantity: null,
ticker: "BOND",
type: "OPERATION_TYPE_COUPON",
}
/* eslint-enable unicorn/no-null */);
const items = accounts.map(account => ({ ...receipt, account }));
const analytics: IncomeAnalytics = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
accountId: "all",
bucketGranularity: "day",
buckets: [],
calculatedAt: "2026-09-01T12:00:00Z",
entries: items.map(entry => ({ ...entry, instrumentKey: "bond:RUB" })),
instruments: [
{
coupon: { currency: "RUB", value: "2" },
displayName: "Облигация",
dividend: { currency: "RUB", value: "0" },
figi: null,
instrumentType: "bond",
instrumentUid: null,
key: "bond:RUB",
receiptCount: 2,
ticker: "BOND",
total: { currency: "RUB", value: "2" },
},
],
period: { from: "2026-08-01", to: "2026-08-31" },
previous: {
period: { from: "2026-07-01", to: "2026-07-31" },
totalsByCurrency: [],
},
],
previous: {
period: { from: "2026-07-01", to: "2026-07-31" },
totalsByCurrency: [],
},
yearComparison: null,
bucketGranularity: "day",
buckets: [],
instruments: [
{
key: "bond:RUB",
figi: null,
instrumentUid: null,
ticker: "BOND",
instrumentType: "bond",
displayName: "Облигация",
coupon: { currency: "RUB", value: "2" },
dividend: { currency: "RUB", value: "0" },
total: { currency: "RUB", value: "2" },
receiptCount: 2,
},
],
entries: items.map((entry) => ({ ...entry, instrumentKey: "bond:RUB" })),
};
totalsByCurrency: [
{
coupon: { currency: "RUB", value: "2" },
currency: "RUB",
dividend: { currency: "RUB", value: "0" },
total: { currency: "RUB", value: "2" },
},
],
yearComparison: null,
}
/* eslint-enable unicorn/no-null */);
const CurrentLocation: FC = () => {
const location = useLocation();
return (
@@ -128,18 +138,20 @@ beforeEach(() => {
http.post("*/api/v1/auth/refresh", () =>
HttpResponse.json({
accessToken: "test",
user: { id: "user", email: "user@example.com" },
user: { email: "user@example.com", id: "user" },
}),
),
http.get("*/api/v1/brokerage-accounts", () =>
HttpResponse.json(
resource(
accounts.map((account) => ({
...account,
type: "BROKERAGE",
openedOn: null,
portfolioSummary: null,
})),
accounts.map(account => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
...account,
openedOn: null,
portfolioSummary: null,
type: "BROKERAGE",
}
/* eslint-enable unicorn/no-null */))),
),
),
),
@@ -150,13 +162,15 @@ beforeEach(() => {
"*/api/v1/brokerage-accounts/:accountId/operations",
({ params }) =>
HttpResponse.json(
resource({
accountId: params.accountId,
items,
hasNext: false,
nextCursor: null,
observedAt: receipt.occurredAt,
}),
resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
accountId: params.accountId,
hasNext: false,
items,
nextCursor: null,
observedAt: receipt.occurredAt,
}
/* eslint-enable unicorn/no-null */)),
),
),
http.get("*/api/v1/brokerage-accounts/:accountId/income-analytics", () =>
@@ -167,20 +181,22 @@ beforeEach(() => {
resource({
accountId: "all",
calculatedAt: receipt.occurredAt,
events: accounts.map(account => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
account,
date: "2026-09-15",
dateKind: "event",
displayName: "Облигация",
figi: null,
instrumentUid: null,
isin: null,
logoName: null,
projectedAmount: { currency: "RUB", value: "2" },
ticker: "BOND",
type: "coupon",
}
/* eslint-enable unicorn/no-null */))),
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" },
})),
}),
),
),
@@ -219,7 +235,7 @@ describe("All accounts routes", () => {
);
for (const suffix of ["operations", "income", "events"])
expect(
document.querySelector(`a[href="/accounts/all/${suffix}"]`),
screen.getAllByRole("link").find(link => link.getAttribute("href") === `/accounts/all/${suffix}`),
).toBeInTheDocument();
});
@@ -228,24 +244,26 @@ describe("All accounts routes", () => {
server.use(
http.get(
"*/api/v1/brokerage-accounts/:accountId/operations",
({ request, params }) => {
({ params, request }) => {
const url = new URL(request.url);
requests.push(url);
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,
}),
resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
accountId: params.accountId,
hasNext: !url.searchParams.has("cursor"),
items: [
{
...receipt,
description: url.searchParams.has("cursor")
? "Вторая страница"
: "Первая страница",
},
],
nextCursor: url.searchParams.has("cursor") ? null : "next",
observedAt: receipt.occurredAt,
}
/* eslint-enable unicorn/no-null */)),
);
},
),
@@ -260,10 +278,10 @@ describe("All accounts routes", () => {
fireEvent.click(await screen.findByRole("option", { name: "ИИС" }));
await waitFor(() =>
expect(
requests.some((url) => url.pathname.includes("/b/operations")),
requests.some(url => url.pathname.includes("/b/operations")),
).toBe(true),
);
const selected = requests.find((url) =>
const selected = requests.find(url =>
url.pathname.includes("/b/operations"),
);
expect(selected?.searchParams.get("from")).toBe("2026-08-01T00:00:00.000Z");
@@ -286,8 +304,8 @@ describe("All accounts routes", () => {
: HttpResponse.json(
resource({
accountId: "all",
items,
hasNext: true,
items,
nextCursor: "expired",
observedAt: receipt.occurredAt,
}),
@@ -305,7 +323,7 @@ describe("All accounts routes", () => {
});
it("retains the complete portfolio during a failed refresh", async () => {
const client = renderPage("/accounts/all");
const view = renderPage("/accounts/all");
await screen.findAllByText("Сбербанк");
server.use(
http.get("*/api/v1/brokerage-accounts/all/portfolio", () =>
@@ -313,7 +331,7 @@ describe("All accounts routes", () => {
),
);
await act(() =>
client.invalidateQueries({
view.invalidateQueries({
predicate: ({ queryKey }) => String(queryKey[1]).endsWith("/portfolio"),
}),
);
+33 -29
View File
@@ -2,32 +2,34 @@ import { MantineProvider } from "@mantine/core";
import { QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen } from "@testing-library/react";
import { cssVariablesResolver, theme } from "@wealthledger/ui/theme";
import { HttpResponse, http } from "msw";
import { http, HttpResponse } from "msw";
import { MemoryRouter } from "react-router";
import { describe, expect, it } from "vitest";
import { AuthProvider } from "@/features/auth";
import { createTestQueryClient } from "@/test/query";
import { server } from "@/test/server";
import { AppRoutes } from "./AppRoutes";
describe("AppRoutes", () => {
function renderRoutes(path: string) {
return render(
<QueryClientProvider client={createTestQueryClient()}>
<MemoryRouter initialEntries={[path]}>
<MantineProvider
cssVariablesResolver={cssVariablesResolver}
theme={theme}
>
<AuthProvider>
<AppRoutes />
</AuthProvider>
</MantineProvider>
</MemoryRouter>
</QueryClientProvider>,
);
}
function renderRoutes(path: string) {
return render(
<QueryClientProvider client={createTestQueryClient()}>
<MemoryRouter initialEntries={[path]}>
<MantineProvider
cssVariablesResolver={cssVariablesResolver}
theme={theme}
>
<AuthProvider>
<AppRoutes />
</AuthProvider>
</MantineProvider>
</MemoryRouter>
</QueryClientProvider>,
);
}
describe("AppRoutes", () => {
it.each([
["/", "Вход"],
["/login", "Вход"],
@@ -62,7 +64,7 @@ describe("AppRoutes", () => {
credentials = await request.json();
return HttpResponse.json({
accessToken: "login-token",
user: { id: "user-1", email: "user@example.com" },
user: { email: "user@example.com", id: "user-1" },
});
}),
);
@@ -96,19 +98,21 @@ describe("AppRoutes", () => {
http.post("*/api/v1/auth/login", () =>
HttpResponse.json({
accessToken: "test",
user: { id: "user-1", email: "user@example.com" },
user: { email: "user@example.com", id: "user-1" },
}),
),
http.get("*/api/v1/bank-cards", () => HttpResponse.json([])),
http.get("*/api/v1/bank-cards/summary", () =>
HttpResponse.json({
month: "2026-08",
cardId: null,
expenses: { currency: "RUB", value: "0" },
refunds: { currency: "RUB", value: "0" },
net: { currency: "RUB", value: "0" },
categories: [],
}),
HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
cardId: null,
categories: [],
expenses: { currency: "RUB", value: "0" },
month: "2026-08",
net: { currency: "RUB", value: "0" },
refunds: { currency: "RUB", value: "0" },
}
/* eslint-enable unicorn/no-null */)),
),
);
renderRoutes("/cards?month=2026-08");
@@ -132,7 +136,7 @@ describe("AppRoutes", () => {
http.post("*/api/v1/auth/refresh", () =>
HttpResponse.json({
accessToken: "test-token",
user: { id: "user-1", email: "user@example.com" },
user: { email: "user@example.com", id: "user-1" },
}),
),
);
+62 -60
View File
@@ -1,6 +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";
@@ -71,172 +73,172 @@ const ProtectedLayout = lazy(async () => {
const AppRoutes: FC = () => (
<Routes>
<Route path="/" element={<Navigate to="/accounts" replace />} />
<Route element={<Navigate replace to="/accounts" />} path="/" />
<Route
path="/login"
element={
element={(
<Public>
<LazyPage variant="auth">
<LoginPage />
</LazyPage>
</Public>
}
)}
path="/login"
/>
<Route
path="/register"
element={
element={(
<Public>
<LazyPage variant="auth">
<RegisterPage />
</LazyPage>
</Public>
}
)}
path="/register"
/>
<Route
element={
element={(
<Protected>
<LazyPage variant="shell">
<ProtectedLayout />
</LazyPage>
</Protected>
}
)}
>
<Route
path="/cards/:cardId"
element={
element={(
<LazyPage variant="content">
<CardPage />
</LazyPage>
}
)}
path="/cards/:cardId"
/>
<Route
path="/cards"
element={
element={(
<LazyPage variant="content">
<CardsPage />
</LazyPage>
}
)}
path="/cards"
/>
<Route
path="/bonds"
element={
element={(
<LazyPage variant="content">
<BondsPage />
</LazyPage>
}
)}
path="/bonds"
/>
<Route
path="/bonds/:bondId"
element={
element={(
<LazyPage variant="content">
<BondPage />
</LazyPage>
}
)}
path="/bonds/:bondId"
/>
<Route
path="/stocks"
element={
element={(
<LazyPage variant="content">
<StocksPage />
</LazyPage>
}
)}
path="/stocks"
/>
<Route
path="/stocks/:stockId"
element={
element={(
<LazyPage variant="content">
<StockPage />
</LazyPage>
}
)}
path="/stocks/:stockId"
/>
<Route
path="/accounts"
element={
element={(
<LazyPage variant="content">
<AccountsPage />
</LazyPage>
}
)}
path="/accounts"
/>
<Route
path="/accounts/all"
element={
element={(
<LazyPage variant="content">
<AccountPage accountId="all" />
</LazyPage>
}
)}
path="/accounts/all"
/>
<Route
path="/accounts/all/operations"
element={
element={(
<LazyPage variant="content">
<AccountOperationsPage accountId="all" />
</LazyPage>
}
)}
path="/accounts/all/operations"
/>
<Route
path="/accounts/all/income"
element={
element={(
<LazyPage variant="content">
<AccountIncomePage accountId="all" />
</LazyPage>
}
)}
path="/accounts/all/income"
/>
<Route
path="/accounts/all/events"
element={
element={(
<LazyPage variant="content">
<AccountEventsPage accountId="all" />
</LazyPage>
}
)}
path="/accounts/all/events"
/>
<Route
path="/accounts/:accountId"
element={
element={(
<LazyPage variant="content">
<AccountPage />
</LazyPage>
}
)}
path="/accounts/:accountId"
/>
<Route
path="/accounts/:accountId/events"
element={
element={(
<LazyPage variant="content">
<AccountEventsPage />
</LazyPage>
}
)}
path="/accounts/:accountId/events"
/>
<Route
path="/accounts/:accountId/income"
element={
element={(
<LazyPage variant="content">
<AccountIncomePage />
</LazyPage>
}
)}
path="/accounts/:accountId/income"
/>
<Route
path="/accounts/:accountId/operations"
element={
element={(
<LazyPage variant="content">
<AccountOperationsPage />
</LazyPage>
}
)}
path="/accounts/:accountId/operations"
/>
<Route
path="/settings"
element={
element={(
<LazyPage variant="content">
<SettingsPage />
</LazyPage>
}
)}
path="/settings"
/>
</Route>
<Route
path="*"
element={
element={(
<LazyPage variant="content">
<NotFoundPage />
</LazyPage>
}
)}
path="*"
/>
</Routes>
);
@@ -1,3 +1,5 @@
import type { FC } from "react";
import { QueryClientProvider } from "@tanstack/react-query";
import {
act,
@@ -6,24 +8,25 @@ import {
screen,
waitFor,
} from "@testing-library/react";
import { HttpResponse, http } from "msw";
import type { FC } from "react";
import { http, HttpResponse } from "msw";
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";
const Navigation: FC = () => {
const navigate = useNavigate();
return (
<>
<button type="button" onClick={() => navigate("/accounts/all/income")}>
<button onClick={() => navigate("/accounts/all/income")} type="button">
Все счета
</button>
<button type="button" onClick={() => navigate(-1)}>
<button onClick={() => navigate(-1)} type="button">
Назад
</button>
</>
@@ -48,7 +51,7 @@ beforeEach(() => {
http.post("*/api/v1/auth/refresh", () =>
HttpResponse.json({
accessToken: "test-token",
user: { id: "user-1", email: "user@example.com" },
user: { email: "user@example.com", id: "user-1" },
}),
),
);
@@ -56,10 +59,7 @@ beforeEach(() => {
describe("document titles", () => {
it("updates a loading account name and follows account scope and history", async () => {
let resolveAccounts!: () => void;
const accountsReady = new Promise<void>((resolve) => {
resolveAccounts = resolve;
});
const { promise: accountsReady, resolve: resolveAccounts } = Promise.withResolvers<void>();
server.use(
http.get("*/api/v1/brokerage-accounts", async () => {
await accountsReady;
@@ -68,7 +68,7 @@ describe("document titles", () => {
);
renderTitle("/accounts/a/income?from=2026-01-01&to=2026-08-31");
expect(document.title).toBe("Пассивный доход — Счет — WealthLedger");
await act(async () => resolveAccounts());
await act(() => Promise.resolve(resolveAccounts()));
await waitFor(() =>
expect(document.title).toBe("Пассивный доход — ИИС — WealthLedger"),
);
@@ -98,15 +98,15 @@ describe("document titles", () => {
);
it("keeps a useful title when the instrument is unavailable", async () => {
let requested = false;
let isRequested = false;
server.use(
http.get("*/api/v1/stocks/by-ticker/:ticker", () => {
requested = true;
isRequested = true;
return HttpResponse.json({ code: "NOT_FOUND" }, { status: 404 });
}),
);
renderTitle("/stocks/missing");
await waitFor(() => expect(requested).toBe(true));
await waitFor(() => expect(isRequested).toBe(true));
expect(document.title).toBe("Акция — WealthLedger");
});
});
+30 -30
View File
@@ -1,7 +1,9 @@
import { useDocumentTitle } from "@mantine/hooks";
import type { FC } from "react";
import { useDocumentTitle } from "@mantine/hooks";
import { useTranslation } from "react-i18next";
import { useMatch } from "react-router";
import { useBankCard } from "@/entities/bank-card";
import { useBond } from "@/entities/bond";
import { useBrokerageAccounts } from "@/entities/brokerage-account";
@@ -9,10 +11,9 @@ import { useStock } from "@/entities/stock";
type DocumentTitleProps = { title: string };
const DocumentTitle: FC<DocumentTitleProps> = (props) => {
const DocumentTitle: FC<DocumentTitleProps> = (props): undefined => {
const { t } = useTranslation();
useDocumentTitle(`${props.title} — ${t("appName")}`);
return null;
};
type AccountDocumentTitleProps = {
@@ -23,19 +24,29 @@ type AccountDocumentTitleProps = {
const AccountDocumentTitle: FC<AccountDocumentTitleProps> = (props) => {
const { t } = useTranslation();
const { data } = useBrokerageAccounts();
const accountName =
props.accountId === "all"
const accountName
= props.accountId === "all"
? t("accounts.all")
: (data?.find((account) => account.id === props.accountId)?.name ??
t("account.title"));
const section =
props.section === "income"
? t("income.title")
: props.section === "operations"
? t("ledger.title")
: props.section === "events"
? t("events.title")
: t("portfolio.title");
: (data?.find(account => account.id === props.accountId)?.name
?? t("account.title"));
let section = t("portfolio.title");
switch (props.section ?? "") {
case "income": {
section = t("income.title");
break;
}
case "operations": {
section = t("ledger.title");
break;
}
case "events": {
section = t("events.title");
break;
}
default: {
break;
}
}
return <DocumentTitle title={`${section} — ${accountName}`} />;
};
@@ -80,21 +91,10 @@ const ProtectedDocumentTitle: FC = () => {
if (bond) return <BondDocumentTitle identifier={bond.params.bondId ?? ""} />;
if (stock)
return <StockDocumentTitle identifier={stock.params.stockId ?? ""} />;
return (
<DocumentTitle
title={t(
cards
? "navigation.cards"
: bonds
? "navigation.bonds"
: stocks
? "navigation.stocks"
: settings
? "navigation.settings"
: "navigation.accounts",
)}
/>
);
if (cards) return <DocumentTitle title={t("navigation.cards")} />;
if (bonds) return <DocumentTitle title={t("navigation.bonds")} />;
if (stocks) return <DocumentTitle title={t("navigation.stocks")} />;
return settings ? <DocumentTitle title={t("navigation.settings")} /> : <DocumentTitle title={t("navigation.accounts")} />;
};
export { ProtectedDocumentTitle };
+2
View File
@@ -1,5 +1,7 @@
import type { FC } from "react";
import { AppBreadcrumbs, AppShell } from "@/app/ui";
import { ProtectedDocumentTitle } from "./DocumentTitle/DocumentTitle";
const ProtectedLayout: FC = () => {
@@ -3,11 +3,14 @@ import { fireEvent, render, screen } from "@testing-library/react";
import { type FC, lazy, Suspense } from "react";
import { MemoryRouter, useLocation, useNavigate } from "react-router";
import { describe, expect, it, vi } from "vitest";
import { RouteErrorBoundary } from "./RouteErrorBoundary";
let authenticated = false;
const session = { isAuthenticated: false };
vi.mock("@/features/auth", () => ({
useAuth: () => ({ user: authenticated ? {} : null }),
useAuth: () => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{ user: session.isAuthenticated ? {} : null }
/* eslint-enable unicorn/no-null */)),
}));
const ThrowingRoute: FC = () => {
@@ -17,11 +20,13 @@ const ThrowingRoute: FC = () => {
const HealthyRoute: FC = () => {
return (
<div>
{useLocation().pathname === "/healthy" ? (
"healthy route"
) : (
<ThrowingRoute />
)}
{useLocation().pathname === "/healthy"
? (
"healthy route"
)
: (
<ThrowingRoute />
)}
</div>
);
};
@@ -31,7 +36,7 @@ const RouteHarness: FC = () => {
return (
<>
<button type="button" onClick={() => navigate("/healthy")}>
<button onClick={() => navigate("/healthy")} type="button">
go healthy
</button>
<RouteErrorBoundary>
@@ -55,10 +60,10 @@ describe("RouteErrorBoundary", () => {
it.each(["/accounts", "/login"])(
"recovers a transient failure through the fallback on %s itself",
async (path) => {
authenticated = path === "/accounts";
let failing = true;
session.isAuthenticated = path === "/accounts";
let isFailing = true;
const RecoverableRoute: FC = () => {
if (failing) throw new Error("temporary failure");
if (isFailing) throw new Error("temporary failure");
return <div>recovered route</div>;
};
render(
@@ -71,14 +76,14 @@ describe("RouteErrorBoundary", () => {
</MantineProvider>,
);
const action = screen.getByRole("link", { name: "Продолжить" });
failing = false;
isFailing = false;
fireEvent.click(action);
expect(await screen.findByText("recovered route")).toBeInTheDocument();
},
);
it("keeps a persistent failure recoverable without an automatic reset loop", () => {
authenticated = true;
session.isAuthenticated = true;
renderBoundary("/accounts");
fireEvent.click(screen.getByRole("link", { name: "Продолжить" }));
expect(
@@ -91,7 +96,7 @@ describe("RouteErrorBoundary", () => {
});
it("offers document navigation when React.lazy caches a rejected chunk", async () => {
authenticated = false;
session.isAuthenticated = false;
const load = vi.fn(() => Promise.reject(new Error("chunk failed")));
const Chunk = lazy(load);
render(
@@ -110,18 +115,18 @@ describe("RouteErrorBoundary", () => {
const reload = screen.getByRole("link", { name: "Перезагрузить страницу" });
expect(reload).toHaveAttribute("href", "/login");
// Cancel browser navigation in JSDOM only after proving React Router did not intercept it.
let intercepted = true;
let isIntercepted = true;
const preventNavigation = (event: MouseEvent) => {
intercepted = event.defaultPrevented;
isIntercepted = event.defaultPrevented;
event.preventDefault();
};
document.addEventListener("click", preventNavigation, { once: true });
fireEvent.click(reload);
expect(intercepted).toBe(false);
expect(isIntercepted).toBe(false);
});
it("offers login after a public route error without error details", () => {
authenticated = false;
session.isAuthenticated = false;
renderBoundary("/login");
expect(document.title).toBe("Не удалось открыть страницу — WealthLedger");
expect(screen.getByRole("link", { name: "Продолжить" })).toHaveAttribute(
@@ -132,9 +137,9 @@ describe("RouteErrorBoundary", () => {
});
it("offers accounts after a protected route error and resets on navigation", async () => {
authenticated = true;
session.isAuthenticated = true;
renderBoundary("/accounts");
screen.getByRole("button", { name: "go healthy" }).click();
fireEvent.click(screen.getByRole("button", { name: "go healthy" }));
expect(await screen.findByText("healthy route")).toBeInTheDocument();
});
});
@@ -1,14 +1,16 @@
import type { FC, PropsWithChildren } from "react";
import { Button, Stack, Text, Title } from "@mantine/core";
import { useDocumentTitle } from "@mantine/hooks";
import type { FC, PropsWithChildren } from "react";
import { Component } from "react";
import { useTranslation } from "react-i18next";
import { Link, useLocation } from "react-router";
import { useAuth } from "@/features/auth";
type BoundaryProps = PropsWithChildren<{
routeKey: string;
authenticated: boolean;
routeKey: string;
}>;
type RouteErrorFallbackProps = {
@@ -18,12 +20,12 @@ type RouteErrorFallbackProps = {
type State = { hasError: boolean };
class Boundary extends Component<BoundaryProps, State> {
state: State = { hasError: false };
static getDerivedStateFromError(): State {
return { hasError: true };
}
state: State = { hasError: false };
componentDidUpdate(previousProps: BoundaryProps) {
if (previousProps.routeKey !== this.props.routeKey && this.state.hasError) {
this.setState({ hasError: false });
@@ -31,10 +33,7 @@ class Boundary extends Component<BoundaryProps, State> {
}
render() {
if (this.state.hasError) {
return <RouteErrorFallback authenticated={this.props.authenticated} />;
}
return this.props.children;
return this.state.hasError ? <RouteErrorFallback authenticated={this.props.authenticated} /> : this.props.children;
}
}
@@ -60,7 +59,7 @@ const RouteErrorFallback: FC<RouteErrorFallbackProps> = (props) => {
const RouteErrorBoundary: FC<PropsWithChildren> = (props) => {
const { children } = props;
const { pathname, search, key } = useLocation();
const { key, pathname, search } = useLocation();
const { user } = useAuth();
return (
+12 -8
View File
@@ -1,11 +1,13 @@
import { Container, Group, Skeleton, Stack } from "@mantine/core";
import type { FC, PropsWithChildren } from "react";
import { Container, Group, Skeleton, Stack } from "@mantine/core";
import { Suspense } from "react";
import { useTranslation } from "react-i18next";
import { RouteTransition } from "./RouteTransition";
type RouteSkeletonVariant = "auth" | "content" | "shell";
type LazyPageProps = PropsWithChildren<{ variant: RouteSkeletonVariant }>;
type RouteSkeletonVariant = "auth" | "content" | "shell";
const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => {
const { variant } = props;
@@ -13,7 +15,7 @@ const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => {
if (variant === "auth")
return (
<Container size={420} py="xl">
<Container py="xl" size={420}>
<Stack
aria-busy="true"
aria-label={t("states.loadingTitle")}
@@ -61,11 +63,13 @@ const LazyPage: FC<LazyPageProps> = (props) => {
const { children, variant } = props;
return (
<Suspense fallback={<RouteSkeleton variant={variant} />}>
{variant === "shell" ? (
children
) : (
<RouteTransition>{children}</RouteTransition>
)}
{variant === "shell"
? (
children
)
: (
<RouteTransition>{children}</RouteTransition>
)}
</Suspense>
);
};
+24 -18
View File
@@ -1,37 +1,43 @@
import type { FC, PropsWithChildren } from "react";
import { Navigate, useLocation } from "react-router";
import { useAuth } from "@/features/auth";
import { RouteSkeleton } from "./RouteFallback";
const Protected: FC<PropsWithChildren> = (props) => {
const { children } = props;
const { user, ready } = useAuth();
const { ready, user } = useAuth();
const location = useLocation();
if (!ready) return <RouteSkeleton variant="shell" />;
return user ? (
children
) : (
<Navigate
to="/login"
state={{ returnTo: `${location.pathname}${location.search}` }}
replace
/>
);
return user
? (
<>{children}</>
)
: (
<Navigate
replace
state={{ returnTo: `${location.pathname}${location.search}` }}
to="/login"
/>
);
};
const Public: FC<PropsWithChildren> = (props) => {
const { children } = props;
const { user, ready } = useAuth();
const { ready, user } = useAuth();
const location = useLocation();
const requested = (location.state as { returnTo?: string } | null)?.returnTo;
const returnTo =
typeof requested === "string" &&
requested.startsWith("/") &&
!requested.startsWith("//")
if (!ready) return <RouteSkeleton variant="shell" />;
const requested = (location.state as null | { returnTo?: string })?.returnTo;
const returnTo
= typeof requested === "string"
&& requested.startsWith("/")
&& !requested.startsWith("//")
? requested
: "/accounts";
if (!ready) return <RouteSkeleton variant="shell" />;
return user ? <Navigate to={returnTo} replace /> : children;
return user ? <Navigate replace to={returnTo} /> : <>{children}</>;
};
export { Protected, Public };
+4 -3
View File
@@ -1,6 +1,7 @@
import type { FC, PropsWithChildren } from "react";
import { domAnimation, LazyMotion, useReducedMotion } from "motion/react";
import * as m from "motion/react-m";
import type { FC, PropsWithChildren } from "react";
import { useLocation } from "react-router";
const TRANSITION_DURATION_SECONDS = 0.2;
@@ -13,9 +14,9 @@ const RouteTransition: FC<PropsWithChildren> = (props) => {
return (
<LazyMotion features={domAnimation}>
<m.div
key={pathname}
initial={reduceMotion ? false : { opacity: 0 }}
animate={{ opacity: 1 }}
initial={!reduceMotion && { opacity: 0 }}
key={pathname}
transition={{
duration: reduceMotion ? 0 : TRANSITION_DURATION_SECONDS,
ease: "easeOut",
+4 -2
View File
@@ -1,9 +1,11 @@
import type { FC } from "react";
import { MantineProvider } from "@mantine/core";
import { DatesProvider } from "@mantine/dates";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { cssVariablesResolver, theme } from "@wealthledger/ui/theme";
import type { FC } from "react";
import { BrowserRouter } from "react-router";
import { AppRoutes, RouteErrorBoundary } from "@/app/routes";
import { AuthProvider } from "@/features/auth";
@@ -17,8 +19,8 @@ const App: FC = () => {
return (
<MantineProvider
cssVariablesResolver={cssVariablesResolver}
theme={theme}
forceColorScheme="light"
theme={theme}
>
<DatesProvider settings={{ locale: "ru" }}>
<QueryClientProvider client={queryClient}>
@@ -1,6 +1,9 @@
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { useBrokerageAccounts } from "@/entities/brokerage-account";
import { BreadcrumbTrail } from "./BreadcrumbTrail";
type AccountBreadcrumbsProps = {
@@ -12,11 +15,11 @@ const AccountBreadcrumbs: FC<AccountBreadcrumbsProps> = (props) => {
const { accountId, section } = props;
const { data: accounts } = useBrokerageAccounts();
const { t } = useTranslation();
const accountName =
accountId === "all"
const accountName
= accountId === "all"
? t("accounts.all")
: (accounts?.find((account) => account.id === accountId)?.name ??
t("breadcrumbs.accountFallback"));
: (accounts?.find(account => account.id === accountId)?.name
?? t("breadcrumbs.accountFallback"));
const accountPath = `/accounts/${accountId}`;
const items = [
{ label: t("breadcrumbs.accounts"), to: "/accounts" },
@@ -1,7 +1,9 @@
import { Select } from "@mantine/core";
import type { FC } from "react";
import { Select } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { useLocation, useNavigate } from "react-router";
import { useBrokerageAccounts } from "@/entities/brokerage-account";
type AccountScopeSwitchProps = { accountId: string; section?: string };
@@ -13,31 +15,31 @@ const AccountScopeSwitch: FC<AccountScopeSwitchProps> = (props) => {
const navigate = useNavigate();
const { search } = useLocation();
const data = [
{ value: "all", label: t("accounts.all") },
...(accounts ?? []).map((account) => ({
value: account.id,
{ label: t("accounts.all"), value: "all" },
...(accounts ?? []).map(account => ({
label: account.name,
value: account.id,
})),
];
if (!data.some((item) => item.value === accountId))
data.push({ value: accountId, label: t("breadcrumbs.accountFallback") });
if (data.every(item => item.value !== accountId))
data.push({ label: t("breadcrumbs.accountFallback"), value: accountId });
return (
<Select
label={t("accounts.scope")}
value={accountId}
data={data}
allowDeselect={false}
data={data}
label={t("accounts.scope")}
maw={360}
w="100%"
onChange={(value) => {
if (!value || value === accountId) return;
const filters = new URLSearchParams(search);
filters.delete("cursor");
void navigate({
pathname: `/accounts/${encodeURIComponent(value)}${section ? `/${section}` : ""}`,
pathname: ["/accounts", encodeURIComponent(value), section].filter(Boolean).join("/"),
search: filters.toString(),
});
}}
value={accountId}
w="100%"
/>
);
};
@@ -2,6 +2,7 @@ import { MantineProvider } from "@mantine/core";
import { render, screen, within } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { afterEach, describe, expect, it, vi } from "vitest";
import { AppBreadcrumbs } from "./AppBreadcrumbs";
const { useBrokerageAccounts } = vi.hoisted(() => ({
+12 -12
View File
@@ -1,7 +1,9 @@
import { Stack } from "@mantine/core";
import type { FC } from "react";
import { Stack } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { useMatch } from "react-router";
import { AccountBreadcrumbs } from "./AccountBreadcrumbs";
import { AccountScopeSwitch } from "./AccountScopeSwitch";
import { BondBreadcrumbs } from "./BondBreadcrumbs";
@@ -12,19 +14,19 @@ import { StockBreadcrumbs } from "./StockBreadcrumbs";
const AppBreadcrumbs: FC = () => {
const { t } = useTranslation();
const operations = useMatch({
path: "/accounts/:accountId/operations",
end: true,
path: "/accounts/:accountId/operations",
});
const events = useMatch({ path: "/accounts/:accountId/events", end: true });
const income = useMatch({ path: "/accounts/:accountId/income", end: true });
const account = useMatch({ path: "/accounts/:accountId", end: true });
const events = useMatch({ end: true, path: "/accounts/:accountId/events" });
const income = useMatch({ end: true, path: "/accounts/:accountId/income" });
const account = useMatch({ end: true, path: "/accounts/:accountId" });
const card = useMatch("/cards/:cardId");
const cards = useMatch("/cards");
const accounts = useMatch({ path: "/accounts", end: true });
const settings = useMatch({ path: "/settings", end: true });
const accounts = useMatch({ end: true, path: "/accounts" });
const settings = useMatch({ end: true, path: "/settings" });
const stock = useMatch({ path: "/stocks/:stockId", end: true });
const bond = useMatch({ path: "/bonds/:bondId", end: true });
const stock = useMatch({ end: true, path: "/stocks/:stockId" });
const bond = useMatch({ end: true, path: "/bonds/:bondId" });
if (bond) return <BondBreadcrumbs identifier={bond.params.bondId ?? ""} />;
if (stock)
return <StockBreadcrumbs identifier={stock.params.stockId ?? ""} />;
@@ -78,9 +80,7 @@ const AppBreadcrumbs: FC = () => {
if (cards) return <BreadcrumbTrail items={[{ label: t("bank.title") }]} />;
if (accounts)
return <BreadcrumbTrail items={[{ label: t("breadcrumbs.accounts") }]} />;
if (settings)
return <BreadcrumbTrail items={[{ label: t("breadcrumbs.settings") }]} />;
return null;
return settings ? <BreadcrumbTrail items={[{ label: t("breadcrumbs.settings") }]} /> : undefined;
};
export { AppBreadcrumbs };
@@ -1,6 +1,9 @@
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { useBond } from "@/entities/bond";
import { BreadcrumbTrail } from "./BreadcrumbTrail";
type BondBreadcrumbsProps = { identifier: string };
+16 -12
View File
@@ -1,11 +1,13 @@
import { Breadcrumbs } from "@mantine/core";
import type { FC } from "react";
import { Breadcrumbs } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import classes from "./AppBreadcrumbs.module.css";
type Crumb = { label: string; to?: string };
type BreadcrumbTrailProps = { items: Crumb[] };
type Crumb = { label: string; to?: string };
const BreadcrumbTrail: FC<BreadcrumbTrailProps> = (props) => {
const { items } = props;
@@ -18,16 +20,18 @@ const BreadcrumbTrail: FC<BreadcrumbTrailProps> = (props) => {
data-depth={items.length}
separator={<span aria-hidden="true">→</span>}
>
{items.map((item) =>
item.to ? (
<Link className={classes.link} key={item.to} to={item.to}>
{item.label}
</Link>
) : (
<span aria-current="page" key={item.label}>
{item.label}
</span>
),
{items.map(item =>
item.to
? (
<Link className={classes.link} key={item.to} to={item.to}>
{item.label}
</Link>
)
: (
<span aria-current="page" key={item.label}>
{item.label}
</span>
),
)}
</Breadcrumbs>
);
@@ -1,6 +1,9 @@
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { useBankCard } from "@/entities/bank-card";
import { BreadcrumbTrail } from "./BreadcrumbTrail";
type CardBreadcrumbsProps = { identifier: string };
@@ -1,6 +1,9 @@
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { useStock } from "@/entities/stock";
import { BreadcrumbTrail } from "./BreadcrumbTrail";
type StockBreadcrumbsProps = { identifier: string };
+40 -37
View File
@@ -1,8 +1,11 @@
import { AppShell as MantineAppShell, NavLink, Text } from "@mantine/core";
import type { FC, ReactNode } from "react";
import { AppShell as MantineAppShell, NavLink, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Outlet, NavLink as RouterNavLink, useLocation } from "react-router";
import { bindIconAnimation } from "@/shared/lib";
import classes from "./AppShell.module.css";
type AppShellProps = {
@@ -15,9 +18,6 @@ const AppShell: FC<AppShellProps> = (props) => {
const { pathname } = useLocation();
const items = [
{
to: "/accounts",
label: t("navigation.accounts"),
iconClassName: classes.portfolioIcon,
icon: (
<>
<path d="M3 10v9h18v-9" />
@@ -32,11 +32,11 @@ const AppShell: FC<AppShellProps> = (props) => {
/>
</>
),
iconClassName: classes.portfolioIcon,
label: t("navigation.accounts"),
to: "/accounts",
},
{
to: "/cards",
label: t("navigation.cards"),
iconClassName: classes.cardsIcon,
icon: (
<>
<path d="M3 5h18v14H3V5Zm0 4h18M6 15h4" />
@@ -47,42 +47,42 @@ const AppShell: FC<AppShellProps> = (props) => {
</g>
</>
),
iconClassName: classes.cardsIcon,
label: t("navigation.cards"),
to: "/cards",
},
{
to: "/stocks",
label: t("navigation.stocks"),
iconClassName: classes.stocksIcon,
icon: (
<>
<path d="M3 3v18h18" />
<path
className={classes.drawStroke}
pathLength={1}
d="M7 14l5-5 4 3 5-7"
pathLength={1}
/>
<path className={classes.stockArrow} d="M16 5h5v5" />
</>
),
iconClassName: classes.stocksIcon,
label: t("navigation.stocks"),
to: "/stocks",
},
{
to: "/bonds",
label: t("navigation.bonds"),
iconClassName: classes.bondsIcon,
icon: (
<>
<path d="M6 3h12v18l-3-2-3 2-3-2-3 2V3Z" />
<g className={classes.couponLines}>
<path pathLength={1} d="M9 7h6" />
<path pathLength={1} d="M9 11h6" />
<path pathLength={1} d="M9 15h3" />
<path d="M9 7h6" pathLength={1} />
<path d="M9 11h6" pathLength={1} />
<path d="M9 15h3" pathLength={1} />
</g>
</>
),
iconClassName: classes.bondsIcon,
label: t("navigation.bonds"),
to: "/bonds",
},
{
to: "/settings",
label: t("navigation.settings"),
iconClassName: classes.settingsIcon,
icon: (
<>
<path d="M4 7h16M4 17h16" />
@@ -90,48 +90,51 @@ const AppShell: FC<AppShellProps> = (props) => {
<path className={classes.bottomSlider} d="M10 14v6h4v-6h-4Z" />
</>
),
iconClassName: classes.settingsIcon,
label: t("navigation.settings"),
to: "/settings",
},
];
return (
<MantineAppShell
header={{ height: 60 }}
navbar={{ width: 220, breakpoint: "sm", collapsed: { mobile: true } }}
navbar={{ breakpoint: "sm", collapsed: { mobile: true }, width: 220 }}
padding="md"
>
<MantineAppShell.Header className={classes.header}>
<Text fw={700}>{t("appName")}</Text>
</MantineAppShell.Header>
<MantineAppShell.Navbar p="sm">
{items.map((item) => (
{items.map(item => (
<NavLink
component={RouterNavLink}
active={pathname.startsWith(item.to)}
className={classes.navLink}
component={RouterNavLink}
key={item.to}
to={item.to}
label={item.label}
leftSection={
leftSection={(
<span
className={`${classes.navIcon} ${item.iconClassName ?? ""}`}
>
<svg
ref={bindIconAnimation}
width={20}
height={20}
viewBox="0 0 24 24"
aria-hidden="true"
fill="none"
focusable="false"
height={20}
ref={bindIconAnimation}
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
strokeWidth="1.5"
viewBox="0 0 24 24"
width={20}
>
{item.icon}
</svg>
</span>
}
active={pathname.startsWith(item.to)}
)}
to={item.to}
/>
))}
</MantineAppShell.Navbar>
@@ -141,11 +144,11 @@ const AppShell: FC<AppShellProps> = (props) => {
<Outlet />
</div>
</MantineAppShell.Main>
<nav className={classes.bottomNav} aria-label={t("appName")}>
{items.map((item) => (
<nav aria-label={t("appName")} className={classes.bottomNav}>
{items.map(item => (
<RouterNavLink
className={
pathname.startsWith(item.to) ? classes.active : undefined
(pathname.startsWith(item.to)) ? (classes.active) : undefined
}
key={item.to}
to={item.to}
+71 -69
View File
@@ -1,9 +1,11 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { http, HttpResponse } from "msw";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { apiClient, configureAuthClient } from "@/shared/api";
import { createQueryWrapper } from "@/test/query";
import { server } from "@/test/server";
import { useBankMutations } from "./mutations";
import {
type BankCard,
@@ -17,32 +19,34 @@ import {
useBankSummary,
} from "./queries";
const card: BankCard = {
id: "a",
name: "Daily",
bankName: null,
lastFour: null,
paymentSystem: null,
openingBalance: { currency: "RUB", value: "100" },
openingDate: "2026-09-01",
balance: { currency: "RUB", value: "100" },
archivedAt: null,
version: 1,
};
const card: BankCard = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
archivedAt: null,
balance: { currency: "RUB", value: "100" },
bankName: null,
id: "a",
lastFour: null,
name: "Daily",
openingBalance: { currency: "RUB", value: "100" },
openingDate: "2026-09-01",
paymentSystem: null,
version: 1,
}
/* eslint-enable unicorn/no-null */);
const transfer: CreateBankOperation = {
amount: { currency: "RUB", value: "90071992547409.93" },
cardId: "a",
date: "2026-09-12",
id: "4e6caa65-dd52-4629-81e2-ce8a139a0612",
kind: "transfer",
cardId: "a",
targetCardId: "b",
amount: { currency: "RUB", value: "90071992547409.93" },
date: "2026-09-12",
};
function authenticate() {
configureAuthClient({
accessToken: () => "token",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
}
@@ -59,30 +63,28 @@ function readHandlers(counts: Map<string, number>, categoryName = "Food") {
counts.set(key, (counts.get(key) ?? 0) + 1);
if (url.pathname.endsWith("/categories"))
return HttpResponse.json([
{ id: "food", name: categoryName, isDefault: true, version: 1 },
{ id: "food", isDefault: true, name: categoryName, version: 1 },
]);
if (url.pathname.endsWith("/summary"))
return HttpResponse.json({
month: url.searchParams.get("month"),
cardId: url.searchParams.get("cardId"),
expenses: { currency: "RUB", value: "0" },
refunds: { currency: "RUB", value: "0" },
net: { currency: "RUB", value: "0" },
categories: [],
expenses: { currency: "RUB", value: "0" },
month: url.searchParams.get("month"),
net: { currency: "RUB", value: "0" },
refunds: { currency: "RUB", value: "0" },
});
if (
url.pathname.endsWith("/operations") ||
url.pathname.endsWith("/expenses")
url.pathname.endsWith("/operations")
|| url.pathname.endsWith("/expenses")
)
return HttpResponse.json({
hasNext: false,
items: [],
page: 1,
total: 0,
hasNext: false,
});
if (url.pathname.includes("/operations/"))
return HttpResponse.json({ ...transfer, version: 1 });
return HttpResponse.json({ ...card, id: url.pathname.split("/").at(-1) });
return url.pathname.includes("/operations/") ? HttpResponse.json({ ...transfer, version: 1 }) : HttpResponse.json({ ...card, id: url.pathname.split("/").at(-1) });
}),
];
}
@@ -93,15 +95,16 @@ function useReadModels() {
const b = useBankCard("b");
const categories = useBankCategories();
const history = useBankOperations("a", {
limit: 20,
month: "2026-09",
page: 2,
limit: 20,
});
const expenses = useBankExpenses("a", { page: 1 });
const september = useBankSummary("2026-09");
const august = useBankSummary("2026-08", "b");
const original = useBankOperation("original");
return {
mutations: useBankMutations(),
reads: [
cards,
a,
@@ -113,7 +116,6 @@ function useReadModels() {
august,
original,
],
mutations: useBankMutations(),
};
}
@@ -122,7 +124,7 @@ describe("banking API", () => {
it("loads every page for all mode and fails without exposing partial results", async () => {
const pages: number[] = [];
let fail = false;
let isFail = false;
server.use(
http.get("*/api/v1/bank-cards/a/operations", ({ request }) => {
const url = new URL(request.url);
@@ -130,33 +132,33 @@ describe("banking API", () => {
pages.push(page);
expect(url.searchParams.get("limit")).toBe("100");
expect(url.searchParams.get("month")).toBe("2026-09");
if (fail && page === 2)
if (isFail && page === 2)
return HttpResponse.json({ code: "FAILED" }, { status: 500 });
return HttpResponse.json({
items: [{ ...transfer, id: String(page) }],
total: 2,
page,
hasNext: page === 1,
items: [{ ...transfer, id: String(page) }],
page,
total: 2,
});
}),
);
const { result } = renderHook(
() => useBankOperations("a", { month: "2026-09", page: 1, limit: "all" }),
() => useBankOperations("a", { limit: "all", month: "2026-09", page: 1 }),
{ wrapper: createQueryWrapper().wrapper },
);
await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(pages).toEqual([1, 2]);
expect(result.current.data?.items.map((item) => item.id)).toEqual([
expect(result.current.data?.items.map(item => item.id)).toEqual([
"1",
"2",
]);
fail = true;
const failed = renderHook(
() => useBankOperations("a", { month: "2026-09", page: 1, limit: "all" }),
isFail = true;
const { result: failedResult } = renderHook(
() => useBankOperations("a", { limit: "all", month: "2026-09", page: 1 }),
{ wrapper: createQueryWrapper().wrapper },
);
await waitFor(() => expect(failed.result.current.isError).toBe(true));
expect(failed.result.current.data).toBeUndefined();
await waitFor(() => expect(failedResult.current.isError).toBe(true));
expect(failedResult.current.data).toBeUndefined();
});
it("uses session-aware banking endpoints and explicit month/page without T-Bank", async () => {
@@ -166,29 +168,29 @@ describe("banking API", () => {
wrapper: createQueryWrapper().wrapper,
});
await waitFor(() =>
expect(result.current.reads.every((read) => read.isSuccess)).toBe(true),
expect(result.current.reads.every(read => read.isSuccess)).toBe(true),
);
expect([...counts.keys()]).toContain(
expect(counts.keys()).toContain(
"/api/v1/bank-cards?includeArchived=true",
);
expect([...counts.keys()]).toContain(
"/api/v1/bank-cards/a/operations?month=2026-09&page=2&limit=20",
expect(counts.keys()).toContain(
"/api/v1/bank-cards/a/operations?limit=20&month=2026-09&page=2",
);
expect([...counts.keys()]).toContain(
"/api/v1/bank-cards/summary?month=2026-08&cardId=b",
expect(counts.keys()).toContain(
"/api/v1/bank-cards/summary?cardId=b&month=2026-08",
);
expect(counts.size).toBe(9);
});
it("replays the exact UUID and large Money string once across shared auth refresh", async () => {
let token = "expired";
const refresh = vi.fn(async () => {
const refresh = vi.fn(() => {
token = "renewed";
return true;
return Promise.resolve(true);
});
configureAuthClient({ accessToken: () => token, refresh, clear: vi.fn() });
configureAuthClient({ accessToken: () => token, clear: vi.fn(), refresh });
const bodies: unknown[] = [];
const headers: (string | null)[] = [];
const headers: (null | string)[] = [];
server.use(
http.post("*/api/v1/bank-cards/operations", async ({ request }) => {
bodies.push(await request.json());
@@ -232,10 +234,8 @@ describe("banking API", () => {
it("keeps the confirmed balance while a mutation is pending or fails, and on refetch failure", async () => {
server.use(...readHandlers(new Map()));
let finish: () => void = () => {};
const pending = new Promise<void>((resolve) => {
finish = resolve;
});
const { promise: pending, resolve: finish } = Promise.withResolvers<void>();
server.use(
http.post("*/api/v1/bank-cards/operations", async () => {
await pending;
@@ -243,7 +243,7 @@ describe("banking API", () => {
}),
);
const { result } = renderHook(
() => ({ query: useBankCard("a"), mutations: useBankMutations() }),
() => ({ mutations: useBankMutations(), query: useBankCard("a") }),
{ wrapper: createQueryWrapper().wrapper },
);
await waitFor(() => expect(result.current.query.isSuccess).toBe(true));
@@ -251,7 +251,8 @@ describe("banking API", () => {
act(() => {
saving = result.current.mutations.createOperation
.mutateAsync(transfer)
.catch(() => undefined);
// eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering.
.catch(() => {});
});
await waitFor(() =>
expect(result.current.mutations.createOperation.isPending).toBe(true),
@@ -280,17 +281,18 @@ describe("banking API", () => {
HttpResponse.json({ ...transfer, version: 1 }),
),
);
const { wrapper, queryClient } = createQueryWrapper();
const { queryClient, wrapper } = createQueryWrapper();
const brokerKey = ["get", "/api/v1/brokerage-accounts"];
queryClient.setQueryData(brokerKey, []);
const { result } = renderHook(useReadModels, { wrapper });
await waitFor(() =>
expect(result.current.reads.every((read) => read.isSuccess)).toBe(true),
expect(result.current.reads.every(read => read.isSuccess)).toBe(true),
);
await act(() =>
result.current.mutations.createOperation.mutateAsync(transfer),
);
expect([...counts.values()]).toEqual(Array(9).fill(2));
expect(counts.size).toBe(9);
for (const count of counts.values()) expect(count).toBe(2);
expect(queryClient.getQueryState(brokerKey)?.isInvalidated).toBe(false);
});
@@ -316,8 +318,8 @@ describe("banking API", () => {
await act(async () => {
await expect(
result.current.mutations.updateCard.mutateAsync({
id: "a",
body: { name: "changed", version: 1 },
id: "a",
}),
).rejects.toEqual({ code });
});
@@ -329,7 +331,7 @@ describe("banking API", () => {
let name = "Food";
server.use(
http.get("*/api/v1/bank-cards/categories", () =>
HttpResponse.json([{ id: "food", name, isDefault: true, version: 1 }]),
HttpResponse.json([{ id: "food", isDefault: true, name, version: 1 }]),
),
http.patch("*/api/v1/bank-cards/categories/food", async ({ request }) => {
const body = await request.json();
@@ -337,8 +339,8 @@ describe("banking API", () => {
name = "Groceries";
return HttpResponse.json({
id: "food",
name,
isDefault: true,
name,
version: 2,
});
}),
@@ -366,8 +368,8 @@ describe("banking API", () => {
);
await act(() =>
result.current.mutations.updateCategory.mutateAsync({
id: "food",
body: { name: "Groceries", version: 1 },
id: "food",
}),
);
await waitFor(() =>
@@ -375,8 +377,8 @@ describe("banking API", () => {
);
await act(() =>
result.current.mutations.updateOperation.mutateAsync({
id: "original",
body: { description: "corrected", version: 1 },
id: "original",
}),
);
await act(() =>
@@ -403,8 +405,8 @@ describe("banking API", () => {
}),
),
);
const { wrapper, queryClient } = createQueryWrapper();
const { result, rerender } = renderHook(() => useBankCard("a"), {
const { queryClient, wrapper } = createQueryWrapper();
const { rerender, result } = renderHook(() => useBankCard("a"), {
wrapper,
});
await waitFor(() => expect(result.current.data?.balance.value).toBe("100"));
@@ -413,7 +415,7 @@ describe("banking API", () => {
});
expect(result.current.data?.balance.value).toBe("100");
act(() => {
configureAuthClient(null);
configureAuthClient();
queryClient.clear();
});
rerender();
+29 -25
View File
@@ -1,5 +1,7 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiClient, apiErrorCode } from "@/shared/api";
import type {
CreateBankCard,
CreateBankOperation,
@@ -22,59 +24,61 @@ function useBankMutations() {
const queryClient = useQueryClient();
const invalidate = () =>
queryClient.invalidateQueries({
predicate: ({ queryKey: [method, path] }) =>
method === "get" &&
typeof path === "string" &&
(path === "/api/v1/bank-cards" ||
path.startsWith("/api/v1/bank-cards/")),
predicate: ({ queryKey }) => {
const [method, path] = queryKey;
return method === "get"
&& typeof path === "string"
&& (path === "/api/v1/bank-cards"
|| path.startsWith("/api/v1/bank-cards/"));
},
});
const options = {
retry: false,
onSuccess: invalidate,
onError: (error: unknown) => {
if (
[
"BANK_VERSION_CONFLICT",
"BANK_WRITE_CONFLICT",
"BANK_DEPENDENT_REFUNDS",
"BANK_INTENT_CONFLICT",
"BANK_REFUND_LIMIT",
"BANK_DEPENDENT_REFUNDS",
"BANK_VERSION_CONFLICT",
"BANK_WRITE_CONFLICT",
].includes(apiErrorCode(error) ?? "")
)
return invalidate();
},
onSuccess: invalidate,
retry: false,
} as const;
const createCard = useMutation({
const cardCreation = useMutation({
...options,
mutationFn: (body: CreateBankCard) =>
mutationData(apiClient.POST("/api/v1/bank-cards", { body })),
});
const updateCard = useMutation({
...options,
mutationFn: ({ id, body }: { id: string; body: UpdateBankCard }) =>
mutationFn: ({ body, id }: { body: UpdateBankCard; id: string }) =>
mutationData(
apiClient.PATCH("/api/v1/bank-cards/{id}", {
params: { path: { id } },
body,
params: { path: { id } },
}),
),
});
const createOperation = useMutation({
const operationCreation = useMutation({
...options,
mutationFn: (body: CreateBankOperation) =>
mutationData(apiClient.POST("/api/v1/bank-cards/operations", { body })),
});
const updateOperation = useMutation({
...options,
mutationFn: ({ id, body }: { id: string; body: UpdateBankOperation }) =>
mutationFn: ({ body, id }: { body: UpdateBankOperation; id: string }) =>
mutationData(
apiClient.PATCH("/api/v1/bank-cards/operations/{id}", {
params: { path: { id } },
body,
params: { path: { id } },
}),
),
});
const deleteOperation = useMutation({
const operationDeletion = useMutation({
...options,
mutationFn: ({ id, version }: { id: string; version: number }) =>
mutationData(
@@ -83,29 +87,29 @@ function useBankMutations() {
}),
),
});
const createCategory = useMutation({
const categoryCreation = useMutation({
...options,
mutationFn: (body: CreateExpenseCategory) =>
mutationData(apiClient.POST("/api/v1/bank-cards/categories", { body })),
});
const updateCategory = useMutation({
...options,
mutationFn: ({ id, body }: { id: string; body: UpdateExpenseCategory }) =>
mutationFn: ({ body, id }: { body: UpdateExpenseCategory; id: string }) =>
mutationData(
apiClient.PATCH("/api/v1/bank-cards/categories/{id}", {
params: { path: { id } },
body,
params: { path: { id } },
}),
),
});
return {
createCard,
createCard: cardCreation,
createCategory: categoryCreation,
createOperation: operationCreation,
deleteOperation: operationDeletion,
updateCard,
createOperation,
updateOperation,
deleteOperation,
createCategory,
updateCategory,
updateOperation,
};
}
+125 -124
View File
@@ -7,39 +7,43 @@ import {
import { moneyCents } from "../model/form-validation";
type BankCard =
paths["/api/v1/bank-cards/{id}"]["get"]["responses"][200]["content"]["application/json"];
type BankOperation =
paths["/api/v1/bank-cards/operations/{id}"]["get"]["responses"][200]["content"]["application/json"];
type BankOperations =
paths["/api/v1/bank-cards/{id}/operations"]["get"]["responses"][200]["content"]["application/json"];
type BankSummary =
paths["/api/v1/bank-cards/summary"]["get"]["responses"][200]["content"]["application/json"];
type ExpenseCategory =
paths["/api/v1/bank-cards/categories"]["get"]["responses"][200]["content"]["application/json"][number];
type CreateBankCard =
paths["/api/v1/bank-cards"]["post"]["requestBody"]["content"]["application/json"];
type UpdateBankCard =
paths["/api/v1/bank-cards/{id}"]["patch"]["requestBody"]["content"]["application/json"];
type CreateBankOperation =
paths["/api/v1/bank-cards/operations"]["post"]["requestBody"]["content"]["application/json"];
type UpdateBankOperation =
paths["/api/v1/bank-cards/operations/{id}"]["patch"]["requestBody"]["content"]["application/json"];
type CreateExpenseCategory =
paths["/api/v1/bank-cards/categories"]["post"]["requestBody"]["content"]["application/json"];
type UpdateExpenseCategory =
paths["/api/v1/bank-cards/categories/{id}"]["patch"]["requestBody"]["content"]["application/json"];
type BankCard
= paths["/api/v1/bank-cards/{id}"]["get"]["responses"][200]["content"]["application/json"];
type BankOperation
= paths["/api/v1/bank-cards/operations/{id}"]["get"]["responses"][200]["content"]["application/json"];
type BankOperations
= paths["/api/v1/bank-cards/{id}/operations"]["get"]["responses"][200]["content"]["application/json"];
type BankSummary
= paths["/api/v1/bank-cards/summary"]["get"]["responses"][200]["content"]["application/json"];
type CreateBankCard
= paths["/api/v1/bank-cards"]["post"]["requestBody"]["content"]["application/json"];
type CreateBankOperation
= paths["/api/v1/bank-cards/operations"]["post"]["requestBody"]["content"]["application/json"];
type CreateExpenseCategory
= paths["/api/v1/bank-cards/categories"]["post"]["requestBody"]["content"]["application/json"];
type ExpenseCategory
= paths["/api/v1/bank-cards/categories"]["get"]["responses"][200]["content"]["application/json"][number];
type UpdateBankCard
= paths["/api/v1/bank-cards/{id}"]["patch"]["requestBody"]["content"]["application/json"];
type UpdateBankOperation
= paths["/api/v1/bank-cards/operations/{id}"]["patch"]["requestBody"]["content"]["application/json"];
type UpdateExpenseCategory
= paths["/api/v1/bank-cards/categories/{id}"]["patch"]["requestBody"]["content"]["application/json"];
const OPERATIONS_PAGE_SIZE = 100;
function useBankCards(includeArchived = false) {
return useAuthenticatedQuery(
apiQueryClient.queryOptions("get", "/api/v1/bank-cards", {
params: {
query: { includeArchived: includeArchived ? "true" : "false" },
},
function sortBankSummary(data: BankSummary): BankSummary {
return {
...data,
categories: data.categories.toSorted((a, b) => {
const left = moneyCents(a.net.value);
const right = moneyCents(b.net.value);
if (left === null || right === null)
throw new Error("Invalid bank summary amount");
if (left > right) return -1;
return left < right ? 1 : 0;
}),
);
};
}
function useBankCard(id: string | undefined) {
@@ -51,79 +55,25 @@ function useBankCard(id: string | undefined) {
});
}
function useBankCards(isIncludeArchived = false) {
return useAuthenticatedQuery(
apiQueryClient.queryOptions("get", "/api/v1/bank-cards", {
params: {
query: { includeArchived: isIncludeArchived ? "true" : "false" },
},
}),
);
}
function useBankCategories() {
return useAuthenticatedQuery(
apiQueryClient.queryOptions("get", "/api/v1/bank-cards/categories"),
);
}
function useBankOperations(
id: string | undefined,
query: {
month?: string;
from?: string;
to?: string;
page: number;
limit?: number | "all";
},
) {
const all = query.limit === "all";
const params = {
path: { id: id ?? "" },
query: {
...query,
page: all ? 1 : query.page,
limit: query.limit === "all" ? OPERATIONS_PAGE_SIZE : query.limit,
},
};
const options = apiQueryClient.queryOptions(
"get",
"/api/v1/bank-cards/{id}/operations",
{ params },
);
// eslint-disable-next-line @tanstack/query/exhaustive-deps -- Generated options.queryKey already contains params; retain the shared cache identity.
return useAuthenticatedQuery({
queryKey: all ? ([...options.queryKey, "all"] as const) : options.queryKey,
placeholderData: (
previousData: BankOperations | undefined,
previousQuery,
) => {
const previous = previousQuery?.queryKey[2]?.params;
return !all &&
previousQuery?.queryKey.length === options.queryKey.length &&
previous?.path?.id === id &&
previous?.query?.month === query.month &&
previous?.query?.from === query.from &&
previous?.query?.to === query.to &&
previous?.query?.limit === query.limit
? previousData
: undefined;
},
queryFn: async ({ signal }) => {
const items: BankOperation[] = [];
for (let page = params.query.page; ; page++) {
const { data, error } = await apiClient.GET(
"/api/v1/bank-cards/{id}/operations",
{
params: { ...params, query: { ...params.query, page } },
signal,
},
);
// eslint-disable-next-line @typescript-eslint/only-throw-error -- Preserve generated ProblemDetails for apiErrorCode and field-error consumers.
if (error) throw error;
if (!data) throw new Error("Missing bank operations response");
if (!all) return data;
items.push(...data.items);
if (!data.hasNext) return { ...data, items, page: 1, hasNext: false };
}
},
enabled: Boolean(id && (query.month || (query.from && query.to))),
});
}
function useBankExpenses(
id: string | undefined,
query: { page: number; limit?: number },
query: { limit?: number; page: number },
) {
return useAuthenticatedQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bank-cards/{id}/expenses", {
@@ -133,36 +83,6 @@ function useBankExpenses(
});
}
function sortBankSummary(data: BankSummary): BankSummary {
return {
...data,
categories: data.categories.toSorted((a, b) => {
const left = moneyCents(a.net.value);
const right = moneyCents(b.net.value);
if (left === null || right === null)
throw new Error("Invalid bank summary amount");
return left > right ? -1 : left < right ? 1 : 0;
}),
};
}
function useBankSummary(
period: string | { from: string; to: string },
cardId?: string,
) {
const query =
typeof period === "string"
? { month: period, cardId }
: { ...period, cardId };
return useAuthenticatedQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bank-cards/summary", {
params: { query },
}),
select: sortBankSummary,
enabled: Boolean(period),
});
}
function useBankOperation(id: string | undefined) {
return useAuthenticatedQuery({
...apiQueryClient.queryOptions(
@@ -174,6 +94,87 @@ function useBankOperation(id: string | undefined) {
});
}
function useBankOperations(
id: string | undefined,
query: {
from?: string;
limit?: "all" | number;
month?: string;
page: number;
to?: string;
},
) {
const isAll = query.limit === "all";
const parameters = {
path: { id: id ?? "" },
query: {
...query,
limit: query.limit === "all" ? OPERATIONS_PAGE_SIZE : query.limit,
page: isAll ? 1 : query.page,
},
};
const options = apiQueryClient.queryOptions(
"get",
"/api/v1/bank-cards/{id}/operations",
{ params: parameters },
);
// eslint-disable-next-line @tanstack/query/exhaustive-deps -- Generated options.queryKey already contains params; retain the shared cache identity.
return useAuthenticatedQuery({
enabled: Boolean(id && (query.month || (query.from && query.to))),
placeholderData: (
previousData: BankOperations | undefined,
previousQuery,
) => {
const previous = previousQuery?.queryKey[2]?.params;
return !isAll
&& previousQuery?.queryKey.length === options.queryKey.length
&& previous?.path?.id === id
&& previous?.query?.month === query.month
&& previous?.query?.from === query.from
&& previous?.query?.to === query.to
&& previous?.query?.limit === query.limit
? previousData
: undefined;
},
queryFn: async ({ signal }) => {
const items: BankOperation[] = [];
for (let page = parameters.query.page; ; page++) {
const { data, error } = await apiClient.GET(
"/api/v1/bank-cards/{id}/operations",
{
params: { ...parameters, query: { ...parameters.query, page } },
signal,
},
);
// eslint-disable-next-line @typescript-eslint/only-throw-error -- Preserve generated ProblemDetails for apiErrorCode and field-error consumers.
if (error) throw error;
if (!data) throw new Error("Missing bank operations response");
if (!isAll) return data;
items.push(...data.items);
if (!data.hasNext) return { ...data, hasNext: false, items, page: 1 };
}
},
queryKey: isAll ? ([...options.queryKey, "all"] as const) : options.queryKey,
});
}
function useBankSummary(
period: string | { from: string; to: string },
cardId?: string,
) {
const query
= typeof period === "string"
? { cardId, month: period }
: { ...period, cardId };
return useAuthenticatedQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bank-cards/summary", {
params: { query },
}),
enabled: Boolean(period),
select: sortBankSummary,
});
}
export {
type BankCard,
type BankOperation,
+11 -8
View File
@@ -1,6 +1,9 @@
import { expect, it } from "vitest";
import { type BankSummary, sortBankSummary } from "./queries";
const money = (value: string) => ({ currency: "RUB", value });
it("orders displayed expenses descending, preserving cents, ties and source data", () => {
const values = [
"-10",
@@ -10,23 +13,23 @@ it("orders displayed expenses descending, preserving cents, ties and source data
"-2",
"0",
];
const money = (value: string) => ({ currency: "RUB", value });
const data: BankSummary = {
month: "2026-09",
cardId: "a",
expenses: money("0"),
refunds: money("0"),
net: money("0"),
categories: values.map((value, index) => ({
categoryId: String(index),
categoryName: String(index),
expenses: money("100"),
refunds: money("0"),
net: money(value),
refunds: money("0"),
})),
expenses: money("0"),
month: "2026-09",
net: money("0"),
refunds: money("0"),
};
expect(sortBankSummary(data).categories.map((row) => row.categoryId)).toEqual(
expect(sortBankSummary(data).categories.map(row => row.categoryId)).toEqual(
["3", "1", "2", "5", "4", "0"],
);
expect(data.categories.map((row) => row.net.value)).toEqual(values);
expect(data.categories.map(row => row.net.value)).toEqual(values);
});
@@ -1,4 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
bankCardSchema,
bankDateInputValue,
@@ -27,9 +28,9 @@ describe("bank form input", () => {
}
expect(bankMoneyValue(" -00010,20 ")).toBe("-10.20");
const values = {
name: "A",
bankName: "",
lastFour: "",
name: "A",
openingBalance: "-92233720368547758.08",
openingDate: "2026-01-01",
};
+44 -39
View File
@@ -1,38 +1,43 @@
import { z } from "zod";
import { validationMessage } from "@/shared/i18n";
const DECIMAL_PART_COUNT = 2;
const CENTS_PRECISION = 2;
const ISO_DATE_LENGTH = 10;
const ISO_MONTH_LENGTH = 7;
const MAX_CARD_NAME_LENGTH = 100;
function bankToday() {
return new Intl.DateTimeFormat("en-CA", {
timeZone: "Europe/Moscow",
year: "numeric",
month: "2-digit",
day: "2-digit",
}).format(new Date());
}
function bankDateInputValue(value: string) {
return value.replace(/^(\d{2})\.(\d{2})\.(\d{4})$/, "$3-$2-$1");
}
function bankMonth(value: string | null) {
return value && value >= "0001-01" && /^\d{4}-(0[1-9]|1[0-2])$/.test(value)
? value
: bankToday().slice(0, ISO_MONTH_LENGTH);
}
function bankMoneyValue(value: string) {
return value
.trim()
.replace(",", ".")
.replace(/^(-?)0+(?=\d)/, "$1");
}
function bankMonth(value: null | string) {
return value && value >= "0001-01" && /^\d{4}-(?:0[1-9]|1[0-2])$/.test(value)
? value
: bankToday().slice(0, ISO_MONTH_LENGTH);
}
function bankToday() {
return new Intl.DateTimeFormat("en-CA", {
day: "2-digit",
month: "2-digit",
timeZone: "Europe/Moscow",
year: "numeric",
}).format(new Date());
}
function moneyCents(value: string): bigint | null {
const normalized = value.trim().replace(",", ".");
if (!/^-?\d+(\.\d{1,2})?$/.test(normalized)) return null;
const [whole, fraction = ""] = normalized.replace("-", "").split(".");
if (!/^-?\d+$|^-?\d+\.\d{1,2}$/.test(normalized)) return /* eslint-disable-line unicorn/no-null -- The money parser’s callers distinguish invalid input with null. */ null;
const [whole, fraction = ""] = normalized.replace("-", "").split(".", DECIMAL_PART_COUNT);
return (
BigInt(`${whole}${fraction.padEnd(2, "0")}`) *
(normalized.startsWith("-") ? -1n : 1n)
BigInt(`${whole}${fraction.padEnd(CENTS_PRECISION, "0")}`)
* (normalized.startsWith("-") ? -1n : 1n)
);
}
const MIN_BALANCE_KOPECKS = -9_223_372_036_854_775_808n;
@@ -42,9 +47,9 @@ const moneySchema = z.string().refine(
(value) => {
const cents = moneyCents(value);
return (
cents !== null &&
cents >= MIN_BALANCE_KOPECKS &&
cents <= MAX_BALANCE_KOPECKS
cents !== null
&& cents >= MIN_BALANCE_KOPECKS
&& cents <= MAX_BALANCE_KOPECKS
);
},
{ error: validationMessage("bank.validation.money") },
@@ -59,15 +64,25 @@ const positiveMoneySchema = moneySchema.refine(
const bankDateSchema = z
.string()
.refine(
(value) =>
/^\d{4}-\d{2}-\d{2}$/.test(value) &&
value >= "0001-01-01" &&
!Number.isNaN(Date.parse(`${value}T00:00:00Z`)) &&
new Date(`${value}T00:00:00Z`).toISOString().slice(0, 10) === value &&
value <= bankToday(),
value =>
/^\d{4}-\d{2}-\d{2}$/.test(value)
&& value >= "0001-01-01"
&& !Number.isNaN(Date.parse(`${value}T00:00:00Z`))
&& new Date(`${value}T00:00:00Z`).toISOString().slice(0, ISO_DATE_LENGTH) === value
&& value <= bankToday(),
{ error: validationMessage("bank.validation.date") },
);
const bankCardSchema = z.object({
bankName: z
.string()
.trim()
.max(
MAX_CARD_NAME_LENGTH,
validationMessage("bank.validation.bankName")(undefined),
),
lastFour: z.string().refine(value => !value || /^\d{4}$/.test(value), {
error: validationMessage("bank.validation.lastFour"),
}),
name: z
.string()
.trim()
@@ -76,29 +91,19 @@ const bankCardSchema = z.object({
MAX_CARD_NAME_LENGTH,
validationMessage("bank.validation.name")(undefined),
),
bankName: z
.string()
.trim()
.max(
MAX_CARD_NAME_LENGTH,
validationMessage("bank.validation.bankName")(undefined),
),
lastFour: z.string().refine((value) => !value || /^\d{4}$/.test(value), {
error: validationMessage("bank.validation.lastFour"),
}),
openingBalance: moneySchema,
openingDate: bankDateSchema,
paymentSystem: z
.enum(["", "mir", "visa", "mastercard"], {
error: validationMessage("bank.validation.paymentSystem"),
})
.optional(),
openingBalance: moneySchema,
openingDate: bankDateSchema,
});
type BankCardValues = z.infer<typeof bankCardSchema>;
export {
type BankCardValues,
bankCardSchema,
type BankCardValues,
bankDateInputValue,
bankDateSchema,
bankMoneyValue,
@@ -1,140 +1,137 @@
import type { BankOperation } from "../api/queries";
type OperationIcon = { path: string; color: string; animation?: string };
type OperationIcon = { animation?: string; color: string; path: string };
const categoryIcons: Record<string, OperationIcon> = {
алкоголь: {
"алкоголь": {
animation: "wine",
path: "M7 3h10v5a5 5 0 0 1-10 0V3Z M7 7h10v1a5 5 0 0 1-10 0V7Z M12 13v8 M8 21h8",
color: "grape",
path: "M7 3h10v5a5 5 0 0 1-10 0V3Z M7 7h10v1a5 5 0 0 1-10 0V7Z M12 13v8 M8 21h8",
},
вклады: {
"вклады": {
animation: "deposit",
path: "M6 9a6 6 0 1 0 12 0a6 6 0 1 0-12 0 M10.5 12V6h2a1.5 1.5 0 0 1 0 3h-3m0 1.5h3 M4 16c0 4 16 4 16 0 M4 19c0 4 16 4 16 0",
color: "green",
path: "M6 9a6 6 0 1 0 12 0a6 6 0 1 0-12 0 M10.5 12V6h2a1.5 1.5 0 0 1 0 3h-3m0 1.5h3 M4 16c0 4 16 4 16 0 M4 19c0 4 16 4 16 0",
},
"жилье": { color: "orange", path: "M3 11l9-8 9 8 M5 10v11h14V10 M9 21v-8h6v8" },
"здоровье": { color: "red", path: "M9 3h6v6h6v6h-6v6H9v-6H3V9h6V3Z" },
"инвестиции и накопления": {
animation: "growth",
path: "M3 3v18h18 M6 15l5-5 4 3 6-8 M16 5h5v5",
color: "green",
path: "M3 3v18h18 M6 15l5-5 4 3 6-8 M16 5h5v5",
},
образование: {
"кафе": {
animation: "coffee",
color: "orange",
path: "M4 8h12v7a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4V8Z M16 9h2a3 3 0 0 1 0 6h-2 M8 6c-2-1 2-2 0-4 M12 6c-2-1 2-2 0-4 M3 22h15",
},
"образование": {
color: "blue",
path: "M2 8l10-5 10 5-10 5L2 8Z M6 10v7c4 3 8 3 12 0v-7 M22 8v9",
color: "blue",
},
переводы: {
"переводы": {
animation: "transfer",
path: "M3 7h18l-4-4 M21 17H3l4 4",
color: "blue",
path: "M3 7h18l-4-4 M21 17H3l4 4",
},
"погашение кредита": {
animation: "repayment",
path: "M3 5h18v14H3V5Z M3 9h18 M10 18v-7h3a2 2 0 0 1 0 4H9m0 1.5h4",
color: "orange",
path: "M3 5h18v14H3V5Z M3 9h18 M10 18v-7h3a2 2 0 0 1 0 4H9m0 1.5h4",
},
подписки: {
path: "M4 10a8 8 0 0 1 13-6l3 3 M20 3v4h-4 M20 14a8 8 0 0 1-13 6l-3-3 M4 21v-4h4",
"подписки": {
color: "grape",
path: "M4 10a8 8 0 0 1 13-6l3 3 M20 3v4h-4 M20 14a8 8 0 0 1-13 6l-3-3 M4 21v-4h4",
},
путешествия: {
path: "M10 3h4v7l7 5v3l-7-3v5l2 1v1l-4-1-4 1v-1l2-1v-5l-7 3v-3l7-5V3Z",
"покупки": {
color: "grape",
path: "M5 7h14l2 14H3L5 7Z M8 8V6a4 4 0 0 1 8 0v2",
},
"продукты": {
animation: "basket",
color: "green",
path: "M3 9h18l-2 11H5L3 9Z M8 9l4-6 4 6 M9 13v3 M15 13v3 M10 6a2 2 0 1 0 4 0a2 2 0 1 0-4 0",
},
"путешествия": {
color: "blue",
path: "M10 3h4v7l7 5v3l-7-3v5l2 1v1l-4-1-4 1v-1l2-1v-5l-7 3v-3l7-5V3Z",
},
"развлечения": {
color: "grape",
path: "M9 5v14a3 3 0 1 1-3-3h3 M9 5l11-2v14a3 3 0 1 1-3-3h3 M9 9l11-2",
},
"связь и интернет": {
animation: "wifi",
path: "M3 7a14 14 0 0 1 18 0 M6 11a9 9 0 0 1 12 0 M9 15a4 4 0 0 1 6 0 M12 19h.01",
color: "blue",
path: "M3 7a14 14 0 0 1 18 0 M6 11a9 9 0 0 1 12 0 M9 15a4 4 0 0 1 6 0 M12 19h.01",
},
"снятие наличных": {
color: "green",
path: "M4 10V3h16v7 M7 7h10v14H7V7Z M7 11h10 M10 16h4",
color: "green",
},
ставки: {
path: "M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2Z M7 7h.01 M17 7h.01 M12 12h.01 M7 17h.01 M17 17h.01",
"ставки": {
color: "grape",
path: "M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2Z M7 7h.01 M17 7h.01 M12 12h.01 M7 17h.01 M17 17h.01",
},
страхование: {
path: "M12 2l8 4v6c0 5-8 10-8 10S4 17 4 12V6l8-4Z M8 12l3 3 5-6",
"страхование": {
color: "green",
path: "M12 2l8 4v6c0 5-8 10-8 10S4 17 4 12V6l8-4Z M8 12l3 3 5-6",
},
табак: {
path: "M3 14h18v5H3v-5Z M16 14v5 M8 10V8c0-2 3-2 3-4V2 M15 10V8c0-2 3-2 3-4",
"табак": {
color: "orange",
path: "M3 14h18v5H3v-5Z M16 14v5 M8 10V8c0-2 3-2 3-4V2 M15 10V8c0-2 3-2 3-4",
},
"такси": {
color: "yellow",
path: "M4 10l2-6h12l2 6 M3 10h18v8H3v-8Z M6 18v3 M18 18v3 M6 14h2 M16 14h2 M10 4V2h4v2",
},
"транспорт": {
animation: "car",
color: "blue",
path: "M4 16H2v-4l3-1 3-4h6l4 4 4 1v4h-2 M8 16h8 M6 11h12m-6-4v4 M4 16a2 2 0 1 0 4 0a2 2 0 1 0-4 0m2-2v4m-2-2h4 M16 16a2 2 0 1 0 4 0a2 2 0 1 0-4 0m2-2v4m-2-2h4",
},
"хостинг и ии-сервисы": {
animation: "server",
path: "M3 3h18v7H3V3Z M3 14h18v7H3v-7Z M7 6.5h.01 M7 17.5h.01 M15 6.5h3 M15 17.5h3",
color: "grape",
path: "M3 3h18v7H3V3Z M3 14h18v7H3v-7Z M7 6.5h.01 M7 17.5h.01 M15 6.5h3 M15 17.5h3",
},
"цифровые покупки": {
color: "blue",
path: "M3 3h18v13H3V3Z M8 21h8 M12 16v5 M12 6v7 M9 10l3 3 3-3",
color: "blue",
},
продукты: {
animation: "basket",
path: "M3 9h18l-2 11H5L3 9Z M8 9l4-6 4 6 M9 13v3 M15 13v3 M10 6a2 2 0 1 0 4 0a2 2 0 1 0-4 0",
color: "green",
},
кафе: {
animation: "coffee",
path: "M4 8h12v7a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4V8Z M16 9h2a3 3 0 0 1 0 6h-2 M8 6c-2-1 2-2 0-4 M12 6c-2-1 2-2 0-4 M3 22h15",
color: "orange",
},
такси: {
path: "M4 10l2-6h12l2 6 M3 10h18v8H3v-8Z M6 18v3 M18 18v3 M6 14h2 M16 14h2 M10 4V2h4v2",
color: "yellow",
},
транспорт: {
animation: "car",
path: "M4 16H2v-4l3-1 3-4h6l4 4 4 1v4h-2 M8 16h8 M6 11h12m-6-4v4 M4 16a2 2 0 1 0 4 0a2 2 0 1 0-4 0m2-2v4m-2-2h4 M16 16a2 2 0 1 0 4 0a2 2 0 1 0-4 0m2-2v4m-2-2h4",
color: "blue",
},
жилье: { path: "M3 11l9-8 9 8 M5 10v11h14V10 M9 21v-8h6v8", color: "orange" },
здоровье: { path: "M9 3h6v6h6v6h-6v6H9v-6H3V9h6V3Z", color: "red" },
покупки: {
path: "M5 7h14l2 14H3L5 7Z M8 8V6a4 4 0 0 1 8 0v2",
color: "grape",
},
развлечения: {
path: "M9 5v14a3 3 0 1 1-3-3h3 M9 5l11-2v14a3 3 0 1 1-3-3h3 M9 9l11-2",
color: "grape",
},
};
const otherIcon: OperationIcon = {
animation: "grid",
path: "M4 4h6v6H4V4Z M14 4h6v6h-6V4Z M4 14h6v6H4v-6Z M14 14h6v6h-6v-6Z",
color: "gray",
path: "M4 4h6v6H4V4Z M14 4h6v6h-6V4Z M4 14h6v6H4v-6Z M14 14h6v6h-6v-6Z",
};
const operationIcons: Record<
Exclude<BankOperation["kind"], "expense">,
OperationIcon
> = {
refund: { color: "teal", path: "M8 4L3 9l5 5 M3 9h11a7 7 0 0 1 0 14" },
topup: {
animation: "topup",
path: "M20 8V5H5a2 2 0 0 1 0-4h13v4 M3 3v16a2 2 0 0 0 2 2h15V8H5 M16 12v5m-2.5-2.5h5",
color: "green",
path: "M20 8V5H5a2 2 0 0 1 0-4h13v4 M3 3v16a2 2 0 0 0 2 2h15V8H5 M16 12v5m-2.5-2.5h5",
},
transfer: {
animation: "transfer",
path: "M3 7h18l-4-4 M21 17H3l4 4",
color: "blue",
path: "M3 7h18l-4-4 M21 17H3l4 4",
},
refund: { path: "M8 4L3 9l5 5 M3 9h11a7 7 0 0 1 0 14", color: "teal" },
};
function bankOperationAppearance(
kind: BankOperation["kind"],
categoryName?: string | null,
categoryName?: null | string,
) {
if (kind !== "expense") return /* eslint-disable-line security/detect-object-injection -- Operation kinds are finite; category names are guarded by Object.hasOwn. */ operationIcons[kind];
const name = categoryName
?.trim()
.toLocaleLowerCase("ru-RU")
.replaceAll("ё", "е");
return kind === "expense"
? name && Object.hasOwn(categoryIcons, name)
? categoryIcons[name]
: otherIcon
: operationIcons[kind];
return name && Object.hasOwn(categoryIcons, name) ? /* eslint-disable-line security/detect-object-injection -- Operation kinds are finite; category names are guarded by Object.hasOwn. */ categoryIcons[name] : otherIcon;
}
export { bankOperationAppearance };
@@ -1,4 +1,5 @@
import { afterEach, expect, it, vi } from "vitest";
import { bankPeriod } from "./period";
afterEach(() => vi.useRealTimers());
+12 -11
View File
@@ -1,20 +1,21 @@
import { z } from "zod";
import { bankMonth } from "./form-validation";
const calendarDate = z.string().date();
const calendarDate = z.iso.date();
const ISO_DATE_LENGTH = 10;
function bankPeriod(params: URLSearchParams) {
const month = bankMonth(params.get("month"));
function bankPeriod(parameters: URLSearchParams) {
const month = bankMonth(parameters.get("month"));
const monthEnd = new Date(`${month}-01T00:00:00Z`);
monthEnd.setUTCMonth(monthEnd.getUTCMonth() + 1, 0);
const from = params.get("from");
const to = params.get("to");
return from &&
to &&
calendarDate.safeParse(from).success &&
calendarDate.safeParse(to).success &&
from >= "0001-01-01" &&
from <= to
const from = parameters.get("from");
const to = parameters.get("to");
return from
&& to
&& calendarDate.safeParse(from).success
&& calendarDate.safeParse(to).success
&& from >= "0001-01-01"
&& from <= to
? { from, to }
: {
from: `${month}-01`,
@@ -1,67 +1,75 @@
import { SimpleGrid } from "@mantine/core";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { SimpleGrid } from "@mantine/core";
import { BankCardFace } from "./BankCardFace";
const meta = {
title: "Product/BankCards/CardAppearance",
component: BankCardFace,
tags: ["autodocs"],
const meta = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
args: {
card: {
id: "fictional",
name: "Для повседневных покупок",
bankName: "Сбербанк",
lastFour: "4829",
paymentSystem: "mir",
openingBalance: { value: "0", currency: "RUB" },
openingDate: "2026-01-01",
balance: { value: "128450.75", currency: "RUB" },
archivedAt: null,
balance: { currency: "RUB", value: "128450.75" },
bankName: "Сбербанк",
id: "fictional",
lastFour: "4829",
name: "Для повседневных покупок",
openingBalance: { currency: "RUB", value: "0" },
openingDate: "2026-01-01",
paymentSystem: "mir",
version: 1,
},
},
} satisfies Meta<typeof BankCardFace>;
component: BankCardFace,
tags: ["autodocs"],
title: "Product/BankCards/CardAppearance",
}
/* eslint-enable unicorn/no-null */) satisfies Meta<typeof BankCardFace>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Banks: Story = {
render: (args) => (
render: arguments_ => (
<SimpleGrid cols={{ base: 1, sm: 2 }} maw={920}>
{["Сбербанк", "Т-Банк", "Альфа-Банк", "ВТБ", null].map(
{["Сбербанк", "Т-Банк", "Альфа-Банк", "ВТБ", /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null].map(
(bankName, index) => (
<BankCardFace
card={(/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
...arguments_.card,
bankName,
paymentSystem:
/* eslint-disable-line security/detect-object-injection -- This is a positional index into the local array, not a user-supplied object key. */ (["mir", "mastercard", "visa", "mir", null] as const)[index]
?? null,
}
/* eslint-enable unicorn/no-null */)}
key={bankName ?? "unknown"}
card={{
...args.card,
bankName,
paymentSystem:
(["mir", "mastercard", "visa", "mir", null] as const)[index] ??
null,
}}
/>
),
)}
</SimpleGrid>
),
};
export const MissingDetails: Story = {
args: {
card: {
...meta.args.card,
bankName: null,
lastFour: null,
paymentSystem: null,
export const MissingDetails: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
args: {
card: {
...meta.args.card,
bankName: null,
lastFour: null,
paymentSystem: null,
},
},
},
};
}
/* eslint-enable unicorn/no-null */);
export const LongArchived: Story = {
args: {
card: {
...meta.args.card,
name: "Карта с очень длинным пользовательским названием для повседневных покупок",
bankName: "Банк с очень длинным названием без пробелов".repeat(2),
archivedAt: "2026-09-12",
balance: { currency: "RUB", value: "184467440737095516.14" },
bankName: "Банк с очень длинным названием без пробелов".repeat(2),
name: "Карта с очень длинным пользовательским названием для повседневных покупок",
paymentSystem: "mastercard",
balance: { value: "184467440737095516.14", currency: "RUB" },
},
},
};
@@ -1,7 +1,11 @@
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { formatMoney } from "@/shared/lib";
import type { BankCard } from "../../api/queries";
import classes from "./BankCardFace.module.css";
type BankCardFaceProps = { card: BankCard };
@@ -9,15 +13,7 @@ const BankCardFace: FC<BankCardFaceProps> = (props) => {
const { card } = props;
const { t } = useTranslation();
const bank = card.bankName?.toLocaleLowerCase("ru") ?? "";
const tone = /сбер|sber/.test(bank)
? "green"
: /тинькофф|т[ -]?банк|t[ -]?bank|tinkoff/.test(bank)
? "yellow"
: /альфа|alfa/.test(bank)
? "red"
: /втб|vtb|газпром|gazprom/.test(bank)
? "blue"
: "graphite";
const tone = bankTone(bank);
return (
<div className={classes.face} data-tone={tone}>
<div className={classes.top}>
@@ -26,26 +22,28 @@ const BankCardFace: FC<BankCardFaceProps> = (props) => {
<span className={classes.archive}>{t("bank.archived")}</span>
)}
</div>
<div className={classes.hardware} aria-hidden="true">
<div aria-hidden="true" className={classes.hardware}>
<span className={classes.chip} />
<svg
aria-hidden="true"
width="24"
fill="none"
height="30"
viewBox="0 0 24 30"
fill="none"
width="24"
>
<path
d="M7 11a8 8 0 0 1 0 8m5-12a15 15 0 0 1 0 16m5-20a23 23 0 0 1 0 24"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeWidth="2"
/>
</svg>
</div>
<div
className={classes.number}
>{`•••• •••• •••• ${card.lastFour || "••••"}`}</div>
>
{`•••• •••• •••• ${card.lastFour || "••••"}`}
</div>
<div className={classes.bottom}>
<div className={classes.details}>
<div className={classes.name}>{card.name}</div>
@@ -54,7 +52,7 @@ const BankCardFace: FC<BankCardFaceProps> = (props) => {
{card.paymentSystem && (
<span className={classes.network} data-network={card.paymentSystem}>
{card.paymentSystem === "mastercard" && (
<span className={classes.circles} aria-hidden="true" />
<span aria-hidden="true" className={classes.circles} />
)}
{t(`bank.paymentSystems.${card.paymentSystem}`)}
</span>
@@ -64,4 +62,11 @@ const BankCardFace: FC<BankCardFaceProps> = (props) => {
);
};
function bankTone(bank: string) {
if (/сбер|sber/.test(bank)) return "green";
if (/тинькофф|т[ -]?банк|t[ -]?bank|tinkoff/.test(bank)) return "yellow";
if (/альфа|alfa/.test(bank)) return "red";
return /втб|vtb|газпром|gazprom/.test(bank) ? "blue" : "graphite";
}
export { BankCardFace };
@@ -1,20 +1,21 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { FormProvider, useForm } from "react-hook-form";
import type { BankCardValues } from "../../model/form-validation";
import { BankCardFields } from "./BankCardForm.view";
const meta = {
title: "Product/BankCards/CardFields",
component: BankCardFields,
tags: ["autodocs"],
args: { archived: false },
component: BankCardFields,
decorators: [
(Story) => {
const methods = useForm<BankCardValues>({
defaultValues: {
name: "Учебная повседневная карта",
bankName: "Вымышленный банк",
lastFour: "1234",
name: "Учебная повседневная карта",
openingBalance: "-92233720368547758.08",
openingDate: "2026-08-01",
},
@@ -34,11 +35,13 @@ const meta = {
},
},
},
tags: ["autodocs"],
title: "Product/BankCards/CardFields",
} satisfies Meta<typeof BankCardFields>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Active: Story = { name: "Независимая карта в рублях" };
export const Archived: Story = {
name: "Финансовые поля архивной карты",
args: { archived: true },
name: "Финансовые поля архивной карты",
};
@@ -1,31 +1,36 @@
import { MantineProvider } from "@mantine/core";
import { QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { http, HttpResponse } from "msw";
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 { BankCardForm } from "./BankCardForm";
const card: BankCard = {
id: "a",
name: "Основная",
bankName: "Банк",
lastFour: "1234",
paymentSystem: null,
openingBalance: { currency: "RUB", value: "100" },
balance: { currency: "RUB", value: "50" },
openingDate: "2026-01-01",
archivedAt: null,
version: 1,
};
const card: BankCard = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
archivedAt: null,
balance: { currency: "RUB", value: "50" },
bankName: "Банк",
id: "a",
lastFour: "1234",
name: "Основная",
openingBalance: { currency: "RUB", value: "100" },
openingDate: "2026-01-01",
paymentSystem: null,
version: 1,
}
/* eslint-enable unicorn/no-null */);
function setup(value: BankCard) {
configureAuthClient({
accessToken: () => "test",
refresh: async () => false,
clear: () => {},
refresh: () => Promise.resolve(false),
});
server.use(http.get("*/api/v1/bank-cards/a", () => HttpResponse.json(value)));
const close = vi.fn();
@@ -64,13 +69,15 @@ describe("BankCardForm", () => {
);
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
await waitFor(() => expect(close).toHaveBeenCalled());
expect(body).toEqual({
version: 1,
name: "Основная",
bankName: null,
lastFour: null,
paymentSystem: null,
});
expect(body).toEqual((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
bankName: null,
lastFour: null,
name: "Основная",
paymentSystem: null,
version: 1,
}
/* eslint-enable unicorn/no-null */));
});
it("loads and saves the selected payment system", async () => {
const close = setup({ ...card, paymentSystem: "mir" });
@@ -146,6 +153,6 @@ describe("BankCardForm", () => {
fireEvent.click(adopt);
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
await waitFor(() => expect(close).toHaveBeenCalled());
expect(bodies.map((b) => b.version)).toEqual([1, 2]);
expect(bodies.map(b => b.version)).toEqual([1, 2]);
});
});
@@ -3,12 +3,14 @@ import { Button, Group, Modal, Stack, Text } from "@mantine/core";
import { type FC, useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { formatDate } from "@/shared/lib";
import { useBankMutations } from "../../api/mutations";
import { type BankCard, useBankCard } from "../../api/queries";
import {
type BankCardValues,
bankCardSchema,
type BankCardValues,
bankMoneyValue,
bankToday,
} from "../../model/form-validation";
@@ -29,29 +31,29 @@ const BankCardForm: FC<BankCardFormProps> = (props) => {
const fresh = useBankCard(props.card?.id);
const mutation = useBankMutations();
const methods = useForm<BankCardValues>({
resolver: zodResolver(bankCardSchema),
defaultValues: {
name: props.card?.name ?? "",
bankName: props.card?.bankName ?? "",
lastFour: props.card?.lastFour ?? "",
paymentSystem: props.card?.paymentSystem ?? "",
name: props.card?.name ?? "",
openingBalance: props.card?.openingBalance.value ?? "0",
openingDate: props.card?.openingDate ?? bankToday(),
paymentSystem: props.card?.paymentSystem ?? "",
},
resolver: zodResolver(bankCardSchema),
});
const pending =
!opened ||
methods.formState.isSubmitting ||
(fresh.isFetching && Boolean(error));
const isPending
= !opened
|| methods.formState.isSubmitting
|| (fresh.isFetching && Boolean(error));
return (
<Modal
opened={opened}
closeButtonProps={{ "aria-label": t("bank.close"), "disabled": isPending }}
closeOnClickOutside={!isPending}
closeOnEscape={!isPending}
onClose={() => !isPending && setOpened(false)}
onExitTransitionEnd={props.onClose}
onClose={() => !pending && setOpened(false)}
opened={opened}
title={t(props.card ? "bank.editCard" : "bank.addCard")}
closeButtonProps={{ "aria-label": t("bank.close"), disabled: pending }}
closeOnClickOutside={!pending}
closeOnEscape={!pending}
>
<FormProvider {...methods}>
<form
@@ -59,10 +61,10 @@ const BankCardForm: FC<BankCardFormProps> = (props) => {
setError(undefined);
try {
const metadata = {
bankName: values.bankName || /* eslint-disable-line unicorn/no-null -- PATCH uses null to clear these optional card fields. */ null,
lastFour: values.lastFour || /* eslint-disable-line unicorn/no-null -- PATCH uses null to clear these optional card fields. */ null,
name: values.name,
bankName: values.bankName || null,
lastFour: values.lastFour || null,
paymentSystem: values.paymentSystem || null,
paymentSystem: values.paymentSystem || /* eslint-disable-line unicorn/no-null -- PATCH uses null to clear these optional card fields. */ null,
};
const financial = {
openingBalance: {
@@ -73,12 +75,12 @@ const BankCardForm: FC<BankCardFormProps> = (props) => {
};
if (props.card)
await mutation.updateCard.mutateAsync({
id: props.card.id,
body: {
...metadata,
...(!props.card.archivedAt ? financial : {}),
...(!props.card.archivedAt && financial),
version,
},
id: props.card.id,
});
else
await mutation.createCard.mutateAsync({
@@ -87,32 +89,33 @@ const BankCardForm: FC<BankCardFormProps> = (props) => {
...financial,
});
setOpened(false);
} catch (failure) {
setError(failure);
}
catch (error_) {
setError(error_);
}
})}
>
<fieldset className={classes.fieldset} disabled={pending}>
<fieldset className={classes.fieldset} disabled={isPending}>
<Stack>
<BankCardFields archived={Boolean(props.card?.archivedAt)} />
{error ? (
{!!(error) && ((
<>
<BankFeedback error={error} />
{props.card && (
<Button
variant="default"
onClick={async () => {
const response = await fresh.refetch();
if (response.data && !response.error)
setLatest(response.data);
else setError(response.error);
}}
variant="default"
>
{t("bank.reloadRecord")}
</Button>
)}
</>
) : null}
))}
{latest && (
<>
<Text>
@@ -121,22 +124,22 @@ const BankCardForm: FC<BankCardFormProps> = (props) => {
})}
</Text>
<Button
variant="default"
onClick={() => {
setVersion(latest.version);
setLatest(undefined);
setError(undefined);
}}
variant="default"
>
{t("bank.adoptVersion", { version: latest.version })}
</Button>
</>
)}
<Group>
<Button type="submit" loading={pending}>
<Button loading={isPending} type="submit">
{t("bank.save")}
</Button>
<Button variant="default" onClick={() => setOpened(false)}>
<Button onClick={() => setOpened(false)} variant="default">
{t("bank.cancel")}
</Button>
</Group>
@@ -1,8 +1,10 @@
import type { FC } from "react";
import { Select, Stack, Text, TextInput } from "@mantine/core";
import { DateInput } from "@mantine/dates";
import type { FC } from "react";
import { Controller, useFormContext } from "react-hook-form";
import { useTranslation } from "react-i18next";
import {
type BankCardValues,
bankDateInputValue,
@@ -14,8 +16,8 @@ type BankCardFieldsProps = { archived: boolean };
const BankCardFields: FC<BankCardFieldsProps> = (props) => {
const {
control,
register,
formState: { errors },
register,
} = useFormContext<BankCardValues>();
const { t } = useTranslation();
return (
@@ -32,8 +34,8 @@ const BankCardFields: FC<BankCardFieldsProps> = (props) => {
error={errors.bankName?.message}
/>
<TextInput
label={t("bank.lastFour")}
inputMode="numeric"
label={t("bank.lastFour")}
{...register("lastFour")}
error={errors.lastFour?.message}
/>
@@ -43,25 +45,25 @@ const BankCardFields: FC<BankCardFieldsProps> = (props) => {
render={({ field }) => (
<Select
{...field}
value={field.value || null}
onChange={(value) => field.onChange(value ?? "")}
label={t("bank.paymentSystem")}
placeholder={t("bank.paymentSystemUnknown")}
clearable
data={["mir", "visa", "mastercard"].map((value) => ({
value,
label: t(`bank.paymentSystems.${value}`),
}))}
comboboxProps={{ withinPortal: false }}
data={["mir", "visa", "mastercard"].map(value => ({
label: t(`bank.paymentSystems.${value}`),
value,
}))}
error={errors.paymentSystem?.message}
label={t("bank.paymentSystem")}
onChange={value => field.onChange(value ?? "")}
placeholder={t("bank.paymentSystemUnknown")}
value={field.value || /* eslint-disable-line unicorn/no-null -- Mantine represents an empty controlled field as null. */ null}
/>
)}
/>
<TextInput
label={t("bank.openingBalance")}
required
inputMode="decimal"
label={t("bank.openingBalance")}
readOnly={props.archived}
required
{...register("openingBalance")}
error={errors.openingBalance?.message}
/>
@@ -71,37 +73,35 @@ const BankCardFields: FC<BankCardFieldsProps> = (props) => {
render={({ field }) => (
<DateInput
{...field}
label={t("bank.openingDate")}
required
valueFormat="DD.MM.YYYY"
value={
bankDateSchema.safeParse(field.value).success ? field.value : null
}
dateParser={(value) =>
dateParser={value =>
bankDateSchema.safeParse(bankDateInputValue(value)).success
? bankDateInputValue(value)
: null
}
: /* eslint-disable-line unicorn/no-null -- Mantine represents an empty controlled field as null. */ null}
error={errors.openingDate?.message}
fixOnBlur={false}
onInput={(event) =>
field.onChange(bankDateInputValue(event.currentTarget.value))
}
onChange={(value) => field.onChange(value ?? "")}
label={t("bank.openingDate")}
maxDate={bankToday()}
onBlur={(event) => {
field.onChange(bankDateInputValue(event.currentTarget.value));
field.onBlur();
}}
maxDate={bankToday()}
onChange={value => field.onChange(value ?? "")}
onInput={event =>
field.onChange(bankDateInputValue(event.currentTarget.value))}
popoverProps={{
withinPortal: false,
middlewares: { shift: { crossAxis: true } },
withinPortal: false,
}}
readOnly={props.archived}
error={errors.openingDate?.message}
required
value={
(bankDateSchema.safeParse(field.value).success) ? (field.value) : undefined
}
valueFormat="DD.MM.YYYY"
/>
)}
/>
<Text size="sm" c="dimmed">
<Text c="dimmed" size="sm">
{t("bank.openingHint")}
</Text>
{props.archived && <Text>{t("bank.archiveHint")}</Text>}
+6 -4
View File
@@ -1,13 +1,15 @@
import { Alert, Button, Group, Text } from "@mantine/core";
import type { FC } from "react";
import { Alert, Button, Group, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { apiErrorCode } from "@/shared/api";
type BankFeedbackProps = {
error: unknown;
retry?: () => void;
cached?: boolean;
error: unknown;
loadingError?: boolean;
retry?: () => void;
};
const BankFeedback: FC<BankFeedbackProps> = (props) => {
const { t } = useTranslation();
@@ -25,7 +27,7 @@ const BankFeedback: FC<BankFeedbackProps> = (props) => {
})}
</Text>
{props.retry && (
<Button variant="default" onClick={props.retry}>
<Button onClick={props.retry} variant="default">
{t("bank.retry")}
</Button>
)}
@@ -1,13 +1,15 @@
import { Stack } from "@mantine/core";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { Stack } from "@mantine/core";
import { EntryCard } from "@wealthledger/ui";
import { BankOperationIcon } from "./BankOperationIcon";
const meta = {
title: "Product/BankCards/OperationIcons",
args: { categoryName: "Продукты", kind: "expense" },
component: BankOperationIcon,
tags: ["autodocs"],
args: { kind: "expense", categoryName: "Продукты" },
title: "Product/BankCards/OperationIcons",
} satisfies Meta<typeof BankOperationIcon>;
export default meta;
type Story = StoryObj<typeof meta>;
@@ -40,28 +42,28 @@ export const Categories: Story = {
"Хостинг и ИИ-сервисы",
"Цифровые покупки",
"Моя категория",
].map((name) => (
].map(name => (
<EntryCard
key={name}
title="Расход"
metadata={`12.09.2026 · ${name}`}
initial="Р"
color="red"
icon={<BankOperationIcon kind="expense" categoryName={name} />}
icon={<BankOperationIcon categoryName={name} kind="expense" />}
initial="Р"
key={name}
metadata={`12.09.2026 · ${name}`}
title="Расход"
tone="negative"
value="−1 250,00 ₽"
valueLabel="Расход"
tone="negative"
/>
))}
<EntryCard
title="Пополнение"
metadata="12.09.2026"
initial="П"
color="green"
icon={<BankOperationIcon kind="topup" />}
initial="П"
metadata="12.09.2026"
title="Пополнение"
tone="positive"
value="+15 000,00 ₽"
valueLabel="Пополнение"
tone="positive"
/>
</Stack>
),
@@ -1,36 +1,40 @@
import { render } from "@testing-library/react";
import { expect, it } from "vitest";
import { BankOperationIcon } from "./BankOperationIcon";
it("matches normalized category names, falls back after renaming and distinguishes operation kinds", () => {
const { container, rerender } = render(
<BankOperationIcon kind="expense" categoryName="Жильё" />,
<BankOperationIcon categoryName="Жильё" kind="expense" />,
);
// eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
const path = () => container.querySelector("path")?.getAttribute("d");
const housing = path();
rerender(<BankOperationIcon kind="expense" categoryName=" ЖИЛЬЕ " />);
rerender(<BankOperationIcon categoryName=" ЖИЛЬЕ " kind="expense" />);
expect(path()).toBe(housing);
rerender(<BankOperationIcon kind="expense" categoryName="Другое" />);
rerender(<BankOperationIcon categoryName="Другое" kind="expense" />);
const fallback = path();
expect(fallback).not.toBe(housing);
for (const categoryName of ["Моя категория", "constructor", null]) {
rerender(<BankOperationIcon kind="expense" categoryName={categoryName} />);
for (const categoryName of ["Моя категория", "constructor", /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null]) {
rerender(<BankOperationIcon categoryName={categoryName} kind="expense" />);
expect(path()).toBe(fallback);
}
const paths = [fallback, housing];
for (const kind of ["topup", "transfer", "refund"] as const) {
rerender(<BankOperationIcon kind={kind} categoryName="Жильё" />);
rerender(<BankOperationIcon categoryName="Жильё" kind={kind} />);
expect(path()).toBeTruthy();
paths.push(path());
}
expect(new Set(paths).size).toBe(5);
// eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
expect(container.querySelector("svg")).toHaveAttribute("aria-hidden", "true");
});
it("provides a distinct icon for every existing named category", () => {
const { container, rerender } = render(
<BankOperationIcon kind="expense" categoryName="Другое" />,
<BankOperationIcon categoryName="Другое" kind="expense" />,
);
// eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
const paths = new Set([container.querySelector("path")?.getAttribute("d")]);
for (const categoryName of [
"Алкоголь",
@@ -57,7 +61,8 @@ it("provides a distinct icon for every existing named category", () => {
"Хостинг и ИИ-сервисы",
"Цифровые покупки",
]) {
rerender(<BankOperationIcon kind="expense" categoryName={categoryName} />);
rerender(<BankOperationIcon categoryName={categoryName} kind="expense" />);
// eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
const path = container.querySelector("path")?.getAttribute("d");
expect(path).toBeTruthy();
expect(paths.has(path), categoryName).toBe(false);
@@ -1,34 +1,36 @@
import type { FC } from "react";
import { bindIconAnimation } from "@/shared/lib";
import type { BankOperation } from "../../api/queries";
import { bankOperationAppearance } from "../../model/operation-appearance";
import classes from "./BankOperationIcon.module.css";
type BankOperationIconProps = {
categoryName?: null | string;
kind: BankOperation["kind"];
categoryName?: string | null;
};
const BankOperationIcon: FC<BankOperationIconProps> = (props) => {
const icon = bankOperationAppearance(props.kind, props.categoryName);
return (
<svg
ref={bindIconAnimation}
aria-hidden="true"
className={`${classes.icon} ${icon.animation ? classes[icon.animation] : ""}`}
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
focusable="false"
height="24"
ref={bindIconAnimation}
stroke="currentColor"
strokeWidth="1.6"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
style={{ flexShrink: 0, color: `var(--mantine-color-${icon.color}-7)` }}
strokeWidth="1.6"
style={{ color: `var(--mantine-color-${icon.color}-7)`, flexShrink: 0 }}
viewBox="0 0 24 24"
width="24"
>
{icon.path.split(" M").map((part, index) => (
<path key={part} d={index ? `M${part}` : part} pathLength={1} />
<path d={index ? `M${part}` : part} key={part} pathLength={1} />
))}
</svg>
);
@@ -3,34 +3,34 @@ import { type FC, useState } from "react";
import { useTranslation } from "react-i18next";
type BankPeriodPickerProps = {
onChange: (value: [null | string, null | string]) => void;
period: { from: string; to: string };
onChange: (value: [string | null, string | null]) => void;
};
const BankPeriodPicker: FC<BankPeriodPickerProps> = (props) => {
const { period, onChange } = props;
const { onChange, period } = props;
const { t } = useTranslation();
const scope = `${period.from}-${period.to}`;
const [draft, setDraft] = useState<{
scope: string;
value: [string | null, string | null];
value: [null | string, null | string];
}>();
const value: [string | null, string | null] =
draft?.scope === scope ? draft.value : [period.from, period.to];
const value: [null | string, null | string]
= draft?.scope === scope ? draft.value : [period.from, period.to];
return (
<DatePickerInput
type="range"
allowSingleDateInRange
label={t("bank.period")}
valueFormat="DD.MM.YYYY"
value={value}
onChange={(next) => {
setDraft({ scope, value: next });
onChange(next);
}}
popoverProps={{
returnFocus: true,
middlewares: { shift: { crossAxis: true } },
returnFocus: true,
}}
type="range"
value={value}
valueFormat="DD.MM.YYYY"
/>
);
};
@@ -1,11 +1,54 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { BankSummaryView } from "./BankSummary.view";
const money = (value: string) => ({ currency: "RUB", value });
const meta = {
title: "Product/BankCards/Summary",
const meta = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
args: {
data: {
cardId: null,
categories: [
{
categoryId: "food",
categoryName: "Продукты",
expenses: money("3500"),
net: money("2500"),
refunds: money("1000"),
},
{
categoryId: "cafe",
categoryName: "Кафе",
expenses: money("2200"),
net: money("2200"),
refunds: money("0"),
},
{
categoryId: "taxi",
categoryName: "Такси",
expenses: money("1800"),
net: money("1800"),
refunds: money("0"),
},
{
categoryId: "health",
categoryName: "Здоровье",
expenses: money("1000"),
net: money("1000"),
refunds: money("0"),
},
],
expenses: money("8500"),
month: "2026-09",
net: money("7500"),
refunds: money("1000"),
},
error: false,
fetching: false,
loading: false,
retry: () => {},
},
component: BankSummaryView,
tags: ["autodocs"],
parameters: {
docs: {
description: {
@@ -14,118 +57,84 @@ const meta = {
},
},
},
args: {
loading: false,
error: false,
fetching: false,
retry: () => {},
data: {
month: "2026-09",
cardId: null,
expenses: money("8500"),
refunds: money("1000"),
net: money("7500"),
categories: [
{
categoryId: "food",
categoryName: "Продукты",
expenses: money("3500"),
refunds: money("1000"),
net: money("2500"),
},
{
categoryId: "cafe",
categoryName: "Кафе",
expenses: money("2200"),
refunds: money("0"),
net: money("2200"),
},
{
categoryId: "taxi",
categoryName: "Такси",
expenses: money("1800"),
refunds: money("0"),
net: money("1800"),
},
{
categoryId: "health",
categoryName: "Здоровье",
expenses: money("1000"),
refunds: money("0"),
net: money("1000"),
},
],
},
},
} satisfies Meta<typeof BankSummaryView>;
tags: ["autodocs"],
title: "Product/BankCards/Summary",
}
/* eslint-enable unicorn/no-null */) satisfies Meta<typeof BankSummaryView>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Loaded: Story = { name: "Расходы по категориям" };
export const RefundMonth: Story = {
name: "Возврат покупки прошлого месяца",
args: {
data: {
month: "2026-09",
cardId: null,
expenses: money("0"),
refunds: money("600"),
net: money("-600"),
categories: [
{
categoryId: "shopping",
categoryName:
export const RefundMonth: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
args: {
data: {
cardId: null,
categories: [
{
categoryId: "shopping",
categoryName:
"Покупки с длинным пользовательским названием категории",
expenses: money("0"),
refunds: money("600"),
net: money("-600"),
},
],
expenses: money("0"),
net: money("-600"),
refunds: money("600"),
},
],
expenses: money("0"),
month: "2026-09",
net: money("-600"),
refunds: money("600"),
},
},
},
};
export const Empty: Story = {
name: "Известные нули",
args: {
data: {
month: "2026-09",
cardId: null,
expenses: money("0"),
refunds: money("0"),
net: money("0"),
categories: [],
name: "Возврат покупки прошлого месяца",
}
/* eslint-enable unicorn/no-null */);
export const Empty: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
args: {
data: {
cardId: null,
categories: [],
expenses: money("0"),
month: "2026-09",
net: money("0"),
refunds: money("0"),
},
},
},
};
name: "Известные нули",
}
/* eslint-enable unicorn/no-null */);
export const Loading: Story = {
name: "Начальная загрузка",
args: { data: undefined, loading: true },
name: "Начальная загрузка",
};
export const Failed: Story = {
name: "Ошибка без данных",
args: { data: undefined, error: true },
name: "Ошибка без данных",
};
export const CachedError: Story = {
name: "Сохранённые суммы при ошибке обновления",
args: { error: true },
name: "Сохранённые суммы при ошибке обновления",
};
export const LongAmounts: Story = {
name: "Точный итог длиннее предела отдельного ввода",
args: {
data: {
month: "2026-09",
cardId: null,
expenses: money("184467440737095516.14"),
refunds: money("0"),
net: money("184467440737095516.14"),
categories: [
{
categoryId: "shopping",
categoryName: "Покупки",
expenses: money("184467440737095516.14"),
refunds: money("0"),
net: money("184467440737095516.14"),
},
],
export const LongAmounts: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
args: {
data: {
cardId: null,
categories: [
{
categoryId: "shopping",
categoryName: "Покупки",
expenses: money("184467440737095516.14"),
net: money("184467440737095516.14"),
refunds: money("0"),
},
],
expenses: money("184467440737095516.14"),
month: "2026-09",
net: money("184467440737095516.14"),
refunds: money("0"),
},
},
},
};
name: "Точный итог длиннее предела отдельного ввода",
}
/* eslint-enable unicorn/no-null */);
@@ -1,24 +1,78 @@
import type { CSSProperties, FC } from "react";
import { Button, Group, Skeleton, Stack, Text, Title } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { CSSProperties, FC } from "react";
import { useTranslation } from "react-i18next";
import { formatMoney } from "@/shared/lib";
import type { BankSummary } from "../../api/queries";
import { BankOperationIcon } from "../BankOperationIcon/BankOperationIcon";
import classes from "./BankSummary.module.css";
const CATEGORY_COLUMNS = 2;
type BankSummaryViewProps = {
all?: boolean;
data?: BankSummary;
loading: boolean;
error: boolean;
fetching: boolean;
loading: boolean;
retry: () => void;
all?: boolean;
};
const BankSummaryView: FC<BankSummaryViewProps> = (props) => {
const { t } = useTranslation();
function renderCategories() {
if (props.data) {
if (props.data.categories.length > 0) {
return (
<dl
className={classes.categories}
style={
{
"--category-rows": Math.ceil(props.data.categories.length / CATEGORY_COLUMNS),
} as CSSProperties
}
>
{props.data.categories.map(category => (
<div className={classes.category} key={category.categoryId}>
<dt className={classes.label}>
<BankOperationIcon
categoryName={category.categoryName}
kind="expense"
/>
<span>{category.categoryName}</span>
</dt>
<dd className={classes.amount}>
{formatMoney(category.net, { withZeroCents: true })}
</dd>
</div>
))}
</dl>
);
}
return (
<Text c="dimmed" size="sm">
{t("bank.noExpenses")}
</Text>
);
}
if (props.loading) {
return (
<LoadingSkeleton label={t("bank.loading")}>
<Stack gap="sm">
<Skeleton h={32} w="35%" />
<Skeleton h={40} />
<Skeleton h={40} />
</Stack>
</LoadingSkeleton>
);
}
}
return (
<Stack gap="md" aria-busy={props.loading || props.fetching}>
<Stack aria-busy={props.loading || props.fetching} gap="md">
<div className={classes.header}>
<Title order={2}>
{t(props.all ? "bank.allSummary" : "bank.summary")}
@@ -29,49 +83,11 @@ const BankSummaryView: FC<BankSummaryViewProps> = (props) => {
</Text>
)}
</div>
{props.data ? (
props.data.categories.length ? (
<dl
className={classes.categories}
style={
{
"--category-rows": Math.ceil(props.data.categories.length / 2),
} as CSSProperties
}
>
{props.data.categories.map((category) => (
<div className={classes.category} key={category.categoryId}>
<dt className={classes.label}>
<BankOperationIcon
kind="expense"
categoryName={category.categoryName}
/>
<span>{category.categoryName}</span>
</dt>
<dd className={classes.amount}>
{formatMoney(category.net, { withZeroCents: true })}
</dd>
</div>
))}
</dl>
) : (
<Text size="sm" c="dimmed">
{t("bank.noExpenses")}
</Text>
)
) : props.loading ? (
<LoadingSkeleton label={t("bank.loading")}>
<Stack gap="sm">
<Skeleton h={32} w="35%" />
<Skeleton h={40} />
<Skeleton h={40} />
</Stack>
</LoadingSkeleton>
) : null}
{renderCategories()}
{props.error && (
<Group role="alert">
<Text>{t(props.data ? "bank.refreshError" : "bank.error")}</Text>
<Button variant="default" onClick={props.retry}>
<Button onClick={props.retry} variant="default">
{t("bank.retry")}
</Button>
</Group>
@@ -7,36 +7,36 @@ import {
screen,
waitFor,
} from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { http, HttpResponse } from "msw";
import { describe, expect, it } from "vitest";
import { configureAuthClient } from "@/shared/api";
import { createTestQueryClient } from "@/test/query";
import { server } from "@/test/server";
import { CategoryManager } from "./CategoryManager";
describe("CategoryManager", () => {
it("ignores a late reload for A while editing B and submits B's draft and version", async () => {
configureAuthClient({
accessToken: () => "test",
refresh: async () => false,
clear: () => {},
refresh: () => Promise.resolve(false),
});
const categories = [
{ id: "a", name: "Первая", isDefault: false, version: 1 },
{ id: "b", name: "Вторая", isDefault: false, version: 4 },
{ id: "a", isDefault: false, name: "Первая", version: 1 },
{ id: "b", isDefault: false, name: "Вторая", version: 4 },
];
let reads = 0;
let release = () => {};
const reloaded = new Promise<void>((resolve) => {
release = resolve;
});
const patches: { id: unknown; body: unknown }[] = [];
const { promise: reloaded, resolve: release } = Promise.withResolvers<void>();
const patches: { body: unknown; id: unknown }[] = [];
server.use(
http.get("*/api/v1/bank-cards/categories", async () => {
reads++;
if (reads === 3) await reloaded;
return HttpResponse.json(
categories.map((category) =>
categories.map(category =>
category.id === "a" && reads > 1
? {
...category,
@@ -49,8 +49,8 @@ describe("CategoryManager", () => {
}),
http.patch(
"*/api/v1/bank-cards/categories/:id",
async ({ request, params }) => {
patches.push({ id: params.id, body: await request.json() });
async ({ params, request }) => {
patches.push({ body: await request.json(), id: params.id });
return patches.length === 1
? HttpResponse.json(
{ code: "BANK_VERSION_CONFLICT" },
@@ -67,9 +67,8 @@ describe("CategoryManager", () => {
</MantineProvider>
</QueryClientProvider>,
);
fireEvent.click(
(await screen.findAllByRole("button", { name: "Переименовать" }))[0],
);
const renameButtons = await screen.findAllByRole("button", { name: "Переименовать" });
fireEvent.click(renameButtons[0]);
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
fireEvent.click(
await screen.findByRole("button", { name: "Перечитать запись" }),
@@ -99,8 +98,8 @@ describe("CategoryManager", () => {
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
await waitFor(() =>
expect(patches).toEqual([
{ id: "a", body: { name: "Первая", version: 1 } },
{ id: "b", body: { name: "Новая вторая", version: 4 } },
{ body: { name: "Первая", version: 1 }, id: "a" },
{ body: { name: "Новая вторая", version: 4 }, id: "b" },
]),
);
});
@@ -110,15 +109,15 @@ describe("CategoryManager", () => {
async (action) => {
configureAuthClient({
accessToken: () => "test",
refresh: async () => false,
clear: () => {},
refresh: () => Promise.resolve(false),
});
let version = 1;
let writes = 0;
server.use(
http.get("*/api/v1/bank-cards/categories", () =>
HttpResponse.json([
{ id: "a", name: "Первая", isDefault: false, version },
{ id: "a", isDefault: false, name: "Первая", version },
]),
),
http.patch("*/api/v1/bank-cards/categories/a", () => {
@@ -161,13 +160,13 @@ describe("CategoryManager", () => {
it("rejects duplicate case-insensitive and too long names then renames default identity", async () => {
configureAuthClient({
accessToken: () => "test",
refresh: async () => false,
clear: () => {},
refresh: () => Promise.resolve(false),
});
let category = {
id: "default",
name: "Другое",
isDefault: true,
name: "Другое",
version: 1,
};
let creates = 0;
@@ -17,7 +17,9 @@ import {
} from "react-hook-form";
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";
@@ -60,44 +62,40 @@ const CategoryManager: FC<CategoryManagerProps> = (props) => {
const categories = useBankCategories();
const mutation = useBankMutations();
const [editing, setEditing] = useState<ExpenseCategory>();
const editSession = useRef(0);
const editSessionRef = useRef(0);
const [error, setError] = useState<unknown>();
const [latest, setLatest] = useState<ExpenseCategory>();
const methods = useForm<CategoryValues>({
resolver: zodResolver(
z.object({
name: z
.string()
.trim()
.refine(
(value) =>
value.length > 0 && value.length <= MAX_CATEGORY_NAME_LENGTH,
{ error: validationMessage("bank.validation.category") },
)
.refine(
(value) =>
!categories.data?.some(
(c) =>
c.id !== editing?.id &&
c.name.toLocaleLowerCase("ru-RU") ===
value.toLocaleLowerCase("ru-RU"),
),
{ error: validationMessage("bank.validation.duplicate") },
const schema = z.object({
name: z
.string()
.trim()
.refine(
value =>
value.length > 0 && value.length <= MAX_CATEGORY_NAME_LENGTH,
{ error: validationMessage("bank.validation.category") },
)
.refine(
value =>
!categories.data?.some(
c =>
c.id !== editing?.id
&& c.name.toLocaleLowerCase("ru-RU")
=== value.toLocaleLowerCase("ru-RU"),
),
}),
),
defaultValues: { name: "" },
{ error: validationMessage("bank.validation.duplicate") },
),
});
const pending = !opened || methods.formState.isSubmitting;
const methods = useForm<CategoryValues>({ defaultValues: { name: "" }, resolver: zodResolver(schema) });
const isPending = !opened || methods.formState.isSubmitting;
return (
<Modal
opened={opened}
closeButtonProps={{ "aria-label": t("bank.close"), "disabled": isPending }}
closeOnClickOutside={!isPending}
closeOnEscape={!isPending}
onClose={() => !isPending && setOpened(false)}
onExitTransitionEnd={props.onClose}
onClose={() => !pending && setOpened(false)}
opened={opened}
title={t("bank.categories")}
closeOnClickOutside={!pending}
closeOnEscape={!pending}
closeButtonProps={{ "aria-label": t("bank.close"), disabled: pending }}
>
<FormProvider {...methods}>
<form
@@ -107,8 +105,8 @@ const CategoryManager: FC<CategoryManagerProps> = (props) => {
try {
if (editing)
await mutation.updateCategory.mutateAsync({
id: editing.id,
body: { name: values.name, version: editing.version },
id: editing.id,
});
else {
const result = await mutation.createCategory.mutateAsync({
@@ -116,24 +114,25 @@ const CategoryManager: FC<CategoryManagerProps> = (props) => {
});
if (result) props.onCreated?.(result.id);
}
editSession.current++;
editSessionRef.current++;
setEditing(undefined);
setLatest(undefined);
methods.reset({ name: "" });
} catch (failure) {
setError(failure);
}
catch (error_) {
setError(error_);
}
})(event);
}}
>
<fieldset disabled={pending} className={classes.fieldset}>
<fieldset className={classes.fieldset} disabled={isPending}>
<Stack>
{categories.data?.map((category) => (
{categories.data?.map(category => (
<Group justify="space-between" key={category.id}>
<Group gap="xs">
<BankOperationIcon
kind="expense"
categoryName={category.name}
kind="expense"
/>
<Text>{category.name}</Text>
{category.isDefault && (
@@ -141,14 +140,14 @@ const CategoryManager: FC<CategoryManagerProps> = (props) => {
)}
</Group>
<Button
variant="subtle"
onClick={() => {
editSession.current++;
editSessionRef.current++;
setEditing(category);
methods.reset({ name: category.name });
setError(undefined);
setLatest(undefined);
}}
variant="subtle"
>
{t("bank.rename")}
</Button>
@@ -159,35 +158,35 @@ const CategoryManager: FC<CategoryManagerProps> = (props) => {
)}
{categories.isError && (
<BankFeedback
loadingError
error={categories.error}
cached={Boolean(categories.data)}
error={categories.error}
loadingError
retry={() => void categories.refetch()}
/>
)}
<CategoryFields />
{error ? (
{!!(error) && ((
<>
<BankFeedback error={error} />
{editing && (
<Button
variant="default"
onClick={async () => {
const session = editSession.current;
const session = editSessionRef.current;
const response = await categories.refetch();
if (session !== editSession.current) return;
if (session !== editSessionRef.current) return;
if (response.error) setError(response.error);
else
setLatest(
response.data?.find((c) => c.id === editing.id),
response.data?.find(c => c.id === editing.id),
);
}}
variant="default"
>
{t("bank.reloadRecord")}
</Button>
)}
</>
) : null}
))}
{latest && latest.id === editing?.id && (
<>
<Text>{t("bank.versionHint", { details: latest.name })}</Text>
@@ -203,24 +202,24 @@ const CategoryManager: FC<CategoryManagerProps> = (props) => {
</>
)}
<Group>
<Button type="submit" loading={pending}>
<Button loading={isPending} type="submit">
{t(editing ? "bank.save" : "bank.addCategory")}
</Button>
{editing && (
<Button
variant="default"
onClick={() => {
editSession.current++;
editSessionRef.current++;
setEditing(undefined);
setLatest(undefined);
methods.reset({ name: "" });
setError(undefined);
}}
variant="default"
>
{t("bank.cancel")}
</Button>
)}
<Button variant="default" onClick={() => setOpened(false)}>
<Button onClick={() => setOpened(false)} variant="default">
{t("bank.close")}
</Button>
</Group>
+44 -42
View File
@@ -1,5 +1,7 @@
import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
const MIN_BOND_SEARCH_LENGTH = 2;
type BondPeriod = NonNullable<
NonNullable<
paths["/api/v1/bonds/{uid}/candles"]["get"]["parameters"]["query"]
@@ -8,15 +10,6 @@ type BondPeriod = NonNullable<
const BOND_STALE_TIME_MS = 30_000;
function useBondSearch(query: string) {
return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bonds", {
params: { query: { query } },
}),
enabled: query.length >= 2,
staleTime: BOND_STALE_TIME_MS,
});
}
function bondQueryOptions(uid: string) {
return {
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}", {
@@ -25,10 +18,9 @@ function bondQueryOptions(uid: string) {
staleTime: BOND_STALE_TIME_MS,
};
}
function useBond(identifier: string) {
const isUid =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
const isUid
= /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
identifier,
);
@@ -45,24 +37,7 @@ function useBond(identifier: string) {
});
return isUid ? byUid : byTicker;
}
function useBondMetrics(uid: string) {
return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/metrics", {
params: { path: { uid } },
}),
enabled: Boolean(uid),
staleTime: BOND_STALE_TIME_MS,
});
}
function useBondQuote(uid: string) {
return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/quote", {
params: { path: { uid } },
}),
enabled: Boolean(uid),
staleTime: BOND_STALE_TIME_MS,
});
}
function useBondCandles(uid: string, period: BondPeriod) {
return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/candles", {
@@ -72,16 +47,6 @@ function useBondCandles(uid: string, period: BondPeriod) {
staleTime: BOND_STALE_TIME_MS,
});
}
function useBondPosition(uid: string) {
return useResourceQuery({
meta: { accessGroup: "brokerage" },
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/position", {
params: { path: { uid } },
}),
enabled: Boolean(uid),
staleTime: BOND_STALE_TIME_MS,
});
}
function useBondCoupons(uid: string) {
return useResourceQuery({
meta: { accessGroup: "brokerage" },
@@ -92,9 +57,46 @@ function useBondCoupons(uid: string) {
staleTime: BOND_STALE_TIME_MS,
});
}
function useBondMetrics(uid: string) {
return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/metrics", {
params: { path: { uid } },
}),
enabled: Boolean(uid),
staleTime: BOND_STALE_TIME_MS,
});
}
function useBondPosition(uid: string) {
return useResourceQuery({
meta: { accessGroup: "brokerage" },
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/position", {
params: { path: { uid } },
}),
enabled: Boolean(uid),
staleTime: BOND_STALE_TIME_MS,
});
}
function useBondQuote(uid: string) {
return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/quote", {
params: { path: { uid } },
}),
enabled: Boolean(uid),
staleTime: BOND_STALE_TIME_MS,
});
}
function useBondSearch(query: string) {
return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/bonds", {
params: { query: { query } },
}),
enabled: query.length >= MIN_BOND_SEARCH_LENGTH,
staleTime: BOND_STALE_TIME_MS,
});
}
export {
type BondPeriod,
export { type BondPeriod,
MIN_BOND_SEARCH_LENGTH,
useBond,
useBondCandles,
useBondCoupons,
+2 -2
View File
@@ -1,5 +1,5 @@
export {
type BondPeriod,
export { type BondPeriod,
MIN_BOND_SEARCH_LENGTH,
useBond,
useBondCandles,
useBondCoupons,
@@ -1,9 +1,11 @@
import { renderHook, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { configureAuthClient } from "@/shared/api";
import { createQueryWrapper } from "@/test/query";
import {
brokerageOperationsQueryParams,
brokerageOperationsQueryParams as brokerageOperationsQueryParameters,
useBrokerageOperations,
} from "./useBrokerageOperations";
@@ -11,11 +13,11 @@ describe("useBrokerageOperations", () => {
it("normalizes categories, preserves the cursor and loads a page", async () => {
configureAuthClient({
accessToken: () => "token",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
expect(
brokerageOperationsQueryParams({
brokerageOperationsQueryParameters({
categories: ["tax", "income"],
cursor: "next",
}),
@@ -1,16 +1,16 @@
import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
type OperationsEndpoint =
paths["/api/v1/brokerage-accounts/{accountId}/operations"]["get"];
type BrokerageOperation = NonNullable<
OperationsEndpoint["responses"][200]["content"]["application/json"]["data"]
>["items"][number];
type BrokerageOperationsQuery = Omit<
NonNullable<OperationsEndpoint["parameters"]["query"]>,
"sync"
>;
type OperationCategory = BrokerageOperation["category"];
type OperationsEndpoint
= paths["/api/v1/brokerage-accounts/{accountId}/operations"]["get"];
const operationCategories = [
"trade",
@@ -21,19 +21,6 @@ const operationCategories = [
"other",
] as const satisfies readonly OperationCategory[];
function brokerageOperationsQueryParams(query: BrokerageOperationsQuery) {
return {
...(query.instrumentUid ? { instrumentUid: query.instrumentUid } : {}),
...(query.from ? { from: query.from } : {}),
...(query.to ? { to: query.to } : {}),
...(query.categories?.length
? { categories: [...query.categories].sort() }
: {}),
...(query.cursor ? { cursor: query.cursor } : {}),
...(query.limit ? { limit: query.limit } : {}),
};
}
function brokerageOperationsQueryOptions(
accountId: string | undefined,
query: BrokerageOperationsQuery = {},
@@ -44,12 +31,23 @@ function brokerageOperationsQueryOptions(
{
params: {
path: { accountId: accountId ?? "" },
query: brokerageOperationsQueryParams(query),
query: brokerageOperationsQueryParameters(query),
},
},
);
}
function brokerageOperationsQueryParameters(query: BrokerageOperationsQuery) {
return {
...(query.instrumentUid && { instrumentUid: query.instrumentUid }),
...(query.from && { from: query.from }),
...(query.to && { to: query.to }),
...(query.categories?.length && { categories: query.categories.toSorted((left, right) => left.localeCompare(right)) }),
...(query.cursor && { cursor: query.cursor }),
...(query.limit && { limit: query.limit }),
};
}
function useBrokerageOperations(
accountId: string | undefined,
query: BrokerageOperationsQuery = {},
@@ -65,8 +63,8 @@ function useBrokerageOperations(
export {
type BrokerageOperation,
brokerageOperationsQueryOptions,
brokerageOperationsQueryParams,
type OperationCategory,
brokerageOperationsQueryParameters as brokerageOperationsQueryParams,
operationCategories,
type OperationCategory,
useBrokerageOperations,
};
+1 -1
View File
@@ -1,8 +1,8 @@
export {
type BrokerageOperation,
brokerageOperationsQueryOptions,
type OperationCategory,
operationCategories,
type OperationCategory,
useBrokerageOperations,
} from "./api/useBrokerageOperations";
export { LedgerEntryRow } from "./ui/LedgerEntryRow";
+40 -41
View File
@@ -1,10 +1,11 @@
import { formatMoney } from "@/shared/lib";
import type { BrokerageOperation } from "../api/useBrokerageOperations";
type PaymentPresentation = {
amount: string;
label: string;
tone: "positive" | "negative" | "neutral";
tone: "negative" | "neutral" | "positive";
};
function entryLabelKey(operation: BrokerageOperation): string {
@@ -15,6 +16,44 @@ function entryLabelKey(operation: BrokerageOperation): string {
return `ledger.category.${operation.category}`;
}
function isZeroDecimal(value: string): boolean {
return /^-?0$|^-?0\.0+$/.test(value);
}
function operationLabelKey(type: string): string {
if (
[
"OPERATION_TYPE_BUY",
"OPERATION_TYPE_BUY_CARD",
"OPERATION_TYPE_BUY_MARGIN",
].includes(type)
)
return "ledger.operationType.buy";
if (
[
"OPERATION_TYPE_SELL",
"OPERATION_TYPE_SELL_CARD",
"OPERATION_TYPE_SELL_MARGIN",
].includes(type)
)
return "ledger.operationType.sell";
if (
[
"OPERATION_TYPE_DIV_EXT",
"OPERATION_TYPE_DIVIDEND",
"OPERATION_TYPE_DIVIDEND_TRANSFER",
].includes(type)
)
return "ledger.operationType.dividend";
if (type.includes("TAX")) return "ledger.operationType.tax";
if (type.includes("FEE")) return "ledger.operationType.fee";
if (type === "OPERATION_TYPE_INPUT_SECURITIES")
return "ledger.operationType.input";
if (type === "OPERATION_TYPE_OUTPUT_SECURITIES")
return "ledger.operationType.output";
return type.startsWith("OPERATION_TYPE_TRANS_") ? "ledger.operationType.transfer" : "ledger.operationType.other";
}
function paymentPresentation(
operation: BrokerageOperation,
): PaymentPresentation {
@@ -46,44 +85,4 @@ function paymentPresentation(
};
}
function isZeroDecimal(value: string): boolean {
return /^-?0(?:\.0+)?$/.test(value);
}
function operationLabelKey(type: string): string {
if (
[
"OPERATION_TYPE_BUY",
"OPERATION_TYPE_BUY_CARD",
"OPERATION_TYPE_BUY_MARGIN",
].includes(type)
)
return "ledger.operationType.buy";
if (
[
"OPERATION_TYPE_SELL",
"OPERATION_TYPE_SELL_CARD",
"OPERATION_TYPE_SELL_MARGIN",
].includes(type)
)
return "ledger.operationType.sell";
if (
[
"OPERATION_TYPE_DIVIDEND",
"OPERATION_TYPE_DIV_EXT",
"OPERATION_TYPE_DIVIDEND_TRANSFER",
].includes(type)
)
return "ledger.operationType.dividend";
if (type.includes("TAX")) return "ledger.operationType.tax";
if (type.includes("FEE")) return "ledger.operationType.fee";
if (type === "OPERATION_TYPE_INPUT_SECURITIES")
return "ledger.operationType.input";
if (type === "OPERATION_TYPE_OUTPUT_SECURITIES")
return "ledger.operationType.output";
if (type.startsWith("OPERATION_TYPE_TRANS_"))
return "ledger.operationType.transfer";
return "ledger.operationType.other";
}
export { operationLabelKey, paymentPresentation };
@@ -1,15 +1,19 @@
import type { FC } from "react";
import { Anchor, Group, Text } from "@mantine/core";
import { EntryCard } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import {
formatDecimal,
formatMoney,
formatSnapshotTime,
instrumentLogoUrl,
} from "@/shared/lib";
import type { BrokerageOperation } from "../api/useBrokerageOperations";
import { operationLabelKey, paymentPresentation } from "../model/display";
type LedgerEntryRowProps = {
@@ -20,55 +24,57 @@ type LedgerEntryRowProps = {
const LedgerEntryRow: FC<LedgerEntryRowProps> = (props) => {
const { operation } = props;
const { t } = useTranslation();
const instrument =
operation.ticker ?? operation.instrumentType ?? t("ledger.noInstrument");
const instrument
= operation.ticker ?? operation.instrumentType ?? t("ledger.noInstrument");
const payment = paymentPresentation(operation);
const metadata = [
t("ledger.occurredAt", { date: formatSnapshotTime(operation.occurredAt) }),
instrument,
props.withDetails ? null : operation.account?.name,
props.withDetails ? /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null : operation.account?.name,
]
.filter(Boolean)
.join(" · ");
return (
<EntryCard
title={operation.description || t(operationLabelKey(operation.type))}
metadata={metadata}
details={
props.withDetails ? (
<>
<Group gap="sm">
{operation.quantity != null ? (
<Text size="xs" c="dimmed">
{t("ledger.quantity", {
value: formatDecimal(operation.quantity),
})}
</Text>
) : null}
{operation.price ? (
<Text size="xs" c="dimmed">
{t("ledger.price", { value: formatMoney(operation.price) })}
</Text>
) : null}
</Group>
{operation.account ? (
<Anchor
component={Link}
size="sm"
to={`/accounts/${encodeURIComponent(operation.account.id)}`}
>
{operation.account.name}
</Anchor>
) : null}
</>
) : undefined
(props.withDetails)
? ((
<>
<Group gap="sm">
{operation.quantity != undefined && ((
<Text c="dimmed" size="xs">
{t("ledger.quantity", {
value: formatDecimal(operation.quantity),
})}
</Text>
))}
{!!(operation.price) && ((
<Text c="dimmed" size="xs">
{t("ledger.price", { value: formatMoney(operation.price) })}
</Text>
))}
</Group>
{!!(operation.account) && ((
<Anchor
component={Link}
size="sm"
to={`/accounts/${encodeURIComponent(operation.account.id)}`}
>
{operation.account.name}
</Anchor>
))}
</>
))
: undefined
}
initial={(instrument.trim()[0] ?? "?").toUpperCase()}
imageSrc={instrumentLogoUrl(operation.logoName)}
initial={(instrument.trim()[0] ?? "?").toUpperCase()}
metadata={metadata}
title={operation.description || t(operationLabelKey(operation.type))}
tone={payment.tone}
value={payment.amount}
valueLabel={t(payment.label)}
tone={payment.tone}
/>
);
};
@@ -1,18 +1,20 @@
import { renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { http, HttpResponse } 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";
describe("useBrokerageAccounts", () => {
it("loads accounts through the authenticated query seam", async () => {
configureAuthClient({
accessToken: () => "token",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
server.use(
http.get("*/api/v1/brokerage-accounts", () =>
@@ -21,8 +23,8 @@ describe("useBrokerageAccounts", () => {
{
id: "account-1",
name: "Основной",
type: "BROKERAGE",
openedOn: "2024-08-13",
type: "BROKERAGE",
},
]),
),
@@ -38,8 +40,8 @@ describe("useBrokerageAccounts", () => {
{
id: "account-1",
name: "Основной",
type: "BROKERAGE",
openedOn: "2024-08-13",
type: "BROKERAGE",
},
]);
});
@@ -47,8 +49,8 @@ describe("useBrokerageAccounts", () => {
it("keeps the current connection snapshot after a background refetch error", async () => {
configureAuthClient({
accessToken: () => "token",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
let calls = 0;
server.use(
@@ -60,8 +62,8 @@ describe("useBrokerageAccounts", () => {
{
id: "account-1",
name: "Основной",
type: "BROKERAGE",
openedOn: "2024-08-13",
type: "BROKERAGE",
},
]),
)
+19 -17
View File
@@ -3,24 +3,26 @@ import type {
useBrokerageAccounts,
} from "../api/useBrokerageAccounts";
type Money = NonNullable<
BrokerageAccount["portfolioSummary"]
>["totalsByCurrency"][number];
const VISIBLE_CURRENCY_LIMIT = 2;
type BrokerageAccountCard = {
account: BrokerageAccount;
positionCounts: null | { bonds: number; stocks: number };
source?: NonNullable<
ReturnType<typeof useBrokerageAccounts>["meta"]
>["dependencies"] extends (infer T)[] | undefined
? T
: never;
account: BrokerageAccount;
positionCounts: { stocks: number; bonds: number } | null;
summary:
| { state: "unavailable" }
| { remainingCurrencyCount: number; state: "available"; totals: Money[] }
| { state: "empty" }
| { state: "available"; totals: Money[]; remainingCurrencyCount: number };
| { state: "unavailable" };
};
type Money = NonNullable<
BrokerageAccount["portfolioSummary"]
>["totalsByCurrency"][number];
function accountTypeKey(type: BrokerageAccount["type"]) {
return `accounts.types.${type}` as const;
}
@@ -33,34 +35,34 @@ function brokerageAccountCards(
): BrokerageAccountCard[] {
return accounts.map((account) => {
const source = dependencies.find(
(item) =>
item =>
item.resourceKey === `portfolio/${encodeURIComponent(account.id)}`,
);
const summary = account.portfolioSummary;
if (!summary)
return {
source,
account,
positionCounts: null,
positionCounts: /* eslint-disable-line unicorn/no-null -- The existing formatter contract uses null for unavailable data. */ null,
source,
summary: { state: "unavailable" },
};
const positionCounts = {
stocks: summary.stockPositionCount,
bonds: summary.bondPositionCount,
stocks: summary.stockPositionCount,
};
if (!summary.totalsByCurrency.length)
return { source, account, positionCounts, summary: { state: "empty" } };
if (summary.totalsByCurrency.length === 0)
return { account, positionCounts, source, summary: { state: "empty" } };
return {
source,
account,
positionCounts,
source,
summary: {
state: "available",
totals: summary.totalsByCurrency.slice(0, 2),
remainingCurrencyCount: Math.max(
summary.totalsByCurrency.length - 2,
summary.totalsByCurrency.length - VISIBLE_CURRENCY_LIMIT,
0,
),
state: "available",
totals: summary.totalsByCurrency.slice(0, VISIBLE_CURRENCY_LIMIT),
},
};
});
@@ -1,34 +1,36 @@
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 { BrokerageAccountList } from "./BrokerageAccountList";
const syntheticAccount = {
id: "storybook-account",
name: "Учебный брокерский счёт",
type: "BROKERAGE",
openedOn: "2025-03-15",
portfolioSummary: {
stockPositionCount: 5,
bondPositionCount: 12,
stockPositionCount: 5,
totalsByCurrency: [
{ currency: "RUB", value: "125000.50" },
{ currency: "USD", value: "320" },
{ currency: "EUR", value: "210" },
],
},
type: "BROKERAGE",
} satisfies BrokerageAccount;
const meta = {
title: "Product/BrokerageAccountList",
component: BrokerageAccountList,
tags: ["autodocs"],
args: { accounts: brokerageAccountCards([syntheticAccount]) },
argTypes: {
accounts: { control: false },
},
component: BrokerageAccountList,
decorators: [
(Story) => (
Story => (
<MemoryRouter initialEntries={["/accounts"]}>
<Story />
</MemoryRouter>
@@ -42,7 +44,8 @@ const meta = {
},
},
},
args: { accounts: brokerageAccountCards([syntheticAccount]) },
tags: ["autodocs"],
title: "Product/BrokerageAccountList",
} satisfies Meta<typeof BrokerageAccountList>;
export default meta;
@@ -61,37 +64,39 @@ export const Available: Story = {
},
};
export const Unavailable: Story = {
name: "Сводка недоступна",
args: {
accounts: brokerageAccountCards([
{ ...syntheticAccount, portfolioSummary: null, openedOn: null },
]),
},
parameters: {
docs: {
description: {
story:
export const Unavailable: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
args: {
accounts: brokerageAccountCards([
{ ...syntheticAccount, openedOn: null, portfolioSummary: null },
]),
},
name: "Сводка недоступна",
parameters: {
docs: {
description: {
story:
"Счёт остаётся доступен для открытия, даже если сводка временно недоступна. Неизвестные суммы не заменяются нулём; отсутствующая дата открытия не отображается.",
},
},
},
},
};
}
/* eslint-enable unicorn/no-null */);
export const Empty: Story = {
name: "Нет текущих сумм",
args: {
accounts: brokerageAccountCards([
{
...syntheticAccount,
portfolioSummary: {
totalsByCurrency: [],
stockPositionCount: 0,
bondPositionCount: 0,
stockPositionCount: 0,
totalsByCurrency: [],
},
},
]),
},
name: "Нет текущих сумм",
parameters: {
docs: {
description: {
@@ -103,7 +108,6 @@ export const Empty: Story = {
};
export const LongName: Story = {
name: "Длинное название счёта",
args: {
accounts: brokerageAccountCards([
{
@@ -113,6 +117,7 @@ export const LongName: Story = {
},
]),
},
name: "Длинное название счёта",
parameters: {
docs: {
description: {
@@ -124,105 +129,107 @@ export const LongName: Story = {
};
export const AccountGrid: Story = {
name: "Несколько счетов",
args: {
accounts: brokerageAccountCards([
{
...syntheticAccount,
name: "Основной",
portfolioSummary: {
totalsByCurrency: [{ currency: "RUB", value: "1256430.50" }],
stockPositionCount: 8,
bondPositionCount: 14,
stockPositionCount: 8,
totalsByCurrency: [{ currency: "RUB", value: "1256430.50" }],
},
},
{
...syntheticAccount,
id: "storybook-iis",
name: "Долгосрочные инвестиции",
type: "INDIVIDUAL_INVESTMENT",
portfolioSummary: {
totalsByCurrency: [{ currency: "RUB", value: "480250" }],
stockPositionCount: 0,
bondPositionCount: 6,
stockPositionCount: 0,
totalsByCurrency: [{ currency: "RUB", value: "480250" }],
},
type: "INDIVIDUAL_INVESTMENT",
},
]),
},
name: "Несколько счетов",
};
export const UnvaluedPositions: Story = {
name: "Бумаги без текущей оценки",
args: {
accounts: brokerageAccountCards([
{
...syntheticAccount,
portfolioSummary: {
totalsByCurrency: [],
stockPositionCount: 2,
bondPositionCount: 1,
stockPositionCount: 2,
totalsByCurrency: [],
},
},
]),
},
name: "Бумаги без текущей оценки",
};
export const LargeValues: Story = {
name: "Длинные суммы",
args: {
accounts: brokerageAccountCards([
{
...syntheticAccount,
portfolioSummary: {
bondPositionCount: 105,
stockPositionCount: 21,
totalsByCurrency: [
{ currency: "RUB", value: "1234567890123456789.50" },
{ currency: "USD", value: "-9876543210987654321.50" },
],
stockPositionCount: 21,
bondPositionCount: 105,
},
},
]),
},
name: "Длинные суммы",
};
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",
export const IndependentFreshness: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
args: {
accounts: brokerageAccountCards(
[
syntheticAccount,
{
...syntheticAccount,
id: "waiting",
name: "Новый счёт",
portfolioSummary: null,
},
},
{
resourceKey: "portfolio/waiting",
dataRevision: "0",
stateVersion: "waiting",
availability: "missing",
freshness: "unknown",
lastSuccessfulAt: null,
sync: { id: "waiting", state: "running", errorCode: null },
},
],
),
},
};
],
[
{
availability: "complete",
dataRevision: "1",
freshness: "stale",
lastSuccessfulAt: "2026-09-24T10:30:00Z",
resourceKey: "portfolio/storybook-account",
stateVersion: "failed",
sync: {
errorCode: "TBANK_UNAVAILABLE",
id: "failed",
state: "failed",
},
},
{
availability: "missing",
dataRevision: "0",
freshness: "unknown",
lastSuccessfulAt: null,
resourceKey: "portfolio/waiting",
stateVersion: "waiting",
sync: { errorCode: null, id: "waiting", state: "running" },
},
],
),
},
name: "Независимая свежесть и ошибка сводок",
}
/* eslint-enable unicorn/no-null */);
@@ -2,7 +2,9 @@ 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 { resource } from "@/test/resource";
import { brokerageAccountCards } from "../../model/display";
import { BrokerageAccountList } from "./BrokerageAccountList";
@@ -16,36 +18,40 @@ describe("BrokerageAccountList", () => {
{
id: "account-1",
name: "Основной",
type: "BROKERAGE",
openedOn: "2024-08-13",
portfolioSummary: {
stockPositionCount: 5,
bondPositionCount: 12,
stockPositionCount: 5,
totalsByCurrency: [
{ currency: "RUB", value: "1500" },
{ currency: "USD", value: "20" },
{ currency: "EUR", value: "5" },
],
},
},
{
id: "account-2",
name: "Недоступный",
type: "BROKERAGE",
openedOn: null,
portfolioSummary: null,
},
{
id: "account-3",
name: "Пустой",
type: "BROKERAGE",
openedOn: null,
portfolioSummary: {
totalsByCurrency: [],
stockPositionCount: 2,
bondPositionCount: 0,
},
},
(/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
id: "account-2",
name: "Недоступный",
openedOn: null,
portfolioSummary: null,
type: "BROKERAGE",
}
/* eslint-enable unicorn/no-null */),
(/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
id: "account-3",
name: "Пустой",
openedOn: null,
portfolioSummary: {
bondPositionCount: 0,
stockPositionCount: 2,
totalsByCurrency: [],
},
type: "BROKERAGE",
}
/* eslint-enable unicorn/no-null */),
])}
/>
</MemoryRouter>
@@ -65,18 +71,18 @@ describe("BrokerageAccountList", () => {
expect(screen.getByText("Нет текущих сумм")).toBeInTheDocument();
expect(screen.getAllByText("Открыть счет")).toHaveLength(3);
const available = within(screen.getByRole("link", { name: /Основной/ }));
expect(available.getByText("Акции").nextElementSibling).toHaveTextContent(
expect(available.getAllByRole("definition")[0]).toHaveTextContent(
"5",
);
expect(
available.getByText("Облигации").nextElementSibling,
available.getAllByRole("definition")[1],
).toHaveTextContent("12");
const unvalued = within(screen.getByRole("link", { name: /Пустой/ }));
expect(unvalued.getByText("Акции").nextElementSibling).toHaveTextContent(
expect(unvalued.getAllByRole("definition")[0]).toHaveTextContent(
"2",
);
expect(
unvalued.getByText("Облигации").nextElementSibling,
unvalued.getAllByRole("definition")[1],
).toHaveTextContent("0");
expect(
within(screen.getByRole("link", { name: /Недоступный/ })).queryByText(
@@ -88,21 +94,23 @@ describe("BrokerageAccountList", () => {
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" }],
},
})),
["fresh", "stale"].map(id => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
id,
name: id,
openedOn: null,
portfolioSummary: {
bondPositionCount: 0,
stockPositionCount: 1,
totalsByCurrency: [{ currency: "RUB", value: "10" }],
},
type: "BROKERAGE" as const,
}
/* eslint-enable unicorn/no-null */))),
[
resource(null, { resourceKey: "portfolio/fresh", freshness: "fresh" })
resource(null, { freshness: "fresh", resourceKey: "portfolio/fresh" })
.meta,
resource(null, { resourceKey: "portfolio/stale", freshness: "stale" })
resource(null, { freshness: "stale", resourceKey: "portfolio/stale" })
.meta,
],
);
@@ -1,9 +1,13 @@
import { Card, Group, SimpleGrid, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { Card, Group, SimpleGrid, Stack, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { formatDate, formatMoney, formatSnapshotTime } from "@/shared/lib";
import type { BrokerageAccountCard } from "../../model/display";
import { accountTypeKey } from "../../model/display";
import classes from "./BrokerageAccountList.module.css";
@@ -31,18 +35,18 @@ const BrokerageAccountSummary: FC<BrokerageAccountSummaryProps> = (props) => {
return (
<Stack className={classes.summary} gap={4}>
{summary.totals.map((total) => (
{summary.totals.map(total => (
<Text className={classes.total} fw={700} key={total.currency}>
{formatMoney(total)}
</Text>
))}
{summary.remainingCurrencyCount ? (
{!!(summary.remainingCurrencyCount) && ((
<Text c="dimmed" size="sm">
{t("accounts.remainingCurrencies", {
count: summary.remainingCurrencyCount,
})}
</Text>
) : null}
))}
</Stack>
);
};
@@ -53,37 +57,37 @@ const BrokerageAccountList: FC<BrokerageAccountListProps> = (props) => {
return (
<SimpleGrid className={classes.list} cols={1} spacing="lg">
{accounts.map(({ account, summary, positionCounts, source }) => (
{accounts.map(({ account, positionCounts, source, summary }) => (
<Card
component={Link}
to={`/accounts/${account.id}`}
key={account.id}
className={classes.card}
component={Link}
key={account.id}
padding="xl"
radius="lg"
to={`/accounts/${account.id}`}
withBorder
>
<Stack className={classes.identity} gap="sm">
<Group justify="space-between" wrap="nowrap" gap="sm">
<Text className={classes.kicker} size="xs" fw={700}>
<Group gap="sm" justify="space-between" wrap="nowrap">
<Text className={classes.kicker} fw={700} size="xs">
{t(accountTypeKey(account.type))}
</Text>
<svg
aria-hidden="true"
className={classes.accountIcon}
viewBox="0 0 24 24"
fill="none"
focusable="false"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
strokeWidth="1.5"
viewBox="0 0 24 24"
>
<rect x="3" y="5" width="18" height="15" rx="3" />
<rect height="15" rx="3" width="18" x="3" y="5" />
<path d="M3 9h18M7 15h3M14 5V3H7a4 4 0 0 0-4 4" />
</svg>
</Group>
<Text component="h2" className={classes.name} fw={700}>
<Text className={classes.name} component="h2" fw={700}>
{account.name}
</Text>
</Stack>
@@ -92,27 +96,27 @@ const BrokerageAccountList: FC<BrokerageAccountListProps> = (props) => {
{t("accounts.currentValue")}
</Text>
<BrokerageAccountSummary summary={summary} />
{source?.lastSuccessfulAt ? (
<Text size="xs" c="dimmed">
{!!(source?.lastSuccessfulAt) && ((
<Text c="dimmed" size="xs">
{t("investment.sourceTime", {
date: formatSnapshotTime(source.lastSuccessfulAt),
})}
</Text>
) : null}
{source?.sync.state === "running" ||
source?.sync.state === "queued" ? (
<Text size="xs" role="status">
))}
{(source?.sync.state === "running"
|| source?.sync.state === "queued") && ((
<Text role="status" size="xs">
{t("accounts.refreshing")}
</Text>
) : null}
{source?.sync.state === "failed" ? (
))}
{(source?.sync.state === "failed") && ((
<Text size="xs">{t("accounts.refreshError")}</Text>
) : null}
{source?.freshness === "stale" ? (
))}
{(source?.freshness === "stale") && ((
<Text size="xs">{t("investment.stale")}</Text>
) : null}
))}
</Stack>
{positionCounts ? (
{!!(positionCounts) && ((
<dl className={classes.positions}>
<div className={classes.stocks}>
<dt>{t("accounts.stocks")}</dt>
@@ -127,18 +131,18 @@ const BrokerageAccountList: FC<BrokerageAccountListProps> = (props) => {
</dd>
</div>
</dl>
) : null}
<Group className={classes.footer} justify="space-between" gap="sm">
{account.openedOn ? (
))}
<Group className={classes.footer} gap="sm" justify="space-between">
{!!(account.openedOn) && ((
<Text c="dimmed" size="xs">
{t("accounts.openedOn", {
date: formatDate(account.openedOn),
})}
</Text>
) : null}
<Text component="span" className={classes.open} size="sm" fw={600}>
))}
<Text className={classes.open} component="span" fw={600} size="sm">
{t("accounts.openAccount")}
<span className={classes.arrow} aria-hidden="true">
<span aria-hidden="true" className={classes.arrow}>
→
</span>
</Text>
@@ -1,18 +1,20 @@
import { renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { http, HttpResponse } 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";
describe("useBrokerageEvents", () => {
it("does not fetch events without an account ID", async () => {
configureAuthClient({
accessToken: () => "token",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
const requested = vi.fn(() => HttpResponse.json({ events: [] }));
server.use(
@@ -27,29 +29,31 @@ describe("useBrokerageEvents", () => {
it("loads future cash events through the authenticated query seam", async () => {
configureAuthClient({
accessToken: () => "token",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/events", () =>
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" },
},
],
}),
resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
accountId: "account-1",
calculatedAt: "2026-08-14T00:00:00Z",
events: [
{
date: "2026-09-01",
dateKind: "registry",
displayName: "Сбер",
figi: "figi-1",
instrumentUid: null,
logoName: "sber3.png",
projectedAmount: { currency: "RUB", value: "12.34" },
ticker: "SBER",
type: "dividend",
},
],
}
/* eslint-enable unicorn/no-null */)),
),
),
);
@@ -60,17 +64,19 @@ describe("useBrokerageEvents", () => {
await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(result.current.data?.events).toEqual([
{
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" },
},
(/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
date: "2026-09-01",
dateKind: "registry",
displayName: "Сбер",
figi: "figi-1",
instrumentUid: null,
logoName: "sber3.png",
projectedAmount: { currency: "RUB", value: "12.34" },
ticker: "SBER",
type: "dividend",
}
/* eslint-enable unicorn/no-null */),
]);
});
});
@@ -1,10 +1,10 @@
import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
type EventsEndpoint =
paths["/api/v1/brokerage-accounts/{accountId}/events"]["get"];
type BrokerageEvent = NonNullable<
EventsEndpoint["responses"][200]["content"]["application/json"]["data"]
>["events"][number];
type EventsEndpoint
= paths["/api/v1/brokerage-accounts/{accountId}/events"]["get"];
function useBrokerageEvents(
accountId: string | undefined,
@@ -1,7 +1,10 @@
import { EntryCard } from "@wealthledger/ui";
import type { FC } from "react";
import { EntryCard } from "@wealthledger/ui";
import { useTranslation } from "react-i18next";
import { formatDate, formatMoney, instrumentLogoUrl } from "@/shared/lib";
import type { BrokerageEvent } from "../api/useBrokerageEvents";
type BrokerageEventCardProps = { event: BrokerageEvent };
@@ -14,7 +17,7 @@ const BrokerageEventCard: FC<BrokerageEventCardProps> = (props) => {
const metadata = [
date,
event.dateKind === "registry" ? t("events.dateKind.registry") : null,
event.dateKind === "registry" ? t("events.dateKind.registry") : /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null,
event.isin,
event.account?.name,
]
@@ -23,19 +26,19 @@ const BrokerageEventCard: FC<BrokerageEventCardProps> = (props) => {
return (
<EntryCard
title={`${t(`events.type.${event.type}`)} · ${event.displayName}`}
metadata={metadata}
imageSrc={instrumentLogoUrl(event.logoName)}
initial={(
(event.ticker ?? event.displayName).trim()[0] ?? "?"
).toUpperCase()}
imageSrc={instrumentLogoUrl(event.logoName)}
metadata={metadata}
title={[t(`events.type.${event.type}`), event.displayName].join(" · ")}
tone="neutral"
value={
event.projectedAmount
? formatMoney(event.projectedAmount)
: t("events.noAmount")
}
valueLabel={t("events.projectedAmount")}
tone="neutral"
/>
);
};
@@ -1,32 +1,53 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { MemoryRouter } from "react-router";
import type { BrokerageEvent } from "../../api/useBrokerageEvents";
import { BrokerageEventsPreview } from "./BrokerageEventsPreview";
const syntheticEvent = {
type: "coupon",
const syntheticEvent = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
date: "2026-10-15",
dateKind: "event",
displayName: "Учебные облигации",
figi: null,
instrumentUid: null,
ticker: "DEMO",
displayName: "Учебные облигации",
logoName: null,
isin: "RU000A0JX0J2",
logoName: null,
projectedAmount: { currency: "RUB", value: "850.50" },
} satisfies BrokerageEvent;
ticker: "DEMO",
type: "coupon",
}
/* eslint-enable unicorn/no-null */) satisfies BrokerageEvent;
const eventsPath = "/accounts/storybook-account/events";
const meta = {
title: "Product/RecentEvents",
component: BrokerageEventsPreview,
tags: ["autodocs"],
args: {
events: {
items: [
syntheticEvent,
{
...syntheticEvent,
date: "2026-11-01",
dateKind: "registry",
displayName: "Учебные технологии",
projectedAmount: { currency: "RUB", value: "1200" },
ticker: "EXAMPLE",
type: "dividend",
},
],
state: "loaded",
to: eventsPath,
},
},
argTypes: {
events: { control: false },
},
component: BrokerageEventsPreview,
decorators: [
(Story) => (
Story => (
<MemoryRouter initialEntries={["/accounts/storybook-account"]}>
<Story />
</MemoryRouter>
@@ -40,24 +61,8 @@ const meta = {
},
},
},
args: {
events: {
state: "loaded",
to: eventsPath,
items: [
syntheticEvent,
{
...syntheticEvent,
type: "dividend",
date: "2026-11-01",
dateKind: "registry",
ticker: "EXAMPLE",
displayName: "Учебные технологии",
projectedAmount: { currency: "RUB", value: "1200" },
},
],
},
},
tags: ["autodocs"],
title: "Product/RecentEvents",
} satisfies Meta<typeof BrokerageEventsPreview>;
export default meta;
@@ -77,8 +82,8 @@ export const Loaded: Story = {
};
export const Loading: Story = {
name: "Загрузка раздела",
args: { events: { state: "loading", to: eventsPath } },
name: "Загрузка раздела",
parameters: {
docs: {
description: {
@@ -90,8 +95,8 @@ export const Loading: Story = {
};
export const Failed: Story = {
name: "Ошибка получения событий",
args: { events: { state: "error", to: eventsPath } },
name: "Ошибка получения событий",
parameters: {
docs: {
description: {
@@ -103,8 +108,8 @@ export const Failed: Story = {
};
export const Empty: Story = {
name: "Нет ближайших событий",
args: { events: { state: "empty", to: eventsPath } },
name: "Нет ближайших событий",
parameters: {
docs: {
description: {
@@ -115,40 +120,44 @@ export const Empty: Story = {
},
};
export const MissingAmount: Story = {
name: "Событие без ожидаемой суммы",
args: {
events: {
state: "loaded",
to: eventsPath,
items: [{ ...syntheticEvent, projectedAmount: null }],
},
},
parameters: {
docs: {
description: {
story:
"Событие остаётся видимым при неизвестной ожидаемой сумме. Отсутствие оценки не подменяется нулевой выплатой.",
export const MissingAmount: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
args: {
events: {
items: [{ ...syntheticEvent, projectedAmount: null }],
state: "loaded",
to: eventsPath,
},
},
},
};
export const LongEvent: Story = {
name: "Длинное название на узком экране",
args: {
events: {
state: "loaded",
to: eventsPath,
items: [
{
...syntheticEvent,
type: "offer",
displayName:
"Учебные облигации компании с очень длинным названием инструмента",
projectedAmount: null,
name: "Событие без ожидаемой суммы",
parameters: {
docs: {
description: {
story:
"Событие остаётся видимым при неизвестной ожидаемой сумме. Отсутствие оценки не подменяется нулевой выплатой.",
},
],
},
},
},
};
}
/* eslint-enable unicorn/no-null */);
export const LongEvent: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
args: {
events: {
items: [
{
...syntheticEvent,
displayName:
"Учебные облигации компании с очень длинным названием инструмента",
projectedAmount: null,
type: "offer",
},
],
state: "loaded",
to: eventsPath,
},
},
name: "Длинное название на узком экране",
}
/* eslint-enable unicorn/no-null */);
@@ -1,26 +1,30 @@
import type { FC } from "react";
import { Alert, Button, Skeleton, Stack, Text } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { formatSnapshotTime } from "@/shared/lib";
import type { BrokerageEvent } from "../../api/useBrokerageEvents";
import { BrokerageEventCard } from "../BrokerageEventCard";
type BrokerageEventsPreviewProps = {
events: BrokerageEventsPreviewState;
};
type BrokerageEventsPreviewState =
| { state: "loading" | "error" | "empty"; to: string }
| {
state: "loaded" | "partial";
to: string;
lastSuccessfulAt?: string | null;
stale?: boolean;
refreshError?: boolean;
items: BrokerageEvent[];
};
type BrokerageEventsPreviewState
= | {
items: BrokerageEvent[];
lastSuccessfulAt?: null | string;
refreshError?: boolean;
stale?: boolean;
state: "loaded" | "partial";
to: string;
}
| { state: "empty" | "error" | "loading"; to: string };
const BrokerageEventsPreview: FC<BrokerageEventsPreviewProps> = (props) => {
const { events } = props;
@@ -28,53 +32,51 @@ const BrokerageEventsPreview: FC<BrokerageEventsPreviewProps> = (props) => {
return (
<Stack gap="sm">
{events.state === "loaded" ? (
{(events.state === "loaded") && ((
<>
{events.lastSuccessfulAt ? (
<Text size="xs" c="dimmed">
{!!(events.lastSuccessfulAt) && ((
<Text c="dimmed" size="xs">
{t("investment.sourceTime", {
date: formatSnapshotTime(events.lastSuccessfulAt),
})}
</Text>
) : null}
{events.stale ? <Text size="xs">{t("investment.stale")}</Text> : null}
{events.refreshError ? (
))}
{!!(events.stale) && (<Text size="xs">{t("investment.stale")}</Text>)}
{!!(events.refreshError) && ((
<Text role="status">{t("accounts.refreshError")}</Text>
) : null}
))}
</>
) : null}
{events.state === "loading" ? (
))}
{(events.state === "loading") && ((
<LoadingSkeleton label={t("events.recentLoading")}>
{[0, 1, 2].map((index) => (
<Skeleton key={index} height={48} radius="sm" />
{["first", "second", "third"].map(placeholder => (
<Skeleton height={48} key={placeholder} radius="sm" />
))}
</LoadingSkeleton>
) : null}
{events.state === "error" ? (
))}
{(events.state === "error") && ((
<Alert color="red">{t("events.recentError")}</Alert>
) : null}
{events.state === "empty" ? (
))}
{(events.state === "empty") && ((
<Text c="dimmed">{t("events.recentEmpty")}</Text>
) : null}
{events.state === "partial" ? (
))}
{(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([
event.account?.id,
event.type,
event.date,
event.instrumentUid,
event.figi,
event.ticker,
event.logoName,
])}
event={event}
/>
))
: null}
))}
{(events.state === "loaded" || events.state === "partial") && (events.items.map(event => (
<BrokerageEventCard
event={event}
key={JSON.stringify([
event.account?.id,
event.type,
event.date,
event.instrumentUid,
event.figi,
event.ticker,
event.logoName,
])}
/>
)))}
<Button component={Link} to={events.to} variant="subtle">
{t("events.open")}
</Button>
+16 -16
View File
@@ -1,24 +1,11 @@
import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
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 useResourceQuery({
meta: { accessGroup: "brokerage" },
...apiQueryClient.queryOptions(
"get",
"/api/v1/brokerage-accounts/{accountId}/income-summary",
{ params: { path: { accountId: accountId ?? "" } } },
),
enabled: Boolean(accountId),
staleTime: 30_000,
});
}
type IncomeSummary = NonNullable<
paths["/api/v1/brokerage-accounts/{accountId}/income-summary"]["get"]["responses"][200]["content"]["application/json"]["data"]
>;
function useIncomeAnalytics(
accountId: string | undefined,
@@ -41,6 +28,19 @@ function useIncomeAnalytics(
});
}
function useIncomeSummary(accountId: string | undefined) {
return useResourceQuery({
meta: { accessGroup: "brokerage" },
...apiQueryClient.queryOptions(
"get",
"/api/v1/brokerage-accounts/{accountId}/income-summary",
{ params: { path: { accountId: accountId ?? "" } } },
),
enabled: Boolean(accountId),
staleTime: 30_000,
});
}
export {
type IncomeAnalytics,
type IncomeSummary,
@@ -1,10 +1,12 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { http, HttpResponse } 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,
@@ -12,25 +14,25 @@ import {
} from "./usePortfolio";
const snapshot: Portfolio = {
positions: [],
totalsByCurrency: [{ currency: "RUB", value: "123.000000001" }],
cashBalances: [],
structure: { currencies: [], unvaluedCategories: [] },
lastSuccessfulAt: "2026-08-14T00:00:00Z",
isStale: false,
lastSuccessfulAt: "2026-08-14T00:00:00Z",
positions: [],
structure: { currencies: [], unvaluedCategories: [] },
totalsByCurrency: [{ currency: "RUB", value: "123.000000001" }],
};
function auth() {
configureAuthClient({
accessToken: () => "synthetic",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
}
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)[] = [];
const modes: (null | string)[] = [];
let observations = 0;
server.use(
http.get(
@@ -47,16 +49,17 @@ describe("persistent resource query lifecycle", () => {
},
),
);
const { wrapper, queryClient } = createQueryWrapper();
const { queryClient, wrapper } = 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"));
// eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response.
expect(modes).toEqual([null, "observe", "observe"]);
expect(queryClient.getQueryCache().getAll()).toHaveLength(1);
expect(
queryClient.getQueryData(portfolioQueryOptions("a").queryKey),
).toMatchObject({ meta: { stateVersion: "new" }, data: snapshot });
).toMatchObject({ data: snapshot, meta: { stateVersion: "new" } });
});
it("does not convert missing or failed source data to empty financial success", async () => {
auth();
@@ -65,9 +68,9 @@ describe("persistent resource query lifecycle", () => {
HttpResponse.json(
resource(null, {
sync: {
errorCode: "TBANK_UNAVAILABLE",
id: "work",
state: "failed",
errorCode: "TBANK_UNAVAILABLE",
},
}),
),
@@ -82,20 +85,22 @@ describe("persistent resource query lifecycle", () => {
expect(result.current.status).toBe("pending");
expect(result.current.isPending).toBe(true);
expect(result.current.isLoading).toBe(false);
expect(result.current.transport).toEqual({
status: "success",
fetchStatus: "idle",
error: null,
});
expect(result.current.transport).toEqual((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
error: null,
fetchStatus: "idle",
status: "success",
}
/* eslint-enable unicorn/no-null */));
expect(result.current.meta?.availability).toBe("missing");
});
it("keeps the refetch envelope while exposing the refreshed resource payload", async () => {
auth();
let ready = false;
let isReady = false;
const refreshed = resource(snapshot, { stateVersion: "ready" });
server.use(
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
HttpResponse.json(ready ? refreshed : resource(null)),
HttpResponse.json(isReady ? refreshed : resource(null)),
),
);
const { result } = renderHook(() => usePortfolio("a"), {
@@ -109,7 +114,7 @@ describe("persistent resource query lifecycle", () => {
expect(missing.status).toBe("success");
expect(missing.data).toEqual(resource(null));
expect(missing.data?.data).toBeNull();
ready = true;
isReady = true;
const loaded = await result.current.refetch();
expect(loaded.data).toEqual(refreshed);
expect(loaded.data?.data?.totalsByCurrency).toEqual(
@@ -124,10 +129,8 @@ describe("persistent resource query lifecycle", () => {
});
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;
});
const { promise: blocked, resolve: release } = Promise.withResolvers<void>();
server.use(
http.get(
"*/api/v1/brokerage-accounts/:accountId/portfolio",
@@ -151,19 +154,15 @@ describe("persistent resource query lifecycle", () => {
});
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;
});
let isDenied = false;
const { promise: blocked, resolve: release } = Promise.withResolvers<void>();
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));
return isDenied && params.accountId === "a" ? HttpResponse.json({ code: "NOT_FOUND" }, { status: 404 }) : HttpResponse.json(resource(snapshot));
},
),
);
@@ -173,7 +172,7 @@ describe("persistent resource query lifecycle", () => {
{ wrapper },
);
await waitFor(() => expect(result.current.a.data).toEqual(snapshot));
denied = true;
isDenied = true;
await act(() => result.current.a.refetch());
await waitFor(() => expect(result.current.a.data).toBeUndefined());
await act(async () => {
@@ -1,18 +1,20 @@
import { renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { http, HttpResponse } 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";
describe("usePortfolio", () => {
it("loads the account portfolio", async () => {
configureAuthClient({
accessToken: () => "token",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
const { result } = renderHook(() => usePortfolio("account-1"), {
wrapper: createQueryWrapper().wrapper,
@@ -25,8 +27,8 @@ describe("usePortfolio", () => {
it("keeps the current connection snapshot after a background refetch error", async () => {
configureAuthClient({
accessToken: () => "token",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
let calls = 0;
server.use(
@@ -35,12 +37,12 @@ describe("usePortfolio", () => {
return calls === 1
? HttpResponse.json(
resource({
lastSuccessfulAt: "2026-08-14T00:00:00Z",
cashBalances: [],
isStale: false,
totalsByCurrency: [],
lastSuccessfulAt: "2026-08-14T00:00:00Z",
positions: [],
structure: { currencies: [], unvaluedCategories: [] },
cashBalances: [],
totalsByCurrency: [],
}),
)
: HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 });
@@ -1,4 +1,5 @@
import { describe, expect, it } from "vitest";
import { formatShare } from "./display";
describe("portfolio display helpers", () => {
+7 -6
View File
@@ -1,17 +1,18 @@
import type { Portfolio } from "../api/usePortfolio";
const PERCENT_SCALE = 100;
type Money = Portfolio["totalsByCurrency"][number];
function formatShare(
numerator: Money | null,
denominator: Money | null,
): string | null {
if (!numerator || !denominator) return null;
): null | string {
if (!numerator || !denominator) return /* eslint-disable-line unicorn/no-null -- The existing formatter contract uses null for unavailable data. */ null;
const total = Number(denominator.value);
if (!Number.isFinite(total) || total <= 0) return null;
// biome-ignore lint/style/noMagicNumbers: obvious conversion of a ratio to percent.
const percent = (Number(numerator.value) / total) * 100;
if (!Number.isFinite(percent)) return null;
if (!Number.isFinite(total) || total <= 0) return /* eslint-disable-line unicorn/no-null -- The existing formatter contract uses null for unavailable data. */ null;
const percent = (Number(numerator.value) / total) * PERCENT_SCALE;
if (!Number.isFinite(percent)) return /* eslint-disable-line unicorn/no-null -- The existing formatter contract uses null for unavailable data. */ null;
const rounded = new Intl.NumberFormat("ru-RU", {
maximumFractionDigits: 1,
}).format(percent);
+46 -44
View File
@@ -6,6 +6,8 @@ import {
useResourceQuery,
} from "@/shared/api";
const MIN_STOCK_SEARCH_LENGTH = 2;
type StockPeriod = NonNullable<
NonNullable<
paths["/api/v1/stocks/{uid}/candles"]["get"]["parameters"]["query"]
@@ -14,15 +16,6 @@ type StockPeriod = NonNullable<
const STOCK_STALE_TIME_MS = 30_000;
function useStockSearch(query: string) {
return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/stocks", {
params: { query: { query } },
}),
enabled: query.length >= 2,
staleTime: STOCK_STALE_TIME_MS,
});
}
function stockQueryOptions(uid: string) {
return {
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}", {
@@ -31,21 +24,9 @@ function stockQueryOptions(uid: string) {
staleTime: STOCK_STALE_TIME_MS,
};
}
function useStocks(uids: string[]) {
const uniqueUids = [...new Set(uids)];
const queries = useAuthenticatedQueries(uniqueUids.map(stockQueryOptions));
return new Map(
queries.map((query, index) => [
uniqueUids[index],
unwrapResourceResult(query).data,
]),
);
}
function useStock(identifier: string) {
const isUid =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
const isUid
= /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
identifier,
);
@@ -62,15 +43,7 @@ function useStock(identifier: string) {
});
return isUid ? byUid : byTicker;
}
function useStockQuote(uid: string) {
return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/quote", {
params: { path: { uid } },
}),
enabled: Boolean(uid),
staleTime: STOCK_STALE_TIME_MS,
});
}
function useStockCandles(uid: string, period: StockPeriod) {
return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/candles", {
@@ -80,16 +53,7 @@ function useStockCandles(uid: string, period: StockPeriod) {
staleTime: STOCK_STALE_TIME_MS,
});
}
function useStockPosition(uid: string) {
return useResourceQuery({
meta: { accessGroup: "brokerage" },
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/position", {
params: { path: { uid } },
}),
enabled: Boolean(uid),
staleTime: STOCK_STALE_TIME_MS,
});
}
function useStockCompany(uid: string) {
return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/company", {
@@ -109,8 +73,46 @@ function useStockDividends(uid: string) {
staleTime: STOCK_STALE_TIME_MS,
});
}
function useStockPosition(uid: string) {
return useResourceQuery({
meta: { accessGroup: "brokerage" },
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/position", {
params: { path: { uid } },
}),
enabled: Boolean(uid),
staleTime: STOCK_STALE_TIME_MS,
});
}
function useStockQuote(uid: string) {
return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/quote", {
params: { path: { uid } },
}),
enabled: Boolean(uid),
staleTime: STOCK_STALE_TIME_MS,
});
}
function useStocks(uids: string[]) {
const uniqueUids = [...new Set(uids)];
const queries = useAuthenticatedQueries(uniqueUids.map(uniqueUid => stockQueryOptions(uniqueUid)));
return new Map(
queries.map((query, index) => [
/* eslint-disable-line security/detect-object-injection -- This is a positional index into the local array, not a user-supplied object key. */ uniqueUids[index],
unwrapResourceResult(query).data,
]),
);
}
function useStockSearch(query: string) {
return useResourceQuery({
...apiQueryClient.queryOptions("get", "/api/v1/stocks", {
params: { query: { query } },
}),
enabled: query.length >= MIN_STOCK_SEARCH_LENGTH,
staleTime: STOCK_STALE_TIME_MS,
});
}
export {
export { MIN_STOCK_SEARCH_LENGTH,
type StockPeriod,
useStock,
useStockCandles,
@@ -118,6 +120,6 @@ export {
useStockDividends,
useStockPosition,
useStockQuote,
useStockSearch,
useStocks,
useStockSearch,
};
+2 -2
View File
@@ -1,4 +1,4 @@
export {
export { MIN_STOCK_SEARCH_LENGTH,
type StockPeriod,
useStock,
useStockCandles,
@@ -6,6 +6,6 @@ export {
useStockDividends,
useStockPosition,
useStockQuote,
useStockSearch,
useStocks,
useStockSearch,
} from "./api/queries";
+11 -10
View File
@@ -1,23 +1,24 @@
import { createContext, useContext } from "react";
import { createContext, use } from "react";
import type { paths } from "@/shared/api";
type User =
paths["/api/v1/auth/me"]["get"]["responses"][200]["content"]["application/json"];
type AuthContextValue = {
user: User | null;
accessToken: string | null;
ready: boolean;
accessToken: string | undefined;
login: (email: string, password: string) => Promise<void>;
register: (email: string, password: string) => Promise<void>;
logout: () => Promise<void>;
ready: boolean;
refresh: () => Promise<boolean>;
register: (email: string, password: string) => Promise<void>;
user: undefined | User;
};
const AuthContext = createContext<AuthContextValue | null>(null);
type User
= paths["/api/v1/auth/me"]["get"]["responses"][200]["content"]["application/json"];
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
function useAuth() {
const context = useContext(AuthContext);
const context = use(AuthContext);
if (!context) throw new Error("AuthProvider is required");
return context;
}
export { AuthContext, type User, useAuth };
export { AuthContext, useAuth, type User };
+50 -81
View File
@@ -1,12 +1,15 @@
import type { FC, PropsWithChildren } from "react";
import { QueryClientProvider, useQueryClient } from "@tanstack/react-query";
import { act, renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import type { FC, PropsWithChildren } from "react";
import { http, HttpResponse } from "msw";
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 } from "./auth";
import { useAuth } from "./auth-context";
@@ -14,14 +17,22 @@ const bankCardsKey = apiQueryClient.queryOptions("get", "/api/v1/bank-cards", {
params: { query: { includeArchived: "false" } },
}).queryKey;
function createAuthWrapper(queryClient: ReturnType<typeof createTestQueryClient>): FC<PropsWithChildren> {
return props => (
<QueryClientProvider client={queryClient}>
<AuthProvider>{props.children}</AuthProvider>
</QueryClientProvider>
);
}
describe("AuthProvider", () => {
it("authorizes requests after restoring the initial session", async () => {
let authorization: string | null = null;
let authorization: null | string = /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null;
server.use(
http.post("*/api/v1/auth/refresh", () =>
HttpResponse.json({
accessToken: "restored-token",
user: { id: "user-1", email: "user@example.com" },
user: { email: "user@example.com", id: "user-1" },
}),
),
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
@@ -30,16 +41,8 @@ describe("AuthProvider", () => {
}),
);
const queryClient = createTestQueryClient();
const wrapper: FC<PropsWithChildren> = (props) => {
const { children } = props;
return (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
};
const { result, rerender } = renderHook(
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
const { rerender, result } = renderHook(
() => ({ ...useAuth(), queryClient: useQueryClient() }),
{ wrapper },
);
@@ -61,21 +64,13 @@ describe("AuthProvider", () => {
const queryClient = createTestQueryClient();
queryClient.setQueryData(["cached-query"], { value: "stale" });
queryClient.setQueryData(bankCardsKey, [{ id: "bank-card-1" }]);
const wrapper: FC<PropsWithChildren> = (props) => {
const { children } = props;
return (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
};
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(result.current.ready).toBe(true));
expect(result.current.user).toBeNull();
expect(result.current.accessToken).toBeNull();
expect(result.current.user).toBeUndefined();
expect(result.current.accessToken).toBeUndefined();
expect(queryClient.getQueryData(["cached-query"])).toBeUndefined();
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
});
@@ -88,7 +83,7 @@ describe("AuthProvider", () => {
return refreshCalls === 1
? HttpResponse.json({
accessToken: "restored-token",
user: { id: "user-1", email: "user@example.com" },
user: { email: "user@example.com", id: "user-1" },
})
: HttpResponse.error();
}),
@@ -99,15 +94,7 @@ describe("AuthProvider", () => {
const queryClient = createTestQueryClient();
queryClient.setQueryData(["cached-query"], { value: "stale" });
queryClient.setQueryData(bankCardsKey, [{ id: "bank-card-1" }]);
const wrapper: FC<PropsWithChildren> = (props) => {
const { children } = props;
return (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
};
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() =>
@@ -116,8 +103,8 @@ describe("AuthProvider", () => {
const response = await apiClient.GET("/api/v1/brokerage-accounts");
expect(response.response.status).toBe(401);
await waitFor(() => expect(result.current.user).toBeNull());
expect(result.current.accessToken).toBeNull();
await waitFor(() => expect(result.current.user).toBeUndefined());
expect(result.current.accessToken).toBeUndefined();
expect(queryClient.getQueryData(["cached-query"])).toBeUndefined();
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
});
@@ -127,7 +114,7 @@ describe("AuthProvider", () => {
http.post("*/api/v1/auth/refresh", () =>
HttpResponse.json({
accessToken: "test-token",
user: { id: "user-1", email: "user@example.com" },
user: { email: "user@example.com", id: "user-1" },
}),
),
);
@@ -147,14 +134,7 @@ describe("AuthProvider", () => {
});
queryClient.setQueryData(portfolioKey, { source: "current-connection" });
queryClient.setQueryData(bankCardsKey, [{ id: "bank-card-1" }]);
const wrapper: FC<PropsWithChildren> = (props) => {
const { children } = props;
return (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
};
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(result.current.accessToken).toBe("test-token"));
@@ -163,8 +143,8 @@ describe("AuthProvider", () => {
]);
await act(() => result.current.logout());
expect(result.current.user).toBeNull();
expect(result.current.accessToken).toBeNull();
expect(result.current.user).toBeUndefined();
expect(result.current.accessToken).toBeUndefined();
expect(queryClient.getQueryData(statusKey)).toBeUndefined();
expect(queryClient.getQueryData(portfolioKey)).toBeUndefined();
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
@@ -177,10 +157,7 @@ describe("AuthProvider", () => {
])(
"serializes late refresh (failure=%s, login=%s)",
async (failure, loginAfterLogout) => {
let release!: () => void;
const pending = new Promise<void>((resolve) => {
release = resolve;
});
const { promise: pending, resolve: release } = Promise.withResolvers<void>();
let calls = 0;
const order: string[] = [];
server.use(
@@ -194,7 +171,7 @@ describe("AuthProvider", () => {
? HttpResponse.error()
: HttpResponse.json({
accessToken: "a",
user: { id: "a", email: "a@example.com" },
user: { email: "a@example.com", id: "a" },
});
}),
http.post("*/api/v1/auth/logout", () => {
@@ -205,7 +182,7 @@ describe("AuthProvider", () => {
order.push("login-cookie");
return HttpResponse.json({
accessToken: "b",
user: { id: "b", email: "b@example.com" },
user: { email: "b@example.com", id: "b" },
});
}),
http.get("*/api/v1/brokerage-accounts", () =>
@@ -213,22 +190,20 @@ describe("AuthProvider", () => {
),
);
const queryClient = createTestQueryClient();
const wrapper: FC<PropsWithChildren> = ({ children }) => (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(result.current.ready).toBe(true));
const oldRequest = apiClient
.GET("/api/v1/brokerage-accounts")
.catch(() => null);
// eslint-disable-next-line unicorn/prefer-await -- Attach rejection handling before releasing the deliberately pending query.
.catch(() => {});
await waitFor(() => expect(order).toContain("refresh-start"));
let logout!: Promise<void>;
act(() => {
logout = result.current.logout();
});
await waitFor(() => expect(result.current.user).toBeNull());
await waitFor(() => expect(result.current.user).toBeUndefined());
let login!: Promise<void>;
act(() => {
login = loginAfterLogout
@@ -239,8 +214,8 @@ describe("AuthProvider", () => {
release();
await Promise.all([oldRequest, logout, login]);
});
expect(result.current.user?.id ?? null).toBe(
loginAfterLogout ? "b" : null,
expect(result.current.user?.id ?? /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null).toBe(
loginAfterLogout ? "b" : /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null,
);
expect(order).toEqual([
"refresh-start",
@@ -257,16 +232,12 @@ describe("AuthProvider", () => {
http.post("*/api/v1/auth/refresh", () =>
HttpResponse.json({
accessToken: identity,
user: { id: identity, email: `${identity}@example.com` },
user: { email: `${identity}@example.com`, id: identity },
}),
),
);
const queryClient = createTestQueryClient();
const wrapper: FC<PropsWithChildren> = ({ children }) => (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(result.current.ready).toBe(true));
queryClient.setQueryData(bankCardsKey, [{ id: "a-card" }]);
@@ -274,14 +245,16 @@ describe("AuthProvider", () => {
expect(queryClient.getQueryData(bankCardsKey)).toEqual([{ id: "a-card" }]);
let release!: (value: string) => void;
const pending = queryClient
.fetchQuery({
.query({
queryFn: () => {
const deferred = Promise.withResolvers<string>();
release = deferred.resolve;
return deferred.promise;
},
queryKey: ["pending-finance"],
queryFn: () =>
new Promise<string>((resolve) => {
release = resolve;
}),
})
.catch(() => null);
// eslint-disable-next-line unicorn/prefer-await -- Attach rejection handling before releasing the deliberately pending query.
.catch(() => {});
identity = "b";
await act(() => result.current.refresh());
release("a-data");
@@ -296,7 +269,7 @@ describe("AuthProvider", () => {
http.post("*/api/v1/auth/refresh", () =>
HttpResponse.json({
accessToken: identity,
user: { id: identity, email: `${identity}@example.com` },
user: { email: `${identity}@example.com`, id: identity },
}),
),
http.get("*/api/v1/bank-cards", () =>
@@ -304,11 +277,7 @@ describe("AuthProvider", () => {
),
);
const queryClient = createTestQueryClient();
const wrapper: FC<PropsWithChildren> = (props) => (
<QueryClientProvider client={queryClient}>
<AuthProvider>{props.children}</AuthProvider>
</QueryClientProvider>
);
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
const { result } = renderHook(
() => ({
auth: useAuth(),
+46 -39
View File
@@ -1,13 +1,16 @@
import { useQueryClient } from "@tanstack/react-query";
import type { FC, PropsWithChildren } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useRef, useState } from "react";
import { apiClient, configureAuthClient, type paths } from "@/shared/api";
import { AuthContext, type User } from "./auth-context";
type Authentication =
paths["/api/v1/auth/login"]["post"]["responses"][200]["content"]["application/json"];
type Credentials =
paths["/api/v1/auth/login"]["post"]["requestBody"]["content"]["application/json"];
type Authentication
= paths["/api/v1/auth/login"]["post"]["responses"][200]["content"]["application/json"];
type Credentials
= paths["/api/v1/auth/login"]["post"]["requestBody"]["content"]["application/json"];
async function request(
path: "/api/v1/auth/login" | "/api/v1/auth/register",
email: string,
@@ -24,32 +27,34 @@ async function request(
const AuthProvider: FC<PropsWithChildren> = (props) => {
const { children } = props;
const queryClient = useQueryClient();
const [user, setUser] = useState<User | null>(null);
const [accessToken, setAccessToken] = useState<string | null>(null);
const accessTokenRef = useRef<string | null>(null);
const [user, setUser] = useState<undefined | User>(undefined);
const [accessToken, setAccessToken] = useState<string | undefined>(undefined);
const accessTokenRef = useRef<string | undefined>(undefined);
const [ready, setReady] = useState(false);
const generation = useRef(0);
const userRef = useRef<User | null>(null);
const authQueue = useRef<Promise<unknown>>(Promise.resolve());
const refreshPromise = useRef<Promise<boolean> | null>(null);
const generationRef = useRef(0);
const userRef = useRef<undefined | User>(undefined);
const authQueueRef = useRef<Promise<unknown>>(Promise.resolve());
const refreshPromiseRef = useRef<Promise<boolean> | undefined>(undefined);
// Cookie-writing requests share ordering, including across tabs with Web Locks.
const serialize = useCallback(<T,>(run: () => Promise<T>): Promise<T> => {
const next = authQueue.current.then(async () =>
// eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering.
const next = authQueueRef.current.then(async () =>
"locks" in navigator
? navigator.locks.request("wealth-ledger-refresh", run)
: run(),
);
authQueue.current = next.catch(() => undefined);
// eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering.
authQueueRef.current = next.catch(() => {});
return next;
}, []);
const applyAuthentication = useCallback(
(authentication: Authentication) => {
const changedIdentity =
userRef.current && userRef.current.id !== authentication.user.id;
const changedIdentity
= userRef.current && userRef.current.id !== authentication.user.id;
accessTokenRef.current = authentication.accessToken;
if (changedIdentity) {
generation.current += 1;
generationRef.current += 1;
queryClient.removeQueries({ type: "inactive" });
queryClient.getMutationCache().clear();
void queryClient.resetQueries();
@@ -61,36 +66,38 @@ const AuthProvider: FC<PropsWithChildren> = (props) => {
[queryClient],
);
const clearSession = useCallback(() => {
generation.current += 1;
userRef.current = null;
setUser(null);
setAccessToken(null);
accessTokenRef.current = null;
generationRef.current += 1;
userRef.current = undefined;
setUser(undefined);
setAccessToken(undefined);
accessTokenRef.current = undefined;
queryClient.clear();
}, [queryClient]);
const refresh = useCallback((): Promise<boolean> => {
if (refreshPromise.current) return refreshPromise.current;
const started = generation.current;
if (refreshPromiseRef.current) return refreshPromiseRef.current;
const started = generationRef.current;
const pending = serialize(async () => {
if (started !== generation.current) return false;
if (started !== generationRef.current) return false;
try {
const { data } = await apiClient.POST("/api/v1/auth/refresh");
if (started !== generation.current) return false;
if (started !== generationRef.current) return false;
if (!data) {
clearSession();
return false;
}
applyAuthentication(data);
return true;
} catch {
if (started === generation.current) clearSession();
}
catch {
if (started === generationRef.current) clearSession();
return false;
}
// eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering.
}).finally(() => {
if (refreshPromise.current === pending) refreshPromise.current = null;
if (refreshPromiseRef.current === pending) refreshPromiseRef.current = undefined;
});
refreshPromise.current = pending;
refreshPromiseRef.current = pending;
return pending;
}, [applyAuthentication, clearSession, serialize]);
@@ -104,10 +111,10 @@ const AuthProvider: FC<PropsWithChildren> = (props) => {
password: string,
) {
clearSession();
const started = generation.current;
const started = generationRef.current;
await serialize(async () => {
const authentication = await request(path, email, password);
if (started === generation.current) applyAuthentication(authentication);
if (started === generationRef.current) applyAuthentication(authentication);
});
}
@@ -121,25 +128,25 @@ const AuthProvider: FC<PropsWithChildren> = (props) => {
useEffect(() => {
configureAuthClient({
accessToken: () => accessTokenRef.current,
generation: () => generation.current,
refresh,
clear: clearSession,
generation: () => generationRef.current,
refresh,
});
});
useEffect(() => () => configureAuthClient(null), []);
useEffect(() => () => configureAuthClient(), []);
return (
<AuthContext
value={{
user,
accessToken,
ready,
login: (email, password) =>
authenticate("/api/v1/auth/login", email, password),
logout,
ready,
refresh,
register: (email, password) =>
authenticate("/api/v1/auth/register", email, password),
logout,
refresh,
user,
}}
>
{children}
+16 -12
View File
@@ -1,6 +1,9 @@
import { z } from "zod";
import { validationMessage } from "@/shared/i18n";
const EMAIL_PART_COUNT = 2;
const ASCII_SPACE = 32;
const ASCII_DELETE = 127;
const MAX_EMAIL_LENGTH = 254;
@@ -8,10 +11,11 @@ const MIN_PASSWORD_BYTES = 12;
const MAX_PASSWORD_BYTES = 72;
function isEmailCharacterInvalid(character: string): boolean {
const codePoint = character.codePointAt(0);
return (
/\s/.test(character) ||
character.charCodeAt(0) < ASCII_SPACE ||
character.charCodeAt(0) === ASCII_DELETE
/\s/.test(character)
|| (codePoint !== undefined && codePoint < ASCII_SPACE)
|| codePoint === ASCII_DELETE
);
}
@@ -21,18 +25,18 @@ const email = z
.toLowerCase()
.max(MAX_EMAIL_LENGTH)
.refine(
(value) =>
value.split("@").length === 2 &&
value.split("@").every(Boolean) &&
!value.split("").some(isEmailCharacterInvalid),
value =>
value.split("@").length === EMAIL_PART_COUNT
&& value.split("@").every(Boolean)
&& value.split("").every(element => !isEmailCharacterInvalid(element)),
{ error: validationMessage("auth.validation.invalidEmail") },
);
const password = z
.string()
.refine(
(value) =>
new TextEncoder().encode(value).length >= MIN_PASSWORD_BYTES &&
new TextEncoder().encode(value).length <= MAX_PASSWORD_BYTES,
value =>
new TextEncoder().encode(value).length >= MIN_PASSWORD_BYTES
&& new TextEncoder().encode(value).length <= MAX_PASSWORD_BYTES,
{ error: validationMessage("auth.validation.invalidPasswordLength") },
);
@@ -42,10 +46,10 @@ const loginSchema = z.object({
passwordConfirmation: z.string().optional(),
});
const registerSchema = loginSchema.refine(
(value) => value.password === value.passwordConfirmation,
value => value.password === value.passwordConfirmation,
{
path: ["passwordConfirmation"],
error: validationMessage("auth.validation.passwordsDoNotMatch"),
path: ["passwordConfirmation"],
},
);
@@ -2,6 +2,7 @@ import { MantineProvider } from "@mantine/core";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { describe, expect, it, vi } from "vitest";
import { AuthForm } from "./AuthForm";
describe("AuthForm", () => {
@@ -10,7 +11,7 @@ describe("AuthForm", () => {
render(
<MantineProvider>
<MemoryRouter>
<AuthForm register onSubmit={onSubmit} />
<AuthForm onSubmit={onSubmit} register />
</MemoryRouter>
</MantineProvider>,
);
+9 -6
View File
@@ -1,10 +1,12 @@
import type { FC } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { Alert, Button, PasswordInput, Stack, TextInput } from "@mantine/core";
import type { FC } from "react";
import { useState } from "react";
import { FormProvider, type Resolver, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import {
type AuthFormValues,
loginSchema,
@@ -13,12 +15,12 @@ import {
import classes from "./AuthForm.module.css";
type AuthFormProps = {
register?: true;
onSubmit: (email: string, password: string) => Promise<void>;
register?: true;
};
const AuthForm: FC<AuthFormProps> = (props) => {
const { register, onSubmit } = props;
const { onSubmit, register } = props;
const { t } = useTranslation();
const schema = register ? registerSchema : loginSchema;
const methods = useForm<AuthFormValues>({
@@ -27,7 +29,7 @@ const AuthForm: FC<AuthFormProps> = (props) => {
const {
formState: { errors, isSubmitting },
} = methods;
const [submitError, setSubmitError] = useState<string | null>(null);
const [submitError, setSubmitError] = useState<null | string>(null);
return (
<FormProvider {...methods}>
<form
@@ -35,7 +37,8 @@ const AuthForm: FC<AuthFormProps> = (props) => {
setSubmitError(null);
try {
await onSubmit(values.email, values.password);
} catch {
}
catch {
setSubmitError(t("auth.requestError"));
}
})}
@@ -60,7 +63,7 @@ const AuthForm: FC<AuthFormProps> = (props) => {
/>
)}
{submitError && <Alert color="red">{submitError}</Alert>}
<Button type="submit" loading={isSubmitting}>
<Button loading={isSubmitting} type="submit">
{t(register ? "auth.register" : "auth.login")}
</Button>
<Button
@@ -1,5 +1,7 @@
import { Paper, Stack, Title } from "@mantine/core";
import type { FC, PropsWithChildren } from "react";
import { Paper, Stack, Title } from "@mantine/core";
import classes from "./AuthPageLayout.module.css";
type AuthPageLayoutProps = PropsWithChildren<{ title: string }>;
+4 -2
View File
@@ -1,5 +1,7 @@
import type { FC } from "react";
import { useLocation, useNavigate } from "react-router";
import { useAuth } from "../model/auth-context";
import { AuthForm } from "./AuthForm/AuthForm";
@@ -7,8 +9,8 @@ const LoginForm: FC = () => {
const { login } = useAuth();
const navigate = useNavigate();
const location = useLocation();
const returnTo =
(location.state as { returnTo?: string } | null)?.returnTo ?? "/accounts";
const returnTo
= (location.state as null | { returnTo?: string })?.returnTo ?? "/accounts";
return (
<AuthForm
+5 -3
View File
@@ -1,5 +1,7 @@
import type { FC } from "react";
import { useLocation, useNavigate } from "react-router";
import { useAuth } from "../model/auth-context";
import { AuthForm } from "./AuthForm/AuthForm";
@@ -7,16 +9,16 @@ const RegisterForm: FC = () => {
const { register } = useAuth();
const navigate = useNavigate();
const location = useLocation();
const returnTo =
(location.state as { returnTo?: string } | null)?.returnTo ?? "/accounts";
const returnTo
= (location.state as null | { returnTo?: string })?.returnTo ?? "/accounts";
return (
<AuthForm
register
onSubmit={async (email, password) => {
await register(email, password);
await navigate(returnTo, { replace: true });
}}
register
/>
);
};
@@ -1,5 +1,7 @@
import { describe, expect, it, vi } from "vitest";
import { resource } from "@/test/resource";
import { section } from "./section";
describe("instrument source and transport presentation", () => {
@@ -9,9 +11,9 @@ describe("instrument source and transport presentation", () => {
const data = availability === "missing" ? undefined : { rows: [] };
const state = section({
data,
meta: resource(data, { availability }).meta,
isError: false,
isFetching: false,
meta: resource(data, { availability }).meta,
refetch: vi.fn(),
});
expect(state.loading).toBe(availability === "missing");
@@ -23,37 +25,39 @@ describe("instrument source and transport presentation", () => {
const retry = vi.fn();
const refetch = vi.fn();
const meta = resource([], {
sync: { id: "work", state: "failed", errorCode: "TBANK_UNAVAILABLE" },
sync: { errorCode: "TBANK_UNAVAILABLE", id: "work", state: "failed" },
}).meta;
const state = section(
{ data: [], meta, isError: false, isFetching: false, refetch },
{ data: [], isError: false, isFetching: false, meta, refetch },
retry,
);
expect(state).toMatchObject({
hasData: true,
loading: false,
error: true,
refreshing: false,
hasData: true,
lastSuccessfulAt: meta.lastSuccessfulAt,
loading: false,
refreshing: false,
});
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(),
});
const state = section((
{
data: undefined,
isError: false,
isFetching: false,
meta: resource(null, {
sync: { errorCode: "TBANK_UNAVAILABLE", id: "work", state: "failed" },
}).meta,
refetch: vi.fn(),
}
));
expect(state).toMatchObject({
error: true,
hasData: false,
loading: false,
error: true,
});
});
});
@@ -1,46 +1,46 @@
import type { paths } from "@/shared/api";
type Meta =
paths["/api/v1/tbank-sync/{id}"]["get"]["responses"][200]["content"]["application/json"]["resources"][number];
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;
hasData: boolean;
lastSuccessfulAt?: null | string;
loading: boolean;
partial?: boolean;
refreshing: boolean;
retry: () => void;
sourceError?: boolean;
stale?: boolean;
};
function section(
query: {
data: unknown;
meta?: Meta;
isError: boolean;
isFetching: boolean;
meta?: Meta;
refetch: () => unknown;
},
retry?: () => unknown,
): SectionState {
const error = query.isError || query.meta?.sync.state === "failed";
const isError = 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,
error: isError,
hasData: Boolean(query.data),
loading: !query.data && !error,
error,
lastSuccessfulAt: query.meta?.lastSuccessfulAt,
loading: !query.data && !isError,
partial: query.meta?.availability === "partial",
refreshing:
Boolean(query.data) &&
(query.isFetching ||
query.meta?.sync.state === "running" ||
query.meta?.sync.state === "queued"),
Boolean(query.data)
&& (query.isFetching
|| query.meta?.sync.state === "running"
|| query.meta?.sync.state === "queued"),
retry: () => {
void (retry ?? query.refetch)();
},
sourceError: query.meta?.sync.state === "failed",
stale: query.meta?.freshness === "stale",
};
}
export { type SectionState, section };
export { section, type SectionState };
+25 -24
View File
@@ -1,38 +1,39 @@
import type { BrokerageOperation } from "@/entities/broker-operation";
import type { paths } from "@/shared/api";
import type { SectionState } from "./section";
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 InstrumentChartVm = {
averageLine: null | number;
candles?: Candles;
candlesState: SectionState;
chartData: ChartRow[];
hasIncompleteCandle: boolean;
period: string;
position?: Position;
priceRows: ChartRow[];
setPeriod: (value: string) => void;
};
type InstrumentEventsVm = {
eventRows: BrokerageOperation[];
filter: string;
hasPrevious: boolean;
onNext: () => void;
onPrevious: () => void;
operations?: { hasNext: boolean };
operationsState: SectionState;
setFilter: (value: string) => void;
};
type InstrumentPositionVm = {
position?: Position;
positionState: SectionState;
};
type InstrumentChartVm = {
candles?: Candles;
candlesState: SectionState;
chartData: ChartRow[];
priceRows: ChartRow[];
period: string;
setPeriod: (value: string) => void;
averageLine: number | null;
hasIncompleteCandle: boolean;
position?: Position;
};
type InstrumentEventsVm = {
operations?: { hasNext: boolean };
operationsState: SectionState;
filter: string;
setFilter: (value: string) => void;
eventRows: BrokerageOperation[];
hasPrevious: boolean;
onPrevious: () => void;
onNext: () => void;
};
type Position = NonNullable<
paths["/api/v1/stocks/{uid}/position"]["get"]["responses"][200]["content"]["application/json"]["data"]
>;
export type { InstrumentChartVm, InstrumentEventsVm, InstrumentPositionVm };
@@ -1,5 +1,6 @@
import { useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import {
brokerageOperationsQueryOptions,
type OperationCategory,
@@ -14,37 +15,38 @@ function useInstrumentOperations(
) {
const scope = `${uid}:${filter}`;
const [pagination, setPagination] = useState<{
scope: string;
cursors: string[];
}>({ scope, cursors: [] });
scope: string;
}>({ cursors: [], scope });
const cursors = pagination.scope === scope ? pagination.cursors : [];
const client = useQueryClient();
const firstPage = { instrumentUid: uid, categories, limit: 20 };
const firstPage = { categories, instrumentUid: uid, limit: 20 };
const operations = useBrokerageOperations(uid ? "all" : undefined, {
...firstPage,
cursor: cursors.at(-1),
});
const retry = (retryScreen: () => unknown) => {
if (apiErrorCode(operations.error) === "INVALID_OPERATIONS_CURSOR") {
setPagination({ scope, cursors: [] });
setPagination({ cursors: [], scope });
void client.invalidateQueries({
queryKey: brokerageOperationsQueryOptions("all", firstPage).queryKey,
exact: true,
queryKey: brokerageOperationsQueryOptions("all", firstPage).queryKey,
});
} else void retryScreen();
}
else void retryScreen();
};
return {
operations,
retry,
hasPrevious: cursors.length > 0,
onPrevious: () => setPagination({ scope, cursors: cursors.slice(0, -1) }),
onNext: () => {
if (operations.data?.nextCursor)
setPagination({
scope,
cursors: [...cursors, operations.data.nextCursor],
scope,
});
},
onPrevious: () => setPagination({ cursors: cursors.slice(0, -1), scope }),
operations,
retry,
};
}
@@ -1,3 +1,5 @@
import type { FC } from "react";
import { AreaChart } from "@mantine/charts";
import {
Accordion,
@@ -7,185 +9,187 @@ import {
Table,
Text,
} from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { formatDecimal, formatMoney } from "@/shared/lib";
import type { InstrumentChartVm } from "../model/types";
import classes from "./InstrumentDetails.module.css";
import { InstrumentSection } from "./InstrumentSection.view";
type InstrumentChartProps = { vm: InstrumentChartVm; priceUnit?: "percent" };
type InstrumentChartProps = { priceUnit?: "percent"; vm: InstrumentChartVm };
const InstrumentChart: FC<InstrumentChartProps> = (props) => {
const { vm } = props;
const { t } = useTranslation();
const priceLabel = (value: string) => {
if (props.priceUnit === "percent") return `${formatDecimal(value)} %`;
const currency = vm.candles?.currency;
return formatMoney(currency ? { currency, value } : undefined);
};
return (
<InstrumentSection
title={t("stock.chart")}
state={vm.candlesState}
large
controls={
controls={(
<div className={classes.controls}>
<SegmentedControl
aria-label={t("stock.period")}
value={vm.period}
onChange={vm.setPeriod}
data={["month", "halfYear", "year", "all"].map((value) => ({
value,
data={["month", "halfYear", "year", "all"].map(value => ({
label: t(`stock.periods.${value}`),
value,
}))}
onChange={vm.setPeriod}
value={vm.period}
/>
</div>
}
)}
large
state={vm.candlesState}
title={t("stock.chart")}
>
{vm.candles ? (
vm.chartData.length ? (
<>
<AreaChart
h={310}
data={vm.chartData}
dataKey="date"
series={[
{ name: "price", color: "blue.6", label: t("stock.price") },
]}
curveType="linear"
withDots={vm.chartData.length === 1}
withGradient
gridAxis="y"
tickLine="none"
tooltipAnimationDuration={0}
areaProps={{ isAnimationActive: false }}
yAxisProps={{ domain: ["auto", "auto"], width: 64 }}
referenceLines={
vm.averageLine === null
? []
: [
{
y: vm.averageLine,
ifOverflow: "extendDomain",
color: "orange.7",
label: t("stock.averageLine"),
},
]
}
valueFormatter={(value) =>
new Intl.NumberFormat("ru-RU", {
maximumFractionDigits: 4,
}).format(value)
}
aria-label={t(
props.priceUnit === "percent"
? "bond.chartLabel"
: "stock.chartLabel",
{
currency:
{!!(vm.candles) && ((
vm.chartData.length > 0
? (
<>
<AreaChart
areaProps={{ isAnimationActive: false }}
aria-label={t(
props.priceUnit === "percent"
? "bond.chartLabel"
: "stock.chartLabel",
{
currency:
props.priceUnit === "percent"
? t("bond.percentOfNominal")
: (vm.candles.currency ?? ""),
},
)}
/>
<Text size="xs" c="dimmed" mt="sm">
{t(
props.priceUnit === "percent"
? "bond.chartNote"
: "stock.chartNote",
)}
</Text>
{vm.hasIncompleteCandle ? (
<Text size="xs" c="dimmed">
{t("stock.incomplete")}
</Text>
) : null}
{vm.averageLine !== null ? (
<Text size="sm" mt="xs">
{t("stock.averageLine")}:{" "}
{formatMoney(vm.position?.averagePurchasePrice ?? null)}
</Text>
) : null}
<Accordion
className={classes.priceTable}
variant="contained"
radius="md"
>
<Accordion.Item value="prices">
<Accordion.Control>
<Text fw={600}>{t("stock.priceTable")}</Text>
<Text size="xs" c="dimmed">
{t("stock.priceTableHint", { count: vm.chartData.length })}
},
)}
curveType="linear"
data={vm.chartData}
dataKey="date"
gridAxis="y"
h={310}
referenceLines={
vm.averageLine === null
? []
: [
{
color: "orange.7",
ifOverflow: "extendDomain",
label: t("stock.averageLine"),
y: vm.averageLine,
},
]
}
series={[
{ color: "blue.6", label: t("stock.price"), name: "price" },
]}
tickLine="none"
tooltipAnimationDuration={0}
valueFormatter={value =>
new Intl.NumberFormat("ru-RU", {
maximumFractionDigits: 4,
}).format(value)}
withDots={vm.chartData.length === 1}
withGradient
yAxisProps={{ domain: ["auto", "auto"], width: 64 }}
/>
<Text c="dimmed" mt="sm" size="xs">
{t(
props.priceUnit === "percent"
? "bond.chartNote"
: "stock.chartNote",
)}
</Text>
{!!(vm.hasIncompleteCandle) && ((
<Text c="dimmed" size="xs">
{t("stock.incomplete")}
</Text>
</Accordion.Control>
<Accordion.Panel>
<ScrollArea.Autosize
mah={360}
type="auto"
viewportProps={{
tabIndex: 0,
role: "region",
"aria-label": t("stock.priceTable"),
}}
>
<Table
striped
highlightOnHover
stickyHeader
verticalSpacing="sm"
horizontalSpacing="md"
>
<Table.Thead>
<Table.Tr>
<Table.Th>{t("stock.date")}</Table.Th>
<Table.Th>{t("stock.price")}</Table.Th>
<Table.Th>{t("stock.candle")}</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{vm.priceRows.map((candle) => (
<Table.Tr key={candle.time}>
<Table.Td>{candle.date}</Table.Td>
<Table.Td>
{props.priceUnit === "percent"
? `${formatDecimal(candle.close)} %`
: formatMoney(
vm.candles?.currency
? {
value: candle.close,
currency: vm.candles.currency,
}
: null,
)}
</Table.Td>
<Table.Td>
<Badge
variant="light"
color={candle.isComplete ? "gray" : "blue"}
size="sm"
>
{t(
candle.isComplete
? "stock.complete"
: "stock.forming",
)}
</Badge>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
</ScrollArea.Autosize>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
</>
) : (
<Text c="dimmed">
{t(
vm.candlesState.partial
? "investment.partial"
: "stock.noCandles",
)}
</Text>
)
) : null}
))}
{vm.averageLine !== null && ((
<Text mt="xs" size="sm">
{t("stock.averageLine")}
:
{" "}
{formatMoney(vm.position?.averagePurchasePrice)}
</Text>
))}
<Accordion
className={classes.priceTable}
radius="md"
variant="contained"
>
<Accordion.Item value="prices">
<Accordion.Control>
<Text fw={600}>{t("stock.priceTable")}</Text>
<Text c="dimmed" size="xs">
{t("stock.priceTableHint", { count: vm.chartData.length })}
</Text>
</Accordion.Control>
<Accordion.Panel>
<ScrollArea.Autosize
mah={360}
type="auto"
viewportProps={{
"aria-label": t("stock.priceTable"),
"role": "region",
"tabIndex": 0,
}}
>
<Table
highlightOnHover
horizontalSpacing="md"
stickyHeader
striped
verticalSpacing="sm"
>
<Table.Thead>
<Table.Tr>
<Table.Th>{t("stock.date")}</Table.Th>
<Table.Th>{t("stock.price")}</Table.Th>
<Table.Th>{t("stock.candle")}</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{vm.priceRows.map(candle => (
<Table.Tr key={candle.time}>
<Table.Td>{candle.date}</Table.Td>
<Table.Td>
{priceLabel(candle.close)}
</Table.Td>
<Table.Td>
<Badge
color={candle.isComplete ? "gray" : "blue"}
size="sm"
variant="light"
>
{t(
candle.isComplete
? "stock.complete"
: "stock.forming",
)}
</Badge>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
</ScrollArea.Autosize>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
</>
)
: (
<Text c="dimmed">
{t(
vm.candlesState.partial
? "investment.partial"
: "stock.noCandles",
)}
</Text>
)
))}
</InstrumentSection>
);
};
@@ -1,16 +1,20 @@
import { Button, Group, SegmentedControl, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { Button, Group, SegmentedControl, Stack, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { LedgerEntryRow } from "@/entities/broker-operation";
import type { InstrumentEventsVm } from "../model/types";
import classes from "./InstrumentDetails.module.css";
import { InstrumentSection } from "./InstrumentSection.view";
type InstrumentEventsProps = {
vm: InstrumentEventsVm;
incomeLabel?: string;
incomeFilter?: string;
historyNote?: string;
incomeFilter?: string;
incomeLabel?: string;
vm: InstrumentEventsVm;
};
const InstrumentEvents: FC<InstrumentEventsProps> = (props) => {
@@ -18,73 +22,75 @@ const InstrumentEvents: FC<InstrumentEventsProps> = (props) => {
const { t } = useTranslation();
return (
<InstrumentSection
title={t("stock.history")}
state={vm.operationsState}
controls={
controls={(
<div className={classes.controls}>
<SegmentedControl
aria-label={t("stock.eventFilter")}
value={vm.filter}
onChange={vm.setFilter}
data={[
"all",
"trades",
props.incomeFilter ?? "dividends",
"other",
].map((value) => ({
value,
].map(value => ({
label:
value === (props.incomeFilter ?? "dividends") &&
props.incomeLabel
value === (props.incomeFilter ?? "dividends")
&& props.incomeLabel
? props.incomeLabel
: t(`stock.filters.${value}`),
value,
}))}
onChange={vm.setFilter}
value={vm.filter}
/>
</div>
}
)}
state={vm.operationsState}
title={t("stock.history")}
>
{vm.operations ? (
{!!(vm.operations) && ((
<>
<Text size="xs" c="dimmed">
<Text c="dimmed" size="xs">
{props.historyNote ?? t("stock.historyNote")}
</Text>
{vm.eventRows.length ? (
<Stack gap="sm" mt="md">
{vm.eventRows.map((event) => (
<LedgerEntryRow
key={`${event.account?.id}:${event.id}`}
operation={event}
withDetails
/>
))}
</Stack>
) : (
<Text c="dimmed" py="lg">
{t(
vm.operationsState.partial
? "investment.partial"
: "stock.noOperations",
{vm.eventRows.length > 0
? (
<Stack gap="sm" mt="md">
{vm.eventRows.map(event => (
<LedgerEntryRow
key={`${event.account?.id}:${event.id}`}
operation={event}
withDetails
/>
))}
</Stack>
)
: (
<Text c="dimmed" py="lg">
{t(
vm.operationsState.partial
? "investment.partial"
: "stock.noOperations",
)}
</Text>
)}
</Text>
)}
<Group justify="space-between" mt="md">
<Button
variant="default"
disabled={!vm.hasPrevious || vm.operationsState.refreshing}
onClick={vm.onPrevious}
variant="default"
>
{t("stock.previous")}
</Button>
<Button
variant="default"
disabled={!vm.operations.hasNext || vm.operationsState.refreshing}
onClick={vm.onNext}
variant="default"
>
{t("stock.next")}
</Button>
</Group>
</>
) : null}
))}
</InstrumentSection>
);
};
@@ -1,31 +1,35 @@
import { Alert, Anchor, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { Alert, Anchor, Stack, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { formatDecimal, formatMoney, formatSnapshotTime } from "@/shared/lib";
import type { InstrumentPositionVm } from "../model/types";
import classes from "./InstrumentDetails.module.css";
import { InstrumentSection } from "./InstrumentSection.view";
type InstrumentPositionProps = {
vm: InstrumentPositionVm;
returnNote?: string;
quantityLabel?: string;
returnNote?: string;
vm: InstrumentPositionVm;
};
const InstrumentPosition: FC<InstrumentPositionProps> = (props) => {
const { vm } = props;
const { t } = useTranslation();
if (vm.position && !vm.position.accounts.length) return null;
if (vm.position && vm.position.accounts.length === 0) return;
return (
<InstrumentSection title={t("stock.position")} state={vm.positionState}>
{vm.position ? (
<InstrumentSection state={vm.positionState} title={t("stock.position")}>
{!!(vm.position) && ((
<Stack gap="md">
{vm.position.isStale ? (
{!!(vm.position.isStale) && ((
<Alert color="orange">{t("portfolio.staleWarning")}</Alert>
) : null}
))}
<div className={`${classes.metrics} ${classes.holding}`}>
<div>
<Text size="sm" c="dimmed">
<Text c="dimmed" size="sm">
{props.quantityLabel ?? t("stock.quantity")}
</Text>
<Text className={classes.metricValue}>
@@ -33,7 +37,7 @@ const InstrumentPosition: FC<InstrumentPositionProps> = (props) => {
</Text>
</div>
<div>
<Text size="sm" c="dimmed">
<Text c="dimmed" size="sm">
{t("stock.value")}
</Text>
<Text className={classes.metricValue}>
@@ -41,7 +45,7 @@ const InstrumentPosition: FC<InstrumentPositionProps> = (props) => {
</Text>
</div>
<div>
<Text size="sm" c="dimmed">
<Text c="dimmed" size="sm">
{t("stock.average")}
</Text>
<Text className={classes.metricValue}>
@@ -49,89 +53,93 @@ const InstrumentPosition: FC<InstrumentPositionProps> = (props) => {
</Text>
</div>
<div>
<Text size="sm" c="dimmed">
<Text c="dimmed" size="sm">
{t("stock.openReturn")}
</Text>
<Text
className={classes.metricValue}
c={
vm.position.absoluteReturn?.value.startsWith("-")
? "red.8"
: "green.8"
}
className={classes.metricValue}
>
{formatMoney(vm.position.absoluteReturn)}
</Text>
{vm.position.returnPercent !== null ? (
{vm.position.returnPercent !== null && ((
<Text size="sm">
{formatDecimal(vm.position.returnPercent)} %
{formatDecimal(vm.position.returnPercent)}
{" "}
%
</Text>
) : null}
))}
</div>
</div>
<Text size="xs" c="dimmed">
<Text c="dimmed" size="xs">
{props.returnNote ?? t("stock.openReturnNote")}
</Text>
<div>
{vm.position.accounts.map((account) => (
{vm.position.accounts.map(account => (
<div className={classes.accountRow} key={account.account?.id}>
{account.account ? (
<Anchor
component={Link}
to={`/accounts/${encodeURIComponent(account.account.id)}`}
>
{account.account.name}
</Anchor>
) : (
<Text>{t("stock.portfolio")}</Text>
)}
{account.account
? (
<Anchor
component={Link}
to={`/accounts/${encodeURIComponent(account.account.id)}`}
>
{account.account.name}
</Anchor>
)
: (
<Text>{t("stock.portfolio")}</Text>
)}
<div>
<Text size="xs" c="dimmed">
<Text c="dimmed" size="xs">
{props.quantityLabel ?? t("stock.quantity")}
</Text>
<Text>{formatDecimal(account.quantity)}</Text>
</div>
<div>
<Text size="xs" c="dimmed">
<Text c="dimmed" size="xs">
{t("stock.average")}
</Text>
<Text>{formatMoney(account.averagePurchasePrice)}</Text>
</div>
<div>
<Text size="xs" c="dimmed">
<Text c="dimmed" size="xs">
{t("stock.value")}
</Text>
<Text>{formatMoney(account.currentValue)}</Text>
</div>
<div>
<Text size="xs" c="dimmed">
<Text c="dimmed" size="xs">
{t("stock.openReturn")}
</Text>
<Text
c={
account.absoluteReturn?.value.startsWith("-")
? "red.8"
: undefined
(account.absoluteReturn?.value.startsWith("-")) ? ("red.8") : undefined
}
>
{formatMoney(account.absoluteReturn)}
</Text>
{account.returnPercent !== null ? (
{account.returnPercent !== null && ((
<Text size="xs">
{formatDecimal(account.returnPercent)} %
{formatDecimal(account.returnPercent)}
{" "}
%
</Text>
) : null}
))}
</div>
</div>
))}
</div>
<Text size="xs" c="dimmed">
<Text c="dimmed" size="xs">
{t("stock.snapshotAt", {
date: formatSnapshotTime(vm.position.observedAt),
})}
</Text>
</Stack>
) : null}
))}
</InstrumentSection>
);
};
@@ -1,3 +1,5 @@
import type { FC, PropsWithChildren, ReactNode } from "react";
import {
Alert,
Button,
@@ -9,28 +11,31 @@ import {
Title,
} from "@mantine/core";
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";
const CHART_SKELETON_HEIGHT_PX = 280;
const SECTION_SKELETON_HEIGHT_PX = 65;
type InstrumentSectionProps = PropsWithChildren<{
title: string;
state: SectionState;
controls?: ReactNode;
large?: boolean;
embedded?: boolean;
large?: boolean;
state: SectionState;
title: string;
}>;
const InstrumentSection: FC<InstrumentSectionProps> = (props) => {
const { t } = useTranslation();
const readError = t(props.state.hasData ? "accounts.refreshError" : "stock.sectionError");
return (
<Paper
component="section"
className={props.embedded ? classes.embeddedSection : classes.section}
component="section"
withBorder={!props.embedded}
>
<Group justify="space-between" mb="md">
@@ -39,63 +44,63 @@ const InstrumentSection: FC<InstrumentSectionProps> = (props) => {
</Title>
{props.controls}
</Group>
{props.state.stale ? (
{!!(props.state.stale) && ((
<Text size="xs">{t("investment.stale")}</Text>
) : null}
{props.state.partial ? (
))}
{!!(props.state.partial) && ((
<Text role="status">{t("investment.partial")}</Text>
) : null}
{props.state.lastSuccessfulAt ? (
<Text size="xs" c="dimmed">
))}
{!!(props.state.lastSuccessfulAt) && ((
<Text c="dimmed" size="xs">
{t("investment.sourceTime", {
date: formatSnapshotTime(props.state.lastSuccessfulAt),
})}
</Text>
) : null}
{props.state.refreshing ? (
<Text role="status" size="xs" c="dimmed">
))}
{!!(props.state.refreshing) && ((
<Text c="dimmed" role="status" size="xs">
{t("accounts.refreshing")}
</Text>
) : null}
{props.state.error ? (
<Alert color="orange" mb="sm" role="status" aria-live="polite">
))}
{!!(props.state.error) && ((
<Alert aria-live="polite" color="orange" mb="sm" role="status">
<Group justify="space-between">
<Text size="sm">
{props.state.sourceError
? t("investment.syncFailed")
: props.state.hasData
? t("accounts.refreshError")
: t("stock.sectionError")}
: readError}
</Text>
<Button
disabled={props.state.refreshing}
onClick={props.state.retry}
size="xs"
variant="default"
onClick={props.state.retry}
disabled={props.state.refreshing}
>
{t("accounts.retry")}
</Button>
</Group>
</Alert>
) : null}
{props.state.loading ? (
<LoadingSkeleton
label={t("stock.loadingSection", { section: props.title })}
>
<Stack>
<Skeleton
h={
props.large
? CHART_SKELETON_HEIGHT_PX
: SECTION_SKELETON_HEIGHT_PX
}
/>
<Skeleton h={14} w="60%" />
</Stack>
</LoadingSkeleton>
) : (
props.children
)}
))}
{props.state.loading
? (
<LoadingSkeleton
label={t("stock.loadingSection", { section: props.title })}
>
<Stack>
<Skeleton
h={
props.large
? CHART_SKELETON_HEIGHT_PX
: SECTION_SKELETON_HEIGHT_PX
}
/>
<Skeleton h={14} w="60%" />
</Stack>
</LoadingSkeleton>
)
: (
props.children
)}
</Paper>
);
};
@@ -1,12 +1,13 @@
import type { QueryClient } from "@tanstack/react-query";
import {
apiQueryClient,
invalidateApiRequests,
type paths,
} from "@/shared/api";
type TbankConnectionStatus =
paths["/api/v1/tbank-connection"]["get"]["responses"][200]["content"]["application/json"];
type TbankConnectionStatus
= paths["/api/v1/tbank-connection"]["get"]["responses"][200]["content"]["application/json"];
const brokerageAccountsPath = "/api/v1/brokerage-accounts";
@@ -20,26 +21,26 @@ function commitTbankConnectionBoundary(
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"),
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 }) => {
const [method, path] = queryKey;
return (
method === "get" &&
typeof path === "string" &&
(path.startsWith("/api/v1/tbank-sync") ||
path === "/api/v1/bonds" ||
path.startsWith("/api/v1/bonds/") ||
path === "/api/v1/stocks" ||
path.startsWith("/api/v1/stocks/") ||
path === brokerageAccountsPath ||
path.startsWith(`${brokerageAccountsPath}/`))
method === "get"
&& typeof path === "string"
&& (path.startsWith("/api/v1/tbank-sync")
|| path === "/api/v1/bonds"
|| path.startsWith("/api/v1/bonds/")
|| path === "/api/v1/stocks"
|| path.startsWith("/api/v1/stocks/")
|| path === brokerageAccountsPath
|| path.startsWith(`${brokerageAccountsPath}/`))
);
},
});
@@ -47,6 +48,6 @@ function commitTbankConnectionBoundary(
export {
commitTbankConnectionBoundary,
type TbankConnectionStatus,
tbankConnectionQueryOptions,
type TbankConnectionStatus,
};
@@ -1,41 +1,41 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { http, HttpResponse } from "msw";
import { describe, expect, it, vi } from "vitest";
import { useBrokerageAccounts } from "@/entities/brokerage-account";
import { useStockQuote } from "@/entities/stock";
import { configureAuthClient, invalidateResourceAccess } from "@/shared/api";
import { createQueryWrapper } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server";
import { useScreenSync } from "../index";
import { commitTbankConnectionBoundary } from "./connection-boundary";
function auth() {
configureAuthClient({
accessToken: () => "synthetic",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
}
describe("page-owned screen synchronization", () => {
it("ignores a late sync acceptance after the account scope changes", async () => {
auth();
let release!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
const { promise: blocked, resolve: release } = Promise.withResolvers<void>();
const posted: string[] = [];
const polled: string[] = [];
server.use(
http.post("*/api/v1/tbank-sync", async ({ request }) => {
const scope = (await request.json()) as {
screen: "account";
accountId: string;
screen: "account";
};
posted.push(scope.accountId);
await blocked;
return HttpResponse.json(
{ id: scope.accountId, scope, now: "2026-09-25T00:00:00Z" },
{ id: scope.accountId, now: "2026-09-25T00:00:00Z", scope },
{ status: 202 },
);
}),
@@ -43,13 +43,13 @@ describe("page-owned screen synchronization", () => {
polled.push(String(params.id));
return HttpResponse.json({
id: params.id,
state: "succeeded",
resources: [],
state: "succeeded",
});
}),
);
const { result, rerender } = renderHook(
({ accountId }) => useScreenSync({ screen: "account", accountId }, []),
const { rerender, result } = renderHook(
({ accountId }) => useScreenSync({ accountId, screen: "account" }, []),
{
initialProps: { accountId: "old" },
wrapper: createQueryWrapper().wrapper,
@@ -73,13 +73,13 @@ describe("page-owned screen synchronization", () => {
"retries a failed GET without forcing the source (cached=%s)",
async (cached) => {
auth();
const modes: (string | null)[] = [];
let unavailable = !cached;
const modes: (null | string)[] = [];
let isUnavailable = !cached;
let posts = 0;
server.use(
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
modes.push(new URL(request.url).searchParams.get("sync"));
return unavailable
return isUnavailable
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
: HttpResponse.json(
resource([], { stateVersion: String(modes.length) }),
@@ -90,7 +90,7 @@ describe("page-owned screen synchronization", () => {
return new HttpResponse(null, { status: 500 });
}),
);
const { wrapper, queryClient } = createQueryWrapper();
const { queryClient, wrapper } = createQueryWrapper();
const { result } = renderHook(
() => {
const accounts = useBrokerageAccounts();
@@ -105,20 +105,21 @@ describe("page-owned screen synchronization", () => {
);
if (cached) {
await waitFor(() =>
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
expect(result.current.accounts.isSuccess).toBe(true),
);
unavailable = true;
isUnavailable = true;
await act(() => result.current.accounts.refetch());
}
await waitFor(() => expect(result.current.accounts.isError).toBe(true));
unavailable = false;
isUnavailable = false;
await act(() => result.current.sync.retry());
await waitFor(() => expect(result.current.accounts.isSuccess).toBe(true));
expect(result.current.accounts.meta?.stateVersion).toBe(
cached ? "3" : "2",
);
expect(modes).toEqual(
cached ? [null, null, "observe"] : [null, "observe"],
cached ? [null, /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null, "observe"] : [null, "observe"],
);
expect(posts).toBe(0);
expect(result.current.disabled.data).toBeUndefined();
@@ -139,26 +140,24 @@ describe("page-owned screen synchronization", () => {
"discards recovery after %s changes (HTTP already pending=%s)",
async (boundary, pending) => {
auth();
let release!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
let recovering = false;
let changed = false;
const { promise: blocked, resolve: release } = Promise.withResolvers<void>();
let isRecovering = false;
let isChanged = false;
server.use(
http.get("*/api/v1/brokerage-accounts", async ({ request }) => {
if (boundary === "connection" && changed && !request.signal.aborted)
if (boundary === "connection" && isChanged && !request.signal.aborted)
return HttpResponse.json(resource([], { stateVersion: "current" }));
if (!new URL(request.url).searchParams.has("sync"))
return changed
return isChanged
? HttpResponse.json(resource([], { stateVersion: "current" }))
: HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 });
recovering = true;
isRecovering = true;
await blocked;
return HttpResponse.json(resource([], { stateVersion: "old" }));
}),
);
const { wrapper, queryClient } = createQueryWrapper();
const { queryClient, wrapper } = createQueryWrapper();
const published: unknown[] = [];
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
if (event.type === "updated" && event.action.type === "success")
@@ -179,29 +178,42 @@ describe("page-owned screen synchronization", () => {
act(() => {
recovery = result.current.sync.retry();
});
if (pending) await waitFor(() => expect(recovering).toBe(true));
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
if (pending) await waitFor(() => expect(isRecovering).toBe(true));
await act(async () => {
changed = true;
if (boundary === "logout") {
configureAuthClient(null);
queryClient.clear();
} else if (boundary === "session") {
auth();
queryClient.clear();
} else if (boundary === "access") {
invalidateResourceAccess(queryClient, "brokerage", {
code: "FORBIDDEN",
});
} else
commitTbankConnectionBoundary(queryClient, {
isChanged = true;
switch (boundary) {
case "access": {
invalidateResourceAccess(queryClient, "brokerage", {
code: "FORBIDDEN",
});
break;
}
case "logout": {
configureAuthClient();
queryClient.clear();
break;
}
case "session": {
auth();
queryClient.clear();
break;
}
case "connection": { commitTbankConnectionBoundary(queryClient, {
connected: true,
connectedAt: "2026-09-27T00:00:00Z",
});
}
}
release();
await recovery;
});
if (boundary === "connection")
await waitFor(() =>
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
expect(result.current.accounts.meta?.stateVersion).toBe("current"),
);
expect(published).not.toContainEqual(
@@ -216,7 +228,7 @@ describe("page-owned screen synchronization", () => {
"recovers an initial GET failure after forced sync without metadata (status retry=%s)",
async (retryStatus) => {
auth();
const modes: (string | null)[] = [];
const modes: (null | string)[] = [];
let polls = 0;
server.use(
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
@@ -234,12 +246,12 @@ describe("page-owned screen synchronization", () => {
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
: HttpResponse.json({
id: "recover",
state: "succeeded",
resources: [resource([]).meta],
state: "succeeded",
});
}),
);
const { wrapper, queryClient } = createQueryWrapper();
const { queryClient, wrapper } = createQueryWrapper();
const { result } = renderHook(
() => {
const accounts = useBrokerageAccounts();
@@ -256,12 +268,14 @@ describe("page-owned screen synchronization", () => {
await act(() => result.current.sync.refresh());
if (retryStatus) {
await waitFor(() =>
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
expect(result.current.sync.transportError).toBe(true),
);
await act(() => result.current.sync.retry());
}
await waitFor(() => expect(result.current.accounts.isSuccess).toBe(true));
expect(result.current.accounts.data).toEqual([]);
// eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response.
expect(modes).toEqual([null, "observe"]);
expect(
queryClient
@@ -272,12 +286,12 @@ describe("page-owned screen synchronization", () => {
);
it("posts only its scope once and observes completion without importing again", async () => {
auth();
const modes: (string | null)[] = [];
const modes: (null | string)[] = [];
const bodies: unknown[] = [];
let completed = false;
let isCompleted = false;
let polls = 0;
const meta = () =>
resource([], { stateVersion: completed ? "2" : "1" }).meta;
resource([], { stateVersion: isCompleted ? "2" : "1" }).meta;
server.use(
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
modes.push(new URL(request.url).searchParams.get("sync"));
@@ -285,27 +299,29 @@ describe("page-owned screen synchronization", () => {
}),
http.post("*/api/v1/tbank-sync", async ({ request }) => {
bodies.push(await request.json());
completed = true;
isCompleted = true;
return HttpResponse.json(
{
id: "screen",
scope: { screen: "accounts" },
now: "2026-09-25T00:00:00Z",
scope: { screen: "accounts" },
},
{ 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()],
});
return HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
errorCode: null,
id: "screen",
now: "2026-09-25T00:00:00Z",
progress: { completed: 1, discovering: false, total: 1 },
resources: [meta()],
scope: { screen: "accounts" },
state: "succeeded",
}
/* eslint-enable unicorn/no-null */));
}),
);
const { result, unmount } = renderHook(
@@ -329,16 +345,19 @@ describe("page-owned screen synchronization", () => {
expect(result.current.accounts.meta?.stateVersion).toBe("2"),
);
expect(bodies).toEqual([{ screen: "accounts" }]);
// eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response.
expect(modes).toEqual([null, "observe"]);
vi.useFakeTimers();
try {
await act(() => vi.advanceTimersByTimeAsync(120000));
await act(() => vi.advanceTimersByTimeAsync(120_000));
expect(polls).toBe(1);
// eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response.
expect(modes).toEqual([null, "observe"]);
unmount();
await vi.advanceTimersByTimeAsync(120000);
await vi.advanceTimersByTimeAsync(120_000);
expect(polls).toBe(1);
} finally {
}
finally {
vi.useRealTimers();
}
});
@@ -348,14 +367,16 @@ describe("page-owned screen synchronization", () => {
vi.useFakeTimers({ toFake: ["Date"] });
try {
auth();
let completed = false;
let isCompleted = false;
let polls = 0;
const modes: (string | null)[] = [];
const modes: (null | string)[] = [];
const snapshot = () =>
resource(completed ? [] : null, {
stateVersion: completed ? "covered" : "initial",
sync: { id: "history", state: "running", errorCode: null },
});
resource(isCompleted ? [] : /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null, (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
stateVersion: isCompleted ? "covered" : "initial",
sync: { errorCode: null, id: "history", state: "running" },
}
/* eslint-enable unicorn/no-null */));
server.use(
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
modes.push(new URL(request.url).searchParams.get("sync"));
@@ -363,19 +384,21 @@ describe("page-owned screen synchronization", () => {
}),
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],
});
return HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
errorCode: null,
id: "history",
now: "2026-09-25T00:00:00Z",
progress: {
completed: isCompleted ? 1 : 0,
discovering: true,
total: 2,
},
resources: [snapshot().meta],
scope: null,
state: "running",
}
/* eslint-enable unicorn/no-null */));
}),
);
const { result, unmount } = renderHook(
@@ -394,24 +417,26 @@ describe("page-owned screen synchronization", () => {
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);
isCompleted = true;
vi.setSystemTime(Date.now() + 61_000);
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));
await new Promise(resolve => setTimeout(resolve, 1100));
});
// eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response.
expect(modes).toEqual([null, "observe"]);
if (boundary === "leave") unmount();
else act(() => configureAuthClient(null));
else act(() => configureAuthClient());
const stopped = polls;
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 1100));
await new Promise(resolve => setTimeout(resolve, 1100));
});
expect(polls).toBe(stopped);
} finally {
}
finally {
vi.useRealTimers();
}
},
@@ -422,9 +447,11 @@ describe("page-owned screen synchronization", () => {
server.use(
http.get("*/api/v1/brokerage-accounts", () =>
HttpResponse.json(
resource([], {
sync: { id: "revoked", state: "running", errorCode: null },
}),
resource([], (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
sync: { errorCode: null, id: "revoked", state: "running" },
}
/* eslint-enable unicorn/no-null */)),
),
),
http.get("*/api/v1/tbank-sync/:id", () =>
@@ -446,41 +473,45 @@ describe("page-owned screen synchronization", () => {
});
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;
let isObserved = false;
const modes: (null | string)[] = [];
const dependency = resource([], (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
resourceKey: "operations",
stateVersion: isObserved ? "covered" : "initial",
sync: {
errorCode: null,
id: "dependency",
state: isObserved ? "idle" : "running",
},
}
/* eslint-enable unicorn/no-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;
if (mode) isObserved = true;
return HttpResponse.json(
resource(observed ? [] : null, {
resourceKey: "projection",
resource(isObserved ? [] : /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null, {
dependencies: [
{ ...dependency, stateVersion: observed ? "covered" : "initial" },
{ ...dependency, stateVersion: isObserved ? "covered" : "initial" },
],
resourceKey: "projection",
}),
);
}),
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" }],
}),
HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
errorCode: null,
id: "dependency",
now: "2026-09-25T00:00:00Z",
progress: { completed: 1, discovering: false, total: 1 },
resources: [{ ...dependency, stateVersion: "covered" }],
scope: null,
state: "succeeded",
}
/* eslint-enable unicorn/no-null */)),
),
);
const { result } = renderHook(
@@ -492,6 +523,7 @@ describe("page-owned screen synchronization", () => {
{ wrapper: createQueryWrapper().wrapper },
);
await waitFor(() => expect(result.current.data).toEqual([]));
// eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response.
expect(modes).toEqual([null, "observe"]);
});
+117 -107
View File
@@ -1,5 +1,6 @@
import { type QueryKey, useQueryClient } from "@tanstack/react-query";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import {
apiErrorCode,
apiQueryClient,
@@ -7,37 +8,74 @@ import {
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 ResourceMeta
= paths["/api/v1/tbank-sync/{id}"]["get"]["responses"][200]["content"]["application/json"]["resources"][number];
type ScreenResource = {
queryKey: QueryKey;
meta?: ResourceMeta;
transport: {
status: "pending" | "success" | "error";
fetchStatus: "idle" | "fetching" | "paused";
};
observe: (version?: string) => Promise<unknown>;
queryKey: QueryKey;
transport: {
fetchStatus: "fetching" | "idle" | "paused";
status: "error" | "pending" | "success";
};
};
const STATUS_INTERVAL_MS = 1000;
function observeResource(
resource: ScreenResource,
latest: Map<string, ResourceMeta>,
completedId: string | undefined,
observed: Map<string, string>,
) {
if (!resource.meta) {
if (!completedId || resource.transport.fetchStatus !== "idle") return;
const key = `query:${JSON.stringify(resource.queryKey)}`;
if (observed.get(key) === completedId) return;
observed.set(key, completedId);
void resource.observe().catch(() => {});
return;
}
const changed = [
resource.meta,
...(resource.meta.dependencies ?? []),
].flatMap((current) => {
const notified = latest.get(current.resourceKey);
return notified && notified.stateVersion !== current.stateVersion
? [notified]
: [];
});
if (changed.length === 0) return;
const notification = JSON.stringify(
changed.map(meta => [meta.resourceKey, meta.stateVersion]),
);
if (observed.get(resource.meta.resourceKey) === notification)
return;
observed.set(resource.meta.resourceKey, notification);
const own = changed.find(
meta => meta.resourceKey === resource.meta?.resourceKey,
);
void resource.observe(own?.stateVersion).catch(() => {});
}
function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
const mutation = useTbankSync();
const client = useQueryClient();
const denied = useRef(new Set<unknown>());
const deniedRef = useRef(new Set<unknown>());
const scopeKey = JSON.stringify(scope);
const [requested, setRequested] = useState<{
scope: string;
const [requested, setRequested] = useState<null | {
id: string;
} | null>(null);
const requestInFlight = useRef<string | null>(null);
const currentScope = useRef(scopeKey);
scope: string;
}>(null);
const requestInFlightRef = useRef<null | string>(null);
const currentScopeRef = useRef(scopeKey);
useLayoutEffect(() => {
currentScope.current = scopeKey;
currentScopeRef.current = scopeKey;
}, [scopeKey]);
const currentMutation = JSON.stringify(mutation.variables?.body) === scopeKey;
const observed = useRef(new Map<string, string>());
const isCurrentMutation = JSON.stringify(mutation.variables?.body) === scopeKey;
const observedRef = useRef(new Map<string, string>());
const ids = [
...new Set([
...(requested?.scope === scopeKey ? [requested.id] : []),
@@ -45,139 +83,111 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
.flatMap(({ meta }) =>
meta ? [meta, ...(meta.dependencies ?? [])] : [],
)
.flatMap((meta) =>
meta?.sync.id &&
(meta.sync.state === "running" || meta.sync.state === "queued")
.flatMap(meta =>
meta?.sync.id
&& (meta.sync.state === "running" || meta.sync.state === "queued")
? [meta.sync.id]
: [],
),
]),
];
const statuses = useAuthenticatedQueries(
ids.map((id) => ({
ids.map(id => ({
...apiQueryClient.queryOptions("get", "/api/v1/tbank-sync/{id}", {
params: { path: { id } },
}),
retry: false,
refetchInterval: (query: {
state: { data?: { state: string }; error: unknown };
}) =>
!(query.state.error || (query.state.data && query.state.data.state !== "running")) && STATUS_INTERVAL_MS,
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,
retry: false,
})),
);
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);
if (!status.error || deniedRef.current.has(status.error)) {
continue;
}
deniedRef.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 ?? []) {
const orderedStatuses = statuses.toSorted((a, b) => a.dataUpdatedAt - b.dataUpdatedAt);
for (const status of orderedStatuses) {
const statusResources = status.data?.resources ?? [];
for (const meta of statusResources) {
latest.set(meta.resourceKey, meta);
for (const dependency of meta.dependencies ?? [])
const dependencies = meta.dependencies ?? [];
for (const dependency of dependencies)
latest.set(dependency.resourceKey, dependency);
}
for (const resource of resources) {
if (!resource.meta) {
if (resource.transport.fetchStatus !== "idle") continue;
const completed = statuses.find(
(status) =>
requested?.scope === scopeKey &&
status.data?.id === requested.id &&
status.data.state !== "running",
)?.data;
const key = `query:${JSON.stringify(resource.queryKey)}`;
if (completed && observed.current.get(key) !== completed.id) {
observed.current.set(key, completed.id);
void resource.observe().catch(() => undefined);
}
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);
}
const completed = statuses.find(status => requested?.scope === scopeKey
&& status.data?.id === requested.id && status.data.state !== "running")?.data;
for (const resource of resources) observeResource(resource, latest, completed?.id, observedRef.current);
}, [client, statuses, resources, requested, scopeKey]);
const 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 isRefreshing
= (isCurrentMutation && 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;
if (isRefreshing || requestInFlightRef.current === scopeKey) return;
requestInFlightRef.current = scopeKey;
try {
const accepted = await mutation.mutateAsync({ body: scope });
if (
currentScope.current === scopeKey &&
requestInFlight.current === scopeKey
currentScopeRef.current === scopeKey
&& requestInFlightRef.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;
setRequested({ id: accepted.id, scope: scopeKey });
}
catch {
/*
The mutation retains the transport error for presentation.
*/
}
finally {
if (requestInFlightRef.current === scopeKey) requestInFlightRef.current = /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null;
}
};
// Retry failed HTTP reads without asking the source to import again.
// A source failure (or explicit refresh with no read error) still needs a sync.
const retry = async () => {
const failed = resources.filter(
(resource) => resource.transport.status === "error",
resource => resource.transport.status === "error",
);
const failedStatuses = statuses.filter((status) => status.isError);
if (failed.length || failedStatuses.length) {
const failedStatuses = statuses.filter(status => status.isError);
if (failed.length > 0 || failedStatuses.length > 0) {
await Promise.allSettled([
...failed.map((resource) => resource.observe()),
...failedStatuses.map((status) => status.refetch()),
...failed.map(resource => resource.observe()),
...failedStatuses.map(status => status.refetch()),
]);
} else await refresh();
}
else await refresh();
};
return {
refresh,
refreshing: isRefreshing,
retry,
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"),
statuses.some(status => status.data?.state === "failed")
|| resources.some(({ meta }) => meta?.sync.state === "failed"),
transportError:
(isCurrentMutation && mutation.isError)
|| statuses.some(status => status.isError),
};
}
@@ -1,9 +1,11 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { http, HttpResponse } 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,
@@ -17,22 +19,20 @@ describe("sync connection and session boundaries", () => {
async (boundary) => {
let generation = 0;
configureAuthClient({
generation: () => generation,
accessToken: () => "synthetic",
refresh: async () => true,
clear: vi.fn(),
generation: () => generation,
refresh: () => Promise.resolve(true),
});
let release!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
const { promise: blocked, resolve: release } = Promise.withResolvers<void>();
const accepted = {
id: "work",
scope: { screen: "accounts" },
now: "2026-09-25T12:00:00Z",
scope: { screen: "accounts" },
};
let started = 0;
let changed = false;
let isChanged = false;
server.use(
http.post("*/api/v1/tbank-sync", async () => {
started += 1;
@@ -40,29 +40,31 @@ describe("sync connection and session boundaries", () => {
return HttpResponse.json(accepted, { status: 202 });
}),
http.get("*/api/v1/tbank-sync/:id", async () => {
const now = changed ? "2026-09-25T12:01:00Z" : accepted.now;
const now = isChanged ? "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: [],
});
return HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
...accepted,
errorCode: null,
now,
progress: { completed: 1, discovering: false, total: 1 },
resources: [],
state: "succeeded",
}
/* eslint-enable unicorn/no-null */));
}),
);
const { wrapper, queryClient } = createQueryWrapper();
const { queryClient, wrapper } = createQueryWrapper();
const published: string[] = [];
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
if (
(event.query.queryKey as readonly unknown[])[1] ===
"/api/v1/tbank-sync/{id}"
) {
const data = event.query.state.data as { now?: string } | undefined;
if (data?.now) published.push(data.now);
if ((event.query.queryKey as readonly unknown[])[1]
!== "/api/v1/tbank-sync/{id}") {
return;
}
const data = event.query.state.data as undefined | { now?: string };
if (data?.now) published.push(data.now);
});
const { result } = renderHook(
() => ({
@@ -82,12 +84,14 @@ describe("sync connection and session boundaries", () => {
});
await waitFor(() => expect(started).toBe(2));
await act(async () => {
changed = true;
isChanged = true;
if (boundary === "connection")
commitTbankConnectionBoundary(queryClient, {
connected: false,
connectedAt: null,
});
commitTbankConnectionBoundary(queryClient, (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
connected: false,
connectedAt: null,
}
/* eslint-enable unicorn/no-null */));
else {
generation += 1;
queryClient.clear();
@@ -104,9 +108,11 @@ describe("sync connection and session boundaries", () => {
).queryKey;
// A new request may start after a successful connection boundary; an old result cannot win it.
if (boundary === "session")
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
expect(queryClient.getQueryData(key)).toBeUndefined();
else
await waitFor(() =>
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
expect(queryClient.getQueryData(key)).toMatchObject({
now: "2026-09-25T12:01:00Z",
}),
+3 -3
View File
@@ -4,14 +4,14 @@ import {
useAuthenticatedQuery,
} from "@/shared/api";
type InvestmentScreen =
paths["/api/v1/tbank-sync"]["post"]["requestBody"]["content"]["application/json"];
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) {
function useTbankSyncStatus(id: null | string) {
return useAuthenticatedQuery({
...apiQueryClient.queryOptions("get", "/api/v1/tbank-sync/{id}", {
params: { path: { id: id ?? "" } },
@@ -7,11 +7,13 @@ import {
waitFor,
within,
} from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { http, HttpResponse } from "msw";
import { describe, expect, it, vi } from "vitest";
import { apiQueryClient, configureAuthClient } from "@/shared/api";
import { createTestQueryClient } from "@/test/query";
import { server } from "@/test/server";
import { tbankConnectionQueryOptions } from "../../model/connection-boundary";
import { TbankConnectionSection } from "./TbankConnectionSection";
@@ -54,8 +56,8 @@ const unrelatedQueryKey = apiQueryClient.queryOptions(
function renderSection(client: QueryClient) {
configureAuthClient({
accessToken: () => "test-token",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
return render(
<MantineProvider>
@@ -69,12 +71,14 @@ function renderSection(client: QueryClient) {
function seededClient() {
const client = createTestQueryClient();
client.setQueryData(brokerageAccountsQueryKey, [
{
id: "account-1",
name: "Основной счет",
type: "BROKERAGE",
openedOn: null,
},
(/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
id: "account-1",
name: "Основной счет",
openedOn: null,
type: "BROKERAGE",
}
/* eslint-enable unicorn/no-null */),
]);
client.setQueryData(portfolioQueryKey, { source: "previous-connection" });
client.setQueryData(stockQueryKey, { source: "previous-connection" });
@@ -87,10 +91,8 @@ function seededClient() {
describe("TbankConnectionSection", () => {
it("preserves cached status and a draft entered during a delayed failed refetch", async () => {
const status = { connected: true, connectedAt: "2026-08-14T00:00:00Z" };
let finishRefetch: (() => void) | undefined;
const response = new Promise<void>((resolve) => {
finishRefetch = resolve;
});
const { promise: response, resolve: finishRefetch } = Promise.withResolvers<void>();
let reads = 0;
server.use(
http.get("*/api/v1/tbank-connection", async () => {
@@ -141,7 +143,9 @@ describe("TbankConnectionSection", () => {
reads += 1;
return reads === 1
? HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 })
: HttpResponse.json({ connected: false, connectedAt: null });
: HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{ connected: false, connectedAt: null }
/* eslint-enable unicorn/no-null */));
}),
);
renderSection(createTestQueryClient());
@@ -238,22 +242,21 @@ describe("TbankConnectionSection", () => {
it("cancels an in-flight previous-boundary query and ignores its late response", async () => {
const client = seededClient();
let finishPrevious: ((value: { source: string }) => void) | undefined;
let aborted = false;
const previousResponse = new Promise<{ source: string }>((resolve) => {
finishPrevious = resolve;
});
let isAborted = false;
const { promise: previousResponse, resolve: finishPrevious } = Promise.withResolvers<{ source: string }>();
const previousRequest = client
.fetchQuery({
queryKey: operationsQueryKey,
.query({
queryFn: ({ signal }) => {
signal.addEventListener("abort", () => {
aborted = true;
isAborted = true;
});
return previousResponse;
},
queryKey: operationsQueryKey,
})
.catch(() => undefined);
// eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering.
.catch(() => {});
renderSection(client);
await screen.findByText("Не подключено");
@@ -262,7 +265,7 @@ describe("TbankConnectionSection", () => {
});
fireEvent.click(screen.getByRole("button", { name: "Подключить" }));
await waitFor(() => expect(aborted).toBe(true));
await waitFor(() => expect(isAborted).toBe(true));
await previousRequest;
finishPrevious?.({ source: "previous-connection" });
await Promise.resolve();
@@ -298,10 +301,8 @@ describe("TbankConnectionSection", () => {
it("keeps DELETE recovery inside the dialog and preserves cache until successful retry", async () => {
let deletes = 0;
let finishDelete: (() => void) | undefined;
const response = new Promise<void>((resolve) => {
finishDelete = resolve;
});
const { promise: response, resolve: finishDelete } = Promise.withResolvers<void>();
server.use(
http.get("*/api/v1/tbank-connection", () =>
HttpResponse.json({
@@ -327,6 +328,7 @@ describe("TbankConnectionSection", () => {
name: "Удалить подключение?",
});
await waitFor(() =>
// eslint-disable-next-line testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
expect(dialog.contains(document.activeElement)).toBe(true),
);
const confirm = within(dialog).getByRole("button", { name: /^Удалить$/ });
@@ -340,7 +342,7 @@ describe("TbankConnectionSection", () => {
document.body.tabIndex = -1;
document.body.focus();
document.body.removeAttribute("tabindex");
expect(document.activeElement).toBe(document.body);
expect(document.body).toHaveFocus();
finishDelete?.();
expect(await within(dialog).findByRole("alert")).toHaveTextContent(
@@ -1,4 +1,5 @@
import type { FC } from "react";
import {
TbankConnectionError,
TbankConnectionLoading,
@@ -9,9 +10,7 @@ import { TbankConnectionSectionLoaded } from "./TbankConnectionSectionLoaded";
const TbankConnectionSection: FC = () => {
const viewModel = useTbankConnectionViewModel();
if (viewModel.state === "loading") return <TbankConnectionLoading />;
if (viewModel.state === "error")
return <TbankConnectionError retry={viewModel.retry} />;
return <TbankConnectionSectionLoaded {...viewModel} />;
return viewModel.state === "error" ? <TbankConnectionError retry={viewModel.retry} /> : <TbankConnectionSectionLoaded {...viewModel} />;
};
export { TbankConnectionSection };
@@ -1,6 +1,7 @@
import { MantineProvider } from "@mantine/core";
import { render, screen } from "@testing-library/react";
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import {
TbankConnectionError,
TbankConnectionLoading,
@@ -23,7 +24,7 @@ describe("TbankConnectionSection state views", () => {
<TbankConnectionError retry={retry} />
</MantineProvider>,
);
screen.getByRole("button", { name: "Повторить" }).click();
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
expect(retry).toHaveBeenCalledOnce();
});
});
@@ -1,6 +1,7 @@
import type { FC } from "react";
import { Alert, Button, Skeleton } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
type TbankConnectionErrorProps = {
@@ -13,7 +14,7 @@ const TbankConnectionLoading: FC = () => {
return (
<LoadingSkeleton label={t("states.loadingTitle")}>
<Skeleton height={20} width="45%" />
<Skeleton height={36} width={140} radius="sm" />
<Skeleton height={36} radius="sm" width={140} />
</LoadingSkeleton>
);
};
@@ -24,7 +25,7 @@ const TbankConnectionError: FC<TbankConnectionErrorProps> = (props) => {
return (
<Alert color="red" title={t("tbank.statusError")}>
<Button variant="subtle" onClick={retry}>
<Button onClick={retry} variant="subtle">
{t("tbank.retry")}
</Button>
</Alert>
@@ -1,4 +1,5 @@
import { useAuthenticatedQuery } from "@/shared/api";
import { tbankConnectionQueryOptions } from "../../model/connection-boundary";
function useTbankConnectionViewModel() {
@@ -6,15 +7,14 @@ function useTbankConnectionViewModel() {
...tbankConnectionQueryOptions(),
});
if (!status.data) {
if (status.isPending) return { state: "loading" as const };
return { state: "error" as const, retry: () => status.refetch() };
return status.isPending ? { state: "loading" as const } : { retry: () => status.refetch(), state: "error" as const };
}
return {
refreshError: status.isError,
refreshing: status.isFetching,
retry: () => status.refetch(),
state: "loaded" as const,
status: status.data,
refreshing: status.isFetching,
refreshError: status.isError,
retry: () => status.refetch(),
};
}
@@ -1,3 +1,5 @@
import type { FC } from "react";
import {
Alert,
Button,
@@ -7,21 +9,22 @@ import {
Text,
} from "@mantine/core";
import { useQueryClient } from "@tanstack/react-query";
import type { FC } from "react";
import { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { apiErrorCode, apiQueryClient } from "@/shared/api";
import {
commitTbankConnectionBoundary,
type TbankConnectionStatus,
} from "../../model/connection-boundary";
type TbankConnectionSectionLoadedProps = {
status: TbankConnectionStatus;
refreshing: boolean;
refreshError: boolean;
refreshing: boolean;
retry: () => void;
status: TbankConnectionStatus;
};
const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
@@ -30,21 +33,21 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
const { status } = props;
const { t } = useTranslation();
const queryClient = useQueryClient();
const [deleteOpened, setDeleteOpened] = useState(false);
const deleteButton = useRef<HTMLButtonElement>(null);
const [requestError, setRequestError] = useState<string | null>(null);
const [isDeleteOpened, setIsDeleteOpened] = useState(false);
const removalButtonRef = useRef<HTMLButtonElement>(null);
const [requestError, setRequestError] = useState<null | string>(null);
const {
register,
handleSubmit,
reset,
formState: { errors },
handleSubmit,
register,
reset,
} = useForm<{ token: string }>();
const update = apiQueryClient.useMutation("put", "/api/v1/tbank-connection", {
onError: error => setRequestError(apiErrorCode(error) ?? "REQUEST_ERROR"),
onSuccess: (data) => {
commitTbankConnectionBoundary(queryClient, data);
reset();
},
onError: (error) => setRequestError(apiErrorCode(error) ?? "REQUEST_ERROR"),
});
const remove = apiQueryClient.useMutation(
"delete",
@@ -53,23 +56,24 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
onSuccess: () => {
commitTbankConnectionBoundary(queryClient, {
connected: false,
connectedAt: null,
connectedAt: /* eslint-disable-line unicorn/no-null -- The disconnected API snapshot requires a null connection timestamp. */ null,
});
setDeleteOpened(false);
setIsDeleteOpened(false);
},
},
);
const pending = update.isPending || remove.isPending;
const connected = status.connected;
const unavailableMessage = requestError === "TBANK_UNAVAILABLE" ? "tbank.unavailable" : "tbank.requestError";
const isPending = update.isPending || remove.isPending;
const isConnected = status.connected;
useEffect(() => {
if (deleteOpened && remove.isError) deleteButton.current?.focus();
}, [deleteOpened, remove.isError]);
if (isDeleteOpened && remove.isError) removalButtonRef.current?.focus();
}, [isDeleteOpened, remove.isError]);
return (
<Stack mt="xl">
<Text fw={600}>{t("tbank.title")}</Text>
<Text size="sm">
{connected
{isConnected
? t("tbank.connected", {
date: new Date(status.connectedAt ?? "").toLocaleDateString(
"ru-RU",
@@ -77,22 +81,22 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
})
: t("tbank.disconnected")}
</Text>
<Text size="sm" c="dimmed">
<Text c="dimmed" size="sm">
{t("tbank.hint")}
</Text>
{props.refreshing && (
<Text role="status" size="sm" c="dimmed">
<Text c="dimmed" role="status" size="sm">
{t("tbank.refreshing")}
</Text>
)}
{props.refreshError && (
<Alert color="orange" role="status" aria-live="polite">
<Alert aria-live="polite" color="orange" role="status">
<Stack gap="sm">
<Text>{t("tbank.refreshError")}</Text>
<Button
variant="default"
disabled={props.refreshing || isPending}
onClick={props.retry}
disabled={props.refreshing || pending}
variant="default"
>
{t("tbank.retry")}
</Button>
@@ -105,7 +109,7 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
update.mutate({ body: { token } });
})}
>
<fieldset disabled={pending}>
<fieldset disabled={isPending}>
<Stack>
<PasswordInput
label={t("tbank.token")}
@@ -117,23 +121,21 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
{t(
requestError === "INVALID_TBANK_TOKEN"
? "tbank.invalidToken"
: requestError === "TBANK_UNAVAILABLE"
? "tbank.unavailable"
: "tbank.requestError",
: unavailableMessage,
)}
</Alert>
)}
<Button type="submit" loading={update.isPending}>
{t(connected ? "tbank.replace" : "tbank.connect")}
<Button loading={update.isPending} type="submit">
{t(isConnected ? "tbank.replace" : "tbank.connect")}
</Button>
{connected && (
{isConnected && (
<Button
variant="outline"
color="red"
onClick={() => {
remove.reset();
setDeleteOpened(true);
setIsDeleteOpened(true);
}}
variant="outline"
>
{t("tbank.delete")}
</Button>
@@ -142,12 +144,12 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
</fieldset>
</form>
<Modal
opened={deleteOpened}
onClose={() => !pending && setDeleteOpened(false)}
closeButtonProps={{ "aria-label": t("tbank.close"), "disabled": isPending }}
closeOnClickOutside={!isPending}
closeOnEscape={!isPending}
onClose={() => !isPending && setIsDeleteOpened(false)}
opened={isDeleteOpened}
title={t("tbank.deleteTitle")}
closeOnClickOutside={!pending}
closeOnEscape={!pending}
closeButtonProps={{ "aria-label": t("tbank.close"), disabled: pending }}
>
<Stack>
<Text>{t("tbank.deleteText")}</Text>
@@ -155,11 +157,11 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
<Alert color="red">{t("tbank.requestError")}</Alert>
)}
<Button
ref={deleteButton}
color="red"
disabled={isPending}
loading={remove.isPending}
disabled={pending}
onClick={() => remove.mutate({})}
ref={removalButtonRef}
>
{t("tbank.deleteConfirm")}
</Button>
+2 -1
View File
@@ -5,10 +5,11 @@ import "@mantine/charts/styles.css";
import "@mantine/dates/styles.css";
import "@wealthledger/ui/styles.css";
import "dayjs/locale/ru";
import "./shared/i18n";
import { App } from "./app";
const root = document.getElementById("root");
const root = document.querySelector("#root");
if (!root) {
throw new Error("Root element not found");
@@ -1,3 +1,5 @@
import type { FC } from "react";
import { MantineProvider } from "@mantine/core";
import { QueryClientProvider } from "@tanstack/react-query";
import {
@@ -8,8 +10,7 @@ import {
screen,
waitFor,
} from "@testing-library/react";
import { HttpResponse, http } from "msw";
import type { FC } from "react";
import { http, HttpResponse } from "msw";
import {
MemoryRouter,
Route,
@@ -18,10 +19,12 @@ import {
useNavigate,
} from "react-router";
import { describe, expect, it, vi } from "vitest";
import { configureAuthClient } from "@/shared/api";
import { createQueryWrapper, createTestQueryClient } from "@/test/query";
import { createTestQueryClient } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server";
import { AccountEventsPage } from "./AccountEventsPage";
import { useAccountEventsPageViewModel } from "./AccountEventsPage.vm";
@@ -31,10 +34,10 @@ const Navigation: FC = () => {
return (
<>
<output aria-label="URL">{location.search}</output>
<button type="button" onClick={() => navigate(-1)}>
<button onClick={() => navigate(-1)} type="button">
History back
</button>
<button type="button" onClick={() => navigate(1)}>
<button onClick={() => navigate(1)} type="button">
History forward
</button>
</>
@@ -45,8 +48,8 @@ describe("Upcoming event date filters", () => {
it("keeps reads and sync disabled without an account scope", async () => {
configureAuthClient({
accessToken: () => "token",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
const requests: string[] = [];
server.use(
@@ -55,17 +58,17 @@ describe("Upcoming event date filters", () => {
return new HttpResponse(null, { status: 503 });
}),
);
const { wrapper: QueryWrapper, queryClient } = createQueryWrapper();
const queryClient = createTestQueryClient();
const { result } = renderHook(() => useAccountEventsPageViewModel(), {
wrapper: ({ children }) => (
<QueryWrapper>
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={["?from=2099-02-01"]}>
{children}
</MemoryRouter>
</QueryWrapper>
</QueryClientProvider>
),
});
await act(async () => {});
await new Promise(resolve => setTimeout(resolve, 0));
expect(result.current).toEqual({ state: "loading" });
expect(queryClient.isFetching()).toBe(0);
expect(requests).toEqual([]);
@@ -80,8 +83,8 @@ describe("Upcoming event date filters", () => {
async (search) => {
configureAuthClient({
accessToken: () => "token",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
const requested: string[] = [];
const syncRequests: unknown[] = [];
@@ -89,13 +92,15 @@ describe("Upcoming event date filters", () => {
http.get("*/api/v1/brokerage-accounts/all/events", ({ request }) => {
requested.push(new URL(request.url).search);
return HttpResponse.json(
resource(null, {
sync: {
id: null,
state: "failed",
errorCode: "TBANK_UNAVAILABLE",
},
}),
resource(null, (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
sync: {
errorCode: "TBANK_UNAVAILABLE",
id: null,
state: "failed",
},
}
/* eslint-enable unicorn/no-null */)),
);
}),
http.post("*/api/v1/tbank-sync", async ({ request }) => {
@@ -107,16 +112,16 @@ describe("Upcoming event date filters", () => {
}),
);
const period = Object.fromEntries(new URLSearchParams(search));
const { wrapper: QueryWrapper } = createQueryWrapper();
const queryClient = createTestQueryClient();
const { result } = renderHook(
() => useAccountEventsPageViewModel("all"),
{
wrapper: ({ children }) => (
<QueryWrapper>
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={[`?${search}`]}>
{children}
</MemoryRouter>
</QueryWrapper>
</QueryClientProvider>
),
},
);
@@ -128,7 +133,7 @@ describe("Upcoming event date filters", () => {
});
await waitFor(() =>
expect(syncRequests).toEqual([
{ screen: "events", accountId: "all", ...period },
{ accountId: "all", screen: "events", ...period },
]),
);
},
@@ -139,8 +144,8 @@ describe("Upcoming event date filters", () => {
async (accountId) => {
configureAuthClient({
accessToken: () => "token",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
const searches: string[] = [];
server.use(
@@ -156,20 +161,20 @@ describe("Upcoming event date filters", () => {
<QueryClientProvider client={createTestQueryClient()}>
<MantineProvider env="test">
<MemoryRouter
initialIndex={0}
initialEntries={[
"?from=bad&to=2099-02-28",
"?from=2099-02-30",
"?from=2099-03-01&to=2099-02-28",
"?from=2099-02-01",
"?to=2099-02-28",
].map((search) => `/accounts/${accountId}/events${search}`)}
].map(search => `/accounts/${accountId}/events${search}`)}
initialIndex={0}
>
<Navigation />
<Routes>
<Route
path="/accounts/:accountId/events"
element={<AccountEventsPage />}
path="/accounts/:accountId/events"
/>
</Routes>
</MemoryRouter>
@@ -182,6 +187,7 @@ describe("Upcoming event date filters", () => {
screen.getByRole("button", { name: "History forward" }),
);
await waitFor(() =>
// eslint-disable-next-line jest-dom/prefer-to-have-text-content -- URL history requires exact equality, including empty search.
expect(screen.getByLabelText("URL").textContent).toBe(expected),
);
await screen.findByLabelText("Период");
@@ -202,8 +208,8 @@ describe("Upcoming event date filters", () => {
async (accountId) => {
configureAuthClient({
accessToken: () => "token",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
server.use(
http.get(
@@ -223,8 +229,8 @@ describe("Upcoming event date filters", () => {
<Navigation />
<Routes>
<Route
path="/accounts/:accountId/events"
element={<AccountEventsPage />}
path="/accounts/:accountId/events"
/>
</Routes>
</MemoryRouter>
@@ -234,7 +240,7 @@ describe("Upcoming event date filters", () => {
await screen.findByRole("button", { name: "Повторить" });
fireEvent.click(screen.getByRole("button", { name: "Сбросить" }));
await screen.findByLabelText("Период");
expect(screen.getByLabelText("URL").textContent).toBe("");
expect(screen.getByLabelText("URL")).toBeEmptyDOMElement();
},
);
@@ -243,8 +249,8 @@ describe("Upcoming event date filters", () => {
async (accountId) => {
configureAuthClient({
accessToken: () => "token",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
const searches: string[] = [];
server.use(
@@ -274,8 +280,8 @@ describe("Upcoming event date filters", () => {
<Navigation />
<Routes>
<Route
path="/accounts/:accountId/events"
element={<AccountEventsPage />}
path="/accounts/:accountId/events"
/>
</Routes>
</MemoryRouter>
@@ -324,41 +330,41 @@ describe("Upcoming event date filters", () => {
it("retains the previous complete forecast and timestamp when its source refresh fails", async () => {
configureAuthClient({
accessToken: () => "synthetic",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
const events = [
{
date: "2026-10-01",
displayName: "Synthetic coupon",
type: "coupon",
projectedAmount: { currency: "RUB", value: "123.45" },
type: "coupon",
},
];
const snapshot = resource(
{ events, incomeTotalsByCurrency: [{ currency: "RUB", value: "123.45" }] },
{ sync: { id: "failed", state: "failed", errorCode: "TBANK_UNAVAILABLE" } },
{ sync: { errorCode: "TBANK_UNAVAILABLE", id: "failed", state: "failed" } },
);
server.use(
http.get("*/api/v1/brokerage-accounts/:accountId/events", () =>
HttpResponse.json(snapshot),
),
);
const { wrapper: QueryWrapper } = createQueryWrapper();
const queryClient = createTestQueryClient();
const { result } = renderHook(() => useAccountEventsPageViewModel("all"), {
wrapper: ({ children }) => (
<QueryWrapper>
<QueryClientProvider client={queryClient}>
<MemoryRouter>{children}</MemoryRouter>
</QueryWrapper>
</QueryClientProvider>
),
});
await waitFor(() =>
expect(result.current).toMatchObject({
state: "loaded",
events,
sourceError: true,
refreshError: true,
lastSuccessfulAt: snapshot.meta.lastSuccessfulAt,
refreshError: true,
sourceError: true,
state: "loaded",
}),
);
});
@@ -1,21 +1,23 @@
import { MantineProvider } from "@mantine/core";
import { fireEvent, render, screen } from "@testing-library/react";
import { fireEvent, render, screen, within } from "@testing-library/react";
import { MemoryRouter, Route, Routes } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { useBrokerageEvents } from "@/entities/brokerage-event";
import { AccountEventsPage } from "./AccountEventsPage";
const { refresh } = vi.hoisted(() => ({ refresh: vi.fn() }));
vi.mock("@/features/tbank-connection", () => ({
useScreenSync: () => ({
refresh,
retry: refresh,
refreshing: false,
retry: refresh,
sourceError: false,
transportError: false,
}),
}));
vi.mock("@/entities/brokerage-event", async (importOriginal) => ({
vi.mock("@/entities/brokerage-event", async importOriginal => ({
...(await importOriginal<typeof import("@/entities/brokerage-event")>()),
useBrokerageEvents: vi.fn(),
}));
@@ -35,20 +37,22 @@ function renderPage() {
describe("AccountEventsPage", () => {
beforeEach(() => {
refresh.mockClear();
query.mockReturnValue({
data: {
accountId: "account",
calculatedAt: "2026-08-14T00:00:00Z",
events: [],
},
meta: {
availability: "complete",
sync: { state: "idle", id: null, errorCode: null },
},
isError: false,
isLoading: false,
refetch: vi.fn(),
} as never);
query.mockReturnValue((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
data: {
accountId: "account",
calculatedAt: "2026-08-14T00:00:00Z",
events: [],
},
isError: false,
isLoading: false,
meta: {
availability: "complete",
sync: { errorCode: null, id: null, state: "idle" },
},
refetch: vi.fn(),
}
/* eslint-enable unicorn/no-null */) as never);
});
it("passes the selected route account to the query", () => {
@@ -57,8 +61,8 @@ describe("AccountEventsPage", () => {
<MemoryRouter initialEntries={["/accounts/selected-account/events"]}>
<Routes>
<Route
path="/accounts/:accountId/events"
element={<AccountEventsPage />}
path="/accounts/:accountId/events"
/>
</Routes>
</MemoryRouter>
@@ -68,16 +72,18 @@ describe("AccountEventsPage", () => {
});
it("keeps the loading fallback when no result or account is available", () => {
query.mockReturnValue({
data: undefined,
meta: {
availability: "complete",
sync: { state: "idle", id: null, errorCode: null },
},
isError: false,
isLoading: false,
refetch: vi.fn(),
} as never);
query.mockReturnValue((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
data: undefined,
isError: false,
isLoading: false,
meta: {
availability: "complete",
sync: { errorCode: null, id: null, state: "idle" },
},
refetch: vi.fn(),
}
/* eslint-enable unicorn/no-null */) as never);
renderPage();
expect(query).toHaveBeenCalledWith("", {});
expect(screen.getByRole("status", { name: "Загрузка" })).toHaveAttribute(
@@ -87,46 +93,48 @@ describe("AccountEventsPage", () => {
});
it("renders events and marks an offer without an amount", () => {
query.mockReturnValue({
data: {
accountId: "account",
calculatedAt: "2026-08-14T00:00:00Z",
events: [
{
date: "2026-08-20",
dateKind: "event",
displayName: "ОФЗ 26238",
figi: "FIGI",
instrumentUid: "UID",
projectedAmount: { currency: "RUB", value: "1250" },
ticker: "OFZ",
type: "coupon",
logoName: "ofz.png",
isin: "RU000A0JX0J2",
},
{
date: "2026-08-25",
dateKind: "event",
displayName: "ОФЗ 26238",
figi: "FIGI",
instrumentUid: "UID",
projectedAmount: null,
ticker: "OFZ",
type: "offer",
logoName: null,
isin: null,
},
],
},
meta: {
availability: "complete",
sync: { state: "idle", id: null, errorCode: null },
},
isError: false,
isLoading: false,
refetch: vi.fn(),
} as never);
const { container } = renderPage();
query.mockReturnValue((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
data: {
accountId: "account",
calculatedAt: "2026-08-14T00:00:00Z",
events: [
{
date: "2026-08-20",
dateKind: "event",
displayName: "ОФЗ 26238",
figi: "FIGI",
instrumentUid: "UID",
isin: "RU000A0JX0J2",
logoName: "ofz.png",
projectedAmount: { currency: "RUB", value: "1250" },
ticker: "OFZ",
type: "coupon",
},
{
date: "2026-08-25",
dateKind: "event",
displayName: "ОФЗ 26238",
figi: "FIGI",
instrumentUid: "UID",
isin: null,
logoName: null,
projectedAmount: null,
ticker: "OFZ",
type: "offer",
},
],
},
isError: false,
isLoading: false,
meta: {
availability: "complete",
sync: { errorCode: null, id: null, state: "idle" },
},
refetch: vi.fn(),
}
/* eslint-enable unicorn/no-null */) as never);
renderPage();
expect(screen.getByText("1 250 ₽")).toBeInTheDocument();
expect(screen.getByText("Сумма неизвестна")).toBeInTheDocument();
expect(screen.getByText("Купон · ОФЗ 26238")).toBeVisible();
@@ -136,7 +144,7 @@ describe("AccountEventsPage", () => {
expect(screen.getByText("25.08.2026")).toBeVisible();
expect(screen.queryByText(/Дата события/)).not.toBeInTheDocument();
expect(screen.getAllByText("Ожидаемая сумма")).toHaveLength(2);
const logo = container.querySelector("img");
const logo = screen.queryByAltText("");
expect(logo).toHaveAttribute(
"src",
"https://invest-brands.cdn-tinkoff.ru/ofzx160.png",
@@ -144,7 +152,7 @@ describe("AccountEventsPage", () => {
expect(screen.getAllByText("O")).toHaveLength(1);
if (!logo) throw new Error("Expected the event logo");
fireEvent.error(logo);
expect(container.querySelector("img")).toBeNull();
expect(screen.queryByAltText("")).not.toBeInTheDocument();
expect(screen.getAllByText("O")).toHaveLength(2);
});
@@ -167,26 +175,28 @@ describe("AccountEventsPage", () => {
</MemoryRouter>
</MantineProvider>,
);
screen.getByRole("button", { name: "Повторить" }).click();
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
expect(refresh).toHaveBeenCalledOnce();
});
it("shows a structural busy state before events are available", () => {
query.mockReturnValue({
data: undefined,
meta: {
availability: "complete",
sync: { state: "idle", id: null, errorCode: null },
},
isError: false,
isLoading: true,
refetch: vi.fn(),
} as never);
query.mockReturnValue((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
data: undefined,
isError: false,
isLoading: true,
meta: {
availability: "complete",
sync: { errorCode: null, id: null, state: "idle" },
},
refetch: vi.fn(),
}
/* eslint-enable unicorn/no-null */) as never);
renderPage();
const status = screen.getByRole("status", { name: "Загрузка" });
expect(status).toHaveAttribute("aria-busy", "true");
expect(status.querySelector("button")).toBeNull();
expect(within(status).queryByRole("button")).not.toBeInTheDocument();
});
});

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