refactor: enforce frontend view model boundaries
This commit is contained in:
@@ -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 })),
|
||||
|
||||
@@ -10,7 +10,14 @@ type AccountIncomePageProps = { accountId?: string };
|
||||
const AccountIncomePage: FC<AccountIncomePageProps> = (props) => {
|
||||
const viewModel = useAccountIncomePageViewModel(props.accountId);
|
||||
if (viewModel.state === "loading") return <AccountIncomePageLoading />;
|
||||
return viewModel.state === "error" ? <AccountIncomePageError {...viewModel} /> : <AccountIncomePageLoaded {...viewModel} />;
|
||||
|
||||
return viewModel.state === "error"
|
||||
? (
|
||||
<AccountIncomePageError {...viewModel} />
|
||||
)
|
||||
: (
|
||||
<AccountIncomePageLoaded {...viewModel} />
|
||||
);
|
||||
};
|
||||
|
||||
export { AccountIncomePage };
|
||||
|
||||
@@ -2,13 +2,12 @@ import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useParams, useSearchParams } from "react-router";
|
||||
import { z } from "zod";
|
||||
|
||||
import { type IncomeAnalytics, useIncomeAnalytics } from "@/entities/income";
|
||||
import { useScreenSync } from "@/features/tbank-connection";
|
||||
import { validationMessage } from "@/shared/i18n";
|
||||
import { formatDate } from "@/shared/lib";
|
||||
|
||||
import { incomeFormSchema } from "../../model/income.schema";
|
||||
import {
|
||||
formatDraftDate,
|
||||
type IncomeForm,
|
||||
@@ -43,6 +42,7 @@ type AccountIncomePageViewModel
|
||||
state: "error";
|
||||
}
|
||||
| { state: "loading" };
|
||||
|
||||
type ComparisonNotice
|
||||
= | "comparisonFailed"
|
||||
| "comparisonPending"
|
||||
@@ -50,15 +50,18 @@ type ComparisonNotice
|
||||
| "yearUnavailable";
|
||||
|
||||
type IncomeDisplayModel = {
|
||||
comparison: null | {
|
||||
comparedPeriod: string;
|
||||
selectedPeriod: string;
|
||||
values: (NonNullable<
|
||||
IncomeAnalytics["yearComparison"]
|
||||
>["totalsByCurrency"][number] & {
|
||||
percentages: Record<"coupon" | "dividend" | "total", null | string>;
|
||||
})[];
|
||||
};
|
||||
comparison: null
|
||||
| {
|
||||
comparedPeriod: string;
|
||||
selectedPeriod: string;
|
||||
values: (NonNullable<
|
||||
IncomeAnalytics["yearComparison"]
|
||||
>["totalsByCurrency"][number] & {
|
||||
percentages: Record<"coupon"
|
||||
| "dividend"
|
||||
| "total", null | string>;
|
||||
})[];
|
||||
};
|
||||
entries: { key: string; operation: IncomeAnalytics["entries"][number] }[];
|
||||
previousComparison: IncomeDisplayModel["comparison"];
|
||||
previousNotice: ComparisonNotice;
|
||||
@@ -67,33 +70,13 @@ type IncomeDisplayModel = {
|
||||
|
||||
type IncomeMeta = ReturnType<typeof useIncomeAnalytics>["meta"];
|
||||
|
||||
const draftDate = z
|
||||
.string()
|
||||
.refine(value => parseDraftDate(value) !== null, {
|
||||
error: validationMessage("income.validation.date"),
|
||||
})
|
||||
.refine(
|
||||
(value) => {
|
||||
const date = parseDraftDate(value);
|
||||
return !date || date <= moscowDate(new Date());
|
||||
},
|
||||
{ error: validationMessage("income.validation.future") },
|
||||
);
|
||||
const incomeFormSchema = z.object({ from: draftDate, to: draftDate }).refine(
|
||||
({ from, to }) => {
|
||||
const start = parseDraftDate(from);
|
||||
const end = parseDraftDate(to);
|
||||
return !start || !end || start <= end;
|
||||
},
|
||||
{ path: ["to"], ...validationMessage("income.validation.period")({}) },
|
||||
);
|
||||
|
||||
const useAccountIncomePageViewModel = (
|
||||
scopeId?: string,
|
||||
): AccountIncomePageViewModel => {
|
||||
const { accountId: routeAccountId } = useParams();
|
||||
const accountId = scopeId ?? routeAccountId ?? "";
|
||||
const [searchParameters, setSearchParameters] = useSearchParams();
|
||||
|
||||
const requested = useMemo(
|
||||
() => ({
|
||||
from: searchParameters.get("from") ?? "",
|
||||
@@ -101,31 +84,39 @@ const useAccountIncomePageViewModel = (
|
||||
}),
|
||||
[searchParameters],
|
||||
);
|
||||
|
||||
const period = useMemo(
|
||||
() => (isValidPeriod(requested) ? requested : defaultPeriod()),
|
||||
[requested],
|
||||
);
|
||||
|
||||
const form = useForm<IncomeForm>({
|
||||
defaultValues: draftPeriod(period),
|
||||
resolver: zodResolver(incomeFormSchema),
|
||||
});
|
||||
|
||||
const [resetRevision, setResetRevision] = useState(0);
|
||||
const analytics = useIncomeAnalytics(accountId, period);
|
||||
|
||||
const sync = useScreenSync(
|
||||
{ accountId, from: period.from, screen: "income", to: period.to },
|
||||
[analytics],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isValidPeriod(requested)) setSearchParameters(period, { replace: true });
|
||||
if (!isValidPeriod(requested))
|
||||
setSearchParameters(period, { replace: true });
|
||||
}, [period, requested, setSearchParameters]);
|
||||
useEffect(() => {
|
||||
form.reset(draftPeriod(period));
|
||||
}, [form, period]);
|
||||
|
||||
if (analytics.isLoading || !analytics.data) {
|
||||
return analytics.isError || analytics.meta?.sync.state === "failed" ? { period, retry: sync.retry, state: "error" } : { state: "loading" };
|
||||
return analytics.isError || analytics.meta?.sync.state === "failed"
|
||||
? { period, retry: sync.retry, state: "error" }
|
||||
: { state: "loading" };
|
||||
}
|
||||
|
||||
const display = toIncomeDisplayModel(analytics.data, analytics.meta);
|
||||
if (!display)
|
||||
return {
|
||||
@@ -133,11 +124,13 @@ const useAccountIncomePageViewModel = (
|
||||
retry: () => analytics.observe(),
|
||||
state: "error",
|
||||
};
|
||||
|
||||
const onSubmit = (values: IncomeForm) => {
|
||||
const from = parseDraftDate(values.from);
|
||||
const to = parseDraftDate(values.to);
|
||||
if (from && to) setSearchParameters({ from, to });
|
||||
};
|
||||
|
||||
const onReset = () => {
|
||||
const next = defaultPeriod();
|
||||
form.reset(draftPeriod(next));
|
||||
@@ -145,6 +138,7 @@ const useAccountIncomePageViewModel = (
|
||||
setResetRevision(revision => revision + 1);
|
||||
setSearchParameters(next, { replace: true });
|
||||
};
|
||||
|
||||
return {
|
||||
analytics: analytics.data,
|
||||
display,
|
||||
@@ -166,7 +160,10 @@ function comparisonDisplay(
|
||||
period: IncomePeriod,
|
||||
comparison: IncomeAnalytics["yearComparison"],
|
||||
): IncomeDisplayModel["comparison"] {
|
||||
if (!comparison) return /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null;
|
||||
if (!comparison)
|
||||
// eslint-disable-next-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model.
|
||||
return null;
|
||||
|
||||
return {
|
||||
comparedPeriod: formatComparisonPeriod(comparison.period),
|
||||
selectedPeriod: formatComparisonPeriod(period),
|
||||
@@ -192,11 +189,11 @@ function comparisonDisplay(
|
||||
|
||||
function comparisonNotice(
|
||||
dependency:
|
||||
| NonNullable<NonNullable<IncomeMeta>["dependencies"]>[number]
|
||||
| undefined,
|
||||
NonNullable<NonNullable<IncomeMeta>["dependencies"]>[number] | undefined,
|
||||
unavailable: "previousUnavailable" | "yearUnavailable",
|
||||
): ComparisonNotice {
|
||||
if (!dependency || dependency.unavailableReason) return unavailable;
|
||||
|
||||
return dependency.sync.state === "failed"
|
||||
? "comparisonFailed"
|
||||
: "comparisonPending";
|
||||
@@ -204,6 +201,7 @@ function comparisonNotice(
|
||||
|
||||
function defaultPeriod(): IncomePeriod {
|
||||
const today = moscowDate(new Date());
|
||||
|
||||
return { from: `${today.slice(0, ISO_MONTH_LENGTH)}-01`, to: today };
|
||||
}
|
||||
|
||||
@@ -221,9 +219,14 @@ function formatIncomeChange(
|
||||
): null | string {
|
||||
// Display-only ratio; server-provided Money values remain exact decimal strings.
|
||||
const base = Number(compared);
|
||||
if (!Number.isFinite(base) || base <= 0) return /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null;
|
||||
if (!Number.isFinite(base) || base <= 0)
|
||||
// eslint-disable-next-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model.
|
||||
return null;
|
||||
const ratio = Number(difference) / base;
|
||||
if (!Number.isFinite(ratio)) return /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null;
|
||||
if (!Number.isFinite(ratio))
|
||||
// eslint-disable-next-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model.
|
||||
return null;
|
||||
|
||||
return new Intl.NumberFormat("ru-RU", {
|
||||
maximumFractionDigits: 1,
|
||||
signDisplay: "exceptZero",
|
||||
@@ -236,6 +239,7 @@ function isValidPeriod(period: IncomePeriod): period is IncomePeriod {
|
||||
const from = new Date(`${period.from}T00:00:00Z`);
|
||||
const to = new Date(`${period.to}T00:00:00Z`);
|
||||
const today = new Date(`${moscowDate(new Date())}T00:00:00Z`);
|
||||
|
||||
return (
|
||||
from.toISOString().slice(0, ISO_DATE_LENGTH) === period.from
|
||||
&& to.toISOString().slice(0, ISO_DATE_LENGTH) === period.to
|
||||
@@ -256,9 +260,11 @@ function toIncomeDisplayModel(
|
||||
receiptCount: number;
|
||||
}
|
||||
>();
|
||||
|
||||
const currencies = new Set(
|
||||
analytics.totalsByCurrency.map(({ currency }) => currency),
|
||||
);
|
||||
|
||||
for (const instrument of analytics.instruments) {
|
||||
if (
|
||||
typeof instrument.key !== "string"
|
||||
@@ -274,8 +280,10 @@ function toIncomeDisplayModel(
|
||||
receiptCount: instrument.receiptCount,
|
||||
});
|
||||
}
|
||||
|
||||
const entries: IncomeDisplayModel["entries"] = [];
|
||||
const occurrences = new Map<string, number>();
|
||||
|
||||
for (const entry of analytics.entries) {
|
||||
if (typeof entry.instrumentKey !== "string" || !entry.instrumentKey.trim())
|
||||
// eslint-disable-next-line unicorn/no-null -- Preserve the existing nullable validation/ref contract.
|
||||
@@ -298,12 +306,16 @@ function toIncomeDisplayModel(
|
||||
operation: entry,
|
||||
});
|
||||
}
|
||||
|
||||
for (const instrument of instruments.values()) {
|
||||
if (instrument.includedCount !== instrument.receiptCount) return /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null;
|
||||
if (instrument.includedCount !== instrument.receiptCount)
|
||||
// eslint-disable-next-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model.
|
||||
return null;
|
||||
}
|
||||
|
||||
const previous = meta?.dependencies?.find(({ role }) => role === "previous");
|
||||
const year = meta?.dependencies?.find(({ role }) => role === "year");
|
||||
|
||||
return {
|
||||
comparison: comparisonDisplay(analytics.period, analytics.yearComparison),
|
||||
entries,
|
||||
|
||||
+1
@@ -10,6 +10,7 @@ type ErrorProps = Extract<AccountIncomePageViewModel, { state: "error" }>;
|
||||
|
||||
const AccountIncomePageError: FC<ErrorProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<StateView
|
||||
action={<Button onClick={props.retry}>{t("income.retry")}</Button>}
|
||||
|
||||
+41
-31
@@ -25,45 +25,46 @@ import { IncomeSummary } from "./IncomeSummary.view";
|
||||
|
||||
type LoadedProps = Extract<AccountIncomePageViewModel, { state: "loaded" }>;
|
||||
|
||||
const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
|
||||
const {
|
||||
analytics,
|
||||
display,
|
||||
form,
|
||||
onReset,
|
||||
onSubmit,
|
||||
refreshError,
|
||||
refreshing,
|
||||
retry,
|
||||
} = props;
|
||||
const AccountIncomePageLoadedSummary: FC<LoadedProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
function renderSummary() {
|
||||
if (props.partial) {
|
||||
return <Alert role="status">{t("investment.partial")}</Alert>;
|
||||
}
|
||||
if (analytics.totalsByCurrency.length > 0) {
|
||||
return <IncomeSummary totals={analytics.totalsByCurrency} />;
|
||||
}
|
||||
return (
|
||||
<StateView
|
||||
text={t("income.emptyText")}
|
||||
title={t("income.emptyTitle")}
|
||||
/>
|
||||
);
|
||||
|
||||
const { analytics } = props;
|
||||
|
||||
if (props.partial) {
|
||||
return <Alert role="status">{t("investment.partial")}</Alert>;
|
||||
}
|
||||
|
||||
return analytics.totalsByCurrency.length > 0
|
||||
? (
|
||||
<IncomeSummary totals={analytics.totalsByCurrency} />
|
||||
)
|
||||
: (
|
||||
<StateView text={t("income.emptyText")} title={t("income.emptyTitle")} />
|
||||
);
|
||||
};
|
||||
|
||||
const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
|
||||
const { display, form, onReset, onSubmit, refreshError, refreshing, retry }
|
||||
= props;
|
||||
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Stack className={classes.page} gap="lg">
|
||||
{!!(props.lastSuccessfulAt) && ((
|
||||
{!!props.lastSuccessfulAt && (
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("investment.sourceTime", {
|
||||
date: formatSnapshotTime(props.lastSuccessfulAt),
|
||||
})}
|
||||
</Text>
|
||||
))}
|
||||
)}
|
||||
|
||||
<Title order={1}>{t("income.title")}</Title>
|
||||
|
||||
<Button disabled={refreshing} onClick={retry} w="fit-content">
|
||||
{t("investment.refresh")}
|
||||
</Button>
|
||||
|
||||
<FormProvider {...form}>
|
||||
<IncomePeriodForm
|
||||
key={props.formRevision}
|
||||
@@ -71,13 +72,16 @@ const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
/>
|
||||
</FormProvider>
|
||||
{!!(refreshing) && ((
|
||||
|
||||
{!!refreshing && (
|
||||
<Group aria-label={t("income.refreshing")} gap="xs" role="status">
|
||||
<Loader size="sm" />
|
||||
|
||||
<Text>{t("income.refreshing")}</Text>
|
||||
</Group>
|
||||
))}
|
||||
{!!(refreshError) && ((
|
||||
)}
|
||||
|
||||
{!!refreshError && (
|
||||
<Alert aria-live="polite" color="orange" role="status">
|
||||
<Stack gap="sm">
|
||||
<Text>
|
||||
@@ -87,24 +91,30 @@ const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
|
||||
: "income.refreshError",
|
||||
)}
|
||||
</Text>
|
||||
|
||||
<Button onClick={retry} variant="default">
|
||||
{t("income.retry")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Alert>
|
||||
))}
|
||||
{renderSummary()}
|
||||
)}
|
||||
|
||||
<AccountIncomePageLoadedSummary {...props} />
|
||||
|
||||
<Alert color="blue">{t("income.taxBoundary")}</Alert>
|
||||
|
||||
<IncomeComparisons
|
||||
comparison={display.previousComparison}
|
||||
notice={t(`income.${display.previousNotice}`)}
|
||||
title={t("income.previousPeriod")}
|
||||
/>
|
||||
|
||||
<IncomeComparisons
|
||||
comparison={display.comparison}
|
||||
notice={t(`income.${display.yearNotice}`)}
|
||||
title={t("income.yearAgo")}
|
||||
/>
|
||||
|
||||
<IncomePayments entries={display.entries} />
|
||||
</Stack>
|
||||
);
|
||||
|
||||
+10
@@ -8,24 +8,34 @@ import classes from "../AccountIncomePage.module.css";
|
||||
|
||||
const AccountIncomePageLoading: FC = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<LoadingSkeleton label={t("states.loadingTitle")}>
|
||||
<Stack gap="lg">
|
||||
<Skeleton height={32} width="40%" />
|
||||
|
||||
<Paper p="md" radius="md" withBorder>
|
||||
<Stack gap="sm">
|
||||
<Skeleton height={20} width="20%" />
|
||||
|
||||
<div className={classes.fields}>
|
||||
<Skeleton height={60} />
|
||||
|
||||
<Skeleton height={60} />
|
||||
</div>
|
||||
|
||||
<Skeleton height={44} width="45%" />
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
<Skeleton height={100} radius="md" />
|
||||
|
||||
<Skeleton height={180} radius="md" />
|
||||
|
||||
<Skeleton height={24} width="25%" />
|
||||
|
||||
<Skeleton height={80} radius="md" />
|
||||
|
||||
<Skeleton height={80} radius="md" />
|
||||
</Stack>
|
||||
</LoadingSkeleton>
|
||||
|
||||
+44
-19
@@ -12,12 +12,16 @@ import classes from "../AccountIncomePage.module.css";
|
||||
type ComparisonProps = NonNullable<IncomeDisplayModel["comparison"]> & {
|
||||
title: string;
|
||||
};
|
||||
|
||||
type ComparisonValuesProps = {
|
||||
kind: "compared" | "difference" | "selected";
|
||||
kind: "compared"
|
||||
| "difference"
|
||||
| "selected";
|
||||
label: string;
|
||||
percentages?: ComparisonProps["values"][number]["percentages"];
|
||||
values: ComparisonProps["values"][number]["selected"];
|
||||
};
|
||||
|
||||
type IncomeComparisonsProps = {
|
||||
comparison: IncomeDisplayModel["comparison"];
|
||||
notice: string;
|
||||
@@ -28,6 +32,7 @@ const IncomeComparisons: FC<IncomeComparisonsProps> = (props) => {
|
||||
return (
|
||||
<Stack>
|
||||
<Title order={2}>{props.title}</Title>
|
||||
|
||||
{props.comparison
|
||||
? (
|
||||
<Comparison {...props.comparison} title={props.title} />
|
||||
@@ -45,6 +50,7 @@ const IncomeComparisons: FC<IncomeComparisonsProps> = (props) => {
|
||||
|
||||
const Comparison: FC<ComparisonProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<section aria-label={props.title} className={classes.comparison}>
|
||||
<Stack gap="md">
|
||||
@@ -61,11 +67,13 @@ const Comparison: FC<ComparisonProps> = (props) => {
|
||||
label={props.selectedPeriod}
|
||||
values={value.selected}
|
||||
/>
|
||||
|
||||
<ComparisonValues
|
||||
kind="compared"
|
||||
label={props.comparedPeriod}
|
||||
values={value.compared}
|
||||
/>
|
||||
|
||||
<ComparisonValues
|
||||
kind="difference"
|
||||
label={t("income.difference")}
|
||||
@@ -75,11 +83,12 @@ const Comparison: FC<ComparisonProps> = (props) => {
|
||||
</div>
|
||||
</Stack>
|
||||
))}
|
||||
{props.values.length === 0 && ((
|
||||
|
||||
{props.values.length === 0 && (
|
||||
<Text c="gray.7" size="sm">
|
||||
{t("income.comparisonEmpty")}
|
||||
</Text>
|
||||
))}
|
||||
)}
|
||||
</Stack>
|
||||
</section>
|
||||
);
|
||||
@@ -87,46 +96,59 @@ const Comparison: FC<ComparisonProps> = (props) => {
|
||||
|
||||
const ComparisonValues: FC<ComparisonValuesProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const data_tone
|
||||
= props.kind === "difference"
|
||||
? differenceTone(props.values.total.value)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<section
|
||||
aria-label={props.label}
|
||||
className={classes.comparisonPanel}
|
||||
data-kind={props.kind}
|
||||
data-tone={
|
||||
(props.kind === "difference") ? (differenceTone(props.values.total.value)) : undefined
|
||||
}
|
||||
data-tone={data_tone}
|
||||
>
|
||||
<Text className={classes.comparisonLabel} fw={600} size="sm">
|
||||
{props.label}
|
||||
</Text>
|
||||
|
||||
<dl className={classes.comparisonValues}>
|
||||
{(["total", "coupon", "dividend"] as const).map((key) => {
|
||||
const money = /* eslint-disable-line security/detect-object-injection -- This lookup uses a fixed typed key set, not an arbitrary external property name. */ props.values[key];
|
||||
const percentage = /* eslint-disable-line security/detect-object-injection -- This lookup uses a fixed typed key set, not an arbitrary external property name. */ props.percentages?.[key];
|
||||
const money
|
||||
// eslint-disable-next-line security/detect-object-injection -- This lookup uses a fixed typed key set, not an arbitrary external property name.
|
||||
= props.values[key];
|
||||
|
||||
const percentage
|
||||
// eslint-disable-next-line security/detect-object-injection -- This lookup uses a fixed typed key set, not an arbitrary external property name.
|
||||
= props.percentages?.[key];
|
||||
|
||||
const tone
|
||||
= props.kind === "difference"
|
||||
? differenceTone(money.value)
|
||||
: undefined;
|
||||
|
||||
const appearanceClass
|
||||
= key === "total"
|
||||
? classes.comparisonTotal
|
||||
: classes.comparisonDetail;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={
|
||||
key === "total"
|
||||
? classes.comparisonTotal
|
||||
: classes.comparisonDetail
|
||||
}
|
||||
key={key}
|
||||
>
|
||||
<div className={appearanceClass} key={key}>
|
||||
<dt>{t(`income.${key}`)}</dt>
|
||||
|
||||
<dd data-tone={tone}>
|
||||
<span>
|
||||
{tone === "positive" ? "+" : ""}
|
||||
|
||||
{formatMoney(money)}
|
||||
</span>
|
||||
{!!(percentage) && ((
|
||||
|
||||
{!!percentage && (
|
||||
<span className={classes.comparisonPercent}>
|
||||
{percentage}
|
||||
</span>
|
||||
))}
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
);
|
||||
@@ -136,8 +158,11 @@ const ComparisonValues: FC<ComparisonValuesProps> = (props) => {
|
||||
);
|
||||
};
|
||||
|
||||
function differenceTone(value: string): "negative" | "neutral" | "positive" {
|
||||
function differenceTone(value: string): "negative"
|
||||
| "neutral"
|
||||
| "positive" {
|
||||
if (!/[1-9]/.test(value)) return "neutral";
|
||||
|
||||
return value.startsWith("-") ? "negative" : "positive";
|
||||
}
|
||||
|
||||
|
||||
@@ -10,13 +10,16 @@ import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
|
||||
import classes from "../AccountIncomePage.module.css";
|
||||
|
||||
type IncomePaymentsProps = { entries: LoadedProps["display"]["entries"] };
|
||||
|
||||
type LoadedProps = Extract<AccountIncomePageViewModel, { state: "loaded" }>;
|
||||
|
||||
const IncomePayments: FC<IncomePaymentsProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Stack aria-label={t("income.payments")} component="section">
|
||||
<Title order={2}>{t("income.payments")}</Title>
|
||||
|
||||
<Stack className={classes.entries} component="ul" gap="sm">
|
||||
{props.entries.map(({ key, operation }) => (
|
||||
<li key={key}>
|
||||
|
||||
+10
-1
@@ -8,6 +8,7 @@ import type { IncomeForm } from "../../../../model/period";
|
||||
import { IncomePeriodForm } from "./IncomePeriodForm.view";
|
||||
|
||||
const period = { from: "01.08.2026", to: "27.08.2026" };
|
||||
|
||||
const errors = {
|
||||
to: { message: "Синтетическая ошибка периода", type: "manual" },
|
||||
};
|
||||
@@ -19,8 +20,13 @@ const PeriodExample: FC<PeriodExampleProps> = (props) => {
|
||||
defaultValues: period,
|
||||
errors: props.invalid ? errors : undefined,
|
||||
});
|
||||
|
||||
const { isSubmitSuccessful } = useFormState({ control: methods.control });
|
||||
const submitted = isSubmitSuccessful ? methods.getValues() : /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null;
|
||||
|
||||
const submitted = isSubmitSuccessful
|
||||
? methods.getValues()
|
||||
: null; // eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
|
||||
|
||||
return (
|
||||
<FormProvider {...methods}>
|
||||
<IncomePeriodForm
|
||||
@@ -29,6 +35,7 @@ const PeriodExample: FC<PeriodExampleProps> = (props) => {
|
||||
}}
|
||||
onSubmit={methods.handleSubmit(() => {})}
|
||||
/>
|
||||
|
||||
<output aria-live="polite">
|
||||
{submitted
|
||||
? `Применено: ${submitted.from} – ${submitted.to}`
|
||||
@@ -54,7 +61,9 @@ const meta = {
|
||||
} satisfies Meta<typeof PeriodExample>;
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Default: Story = {};
|
||||
export const ValidationError: Story = {
|
||||
render: () => <PeriodExample invalid />,
|
||||
|
||||
+20
-38
@@ -2,17 +2,9 @@ import type { FC, SubmitEventHandler } from "react";
|
||||
|
||||
import { Button, Paper, Stack, Text } from "@mantine/core";
|
||||
import { DatePickerInput } from "@mantine/dates";
|
||||
import { useState } from "react";
|
||||
import { useController, useFormContext, useWatch } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import {
|
||||
formatDraftDate,
|
||||
type IncomeForm,
|
||||
moscowDate,
|
||||
parseDraftDate,
|
||||
} from "../../../../model/period";
|
||||
import classes from "../../AccountIncomePage.module.css";
|
||||
import { useIncomePeriodFormVm } from "./IncomePeriodForm.vm";
|
||||
|
||||
type IncomePeriodFormProps = {
|
||||
onReset: () => void;
|
||||
@@ -20,23 +12,20 @@ type IncomePeriodFormProps = {
|
||||
};
|
||||
|
||||
const IncomePeriodForm: FC<IncomePeriodFormProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
const {
|
||||
control,
|
||||
formState: { isSubmitting },
|
||||
} = useFormContext<IncomeForm>();
|
||||
const {
|
||||
field: { onBlur: onFromBlur, onChange: onFromChange, ref: fromRef },
|
||||
fieldState: { error: fromError },
|
||||
} = useController({ control, name: "from" });
|
||||
const {
|
||||
field: { onBlur: onToBlur, onChange: onToChange },
|
||||
fieldState: { error: toError },
|
||||
} = useController({ control, name: "to" });
|
||||
const [from, to] = useWatch({ control, name: ["from", "to"] });
|
||||
const [today, setToday] = useState(() => moscowDate(new Date()));
|
||||
const start = parseDraftDate(from);
|
||||
const end = parseDraftDate(to);
|
||||
end,
|
||||
fromError,
|
||||
fromRef,
|
||||
isSubmitting,
|
||||
onBlur2,
|
||||
onPeriodChange,
|
||||
popoverProps,
|
||||
start,
|
||||
t,
|
||||
today,
|
||||
toError,
|
||||
} = useIncomePeriodFormVm();
|
||||
|
||||
return (
|
||||
<Paper
|
||||
component="form"
|
||||
@@ -47,6 +36,7 @@ const IncomePeriodForm: FC<IncomePeriodFormProps> = (props) => {
|
||||
>
|
||||
<Stack gap="sm">
|
||||
<Text fw={700}>{t("income.period")}</Text>
|
||||
|
||||
<div className={classes.fields}>
|
||||
<DatePickerInput
|
||||
allowSingleDateInRange
|
||||
@@ -56,29 +46,21 @@ const IncomePeriodForm: FC<IncomePeriodFormProps> = (props) => {
|
||||
error={fromError?.message ?? toError?.message}
|
||||
label={t("income.period")}
|
||||
maxDate={today}
|
||||
onBlur={() => {
|
||||
onFromBlur();
|
||||
onToBlur();
|
||||
}}
|
||||
onChange={([from, to]) => {
|
||||
onFromChange(from ? formatDraftDate(from) : "");
|
||||
onToChange(to ? formatDraftDate(to) : "");
|
||||
}}
|
||||
popoverProps={{
|
||||
middlewares: { shift: { crossAxis: true } },
|
||||
onOpen: () => setToday(moscowDate(new Date())),
|
||||
returnFocus: true,
|
||||
}}
|
||||
onBlur={onBlur2}
|
||||
onChange={onPeriodChange}
|
||||
popoverProps={popoverProps}
|
||||
ref={fromRef}
|
||||
type="range"
|
||||
value={[start, end]}
|
||||
valueFormat="DD.MM.YYYY"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={classes.actions}>
|
||||
<Button loading={isSubmitting} type="submit">
|
||||
{t("income.apply")}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
onClick={props.onReset}
|
||||
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
import { useState } from "react";
|
||||
import { useController, useFormContext, useWatch } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import {
|
||||
formatDraftDate,
|
||||
type IncomeForm,
|
||||
moscowDate,
|
||||
parseDraftDate,
|
||||
} from "../../../../model/period";
|
||||
|
||||
function useIncomePeriodFormVm() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const {
|
||||
control,
|
||||
formState: { isSubmitting },
|
||||
} = useFormContext<IncomeForm>();
|
||||
|
||||
const {
|
||||
field: { onBlur: onFromBlur, onChange: onFromChange, ref: fromRef },
|
||||
fieldState: { error: fromError },
|
||||
} = useController({ control, name: "from" });
|
||||
|
||||
const {
|
||||
field: { onBlur: onToBlur, onChange: onToChange },
|
||||
fieldState: { error: toError },
|
||||
} = useController({ control, name: "to" });
|
||||
|
||||
const [from, to] = useWatch({ control, name: ["from", "to"] });
|
||||
const [today, setToday] = useState(() => moscowDate(new Date()));
|
||||
const start = parseDraftDate(from);
|
||||
const end = parseDraftDate(to);
|
||||
|
||||
const onBlur2 = () => {
|
||||
onFromBlur();
|
||||
onToBlur();
|
||||
};
|
||||
|
||||
const onPeriodChange: (value: [null | string, null | string]) => void = ([
|
||||
from,
|
||||
to,
|
||||
]) => {
|
||||
onFromChange(from ? formatDraftDate(from) : "");
|
||||
onToChange(to ? formatDraftDate(to) : "");
|
||||
};
|
||||
|
||||
const popoverProps = {
|
||||
middlewares: { shift: { crossAxis: true } },
|
||||
onOpen: () => setToday(moscowDate(new Date())),
|
||||
returnFocus: true,
|
||||
};
|
||||
|
||||
return {
|
||||
end,
|
||||
fromError,
|
||||
fromRef,
|
||||
isSubmitting,
|
||||
onBlur2,
|
||||
onPeriodChange,
|
||||
popoverProps,
|
||||
start,
|
||||
t,
|
||||
today,
|
||||
toError,
|
||||
};
|
||||
}
|
||||
|
||||
export { useIncomePeriodFormVm };
|
||||
@@ -11,24 +11,18 @@ type IncomeSummaryProps = { totals: IncomeAnalytics["totalsByCurrency"] };
|
||||
|
||||
const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Stack>
|
||||
<Title order={2}>{t("income.summaryTitle")}</Title>
|
||||
|
||||
{props.totals.map(total => (
|
||||
<Paper key={total.currency} p="md" radius="md" withBorder>
|
||||
<Text fw={700}>{formatMoney(total.total)}</Text>
|
||||
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("income.coupon")}
|
||||
:
|
||||
{" "}
|
||||
{formatMoney(total.coupon)}
|
||||
{" "}
|
||||
·
|
||||
{" "}
|
||||
{t("income.dividend")}
|
||||
:
|
||||
{" "}
|
||||
{formatMoney(total.dividend)}
|
||||
{t("income.coupon")}: {formatMoney(total.coupon)} ·{" "}
|
||||
{t("income.dividend")}: {formatMoney(total.dividend)}
|
||||
</Text>
|
||||
</Paper>
|
||||
))}
|
||||
|
||||
Reference in New Issue
Block a user