refactor: enforce frontend view model boundaries
Frontend verify / commits (pull_request) Successful in 28s
Frontend verify / security (pull_request) Successful in 10s
Frontend verify / verify (pull_request) Successful in 8m19s

This commit is contained in:
2026-09-28 18:48:23 +03:00
parent 5b69003516
commit ca0ad4f824
287 changed files with 8558 additions and 4538 deletions
@@ -1,6 +1,5 @@
import type { FC } from "react";
import "dayjs/locale/ru";
import { MantineProvider } from "@mantine/core";
import { DatesProvider } from "@mantine/dates";
import { QueryClientProvider } from "@tanstack/react-query";
@@ -13,6 +12,7 @@ import {
waitFor,
within,
} from "@testing-library/react";
import "dayjs/locale/ru";
import { http, HttpResponse } from "msw";
import {
MemoryRouter,
@@ -38,49 +38,50 @@ import {
} from "./AccountIncomePage.vm";
import { IncomePayments } from "./components/IncomePayments.view";
const analytics = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
accountId: "account-1",
bucketGranularity: "day",
buckets: [
{
period: { from: "2026-08-01", to: "2026-08-01" },
totalsByCurrency: [summary("RUB", "10", "2")],
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
const analytics
= {
accountId: "account-1",
bucketGranularity: "day",
buckets: [
{
period: { from: "2026-08-01", to: "2026-08-01" },
totalsByCurrency: [summary("RUB", "10", "2")],
},
],
calculatedAt: "2026-08-27T00:00:00Z",
entries: [
entry(),
{
...entry(),
id: "dividend-1",
payment: money("RUB", "2"),
type: "OPERATION_TYPE_DIVIDEND",
},
],
instruments: [
{
coupon: money("RUB", "10"),
displayName: "BOND",
dividend: money("RUB", "2"),
figi: "FIGI",
instrumentType: "bond",
instrumentUid: null,
key: "income-group-opaque-v2",
receiptCount: 2,
ticker: "BOND",
total: money("RUB", "12"),
},
],
period: { from: "2026-08-01", to: "2026-08-27" },
previous: {
period: { from: "2026-07-01", to: "2026-07-31" },
totalsByCurrency: [comparison("RUB")],
},
],
calculatedAt: "2026-08-27T00:00:00Z",
entries: [
entry(),
{
...entry(),
id: "dividend-1",
payment: money("RUB", "2"),
type: "OPERATION_TYPE_DIVIDEND",
},
],
instruments: [
{
coupon: money("RUB", "10"),
displayName: "BOND",
dividend: money("RUB", "2"),
figi: "FIGI",
instrumentType: "bond",
instrumentUid: null,
key: "income-group-opaque-v2",
receiptCount: 2,
ticker: "BOND",
total: money("RUB", "12"),
},
],
period: { from: "2026-08-01", to: "2026-08-27" },
previous: {
period: { from: "2026-07-01", to: "2026-07-31" },
totalsByCurrency: [comparison("RUB")],
},
totalsByCurrency: [summary("RUB", "10", "2")],
yearComparison: null,
}
/* eslint-enable unicorn/no-null */) satisfies IncomeAnalytics;
totalsByCurrency: [summary("RUB", "10", "2")],
yearComparison: null,
} satisfies /* eslint-enable unicorn/no-null */ IncomeAnalytics;
function comparison(currency: string) {
return {
@@ -92,7 +93,8 @@ function comparison(currency: string) {
}
function entry(): IncomeAnalytics["entries"][number] {
return (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
return (
{
accruedInterest: null,
category: "income",
@@ -111,7 +113,8 @@ function entry(): IncomeAnalytics["entries"][number] {
ticker: "BOND",
type: "OPERATION_TYPE_COUPON",
}
/* eslint-enable unicorn/no-null */);
/* eslint-enable unicorn/no-null */
);
}
function money(currency: string, value: string) {
@@ -125,6 +128,7 @@ function renderPage(search = "from=2026-08-01&to=2026-08-27") {
refresh: () => Promise.resolve(true),
});
const queryClient = createTestQueryClient();
const view = render(
<MantineProvider env="test">
<DatesProvider settings={{ locale: "ru" }}>
@@ -133,11 +137,13 @@ function renderPage(search = "from=2026-08-01&to=2026-08-27") {
initialEntries={[`/accounts/account-1/income?${search}`]}
>
<LocationProbe />
<Routes>
<Route
element={<AccountIncomePage />}
path="/accounts/:accountId/income"
/>
<Route
element={<h1>Events</h1>}
path="/accounts/:accountId/events"
@@ -148,6 +154,7 @@ function renderPage(search = "from=2026-08-01&to=2026-08-27") {
</DatesProvider>
</MantineProvider>,
);
return { ...view, queryClient };
}
@@ -171,10 +178,12 @@ describe("AccountIncomePage", () => {
server.use(
http.all("*/api/v1/*", ({ request }) => {
requests.push(request.url);
return new HttpResponse(null, { status: 503 });
}),
);
const queryClient = createTestQueryClient();
const { result } = renderHook(() => useAccountIncomePageViewModel(), {
wrapper: ({ children }) => (
<QueryClientProvider client={queryClient}>
@@ -184,6 +193,7 @@ describe("AccountIncomePage", () => {
</QueryClientProvider>
),
});
await new Promise(resolve => setTimeout(resolve, 0));
expect(result.current).toEqual({ state: "loading" });
expect(queryClient.isFetching()).toBe(0);
@@ -198,21 +208,26 @@ describe("AccountIncomePage", () => {
"*/api/v1/brokerage-accounts/:accountId/income-analytics",
({ request }) => {
requested.push(new URL(request.url).search);
return HttpResponse.json(
resource(null, (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
resource(
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
null,
{
sync: {
errorCode: "TBANK_UNAVAILABLE",
id: null,
state: "failed",
},
}
/* eslint-enable unicorn/no-null */)),
},
/* eslint-enable unicorn/no-null */
),
);
},
),
http.post("*/api/v1/tbank-sync", async ({ request }) => {
syncRequests.push(await request.json());
return HttpResponse.json(
{ code: "TBANK_UNAVAILABLE" },
{ status: 503 },
@@ -243,6 +258,7 @@ describe("AccountIncomePage", () => {
"*/api/v1/brokerage-accounts/:accountId/income-analytics",
({ request }) => {
requested.push(new URL(request.url).search);
return HttpResponse.json(resource(analytics));
},
),
@@ -255,18 +271,21 @@ describe("AccountIncomePage", () => {
it("preserves every repeated-ID payment when an open card updates", async () => {
const first = { ...entry(), description: "Выплата A", id: "same-id" };
const second = {
...entry(),
description: "Выплата B",
id: "same-id",
payment: money("RUB", "-2"),
};
const third = {
...entry(),
description: "Выплата C",
id: "other-id",
payment: money("RUB", "1"),
};
function breakdown(entries: IncomeAnalytics["entries"], total: string) {
const display = toIncomeDisplayModel({
...analytics,
@@ -281,19 +300,24 @@ describe("AccountIncomePage", () => {
},
],
});
expect(display).not.toBeNull();
return (
<MantineProvider env="test">
<IncomePayments entries={display?.entries ?? []} />
</MantineProvider>
);
}
const { rerender } = render(breakdown([first, second, third], "9"));
const panel = await screen.findByRole("region", { name: "Выплаты" });
const payments = () =>
within(panel)
.getAllByText(/^Выплата [ABC]$/)
.map(element => element.textContent);
expect(payments()).toEqual(["Выплата A", "Выплата B", "Выплата C"]);
rerender(breakdown([third, first, second], "9"));
@@ -323,6 +347,7 @@ describe("AccountIncomePage", () => {
analytics.entries[1],
],
};
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json(resource(response)),
@@ -409,8 +434,9 @@ describe("AccountIncomePage", () => {
});
it("renders the signed drill-down using opaque membership rather than instrument identity", async () => {
const response = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
const response
= {
...analytics,
entries: [
{
@@ -436,8 +462,9 @@ describe("AccountIncomePage", () => {
total: money("RUB", "8"),
},
],
}
/* eslint-enable unicorn/no-null */);
};
/* eslint-enable unicorn/no-null */
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json(resource(response)),
@@ -486,9 +513,11 @@ describe("AccountIncomePage", () => {
expect(eventsRequest).not.toHaveBeenCalled();
expect(screen.getByRole("region", { name: "Выплаты" })).toBeInTheDocument();
const year = screen.getByRole("region", { name: "Годом ранее" });
const selected = within(year).getByRole("region", {
name: "01.08.2026 – 27.08.2026",
});
expect(
screen.getByRole("region", { name: "01.08.2025 – 27.08.2025" }),
).toBeInTheDocument();
@@ -502,13 +531,17 @@ describe("AccountIncomePage", () => {
).toBeInTheDocument();
expect(screen.queryByText("Сравнения")).not.toBeInTheDocument();
expect(screen.queryByText("RUB", { exact: true })).not.toBeInTheDocument();
for (const amount of ["10 ₽", "2 ₽", "12 ₽"]) {
expect(within(selected).getByText(amount)).toBeInTheDocument();
}
const difference = within(year).getByRole("region", { name: "Разница" });
for (const amount of ["+9 ₽", "+2 ₽", "+11 ₽"]) {
expect(within(difference).getByText(amount)).toBeInTheDocument();
}
expect(within(difference).getByText("+900 %")).toBeInTheDocument();
expect(within(difference).getByText("+1 100 %")).toBeInTheDocument();
expect(within(difference).queryByText("нет базы")).not.toBeInTheDocument();
@@ -523,14 +556,13 @@ describe("AccountIncomePage", () => {
const dependencies = [
{ ...resource(analytics).meta, role: "selected" as const },
{ ...resource(analytics).meta, role: "previous" as const },
(
{
...resource(null).meta,
role: "year" as const,
unavailableReason: "CALENDAR_OR_ACCOUNT_HISTORY",
}
),
{
...resource(null).meta,
role: "year" as const,
unavailableReason: "CALENDAR_OR_ACCOUNT_HISTORY",
},
];
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json(resource(analytics, { dependencies })),
@@ -572,16 +604,47 @@ describe("income comparison display", () => {
["1", "3", "+33,3 %"],
["0.01", "0.04", "+25 %"],
["123456789012345678.123456789", "123456789012345678.123456789", "+100 %"],
["10", "0", /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null],
["0", "0", /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null],
["10", "-0.00", /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null],
["10", "-100", /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null],
["9".repeat(400), "1", /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null],
["1", "9".repeat(400), /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null],
[
"10",
"0",
// eslint-disable-next-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
null,
],
[
"0",
"0",
// eslint-disable-next-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
null,
],
[
"10",
"-0.00",
// eslint-disable-next-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
null,
],
[
"10",
"-100",
// eslint-disable-next-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
null,
],
[
"9".repeat(400),
"1",
// eslint-disable-next-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
null,
],
[
"1",
"9".repeat(400),
// eslint-disable-next-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
null,
],
])("formats change %s against base %s", (difference, base, expected) => {
const value = comparison("RUB");
value.difference.coupon = money("RUB", difference);
value.compared.coupon = money("RUB", base);
const display = toIncomeDisplayModel({
...analytics,
yearComparison: {
@@ -589,10 +652,13 @@ describe("income comparison display", () => {
totalsByCurrency: [value],
},
});
const result = display?.comparison?.values[0];
expect(result?.percentages.coupon?.replaceAll("\u{A0}", " ") ?? /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null).toBe(
expected,
);
expect(
result?.percentages.coupon?.replaceAll("\u{A0}", " ")
// eslint-disable-next-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
?? null,
).toBe(expected);
expect(result?.difference.coupon.value).toBe(difference);
expect(result?.compared.coupon.value).toBe(base);
});
@@ -606,6 +672,7 @@ describe("income comparison display", () => {
totalsByCurrency: [comparison("RUB"), comparison("USD")],
},
});
expect(display?.comparison?.selectedPeriod.replaceAll(/\s/g, " ")).toBe(
"01.12.2025 – 09.01.2026",
);
@@ -622,9 +689,11 @@ describe("income comparison display", () => {
const LocationProbe: FC = () => {
const location = useLocation();
const navigate = useNavigate();
return (
<>
<output data-testid="location">{location.search}</output>
<button onClick={() => navigate(-1)} type="button">
Back
</button>
@@ -639,6 +708,7 @@ function respondWithRequestedPeriod(requests: string[]) {
({ request }) => {
const url = new URL(request.url);
requests.push(url.search);
return HttpResponse.json(
resource({
...analytics,
@@ -753,12 +823,15 @@ describe("income period and snapshot boundary", () => {
await screen.findByLabelText("Период");
selectPeriod();
const { promise: pending, resolve: release } = Promise.withResolvers<void>();
const { promise: pending, resolve: release }
= Promise.withResolvers<void>();
server.use(
http.get(
"*/api/v1/brokerage-accounts/account-1/income-analytics",
async () => {
await pending;
return new HttpResponse(null, { status: 503 });
},
),
@@ -790,7 +863,8 @@ describe("income period and snapshot boundary", () => {
),
),
http.get("*/api/v1/tbank-sync/:id", () =>
HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
HttpResponse.json(
{
errorCode: null,
id: "income",
@@ -799,8 +873,9 @@ describe("income period and snapshot boundary", () => {
resources: [resource(null, { stateVersion: "2" }).meta],
scope: null,
state: "succeeded",
}
/* eslint-enable unicorn/no-null */)),
},
/* eslint-enable unicorn/no-null */
),
),
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json(resource(analytics, { stateVersion: "2" })),
@@ -822,12 +897,15 @@ describe("income period and snapshot boundary", () => {
renderPage();
await screen.findByLabelText("Период");
const { promise: pending, resolve: release } = Promise.withResolvers<void>();
const { promise: pending, resolve: release }
= Promise.withResolvers<void>();
server.use(
http.get(
"*/api/v1/brokerage-accounts/account-1/income-analytics",
async () => {
await pending;
return HttpResponse.json(
resource({
...analytics,
@@ -882,6 +960,7 @@ describe("income period and snapshot boundary", () => {
total: money("RUB", "-3"),
},
];
const display = toIncomeDisplayModel({
...analytics,
entries: instruments.map(instrument => ({
@@ -892,6 +971,7 @@ describe("income period and snapshot boundary", () => {
instruments,
totalsByCurrency: [summary("RUB", "-5", "0"), summary("USD", "10", "0")],
});
render(
<MantineProvider env="test">
<IncomePayments entries={display?.entries ?? []} />
@@ -917,8 +997,11 @@ describe("income period and snapshot boundary", () => {
it("maps comparison notices by role regardless of dependency order or resource key", () => {
const selected = { ...resource(analytics).meta, role: "selected" as const };
const previous = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
const previous
= {
...resource(null).meta,
resourceKey: "opaque/year-looking-key",
role: "previous" as const,
@@ -927,16 +1010,16 @@ it("maps comparison notices by role regardless of dependency order or resource k
id: null,
state: "failed" as const,
},
}
/* eslint-enable unicorn/no-null */);
const year = (
{
...resource(null).meta,
resourceKey: "opaque/previous-looking-key",
role: "year" as const,
unavailableReason: "CALENDAR_OR_ACCOUNT_HISTORY",
}
);
};
/* eslint-enable unicorn/no-null */
const year = {
...resource(null).meta,
resourceKey: "opaque/previous-looking-key",
role: "year" as const,
unavailableReason: "CALENDAR_OR_ACCOUNT_HISTORY",
};
for (const dependencies of [
[selected, previous, year],
[year, selected, previous],
@@ -945,6 +1028,7 @@ it("maps comparison notices by role regardless of dependency order or resource k
...resource(analytics).meta,
dependencies,
});
expect(display?.previousNotice).toBe("comparisonFailed");
expect(display?.yearNotice).toBe("yearUnavailable");
expect(display?.previousComparison).not.toBeNull();
@@ -957,21 +1041,18 @@ it.each([false, true])(
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json(
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
resource(
(/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{ ...analytics, previous: null, yearComparison: null }
/* eslint-enable unicorn/no-null */),
(
{
dependencies: legacy
? [
resource(null).meta,
resource(null).meta,
resource(null).meta,
]
: [],
}
),
{ ...analytics, previous: null, yearComparison: null },
/* eslint-enable unicorn/no-null */ {
dependencies: legacy
? [
resource(null).meta,
resource(null).meta,
resource(null).meta,
]
: [],
},
),
),
),
@@ -992,21 +1073,22 @@ it.each([false, true])(
it("shows selected income before comparison coverage without inventing a zero baseline", async () => {
const dependencies = (["year", "selected", "previous"] as const).map(
role => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
role =>
({
...resource(role === "selected" ? analytics : null).meta,
role,
}
/* eslint-enable unicorn/no-null */)),
}),
/* eslint-enable unicorn/no-null */
);
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json(
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
resource(
(/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{ ...analytics, previous: null, yearComparison: null }
/* eslint-enable unicorn/no-null */),
{ dependencies },
{ ...analytics, previous: null, yearComparison: null },
/* eslint-enable unicorn/no-null */ { dependencies },
),
),
),
@@ -1031,20 +1113,26 @@ it("shows selected income before comparison coverage without inventing a zero ba
it("keeps complete previous comparison while year source failed without inventing its amounts", async () => {
const dependencies = [
{ ...resource(analytics).meta, role: "previous" as const },
(/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
...resource(null).meta,
role: "year" as const,
sync: {
errorCode: "TBANK_UNAVAILABLE",
id: null,
state: "failed" as const,
},
}
/* eslint-enable unicorn/no-null */),
{ ...resource(analytics).meta, role: "selected" as const },
{
...resource(analytics).meta,
role: "previous" as const,
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
},
{
...resource(null).meta,
role: "year" as const,
sync: {
errorCode: "TBANK_UNAVAILABLE",
id: null,
state: "failed" as const,
},
},
/* eslint-enable unicorn/no-null */ {
...resource(analytics).meta,
role: "selected" as const,
},
];
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json(resource(analytics, { dependencies })),