feat: simplify income page filters and payments

This commit is contained in:
2026-09-09 13:50:41 +03:00
parent ab1b53680d
commit 26f229ba3e
13 changed files with 668 additions and 513 deletions
@@ -1,5 +1,8 @@
import "dayjs/locale/ru";
import { MantineProvider } from "@mantine/core";
import { DatesProvider } from "@mantine/dates";
import {
act,
fireEvent,
render,
screen,
@@ -7,15 +10,22 @@ import {
within,
} 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 { FC } from "react";
import {
MemoryRouter,
Route,
Routes,
useLocation,
useNavigate,
} from "react-router";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { IncomeAnalytics } from "@/entities/income";
import { configureAuthClient } from "@/shared/api";
import { createQueryWrapper } from "@/test/query";
import { server } from "@/test/server";
import { AccountIncomePage } from "./AccountIncomePage";
import { isDate, toIncomeDisplayModel } from "./AccountIncomePage.vm";
import { IncomeBreakdown } from "./components/IncomeBreakdown.view";
import { IncomePayments } from "./components/IncomePayments.view";
const analytics = {
accountId: "account-1",
@@ -108,25 +118,31 @@ function renderPage(search = "from=2026-08-01&to=2026-08-27") {
refresh: async () => true,
clear: vi.fn(),
});
const { wrapper: QueryWrapper } = createQueryWrapper();
return render(
<MantineProvider>
<QueryWrapper>
<MemoryRouter initialEntries={[`/accounts/account-1/income?${search}`]}>
<Routes>
<Route
path="/accounts/:accountId/income"
element={<AccountIncomePage />}
/>
<Route
path="/accounts/:accountId/events"
element={<h1>Events</h1>}
/>
</Routes>
</MemoryRouter>
</QueryWrapper>
const { wrapper: QueryWrapper, queryClient } = createQueryWrapper();
const result = render(
<MantineProvider env="test">
<DatesProvider settings={{ locale: "ru" }}>
<QueryWrapper>
<MemoryRouter
initialEntries={[`/accounts/account-1/income?${search}`]}
>
<LocationProbe />
<Routes>
<Route
path="/accounts/:accountId/income"
element={<AccountIncomePage />}
/>
<Route
path="/accounts/:accountId/events"
element={<h1>Events</h1>}
/>
</Routes>
</MemoryRouter>
</QueryWrapper>
</DatesProvider>
</MantineProvider>,
);
return { ...result, queryClient };
}
describe("AccountIncomePage", () => {
@@ -147,7 +163,7 @@ describe("AccountIncomePage", () => {
);
});
it("preserves every repeated-ID payment when an open drill-down updates", async () => {
it("preserves every repeated-ID payment when an open card updates", async () => {
const first = { ...entry(), id: "same-id", description: "Выплата A" };
const second = {
...entry(),
@@ -177,14 +193,13 @@ describe("AccountIncomePage", () => {
});
expect(display).not.toBeNull();
return (
<MantineProvider>
<IncomeBreakdown instruments={display?.instruments ?? []} />
<MantineProvider env="test">
<IncomePayments entries={display?.entries ?? []} />
</MantineProvider>
);
}
const { rerender } = render(breakdown([first, second, third], "9"));
fireEvent.click(screen.getByRole("button", { name: "BOND · 9 ₽ · 3" }));
const panel = await screen.findByRole("region", { name: "BOND · 9 ₽ · 3" });
const panel = await screen.findByRole("region", { name: "Выплаты" });
const payments = () =>
within(panel)
.getAllByText(/^Выплата [ABC]$/)
@@ -201,9 +216,7 @@ describe("AccountIncomePage", () => {
rerender(breakdown([second, first], "8"));
expect(payments()).toEqual(["Выплата B", "Выплата A"]);
expect(
screen.getByRole("button", { name: "BOND · 8 ₽ · 2" }),
).toHaveAttribute("aria-expanded", "true");
expect(within(panel).getAllByRole("listitem")).toHaveLength(2);
});
it.each([
@@ -227,10 +240,14 @@ describe("AccountIncomePage", () => {
);
renderPage();
const retry = await screen.findByRole("button", { name: "Повторить" });
expect(screen.queryByText("BOND · 12 ₽ · 2")).not.toBeInTheDocument();
expect(
screen.queryByRole("region", { name: "Выплаты" }),
).not.toBeInTheDocument();
response = analytics;
fireEvent.click(retry);
expect(await screen.findByText("BOND · 12 ₽ · 2")).toBeInTheDocument();
expect(
await screen.findByRole("region", { name: "Выплаты" }),
).toBeInTheDocument();
});
it.each([
@@ -273,7 +290,9 @@ describe("AccountIncomePage", () => {
expect(
await screen.findByRole("button", { name: "Повторить" }),
).toBeInTheDocument();
expect(screen.queryByText("BOND · 12 ₽ · 2")).not.toBeInTheDocument();
expect(
screen.queryByRole("region", { name: "Выплаты" }),
).not.toBeInTheDocument();
});
it("accepts an empty analytics response", async () => {
@@ -331,10 +350,7 @@ describe("AccountIncomePage", () => {
),
);
renderPage();
fireEvent.click(
await screen.findByRole("button", { name: "BOND · 8 ₽ · 2" }),
);
const panel = await screen.findByRole("region", { name: "BOND · 8 ₽ · 2" });
const panel = await screen.findByRole("region", { name: "Выплаты" });
expect(within(panel).getByText("Исходная выплата")).toBeInTheDocument();
expect(
within(panel).getByText("Отрицательная корректировка"),
@@ -348,39 +364,13 @@ describe("AccountIncomePage", () => {
expect(isDate("2024-02-29")).toBe(true);
});
it("groups income entries once in the view model", () => {
const display = toIncomeDisplayModel(analytics);
expect(display?.instruments[0].entries).toEqual(analytics.entries);
expect(display?.trend[0].buckets[0].total).toEqual(
analytics.buckets[0].totalsByCurrency[0],
);
});
it("renders realized analytics, drill-down, and the independent forecast", async () => {
it("renders realized text and comparisons without subscribing to events", async () => {
const eventsRequest = vi.fn(() => new HttpResponse(null, { status: 503 }));
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json(analytics),
),
http.get("*/api/v1/brokerage-accounts/account-1/events", () =>
HttpResponse.json({
accountId: "account-1",
calculatedAt: "2026-08-27T00:00:00Z",
incomeTotalsByCurrency: [money("RUB", "3")],
events: [
{
type: "coupon",
date: "2026-08-28",
dateKind: "event",
figi: "FIGI",
instrumentUid: null,
ticker: "BOND",
displayName: "BOND",
projectedAmount: money("RUB", "3"),
},
],
}),
),
http.get("*/api/v1/brokerage-accounts/account-1/events", eventsRequest),
);
renderPage();
await waitFor(() =>
@@ -391,8 +381,10 @@ describe("AccountIncomePage", () => {
expect(
screen.getByText("Налоговые операции не включены в этот результат."),
).toBeInTheDocument();
expect(screen.getByText("Ближайший прогноз")).toBeInTheDocument();
expect(screen.getByText("BOND · 12 ₽ · 2")).toBeInTheDocument();
expect(screen.queryByText("Ближайший прогноз")).not.toBeInTheDocument();
expect(screen.queryByText("Динамика")).not.toBeInTheDocument();
expect(eventsRequest).not.toHaveBeenCalled();
expect(screen.getByRole("region", { name: "Выплаты" })).toBeInTheDocument();
expect(
screen.getByText(
"Выбранный период: Купоны 10 ₽ · Дивиденды 2 ₽ · Итого 12 ₽",
@@ -403,54 +395,6 @@ describe("AccountIncomePage", () => {
).toBeInTheDocument();
});
it("renders an empty trend bucket as zero money", async () => {
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json({
...analytics,
buckets: [
...analytics.buckets,
{
period: { from: "2026-08-02", to: "2026-08-02" },
totalsByCurrency: [],
},
],
}),
),
);
renderPage();
await waitFor(() =>
expect(
screen.getByText("2026-08-02 — 2026-08-02: Купоны 0 ₽, Дивиденды 0 ₽"),
).toBeInTheDocument(),
);
});
it("renders signed coupon and dividend segments on opposite baseline sides", async () => {
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json({
...analytics,
buckets: [
{
period: { from: "2026-08-01", to: "2026-08-01" },
totalsByCurrency: [summary("RUB", "-10", "2")],
},
],
}),
),
);
renderPage();
await waitFor(() => {
expect(
screen.getByTestId("trend-negative-coupon-2026-08-01"),
).toBeInTheDocument();
expect(
screen.getByTestId("trend-positive-dividend-2026-08-01"),
).toBeInTheDocument();
});
});
it("shows a recoverable realized error", async () => {
server.use(
http.get(
@@ -466,3 +410,291 @@ describe("AccountIncomePage", () => {
);
});
});
const LocationProbe: FC = () => {
const location = useLocation();
const navigate = useNavigate();
return (
<>
<output data-testid="location">{location.search}</output>
<button type="button" onClick={() => navigate(-1)}>
Back
</button>
</>
);
};
function inputDate(label: string, value: string) {
const field = screen.getByLabelText(label);
fireEvent.focus(field);
fireEvent.input(field, { target: { value } });
fireEvent.blur(field);
return field;
}
function respondWithRequestedPeriod(requests: string[]) {
server.use(
http.get(
"*/api/v1/brokerage-accounts/account-1/income-analytics",
({ request }) => {
const url = new URL(request.url);
requests.push(url.search);
return HttpResponse.json({
...analytics,
period: {
from: url.searchParams.get("from"),
to: url.searchParams.get("to"),
},
});
},
),
);
}
describe("income period and snapshot boundary", () => {
afterEach(() => vi.useRealTimers());
it("restores formatted URL dates, keeps draft unapplied, submits ISO and follows browser history", async () => {
const requests: string[] = [];
respondWithRequestedPeriod(requests);
renderPage();
expect(await screen.findByLabelText("С")).toHaveValue("01.08.2026");
expect(screen.getByLabelText("По")).toHaveValue("27.08.2026");
inputDate("С", "02.08.2026");
expect(requests).toHaveLength(1);
expect(
screen.queryByText("2026-08-01 — 2026-08-27"),
).not.toBeInTheDocument();
expect(screen.getByTestId("location")).toHaveTextContent(
"from=2026-08-01&to=2026-08-27",
);
fireEvent.submit(
screen
.getByRole("button", { name: "Применить" })
.closest("form") as HTMLFormElement,
);
await waitFor(() => expect(requests).toHaveLength(2));
expect(await screen.findByLabelText("С")).toHaveValue("02.08.2026");
expect(screen.getByTestId("location")).toHaveTextContent(
"from=2026-08-02&to=2026-08-27",
);
fireEvent.click(screen.getByRole("button", { name: "Back" }));
await waitFor(() =>
expect(screen.getByLabelText("С")).toHaveValue("01.08.2026"),
);
});
it.each([
["С", "", "Введите существующую дату"],
["С", "31.02.2026", "Введите существующую дату"],
["По", "29.02.2026", "Введите существующую дату"],
["По", "2026-08-02", "Введите существующую дату"],
["С", "01.01.2099", "Дата не может быть позже"],
["По", "01.01.2099", "Дата не может быть позже"],
["По", "31.07.2026", "Укажите корректный период"],
])(
"rejects visible %s=%s without replacing data or URL",
async (label, value, error) => {
const requests: string[] = [];
respondWithRequestedPeriod(requests);
renderPage();
await screen.findByLabelText("С");
const field = inputDate(label, value);
fireEvent.click(screen.getByRole("button", { name: "Применить" }));
expect(await screen.findByText(new RegExp(error))).toBeInTheDocument();
expect(field).toHaveValue(value);
expect(field).toHaveAttribute("aria-invalid", "true");
await waitFor(() => expect(field).toHaveFocus());
expect(requests).toHaveLength(1);
expect(screen.getByTestId("location")).toHaveTextContent(
"from=2026-08-01&to=2026-08-27",
);
expect(
screen.queryByText("2026-08-01 — 2026-08-27"),
).not.toBeInTheDocument();
expect(screen.getByRole("region", { name: "Выплаты" })).toBeVisible();
},
);
it("replaces invalid raw text with a calendar choice and closes the calendar with Escape", async () => {
respondWithRequestedPeriod([]);
renderPage();
const from = await screen.findByLabelText("С");
act(() => from.focus());
fireEvent.input(from, { target: { value: "invalid" } });
// The selected month stays available even when the visible draft is invalid.
const day = await screen.findByRole("button", {
name: /^2 августа 2026$/i,
});
fireEvent.click(day);
expect(from).toHaveValue("02.08.2026");
act(() => from.focus());
fireEvent.keyDown(from, { key: "Escape" });
await waitFor(() =>
expect(
screen.queryByRole("button", { name: /^2 августа 2026$/i }),
).not.toBeInTheDocument(),
);
});
it("resets a dirty default period and errors using Moscow's day across a UTC month boundary", async () => {
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(new Date("2026-08-31T21:30:00Z"));
const requests: string[] = [];
respondWithRequestedPeriod(requests);
renderPage("");
expect(await screen.findByLabelText("С")).toHaveValue("01.09.2026");
expect(screen.getByLabelText("По")).toHaveValue("01.09.2026");
inputDate("С", "wrong");
fireEvent.click(screen.getByRole("button", { name: "Применить" }));
await screen.findByText(/Введите существующую дату/);
fireEvent.click(screen.getByRole("button", { name: "Сбросить" }));
await waitFor(() =>
expect(screen.getByLabelText("С")).toHaveValue("01.09.2026"),
);
expect(
screen.queryByText(/Введите существующую дату/),
).not.toBeInTheDocument();
expect(screen.getByLabelText("По")).toHaveValue("01.09.2026");
expect(screen.getByTestId("location")).toHaveTextContent(
"from=2026-09-01&to=2026-09-01",
);
expect(requests).toEqual(["?from=2026-09-01&to=2026-09-01"]);
});
it("keeps valid data and draft during refetch, warns on failure and retries", async () => {
respondWithRequestedPeriod([]);
const { queryClient } = renderPage();
await screen.findByLabelText("С");
inputDate("С", "02.08.2026");
let release!: () => void;
const pending = new Promise<void>((resolve) => {
release = resolve;
});
server.use(
http.get(
"*/api/v1/brokerage-accounts/account-1/income-analytics",
async () => {
await pending;
return new HttpResponse(null, { status: 503 });
},
),
);
act(() => {
void queryClient.invalidateQueries();
});
expect(
await screen.findByRole("status", { name: "Обновляем пассивный доход" }),
).toBeInTheDocument();
expect(screen.getByRole("region", { name: "Выплаты" })).toBeVisible();
expect(screen.getByLabelText("С")).toHaveValue("02.08.2026");
release();
expect(
await screen.findByText(/Показан последний загруженный результат/),
).toBeInTheDocument();
expect(screen.getByRole("region", { name: "Выплаты" })).toBeVisible();
respondWithRequestedPeriod([]);
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
await waitFor(() =>
expect(
screen.queryByText(/Показан последний загруженный результат/),
).not.toBeInTheDocument(),
);
expect(screen.getByLabelText("С")).toHaveValue("02.08.2026");
});
it("shows busy skeleton for a new uncached period without relabeling the previous result", async () => {
respondWithRequestedPeriod([]);
renderPage();
await screen.findByLabelText("С");
let release!: () => void;
const pending = new Promise<void>((resolve) => {
release = resolve;
});
server.use(
http.get(
"*/api/v1/brokerage-accounts/account-1/income-analytics",
async () => {
await pending;
return HttpResponse.json({
...analytics,
period: { from: "2026-08-02", to: "2026-08-27" },
});
},
),
);
inputDate("С", "02.08.2026");
fireEvent.click(screen.getByRole("button", { name: "Применить" }));
expect(
await screen.findByRole("status", { name: "Загрузка" }),
).toHaveAttribute("aria-busy", "true");
expect(
screen.queryByRole("region", { name: "Выплаты" }),
).not.toBeInTheDocument();
expect(
screen.queryByText("2026-08-02 — 2026-08-27"),
).not.toBeInTheDocument();
release();
expect(await screen.findByLabelText("С")).toHaveValue("02.08.2026");
});
it("shows one flat payment card per entry in server order without currency or instrument groups", () => {
const instruments = [
{
...analytics.instruments[0],
key: "usd",
total: money("USD", "10"),
coupon: money("USD", "10"),
dividend: money("USD", "0"),
receiptCount: 1,
},
{
...analytics.instruments[0],
key: "rub",
total: money("RUB", "-2"),
coupon: money("RUB", "-2"),
dividend: money("RUB", "0"),
receiptCount: 1,
},
{
...analytics.instruments[0],
key: "rub-negative",
displayName: "Другой инструмент",
total: money("RUB", "-3"),
coupon: money("RUB", "-3"),
dividend: money("RUB", "0"),
receiptCount: 1,
},
];
const display = toIncomeDisplayModel({
...analytics,
totalsByCurrency: [summary("RUB", "-5", "0"), summary("USD", "10", "0")],
instruments,
entries: instruments.map((instrument) => ({
...entry(),
instrumentKey: instrument.key,
payment: instrument.total,
})),
});
render(
<MantineProvider env="test">
<IncomePayments entries={display?.entries ?? []} />
</MantineProvider>,
);
expect(
screen.getByRole("heading", { name: "Выплаты" }),
).toBeInTheDocument();
expect(screen.queryByRole("heading", { level: 3 })).not.toBeInTheDocument();
expect(screen.queryByRole("heading", { level: 4 })).not.toBeInTheDocument();
expect(screen.queryByText("RUB")).not.toBeInTheDocument();
expect(screen.queryByText("USD")).not.toBeInTheDocument();
const cards = screen.getAllByRole("listitem");
expect(cards).toHaveLength(3);
expect(cards[0]).toHaveTextContent("+10 USD");
expect(cards[1]).toHaveTextContent("−2 ₽");
expect(cards[2]).toHaveTextContent("−3 ₽");
expect(screen.queryByText(/Итого:|Выплат:/)).not.toBeInTheDocument();
expect(screen.queryByRole("button")).not.toBeInTheDocument();
expect(screen.getAllByText("Купон")).toHaveLength(6);
});
});