feat: add operations page

This commit is contained in:
2026-08-14 13:42:31 +03:00
parent 2cca503519
commit 4f3ee7ddb2
16 changed files with 913 additions and 8 deletions
+1
View File
@@ -0,0 +1 @@
export { AccountOperationsPage } from "./ui/AccountOperationsPage";
@@ -0,0 +1,116 @@
import { MantineProvider } from "@mantine/core";
import { QueryClient, 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 } from "@/entities/broker-operation";
import { server } from "@/test/server";
import { AccountOperationsPage, OperationRow } from "./AccountOperationsPage";
vi.mock("@/features/auth", () => ({
useAuth: () => ({ accessToken: "token" }),
}));
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",
payment: null,
quantity: "2",
price: { currency: "RUB", value: "100" },
accruedInterest: null,
commission: { currency: "RUB", value: "1" },
};
describe("OperationRow", () => {
it("marks cashless operations without rendering operation details", () => {
render(
<MantineProvider>
<MemoryRouter>
<OperationRow operation={operation} />
</MemoryRouter>
</MantineProvider>,
);
expect(screen.getByText("Без движения денег")).toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "Показать детали" }),
).toBeNull();
expect(screen.queryByText("Цена: 100 ₽")).toBeNull();
expect(screen.queryByText("Количество: 2")).toBeNull();
});
});
describe("AccountOperationsPage", () => {
it("resets cursor pagination when filters change", async () => {
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",
});
},
),
);
render(
<QueryClientProvider client={new QueryClient()}>
<MantineProvider>
<MemoryRouter initialEntries={["/accounts/account-1/operations"]}>
<Routes>
<Route
path="/accounts/:accountId/operations"
element={<AccountOperationsPage />}
/>
</Routes>
</MemoryRouter>
</MantineProvider>
</QueryClientProvider>,
);
fireEvent.click(await screen.findByRole("button", { name: "Далее" }));
await waitFor(() => expect(searches.at(-1)).toContain("cursor=next-1"));
fireEvent.click(screen.getByRole("checkbox", { name: "Налог" }));
await waitFor(() => expect(searches.at(-1)).toContain("categories=tax"));
expect(searches.at(-1)).not.toContain("cursor=");
});
it("renders an error state", async () => {
server.use(
http.get("*/api/v1/brokerage-accounts/:accountId/operations", () =>
HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }),
),
);
render(
<QueryClientProvider client={new QueryClient()}>
<MantineProvider>
<MemoryRouter initialEntries={["/accounts/account-1/operations"]}>
<Routes>
<Route
path="/accounts/:accountId/operations"
element={<AccountOperationsPage />}
/>
</Routes>
</MemoryRouter>
</MantineProvider>
</QueryClientProvider>,
);
expect(
await screen.findByText("Не удалось загрузить журнал"),
).toBeInTheDocument();
});
});
@@ -0,0 +1,177 @@
import {
Button,
Card,
Checkbox,
Group,
Stack,
Text,
TextInput,
Title,
} from "@mantine/core";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useParams } from "react-router";
import {
type BrokerageOperation,
type OperationCategory,
operationCategories,
useBrokerageOperations,
} from "@/entities/broker-operation";
import { formatMoney, formatSnapshotTime } from "@/entities/portfolio";
import { useAuth } from "@/features/auth";
import { StateView } from "@/shared/ui";
function dateStart(value: string) {
return value ? `${value}T00:00:00.000Z` : undefined;
}
function dateEnd(value: string) {
return value ? `${value}T23:59:59.999Z` : undefined;
}
export function AccountOperationsPage() {
const { accountId } = useParams();
const { accessToken } = useAuth();
const { t } = useTranslation();
const [from, setFrom] = useState("");
const [to, setTo] = useState("");
const [categories, setCategories] = useState<OperationCategory[]>([]);
const [cursors, setCursors] = useState<string[]>([]);
const cursor = cursors.at(-1);
const operations = useBrokerageOperations(accountId, accessToken, {
from: dateStart(from),
to: dateEnd(to),
...(categories.length ? { categories } : {}),
...(cursor ? { cursor } : {}),
limit: 100,
});
const reset = () => setCursors([]);
if (operations.isLoading)
return (
<StateView
loading
title={t("states.loadingTitle")}
text={t("states.loadingText")}
/>
);
if (operations.isError)
return (
<StateView
error
title={t("ledger.errorTitle")}
text={t("ledger.errorText")}
action={
<Button onClick={() => operations.refetch()}>
{t("ledger.retry")}
</Button>
}
/>
);
return (
<Stack maw={960} gap="lg">
<Group justify="space-between">
<Title order={1}>{t("ledger.title")}</Title>
<Button component={Link} to={`/accounts/${accountId}`} variant="subtle">
{t("ledger.back")}
</Button>
</Group>
<Group align="end">
<TextInput
label={t("ledger.from")}
type="date"
value={from}
onChange={(event) => {
setFrom(event.currentTarget.value);
reset();
}}
/>
<TextInput
label={t("ledger.to")}
type="date"
value={to}
onChange={(event) => {
setTo(event.currentTarget.value);
reset();
}}
/>
</Group>
<Checkbox.Group
label={t("ledger.categories")}
value={categories}
onChange={(value) => {
setCategories(value as OperationCategory[]);
reset();
}}
>
<Group mt="xs">
{operationCategories.map((category) => (
<Checkbox
key={category}
value={category}
label={t(`ledger.category.${category}`)}
/>
))}
</Group>
</Checkbox.Group>
{operations.data.items.length ? (
operations.data.items.map((operation) => (
<OperationRow key={operation.id} operation={operation} />
))
) : (
<StateView
title={t("ledger.emptyTitle")}
text={t("ledger.emptyText")}
/>
)}
{operations.data.hasNext || cursors.length ? (
<Group justify="space-between">
<Button
disabled={!cursors.length}
onClick={() => setCursors((value) => value.slice(0, -1))}
>
{t("ledger.previous")}
</Button>
<Button
disabled={!operations.data.hasNext || !operations.data.nextCursor}
onClick={() =>
operations.data.nextCursor &&
setCursors((value) => [...value, operations.data.nextCursor])
}
>
{t("ledger.next")}
</Button>
</Group>
) : null}
</Stack>
);
}
export function OperationRow({ operation }: { operation: BrokerageOperation }) {
const { t } = useTranslation();
return (
<Card withBorder>
<Group justify="space-between" align="flex-start">
<Stack gap={2}>
<Text fw={700}>{operation.description || operation.type}</Text>
<Text c="dimmed" size="sm">
{formatSnapshotTime(operation.occurredAt)} ·{" "}
{operation.ticker ??
operation.instrumentType ??
t("ledger.noInstrument")}
</Text>
</Stack>
<Stack gap={2} align="end">
<Text fw={700}>
{operation.payment
? formatMoney(operation.payment)
: t("ledger.noMoney")}
</Text>
<Text c="dimmed" size="sm">
{t(`ledger.category.${operation.category}`)}
</Text>
</Stack>
</Group>
</Card>
);
}
+31 -4
View File
@@ -1,8 +1,11 @@
import { MantineProvider } from "@mantine/core";
import { cleanup, render, screen } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { cleanup, render, screen, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { MemoryRouter } from "react-router";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { Portfolio } from "@/entities/portfolio";
import { server } from "@/test/server";
import {
AccountPageEmpty,
AccountPageError,
@@ -12,9 +15,11 @@ import {
function renderPage(ui: React.ReactNode) {
return render(
<MantineProvider>
<MemoryRouter>{ui}</MemoryRouter>
</MantineProvider>,
<QueryClientProvider client={new QueryClient()}>
<MantineProvider>
<MemoryRouter>{ui}</MemoryRouter>
</MantineProvider>
</QueryClientProvider>,
);
}
@@ -114,4 +119,26 @@ describe("AccountPage states", () => {
screen.getByRole("heading", { level: 1, name: "Основной" }),
).toBeInTheDocument();
});
it("keeps the portfolio visible when recent events fail", async () => {
server.use(
http.get("*/api/v1/brokerage-accounts/:accountId/operations", () =>
HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }),
),
);
renderPage(
<AccountPageLoaded
accountId="account-1"
accessToken="token"
portfolio={portfolio}
/>,
);
await waitFor(() =>
expect(
screen.getByText("Не удалось загрузить последние события."),
).toBeInTheDocument(),
);
expect(screen.getByText("Вторая")).toBeInTheDocument();
});
});
+9 -1
View File
@@ -11,10 +11,18 @@ export function AccountPage() {
if (viewModel.state === "loading") return <AccountPageLoading />;
if (viewModel.state === "error") return <AccountPageError {...viewModel} />;
if (viewModel.state === "empty")
return <AccountPageEmpty account={viewModel.account} />;
return (
<AccountPageEmpty
account={viewModel.account}
accountId={viewModel.accountId}
accessToken={viewModel.accessToken}
/>
);
return (
<AccountPageLoaded
account={viewModel.account}
accountId={viewModel.accountId}
accessToken={viewModel.accessToken}
portfolio={viewModel.portfolio}
/>
);
+61 -1
View File
@@ -11,6 +11,7 @@ import {
} from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { useBrokerageOperations } from "@/entities/broker-operation";
import type { BrokerageAccount } from "@/entities/brokerage-account";
import { accountTypeKey } from "@/entities/brokerage-account";
import type { Portfolio } from "@/entities/portfolio";
@@ -80,7 +81,15 @@ export function AccountPageError({
/>
);
}
export function AccountPageEmpty({ account }: { account?: BrokerageAccount }) {
export function AccountPageEmpty({
account,
accountId,
accessToken = null,
}: {
account?: BrokerageAccount;
accountId?: string;
accessToken?: string | null;
}) {
const { t } = useTranslation();
return (
<Stack>
@@ -89,14 +98,19 @@ export function AccountPageEmpty({ account }: { account?: BrokerageAccount }) {
title={t("portfolio.emptyTitle")}
text={t("portfolio.emptyText")}
/>
<RecentOperations accountId={accountId} accessToken={accessToken} />
</Stack>
);
}
export function AccountPageLoaded({
account,
accountId,
accessToken,
portfolio,
}: {
account?: BrokerageAccount;
accountId?: string;
accessToken?: string | null;
portfolio: Portfolio;
}) {
const { t } = useTranslation();
@@ -148,9 +162,55 @@ export function AccountPageLoaded({
</Paper>
))}
</Section>
<RecentOperations
accountId={accountId}
accessToken={accessToken ?? null}
/>
</Stack>
);
}
function RecentOperations({
accountId,
accessToken,
}: {
accountId: string | undefined;
accessToken: string | null;
}) {
const { t } = useTranslation();
const operations = useBrokerageOperations(accountId, accessToken, {
limit: 5,
});
return (
<Section title={t("ledger.recentTitle")}>
{operations.isLoading ? (
<Text c="dimmed">{t("ledger.recentLoading")}</Text>
) : null}
{operations.isError ? (
<Alert color="red">{t("ledger.recentError")}</Alert>
) : null}
{operations.data?.items.length === 0 ? (
<Text c="dimmed">{t("ledger.recentEmpty")}</Text>
) : null}
{operations.data?.items.map((operation) => (
<Paper className={classes.cash} key={operation.id} withBorder>
<Text>{operation.description || operation.type}</Text>
<Text fw={700}>
{operation.payment
? formatMoney(operation.payment)
: t("ledger.noMoney")}
</Text>
</Paper>
))}
<Button
component={Link}
to={`/accounts/${accountId}/operations`}
variant="subtle"
>
{t("ledger.open")}
</Button>
</Section>
);
}
function PositionSection({
title,
positions,
+8 -2
View File
@@ -22,6 +22,12 @@ export function useAccountPageViewModel() {
if (portfolio.isFetching || !portfolio.data)
return { state: "loading" as const };
if (!portfolio.data.positions.length && !portfolio.data.cashBalances.length)
return { state: "empty" as const, account };
return { state: "loaded" as const, account, portfolio: portfolio.data };
return { state: "empty" as const, account, accountId, accessToken };
return {
state: "loaded" as const,
account,
accountId,
accessToken,
portfolio: portfolio.data,
};
}