refactor: colocate frontend component files
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Successful in 5m10s
Conventional commits / commits (pull_request) Successful in 25s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 5m10s

This commit is contained in:
2026-09-23 08:34:58 +03:00
parent 85fcfe3d07
commit b987fd8e78
190 changed files with 131 additions and 108 deletions
@@ -0,0 +1,303 @@
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 { MemoryRouter, Route, Routes } from "react-router";
import { describe, expect, it, vi } from "vitest";
import {
type BrokerageOperation,
LedgerEntryRow,
} from "@/entities/broker-operation";
import { configureAuthClient } from "@/shared/api";
import { createTestQueryClient } from "@/test/query";
import { server } from "@/test/server";
import { AccountOperationsPage } from "./AccountOperationsPage";
const operation: BrokerageOperation = {
id: "operation-1",
occurredAt: "2026-08-14T10:00:00Z",
type: "OPERATION_TYPE_BUY",
category: "trade",
description: "Покупка акций",
figi: null,
instrumentUid: null,
ticker: "SBER",
instrumentType: "share",
logoName: null,
payment: null,
quantity: "2",
price: { currency: "RUB", value: "100" },
accruedInterest: null,
commission: { currency: "RUB", value: "1" },
};
function configureTestAuth() {
configureAuthClient({
accessToken: () => "token",
refresh: async () => true,
clear: vi.fn(),
});
}
function renderPage() {
return render(
<QueryClientProvider client={createTestQueryClient()}>
<MantineProvider>
<MemoryRouter initialEntries={["/accounts/account-1/operations"]}>
<Routes>
<Route
path="/accounts/:accountId/operations"
element={<AccountOperationsPage />}
/>
</Routes>
</MemoryRouter>
</MantineProvider>
</QueryClientProvider>,
);
}
describe("LedgerEntryRow", () => {
it("marks cashless operations without rendering operation details", () => {
render(
<MantineProvider>
<MemoryRouter>
<LedgerEntryRow operation={operation} />
</MemoryRouter>
</MantineProvider>,
);
expect(screen.getByText("Без движения денег")).toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "Показать детали" }),
).toBeNull();
expect(screen.queryByText("Цена: 100 ₽")).toBeNull();
expect(screen.queryByText("Количество: 2")).toBeNull();
});
it("labels a positive payment with its category type", () => {
render(
<MantineProvider>
<MemoryRouter>
<LedgerEntryRow
operation={{
...operation,
payment: { currency: "RUB", value: "15" },
}}
/>
</MemoryRouter>
</MantineProvider>,
);
expect(screen.getByText("Сделка")).toBeInTheDocument();
expect(screen.getByText("+15 ₽")).toBeInTheDocument();
});
it("labels a coupon income as Купон", () => {
render(
<MantineProvider>
<MemoryRouter>
<LedgerEntryRow
operation={{
...operation,
type: "OPERATION_TYPE_COUPON",
category: "income",
payment: { currency: "RUB", value: "8" },
}}
/>
</MemoryRouter>
</MantineProvider>,
);
expect(screen.getByText("Купон")).toBeInTheDocument();
expect(screen.getByText("+8 ₽")).toBeInTheDocument();
});
it("labels a dividend income as Дивиденд", () => {
render(
<MantineProvider>
<MemoryRouter>
<LedgerEntryRow
operation={{
...operation,
type: "OPERATION_TYPE_DIVIDEND",
category: "income",
payment: { currency: "RUB", value: "20" },
}}
/>
</MemoryRouter>
</MantineProvider>,
);
expect(screen.getByText("Дивиденд")).toBeInTheDocument();
expect(screen.getByText("+20 ₽")).toBeInTheDocument();
});
it("labels a fee as Комиссия", () => {
render(
<MantineProvider>
<MemoryRouter>
<LedgerEntryRow
operation={{
...operation,
type: "OPERATION_TYPE_SERVICE_FEE",
category: "fee",
payment: { currency: "RUB", value: "-3" },
}}
/>
</MemoryRouter>
</MantineProvider>,
);
expect(screen.getByText("Комиссия")).toBeInTheDocument();
expect(screen.getByText("−3 ₽")).toBeInTheDocument();
});
it("keeps a zero payment neutral", () => {
render(
<MantineProvider>
<MemoryRouter>
<LedgerEntryRow
operation={{
...operation,
payment: { currency: "RUB", value: "0" },
}}
/>
</MemoryRouter>
</MantineProvider>,
);
expect(screen.getByText("Без движения денег")).toBeInTheDocument();
expect(screen.queryByText("Сделка")).toBeNull();
});
it("uses an instrument initial when the ledger entry has no logo", () => {
render(
<MantineProvider>
<MemoryRouter>
<LedgerEntryRow operation={operation} />
</MemoryRouter>
</MantineProvider>,
);
expect(screen.getByText("S")).toBeInTheDocument();
});
});
describe("AccountOperationsPage", () => {
it("resets cursor pagination when filters change", async () => {
configureTestAuth();
const searches: string[] = [];
server.use(
http.get(
"*/api/v1/brokerage-accounts/:accountId/operations",
({ request }) => {
const url = new URL(request.url);
searches.push(url.search);
return HttpResponse.json({
accountId: "account-1",
items: [operation],
nextCursor: url.searchParams.get("cursor") ? null : "next-1",
hasNext: !url.searchParams.get("cursor"),
observedAt: "2026-08-14T00:00:00Z",
});
},
),
);
renderPage();
expect(
await screen.findByRole("heading", { name: "Журнал операций" }),
).toBeInTheDocument();
expect(
screen.queryByRole("link", { name: "К счету" }),
).not.toBeInTheDocument();
fireEvent.click(await screen.findByRole("button", { name: "Далее" }));
await waitFor(() => expect(searches.at(-1)).toContain("cursor=next-1"));
fireEvent.click(screen.getByRole("combobox", { name: "Категории" }));
fireEvent.click(await screen.findByText("Налог"));
fireEvent.click(screen.getByRole("button", { name: "Применить" }));
await waitFor(() => expect(searches.at(-1)).toContain("categories=tax"));
expect(searches.at(-1)).not.toContain("cursor=");
});
it("does not refetch when draft changes without apply", async () => {
configureTestAuth();
const searches: string[] = [];
server.use(
http.get(
"*/api/v1/brokerage-accounts/:accountId/operations",
({ request }) => {
const url = new URL(request.url);
searches.push(url.search);
return HttpResponse.json({
accountId: "account-1",
items: [operation],
nextCursor: null,
hasNext: false,
observedAt: "2026-08-14T00:00:00Z",
});
},
),
);
renderPage();
expect(
await screen.findByRole("heading", { name: "Журнал операций" }),
).toBeInTheDocument();
await waitFor(() => expect(searches.length).toBeGreaterThan(0));
const countBefore = searches.length;
fireEvent.click(screen.getByRole("combobox", { name: "Категории" }));
fireEvent.click(await screen.findByText("Налог"));
await new Promise((resolve) => setTimeout(resolve, 100));
expect(searches.length).toBe(countBefore);
expect(searches.some((s) => s.includes("categories=tax"))).toBe(false);
});
it("reset clears filters and refetches unfiltered", async () => {
configureTestAuth();
const searches: string[] = [];
server.use(
http.get(
"*/api/v1/brokerage-accounts/:accountId/operations",
({ request }) => {
const url = new URL(request.url);
searches.push(url.search);
return HttpResponse.json({
accountId: "account-1",
items: [operation],
nextCursor: null,
hasNext: false,
observedAt: "2026-08-14T00:00:00Z",
});
},
),
);
renderPage();
expect(
await screen.findByRole("heading", { name: "Журнал операций" }),
).toBeInTheDocument();
fireEvent.click(screen.getByRole("combobox", { name: "Категории" }));
fireEvent.click(await screen.findByText("Налог"));
fireEvent.click(screen.getByRole("button", { name: "Применить" }));
await waitFor(() =>
expect(searches.some((s) => s.includes("categories=tax"))).toBe(true),
);
fireEvent.click(screen.getByRole("button", { name: "Сбросить" }));
await waitFor(() => expect(searches.at(-1)).not.toContain("categories="));
expect(screen.getByRole("button", { name: "Применить" })).toBeDisabled();
});
it("renders an error state", async () => {
configureTestAuth();
server.use(
http.get("*/api/v1/brokerage-accounts/:accountId/operations", () =>
HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }),
),
);
renderPage();
expect(
await screen.findByText("Не удалось загрузить журнал"),
).toBeInTheDocument();
});
});
@@ -0,0 +1,23 @@
import type { FC } from "react";
import { useAccountOperationsPageVm } from "./AccountOperationsPage.vm";
import { AccountOperationsPageError } from "./components/AccountOperationsPageError.view";
import { AccountOperationsPageLoaded } from "./components/AccountOperationsPageLoaded.view";
import { AccountOperationsPageLoading } from "./components/AccountOperationsPageLoading.view";
type AccountOperationsPageProps = { accountId?: string };
const AccountOperationsPage: FC<AccountOperationsPageProps> = (props) => {
const viewModel = useAccountOperationsPageVm(props.accountId);
if (viewModel.state === "loading") {
return <AccountOperationsPageLoading />;
}
if (viewModel.state === "error") {
return <AccountOperationsPageError {...viewModel} />;
}
return <AccountOperationsPageLoaded {...viewModel} />;
};
export { AccountOperationsPage };
@@ -0,0 +1,170 @@
import { useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { useParams, useSearchParams } from "react-router";
import {
type BrokerageOperation,
brokerageOperationsQueryOptions,
type OperationCategory,
operationCategories,
useBrokerageOperations,
} from "@/entities/broker-operation";
import { apiErrorCode } from "@/shared/api";
type AccountOperationsPageViewModel =
| { state: "loading" }
| { state: "error"; retry: () => void }
| {
state: "loaded";
refreshing?: boolean;
refreshError?: boolean;
retry?: () => void;
draftFrom: string | null;
draftTo: string | null;
draftCategories: OperationCategory[];
items: BrokerageOperation[];
hasNext: boolean;
hasPrevious: boolean;
canApply: boolean;
onDraftFromChange: (value: string | null) => void;
onDraftToChange: (value: string | null) => void;
onDraftCategoriesChange: (value: OperationCategory[]) => void;
onApply: () => void;
onReset: () => void;
onNext: () => void;
onPrevious: () => void;
};
const useAccountOperationsPageVm = (
scopeId?: string,
): AccountOperationsPageViewModel => {
const { accountId: routeAccountId } = useParams();
const accountId = scopeId ?? routeAccountId;
const queryClient = useQueryClient();
const [searchParams, setSearchParams] = useSearchParams();
const appliedFrom = searchParams.get("from");
const appliedTo = searchParams.get("to");
const appliedCategories = operationCategories.filter((category) =>
(searchParams.get("categories") ?? "").split(",").includes(category),
);
const [draftFrom, setDraftFrom] = useState<string | null>(appliedFrom);
const [draftTo, setDraftTo] = useState<string | null>(appliedTo);
const [draftCategories, setDraftCategories] =
useState<OperationCategory[]>(appliedCategories);
const scopeKey = JSON.stringify([
accountId,
appliedFrom,
appliedTo,
appliedCategories,
]);
const [pagination, setPagination] = useState<{
scopeKey: string;
cursors: string[];
}>({ scopeKey, cursors: [] });
const cursors = pagination.scopeKey === scopeKey ? pagination.cursors : [];
const cursor = cursors.at(-1);
useEffect(() => {
setDraftFrom(searchParams.get("from"));
setDraftTo(searchParams.get("to"));
setDraftCategories(
operationCategories.filter((category) =>
(searchParams.get("categories") ?? "").split(",").includes(category),
),
);
}, [searchParams]);
const firstPageQuery = {
from: dateStart(appliedFrom),
to: dateEnd(appliedTo),
...(appliedCategories.length ? { categories: appliedCategories } : {}),
limit: 100,
};
const operations = useBrokerageOperations(accountId, {
...firstPageQuery,
...(cursor ? { cursor } : {}),
});
const resetQueryKey = brokerageOperationsQueryOptions(accountId, {
limit: 100,
}).queryKey;
const resetCursors = () => setPagination({ scopeKey, cursors: [] });
const retry = () => {
if (apiErrorCode(operations.error) === "INVALID_OPERATIONS_CURSOR") {
void queryClient.invalidateQueries({
queryKey: brokerageOperationsQueryOptions(accountId, firstPageQuery)
.queryKey,
exact: true,
});
resetCursors();
} else void operations.refetch();
};
if (operations.isLoading) return { state: "loading" };
if (
operations.isError &&
(!operations.data ||
apiErrorCode(operations.error) === "INVALID_OPERATIONS_CURSOR")
)
return { state: "error", retry };
if (!operations.data) return { state: "loading" };
const nextCursor = operations.data.nextCursor;
const isDirty =
draftFrom !== appliedFrom ||
draftTo !== appliedTo ||
!sameCategories(draftCategories, appliedCategories);
return {
state: "loaded",
refreshing: operations.isFetching,
refreshError: operations.isError,
retry,
draftFrom,
draftTo,
draftCategories,
items: operations.data.items,
hasNext: Boolean(operations.data.hasNext && nextCursor),
hasPrevious: Boolean(cursors.length),
canApply: isDirty,
onDraftFromChange: setDraftFrom,
onDraftToChange: setDraftTo,
onDraftCategoriesChange: setDraftCategories,
onApply: () => {
setSearchParams({
...(draftFrom ? { from: draftFrom } : {}),
...(draftTo ? { to: draftTo } : {}),
...(draftCategories.length
? { categories: draftCategories.join(",") }
: {}),
});
resetCursors();
},
onReset: () => {
setDraftFrom(null);
setDraftTo(null);
setDraftCategories([]);
setSearchParams({});
resetCursors();
void queryClient.invalidateQueries({ queryKey: resetQueryKey });
},
onNext: () => {
if (nextCursor)
setPagination({ scopeKey, cursors: [...cursors, nextCursor] });
},
onPrevious: () =>
setPagination({ scopeKey, cursors: cursors.slice(0, -1) }),
};
};
function dateStart(value: string | null) {
return value ? `${value}T00:00:00.000Z` : undefined;
}
function dateEnd(value: string | null) {
return value ? `${value}T23:59:59.999Z` : undefined;
}
function sameCategories(a: OperationCategory[], b: OperationCategory[]) {
return a.length === b.length && a.every((value) => b.includes(value));
}
export { type AccountOperationsPageViewModel, useAccountOperationsPageVm };
@@ -0,0 +1,28 @@
import { Button } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm";
type AccountOperationsPageErrorProps = Extract<
AccountOperationsPageViewModel,
{ state: "error" }
>;
const AccountOperationsPageError: FC<AccountOperationsPageErrorProps> = (
props,
) => {
const { retry } = props;
const { t } = useTranslation();
return (
<StateView
error
title={t("ledger.errorTitle")}
text={t("ledger.errorText")}
action={<Button onClick={retry}>{t("ledger.retry")}</Button>}
/>
);
};
export { AccountOperationsPageError };
@@ -0,0 +1,143 @@
import {
Alert,
Button,
Group,
MultiSelect,
Progress,
Stack,
Title,
} from "@mantine/core";
import { DatePickerInput } from "@mantine/dates";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import {
LedgerEntryRow,
type OperationCategory,
operationCategories,
} from "@/entities/broker-operation";
import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm";
type AccountOperationsPageLoadedProps = Extract<
AccountOperationsPageViewModel,
{ state: "loaded" }
>;
const operationCategorySet = new Set<string>(operationCategories);
function fromMultiSelectValue(value: string[]) {
return value.filter((item): item is OperationCategory =>
operationCategorySet.has(item),
);
}
const AccountOperationsPageLoaded: FC<AccountOperationsPageLoadedProps> = (
props,
) => {
const {
canApply,
draftCategories,
draftFrom,
draftTo,
hasNext,
hasPrevious,
items,
onApply,
onDraftCategoriesChange,
onDraftFromChange,
onDraftToChange,
onNext,
onPrevious,
onReset,
} = props;
const { t } = useTranslation();
const categoryData = operationCategories.map((category) => ({
value: category,
label: t(`ledger.category.${category}`),
}));
return (
<Stack gap="lg">
<Title order={1}>{t("ledger.title")}</Title>
{props.refreshing ? (
<Progress value={100} animated aria-label={t("accounts.refreshing")} />
) : null}
{props.refreshError ? (
<Alert color="yellow">
{t("accounts.refreshError")}
<Button variant="subtle" onClick={props.retry}>
{t("accounts.retry")}
</Button>
</Alert>
) : null}
<Group align="end">
<DatePickerInput
type="range"
allowSingleDateInRange
clearable
clearButtonProps={{ "aria-label": t("ledger.clearPeriod") }}
label={t("ledger.period")}
value={[draftFrom, draftTo]}
onChange={([from, to]) => {
onDraftFromChange(from);
onDraftToChange(to);
}}
valueFormat="DD.MM.YYYY"
popoverProps={{
returnFocus: true,
middlewares: { shift: { crossAxis: true } },
}}
/>
</Group>
<MultiSelect
label={t("ledger.categories")}
placeholder={t("ledger.categoriesPlaceholder")}
data={categoryData}
value={draftCategories}
onChange={(value) =>
onDraftCategoriesChange(fromMultiSelectValue(value))
}
clearable
clearButtonProps={{ "aria-label": t("ledger.clearPeriod") }}
/>
<Group>
<Button onClick={onApply} disabled={!canApply}>
{t("ledger.apply")}
</Button>
<Button variant="default" onClick={onReset}>
{t("ledger.reset")}
</Button>
</Group>
{items.length ? (
items.map((operation) => (
<LedgerEntryRow
key={JSON.stringify([
operation.account?.id,
operation.id,
operation.logoName,
])}
operation={operation}
/>
))
) : (
<StateView
title={t("ledger.emptyTitle")}
text={t("ledger.emptyText")}
/>
)}
{hasNext || hasPrevious ? (
<Group justify="space-between">
<Button disabled={!hasPrevious} onClick={onPrevious}>
{t("ledger.previous")}
</Button>
<Button disabled={!hasNext} onClick={onNext}>
{t("ledger.next")}
</Button>
</Group>
) : null}
</Stack>
);
};
export { AccountOperationsPageLoaded };
@@ -0,0 +1,32 @@
import { Group, Skeleton, Stack } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
const skeletonRowIds = ["first", "second", "third", "fourth"];
const AccountOperationsPageLoading: FC = () => {
const { t } = useTranslation();
return (
<LoadingSkeleton label={t("states.loadingTitle")}>
<Skeleton height={32} width="40%" />
<Group grow>
<Skeleton height={48} radius="sm" />
<Skeleton height={48} radius="sm" />
</Group>
<Skeleton height={48} radius="sm" />
<Group>
<Skeleton height={36} width={110} radius="sm" />
<Skeleton height={36} width={110} radius="sm" />
</Group>
<Stack gap="xs">
{skeletonRowIds.map((id) => (
<Skeleton key={id} height={64} radius="md" />
))}
</Stack>
</LoadingSkeleton>
);
};
export { AccountOperationsPageLoading };