feat: add all-accounts portfolio pages
Reuse account sections and group securities with per-account holdings. Use Mantine Select to preserve filters and reset pagination on scope changes. Document component reuse guardrails and cover routes, grouping and scope switching.
This commit is contained in:
@@ -0,0 +1,309 @@
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import {
|
||||
act,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
} from "@testing-library/react";
|
||||
import { HttpResponse, http } from "msw";
|
||||
import type { FC } from "react";
|
||||
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 { 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 portfolio: Portfolio = {
|
||||
lastSuccessfulAt: "2026-08-15T12:00:00Z",
|
||||
isStale: false,
|
||||
totalsByCurrency: [{ currency: "RUB", value: "1200" }],
|
||||
cashBalances: [],
|
||||
positions: accounts.map((account) => ({ ...position, account })),
|
||||
};
|
||||
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" },
|
||||
},
|
||||
],
|
||||
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" })),
|
||||
};
|
||||
const CurrentLocation: FC = () => {
|
||||
const location = useLocation();
|
||||
return (
|
||||
<output aria-label="Текущий путь">
|
||||
{location.pathname}
|
||||
{location.search}
|
||||
</output>
|
||||
);
|
||||
};
|
||||
function renderPage(path: string) {
|
||||
const client = createTestQueryClient();
|
||||
render(
|
||||
<QueryClientProvider client={client}>
|
||||
<MantineProvider env="test">
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
<AuthProvider>
|
||||
<AppRoutes />
|
||||
<CurrentLocation />
|
||||
</AuthProvider>
|
||||
</MemoryRouter>
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
return client;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
server.use(
|
||||
http.post("*/api/v1/auth/refresh", () =>
|
||||
HttpResponse.json({
|
||||
accessToken: "test",
|
||||
user: { id: "user", email: "user@example.com" },
|
||||
}),
|
||||
),
|
||||
http.get("*/api/v1/brokerage-accounts", () =>
|
||||
HttpResponse.json(
|
||||
accounts.map((account) => ({
|
||||
...account,
|
||||
type: "BROKERAGE",
|
||||
openedOn: null,
|
||||
portfolioSummary: null,
|
||||
})),
|
||||
),
|
||||
),
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
|
||||
HttpResponse.json(portfolio),
|
||||
),
|
||||
http.get(
|
||||
"*/api/v1/brokerage-accounts/:accountId/operations",
|
||||
({ params }) =>
|
||||
HttpResponse.json({
|
||||
accountId: params.accountId,
|
||||
items,
|
||||
hasNext: false,
|
||||
nextCursor: null,
|
||||
observedAt: receipt.occurredAt,
|
||||
}),
|
||||
),
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/income-analytics", () =>
|
||||
HttpResponse.json(analytics),
|
||||
),
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/events", () =>
|
||||
HttpResponse.json({
|
||||
accountId: "all",
|
||||
calculatedAt: receipt.occurredAt,
|
||||
incomeTotalsByCurrency: [],
|
||||
events: accounts.map((account) => ({
|
||||
account,
|
||||
type: "coupon",
|
||||
date: "2026-09-15",
|
||||
dateKind: "event",
|
||||
figi: null,
|
||||
instrumentUid: null,
|
||||
ticker: "BOND",
|
||||
displayName: "Облигация",
|
||||
isin: null,
|
||||
logoName: null,
|
||||
projectedAmount: { currency: "RUB", value: "2" },
|
||||
})),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
describe("All accounts routes", () => {
|
||||
it.each([
|
||||
["/accounts/all", "Все счета"],
|
||||
["/accounts/all/operations", "Журнал операций"],
|
||||
["/accounts/all/income?from=2026-08-01&to=2026-08-31", "Пассивный доход"],
|
||||
["/accounts/all/events", "Будущие события"],
|
||||
])("opens %s directly", async (path, title) => {
|
||||
renderPage(path);
|
||||
expect(
|
||||
await screen.findByRole("heading", { level: 1, name: title }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByRole("combobox", { name: "Счёт" })).toHaveValue(
|
||||
"Все счета",
|
||||
);
|
||||
});
|
||||
|
||||
it("groups the same security and links its accounts and overview sections", async () => {
|
||||
renderPage("/accounts/all");
|
||||
expect(await screen.findAllByText("Сбербанк")).toHaveLength(1);
|
||||
for (const account of accounts)
|
||||
expect(screen.getByRole("link", { name: account.name })).toHaveAttribute(
|
||||
"href",
|
||||
`/accounts/${account.id}`,
|
||||
);
|
||||
for (const suffix of ["operations", "income", "events"])
|
||||
expect(
|
||||
document.querySelector(`a[href="/accounts/all/${suffix}"]`),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("switches accounts within operations with applied filters and a fresh cursor", async () => {
|
||||
const requests: URL[] = [];
|
||||
server.use(
|
||||
http.get(
|
||||
"*/api/v1/brokerage-accounts/:accountId/operations",
|
||||
({ request, params }) => {
|
||||
const url = new URL(request.url);
|
||||
requests.push(url);
|
||||
return HttpResponse.json({
|
||||
accountId: params.accountId,
|
||||
items: [
|
||||
{
|
||||
...receipt,
|
||||
description: url.searchParams.has("cursor")
|
||||
? "Вторая страница"
|
||||
: "Первая страница",
|
||||
},
|
||||
],
|
||||
hasNext: !url.searchParams.has("cursor"),
|
||||
nextCursor: url.searchParams.has("cursor") ? null : "next",
|
||||
observedAt: receipt.occurredAt,
|
||||
});
|
||||
},
|
||||
),
|
||||
);
|
||||
renderPage(
|
||||
"/accounts/all/operations?from=2026-08-01&to=2026-08-31&categories=income",
|
||||
);
|
||||
await screen.findByText("Первая страница");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Далее" }));
|
||||
await screen.findByText("Вторая страница");
|
||||
fireEvent.click(screen.getByRole("combobox", { name: "Счёт" }));
|
||||
fireEvent.click(await screen.findByRole("option", { name: "ИИС" }));
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
requests.some((url) => url.pathname.includes("/b/operations")),
|
||||
).toBe(true),
|
||||
);
|
||||
const selected = requests.find((url) =>
|
||||
url.pathname.includes("/b/operations"),
|
||||
);
|
||||
expect(selected?.searchParams.get("from")).toBe("2026-08-01T00:00:00.000Z");
|
||||
expect(selected?.searchParams.get("to")).toBe("2026-08-31T23:59:59.999Z");
|
||||
expect(selected?.searchParams.get("categories")).toBe("income");
|
||||
expect(selected?.searchParams.has("cursor")).toBe(false);
|
||||
expect(screen.getByLabelText("Текущий путь")).toHaveTextContent(
|
||||
"/accounts/b/operations?from=2026-08-01&to=2026-08-31&categories=income",
|
||||
);
|
||||
});
|
||||
|
||||
it("restarts an expired aggregate cursor without losing filters", async () => {
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts/all/operations", ({ request }) =>
|
||||
new URL(request.url).searchParams.has("cursor")
|
||||
? HttpResponse.json(
|
||||
{ code: "INVALID_OPERATIONS_CURSOR" },
|
||||
{ status: 400 },
|
||||
)
|
||||
: HttpResponse.json({
|
||||
accountId: "all",
|
||||
items,
|
||||
hasNext: true,
|
||||
nextCursor: "expired",
|
||||
observedAt: receipt.occurredAt,
|
||||
}),
|
||||
),
|
||||
);
|
||||
renderPage("/accounts/all/operations?from=2026-08-01&to=2026-08-31");
|
||||
await screen.findAllByText("Выплата купона");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Далее" }));
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Повторить" }));
|
||||
expect(await screen.findAllByText("Выплата купона")).toHaveLength(2);
|
||||
expect(screen.getByLabelText("Текущий путь")).toHaveTextContent(
|
||||
"from=2026-08-01&to=2026-08-31",
|
||||
);
|
||||
});
|
||||
|
||||
it("retains the complete portfolio during a failed refresh", async () => {
|
||||
const client = renderPage("/accounts/all");
|
||||
await screen.findAllByText("Сбербанк");
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts/all/portfolio", () =>
|
||||
HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }),
|
||||
),
|
||||
);
|
||||
await act(() =>
|
||||
client.invalidateQueries({
|
||||
predicate: ({ queryKey }) => String(queryKey[1]).endsWith("/portfolio"),
|
||||
}),
|
||||
);
|
||||
expect(screen.getAllByText("Сбербанк")).toHaveLength(1);
|
||||
expect(
|
||||
await screen.findByRole("button", {
|
||||
name: "Повторить",
|
||||
}),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -85,6 +85,38 @@ const AppRoutes: FC = () => (
|
||||
</LazyPage>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/accounts/all"
|
||||
element={
|
||||
<LazyPage variant="content">
|
||||
<AccountPage accountId="all" />
|
||||
</LazyPage>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/accounts/all/operations"
|
||||
element={
|
||||
<LazyPage variant="content">
|
||||
<AccountOperationsPage accountId="all" />
|
||||
</LazyPage>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/accounts/all/income"
|
||||
element={
|
||||
<LazyPage variant="content">
|
||||
<AccountIncomePage accountId="all" />
|
||||
</LazyPage>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/accounts/all/events"
|
||||
element={
|
||||
<LazyPage variant="content">
|
||||
<AccountEventsPage accountId="all" />
|
||||
</LazyPage>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/accounts/:accountId"
|
||||
element={
|
||||
|
||||
Reference in New Issue
Block a user