feat: simplify income page filters and payments
This commit is contained in:
@@ -1,51 +1,45 @@
|
|||||||
.trendChart {
|
.page {
|
||||||
align-items: stretch;
|
min-width: 0;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
.fields {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: var(--mantine-spacing-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.actions {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: var(--mantine-spacing-xs);
|
flex-wrap: wrap;
|
||||||
height: 160px;
|
gap: var(--mantine-spacing-sm);
|
||||||
overflow-x: auto;
|
|
||||||
padding: 0 var(--mantine-spacing-xs);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.trendColumn {
|
.entries {
|
||||||
flex: 1 0 32px;
|
list-style: none;
|
||||||
min-width: 32px;
|
padding: 0;
|
||||||
position: relative;
|
margin: 0;
|
||||||
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.baseline {
|
/* Keep the reused Ledger row's full text readable inside income cards. */
|
||||||
background: var(--mantine-color-gray-4);
|
.entries :global(.mantine-Text-root) {
|
||||||
height: 1px;
|
-webkit-line-clamp: unset;
|
||||||
left: 0;
|
white-space: normal;
|
||||||
position: absolute;
|
overflow-wrap: anywhere;
|
||||||
right: 0;
|
|
||||||
top: 50%;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.positiveStack,
|
@media (max-width: 35.999em) {
|
||||||
.negativeStack {
|
.fields {
|
||||||
display: flex;
|
grid-template-columns: minmax(0, 1fr);
|
||||||
left: 25%;
|
}
|
||||||
position: absolute;
|
|
||||||
right: 25%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.positiveStack {
|
.actions {
|
||||||
bottom: 50%;
|
flex-direction: column;
|
||||||
flex-direction: column-reverse;
|
}
|
||||||
top: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.negativeStack {
|
.actions > button,
|
||||||
bottom: 0;
|
.fields input {
|
||||||
flex-direction: column;
|
min-height: 44px;
|
||||||
top: 50%;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
.coupon {
|
|
||||||
background: var(--mantine-color-blue-5);
|
|
||||||
}
|
|
||||||
|
|
||||||
.dividend {
|
|
||||||
background: var(--mantine-color-grape-5);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
|
import "dayjs/locale/ru";
|
||||||
import { MantineProvider } from "@mantine/core";
|
import { MantineProvider } from "@mantine/core";
|
||||||
|
import { DatesProvider } from "@mantine/dates";
|
||||||
import {
|
import {
|
||||||
|
act,
|
||||||
fireEvent,
|
fireEvent,
|
||||||
render,
|
render,
|
||||||
screen,
|
screen,
|
||||||
@@ -7,15 +10,22 @@ import {
|
|||||||
within,
|
within,
|
||||||
} from "@testing-library/react";
|
} from "@testing-library/react";
|
||||||
import { HttpResponse, http } from "msw";
|
import { HttpResponse, http } from "msw";
|
||||||
import { MemoryRouter, Route, Routes } from "react-router";
|
import type { FC } from "react";
|
||||||
import { describe, expect, it, vi } from "vitest";
|
import {
|
||||||
|
MemoryRouter,
|
||||||
|
Route,
|
||||||
|
Routes,
|
||||||
|
useLocation,
|
||||||
|
useNavigate,
|
||||||
|
} from "react-router";
|
||||||
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
import type { IncomeAnalytics } from "@/entities/income";
|
import type { IncomeAnalytics } from "@/entities/income";
|
||||||
import { configureAuthClient } from "@/shared/api";
|
import { configureAuthClient } from "@/shared/api";
|
||||||
import { createQueryWrapper } from "@/test/query";
|
import { createQueryWrapper } from "@/test/query";
|
||||||
import { server } from "@/test/server";
|
import { server } from "@/test/server";
|
||||||
import { AccountIncomePage } from "./AccountIncomePage";
|
import { AccountIncomePage } from "./AccountIncomePage";
|
||||||
import { isDate, toIncomeDisplayModel } from "./AccountIncomePage.vm";
|
import { isDate, toIncomeDisplayModel } from "./AccountIncomePage.vm";
|
||||||
import { IncomeBreakdown } from "./components/IncomeBreakdown.view";
|
import { IncomePayments } from "./components/IncomePayments.view";
|
||||||
|
|
||||||
const analytics = {
|
const analytics = {
|
||||||
accountId: "account-1",
|
accountId: "account-1",
|
||||||
@@ -108,25 +118,31 @@ function renderPage(search = "from=2026-08-01&to=2026-08-27") {
|
|||||||
refresh: async () => true,
|
refresh: async () => true,
|
||||||
clear: vi.fn(),
|
clear: vi.fn(),
|
||||||
});
|
});
|
||||||
const { wrapper: QueryWrapper } = createQueryWrapper();
|
const { wrapper: QueryWrapper, queryClient } = createQueryWrapper();
|
||||||
return render(
|
const result = render(
|
||||||
<MantineProvider>
|
<MantineProvider env="test">
|
||||||
<QueryWrapper>
|
<DatesProvider settings={{ locale: "ru" }}>
|
||||||
<MemoryRouter initialEntries={[`/accounts/account-1/income?${search}`]}>
|
<QueryWrapper>
|
||||||
<Routes>
|
<MemoryRouter
|
||||||
<Route
|
initialEntries={[`/accounts/account-1/income?${search}`]}
|
||||||
path="/accounts/:accountId/income"
|
>
|
||||||
element={<AccountIncomePage />}
|
<LocationProbe />
|
||||||
/>
|
<Routes>
|
||||||
<Route
|
<Route
|
||||||
path="/accounts/:accountId/events"
|
path="/accounts/:accountId/income"
|
||||||
element={<h1>Events</h1>}
|
element={<AccountIncomePage />}
|
||||||
/>
|
/>
|
||||||
</Routes>
|
<Route
|
||||||
</MemoryRouter>
|
path="/accounts/:accountId/events"
|
||||||
</QueryWrapper>
|
element={<h1>Events</h1>}
|
||||||
|
/>
|
||||||
|
</Routes>
|
||||||
|
</MemoryRouter>
|
||||||
|
</QueryWrapper>
|
||||||
|
</DatesProvider>
|
||||||
</MantineProvider>,
|
</MantineProvider>,
|
||||||
);
|
);
|
||||||
|
return { ...result, queryClient };
|
||||||
}
|
}
|
||||||
|
|
||||||
describe("AccountIncomePage", () => {
|
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 first = { ...entry(), id: "same-id", description: "Выплата A" };
|
||||||
const second = {
|
const second = {
|
||||||
...entry(),
|
...entry(),
|
||||||
@@ -177,14 +193,13 @@ describe("AccountIncomePage", () => {
|
|||||||
});
|
});
|
||||||
expect(display).not.toBeNull();
|
expect(display).not.toBeNull();
|
||||||
return (
|
return (
|
||||||
<MantineProvider>
|
<MantineProvider env="test">
|
||||||
<IncomeBreakdown instruments={display?.instruments ?? []} />
|
<IncomePayments entries={display?.entries ?? []} />
|
||||||
</MantineProvider>
|
</MantineProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const { rerender } = render(breakdown([first, second, third], "9"));
|
const { rerender } = render(breakdown([first, second, third], "9"));
|
||||||
fireEvent.click(screen.getByRole("button", { name: "BOND · 9 ₽ · 3" }));
|
const panel = await screen.findByRole("region", { name: "Выплаты" });
|
||||||
const panel = await screen.findByRole("region", { name: "BOND · 9 ₽ · 3" });
|
|
||||||
const payments = () =>
|
const payments = () =>
|
||||||
within(panel)
|
within(panel)
|
||||||
.getAllByText(/^Выплата [ABC]$/)
|
.getAllByText(/^Выплата [ABC]$/)
|
||||||
@@ -201,9 +216,7 @@ describe("AccountIncomePage", () => {
|
|||||||
|
|
||||||
rerender(breakdown([second, first], "8"));
|
rerender(breakdown([second, first], "8"));
|
||||||
expect(payments()).toEqual(["Выплата B", "Выплата A"]);
|
expect(payments()).toEqual(["Выплата B", "Выплата A"]);
|
||||||
expect(
|
expect(within(panel).getAllByRole("listitem")).toHaveLength(2);
|
||||||
screen.getByRole("button", { name: "BOND · 8 ₽ · 2" }),
|
|
||||||
).toHaveAttribute("aria-expanded", "true");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it.each([
|
it.each([
|
||||||
@@ -227,10 +240,14 @@ describe("AccountIncomePage", () => {
|
|||||||
);
|
);
|
||||||
renderPage();
|
renderPage();
|
||||||
const retry = await screen.findByRole("button", { name: "Повторить" });
|
const retry = await screen.findByRole("button", { name: "Повторить" });
|
||||||
expect(screen.queryByText("BOND · 12 ₽ · 2")).not.toBeInTheDocument();
|
expect(
|
||||||
|
screen.queryByRole("region", { name: "Выплаты" }),
|
||||||
|
).not.toBeInTheDocument();
|
||||||
response = analytics;
|
response = analytics;
|
||||||
fireEvent.click(retry);
|
fireEvent.click(retry);
|
||||||
expect(await screen.findByText("BOND · 12 ₽ · 2")).toBeInTheDocument();
|
expect(
|
||||||
|
await screen.findByRole("region", { name: "Выплаты" }),
|
||||||
|
).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
it.each([
|
it.each([
|
||||||
@@ -273,7 +290,9 @@ describe("AccountIncomePage", () => {
|
|||||||
expect(
|
expect(
|
||||||
await screen.findByRole("button", { name: "Повторить" }),
|
await screen.findByRole("button", { name: "Повторить" }),
|
||||||
).toBeInTheDocument();
|
).toBeInTheDocument();
|
||||||
expect(screen.queryByText("BOND · 12 ₽ · 2")).not.toBeInTheDocument();
|
expect(
|
||||||
|
screen.queryByRole("region", { name: "Выплаты" }),
|
||||||
|
).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("accepts an empty analytics response", async () => {
|
it("accepts an empty analytics response", async () => {
|
||||||
@@ -331,10 +350,7 @@ describe("AccountIncomePage", () => {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
renderPage();
|
renderPage();
|
||||||
fireEvent.click(
|
const panel = await screen.findByRole("region", { name: "Выплаты" });
|
||||||
await screen.findByRole("button", { name: "BOND · 8 ₽ · 2" }),
|
|
||||||
);
|
|
||||||
const panel = await screen.findByRole("region", { name: "BOND · 8 ₽ · 2" });
|
|
||||||
expect(within(panel).getByText("Исходная выплата")).toBeInTheDocument();
|
expect(within(panel).getByText("Исходная выплата")).toBeInTheDocument();
|
||||||
expect(
|
expect(
|
||||||
within(panel).getByText("Отрицательная корректировка"),
|
within(panel).getByText("Отрицательная корректировка"),
|
||||||
@@ -348,39 +364,13 @@ describe("AccountIncomePage", () => {
|
|||||||
expect(isDate("2024-02-29")).toBe(true);
|
expect(isDate("2024-02-29")).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("groups income entries once in the view model", () => {
|
it("renders realized text and comparisons without subscribing to events", async () => {
|
||||||
const display = toIncomeDisplayModel(analytics);
|
const eventsRequest = vi.fn(() => new HttpResponse(null, { status: 503 }));
|
||||||
|
|
||||||
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 () => {
|
|
||||||
server.use(
|
server.use(
|
||||||
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
|
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
|
||||||
HttpResponse.json(analytics),
|
HttpResponse.json(analytics),
|
||||||
),
|
),
|
||||||
http.get("*/api/v1/brokerage-accounts/account-1/events", () =>
|
http.get("*/api/v1/brokerage-accounts/account-1/events", eventsRequest),
|
||||||
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"),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
renderPage();
|
renderPage();
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
@@ -391,8 +381,10 @@ describe("AccountIncomePage", () => {
|
|||||||
expect(
|
expect(
|
||||||
screen.getByText("Налоговые операции не включены в этот результат."),
|
screen.getByText("Налоговые операции не включены в этот результат."),
|
||||||
).toBeInTheDocument();
|
).toBeInTheDocument();
|
||||||
expect(screen.getByText("Ближайший прогноз")).toBeInTheDocument();
|
expect(screen.queryByText("Ближайший прогноз")).not.toBeInTheDocument();
|
||||||
expect(screen.getByText("BOND · 12 ₽ · 2")).toBeInTheDocument();
|
expect(screen.queryByText("Динамика")).not.toBeInTheDocument();
|
||||||
|
expect(eventsRequest).not.toHaveBeenCalled();
|
||||||
|
expect(screen.getByRole("region", { name: "Выплаты" })).toBeInTheDocument();
|
||||||
expect(
|
expect(
|
||||||
screen.getByText(
|
screen.getByText(
|
||||||
"Выбранный период: Купоны 10 ₽ · Дивиденды 2 ₽ · Итого 12 ₽",
|
"Выбранный период: Купоны 10 ₽ · Дивиденды 2 ₽ · Итого 12 ₽",
|
||||||
@@ -403,54 +395,6 @@ describe("AccountIncomePage", () => {
|
|||||||
).toBeInTheDocument();
|
).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 () => {
|
it("shows a recoverable realized error", async () => {
|
||||||
server.use(
|
server.use(
|
||||||
http.get(
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,36 +1,16 @@
|
|||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import { useEffect, useMemo } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
import { useParams, useSearchParams } from "react-router";
|
import { useParams, useSearchParams } from "react-router";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import type { BrokerageEvent } from "@/entities/brokerage-event";
|
|
||||||
import { useBrokerageEvents } from "@/entities/brokerage-event";
|
|
||||||
import { type IncomeAnalytics, useIncomeAnalytics } from "@/entities/income";
|
import { type IncomeAnalytics, useIncomeAnalytics } from "@/entities/income";
|
||||||
import { validationMessage } from "@/shared/i18n";
|
import { validationMessage } from "@/shared/i18n";
|
||||||
|
|
||||||
type IncomePeriod = { from: string; to: string };
|
type IncomePeriod = { from: string; to: string };
|
||||||
type IncomeForm = IncomePeriod;
|
type IncomeForm = IncomePeriod;
|
||||||
|
|
||||||
type IncomeForecast =
|
|
||||||
| { state: "loading" | "empty" }
|
|
||||||
| { state: "error"; retry: () => void }
|
|
||||||
| {
|
|
||||||
state: "loaded";
|
|
||||||
totals: { currency: string; value: string }[];
|
|
||||||
events: BrokerageEvent[];
|
|
||||||
};
|
|
||||||
|
|
||||||
type IncomeDisplayModel = {
|
type IncomeDisplayModel = {
|
||||||
trend: {
|
entries: { key: string; operation: IncomeAnalytics["entries"][number] }[];
|
||||||
currency: string;
|
|
||||||
buckets: {
|
|
||||||
period: IncomeAnalytics["buckets"][number]["period"];
|
|
||||||
total: IncomeAnalytics["totalsByCurrency"][number];
|
|
||||||
}[];
|
|
||||||
}[];
|
|
||||||
instruments: (IncomeAnalytics["instruments"][number] & {
|
|
||||||
entries: IncomeAnalytics["entries"];
|
|
||||||
})[];
|
|
||||||
};
|
};
|
||||||
|
|
||||||
type AccountIncomePageViewModel =
|
type AccountIncomePageViewModel =
|
||||||
@@ -40,24 +20,34 @@ type AccountIncomePageViewModel =
|
|||||||
state: "loaded";
|
state: "loaded";
|
||||||
analytics: IncomeAnalytics;
|
analytics: IncomeAnalytics;
|
||||||
display: IncomeDisplayModel;
|
display: IncomeDisplayModel;
|
||||||
forecast: IncomeForecast;
|
formRevision: number;
|
||||||
|
refreshing: boolean;
|
||||||
|
refreshError: boolean;
|
||||||
|
retry: () => void;
|
||||||
form: ReturnType<typeof useForm<IncomeForm>>;
|
form: ReturnType<typeof useForm<IncomeForm>>;
|
||||||
onReset: () => void;
|
onReset: () => void;
|
||||||
onSubmit: (values: IncomeForm) => void;
|
onSubmit: (values: IncomeForm) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
const datePattern = /^\d{4}-\d{2}-\d{2}$/;
|
const datePattern = /^\d{4}-\d{2}-\d{2}$/;
|
||||||
const incomeFormSchema = z
|
const draftDate = z
|
||||||
.object({
|
.string()
|
||||||
from: z
|
.refine(
|
||||||
.string()
|
(value) => parseDraftDate(value) !== null,
|
||||||
.refine(isDate, validationMessage("income.validation.date")),
|
validationMessage("income.validation.date"),
|
||||||
to: z.string().refine(isDate, validationMessage("income.validation.date")),
|
)
|
||||||
})
|
.refine((value) => {
|
||||||
.refine(validPeriod, {
|
const date = parseDraftDate(value);
|
||||||
path: ["to"],
|
return !date || date <= moscowDate(new Date());
|
||||||
...validationMessage("income.validation.period")({}),
|
}, 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 = (): AccountIncomePageViewModel => {
|
const useAccountIncomePageViewModel = (): AccountIncomePageViewModel => {
|
||||||
const { accountId } = useParams();
|
const { accountId } = useParams();
|
||||||
@@ -74,19 +64,32 @@ const useAccountIncomePageViewModel = (): AccountIncomePageViewModel => {
|
|||||||
[requested],
|
[requested],
|
||||||
);
|
);
|
||||||
const form = useForm<IncomeForm>({
|
const form = useForm<IncomeForm>({
|
||||||
defaultValues: period,
|
defaultValues: draftPeriod(period),
|
||||||
resolver: zodResolver(incomeFormSchema),
|
resolver: zodResolver(incomeFormSchema),
|
||||||
});
|
});
|
||||||
|
const [formRevision, setFormRevision] = useState(0);
|
||||||
const analytics = useIncomeAnalytics(accountId, period);
|
const analytics = useIncomeAnalytics(accountId, period);
|
||||||
const events = useBrokerageEvents(accountId);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!validPeriod(requested)) setSearchParams(period, { replace: true });
|
if (!validPeriod(requested)) setSearchParams(period, { replace: true });
|
||||||
}, [period, requested, setSearchParams]);
|
}, [period, requested, setSearchParams]);
|
||||||
useEffect(() => form.reset(period), [form, period]);
|
useEffect(() => {
|
||||||
|
form.reset(draftPeriod(period));
|
||||||
|
setFormRevision((revision) => revision + 1);
|
||||||
|
}, [form, period]);
|
||||||
|
|
||||||
const onSubmit = (values: IncomeForm) => setSearchParams(values);
|
const onSubmit = (values: IncomeForm) => {
|
||||||
const onReset = () => setSearchParams(defaultPeriod(), { replace: true });
|
const from = parseDraftDate(values.from);
|
||||||
|
const to = parseDraftDate(values.to);
|
||||||
|
if (from && to) setSearchParams({ from, to });
|
||||||
|
};
|
||||||
|
const onReset = () => {
|
||||||
|
const next = defaultPeriod();
|
||||||
|
form.reset(draftPeriod(next));
|
||||||
|
// DateInput retains raw text while its calendar is open; reset that UI state too.
|
||||||
|
setFormRevision((revision) => revision + 1);
|
||||||
|
setSearchParams(next, { replace: true });
|
||||||
|
};
|
||||||
if (analytics.isLoading || !analytics.data) {
|
if (analytics.isLoading || !analytics.data) {
|
||||||
if (analytics.isError)
|
if (analytics.isError)
|
||||||
return { state: "error", retry: () => analytics.refetch(), period };
|
return { state: "error", retry: () => analytics.refetch(), period };
|
||||||
@@ -99,29 +102,30 @@ const useAccountIncomePageViewModel = (): AccountIncomePageViewModel => {
|
|||||||
state: "loaded",
|
state: "loaded",
|
||||||
analytics: analytics.data,
|
analytics: analytics.data,
|
||||||
display,
|
display,
|
||||||
forecast: toForecast(events),
|
formRevision,
|
||||||
|
refreshing: analytics.isFetching,
|
||||||
|
refreshError: analytics.isError,
|
||||||
|
retry: () => analytics.refetch(),
|
||||||
form,
|
form,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
onReset,
|
onReset,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
function toForecast(
|
function formatDraftDate(value: string): string {
|
||||||
events: ReturnType<typeof useBrokerageEvents>,
|
const [year, month, day] = value.split("-");
|
||||||
): IncomeForecast {
|
return `${day}.${month}.${year}`;
|
||||||
if (events.isLoading) return { state: "loading" };
|
}
|
||||||
if (events.isError) return { state: "error", retry: () => events.refetch() };
|
|
||||||
const response = events.data;
|
function parseDraftDate(value: string): string | null {
|
||||||
const upcoming =
|
if (!/^\d{2}\.\d{2}\.\d{4}$/.test(value)) return null;
|
||||||
response?.events.filter(
|
const [day, month, year] = value.split(".");
|
||||||
(event) => event.type === "coupon" || event.type === "dividend",
|
const date = `${year}-${month}-${day}`;
|
||||||
) ?? [];
|
return isDate(date) ? date : null;
|
||||||
if (!response || !upcoming.length) return { state: "empty" };
|
}
|
||||||
return {
|
|
||||||
state: "loaded",
|
function draftPeriod(period: IncomePeriod): IncomeForm {
|
||||||
totals: response.incomeTotalsByCurrency,
|
return { from: formatDraftDate(period.from), to: formatDraftDate(period.to) };
|
||||||
events: upcoming.slice(0, 3),
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function defaultPeriod(): IncomePeriod {
|
function defaultPeriod(): IncomePeriod {
|
||||||
@@ -156,48 +160,56 @@ function toIncomeDisplayModel(
|
|||||||
): IncomeDisplayModel | null {
|
): IncomeDisplayModel | null {
|
||||||
const instruments = new Map<
|
const instruments = new Map<
|
||||||
string,
|
string,
|
||||||
IncomeDisplayModel["instruments"][number]
|
{
|
||||||
|
currency: string;
|
||||||
|
receiptCount: number;
|
||||||
|
includedCount: number;
|
||||||
|
}
|
||||||
>();
|
>();
|
||||||
|
const currencies = new Set(
|
||||||
|
analytics.totalsByCurrency.map(({ currency }) => currency),
|
||||||
|
);
|
||||||
for (const instrument of analytics.instruments) {
|
for (const instrument of analytics.instruments) {
|
||||||
if (
|
if (
|
||||||
typeof instrument.key !== "string" ||
|
typeof instrument.key !== "string" ||
|
||||||
!instrument.key.trim() ||
|
!instrument.key.trim() ||
|
||||||
instruments.has(instrument.key)
|
instruments.has(instrument.key) ||
|
||||||
|
!currencies.has(instrument.total.currency)
|
||||||
)
|
)
|
||||||
return null;
|
return null;
|
||||||
instruments.set(instrument.key, { ...instrument, entries: [] });
|
instruments.set(instrument.key, {
|
||||||
|
currency: instrument.total.currency,
|
||||||
|
receiptCount: instrument.receiptCount,
|
||||||
|
includedCount: 0,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
const entries: IncomeDisplayModel["entries"] = [];
|
||||||
|
const occurrences = new Map<string, number>();
|
||||||
for (const entry of analytics.entries) {
|
for (const entry of analytics.entries) {
|
||||||
if (typeof entry.instrumentKey !== "string" || !entry.instrumentKey.trim())
|
if (typeof entry.instrumentKey !== "string" || !entry.instrumentKey.trim())
|
||||||
return null;
|
return null;
|
||||||
const instrument = instruments.get(entry.instrumentKey);
|
const instrument = instruments.get(entry.instrumentKey);
|
||||||
if (!instrument || entry.payment?.currency !== instrument.total.currency)
|
if (!instrument || entry.payment?.currency !== instrument.currency)
|
||||||
return null;
|
return null;
|
||||||
instrument.entries.push(entry);
|
const occurrenceKey = JSON.stringify([entry.instrumentKey, entry.id]);
|
||||||
|
const occurrence = occurrences.get(occurrenceKey) ?? 0;
|
||||||
|
occurrences.set(occurrenceKey, occurrence + 1);
|
||||||
|
instrument.includedCount += 1;
|
||||||
|
entries.push({
|
||||||
|
key: JSON.stringify([
|
||||||
|
entry.instrumentKey,
|
||||||
|
entry.id,
|
||||||
|
occurrence,
|
||||||
|
entry.logoName,
|
||||||
|
]),
|
||||||
|
operation: entry,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
for (const instrument of instruments.values()) {
|
for (const instrument of instruments.values()) {
|
||||||
if (instrument.entries.length !== instrument.receiptCount) return null;
|
if (instrument.includedCount !== instrument.receiptCount) return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return { entries };
|
||||||
trend: analytics.totalsByCurrency.map(({ currency }) => ({
|
|
||||||
currency,
|
|
||||||
buckets: analytics.buckets.map((bucket) => ({
|
|
||||||
period: bucket.period,
|
|
||||||
total:
|
|
||||||
bucket.totalsByCurrency.find((item) => item.currency === currency) ??
|
|
||||||
zeroSummary(currency),
|
|
||||||
})),
|
|
||||||
})),
|
|
||||||
instruments: [...instruments.values()],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function zeroSummary(
|
|
||||||
currency: string,
|
|
||||||
): IncomeAnalytics["totalsByCurrency"][number] {
|
|
||||||
const zero = { currency, value: "0" };
|
|
||||||
return { currency, coupon: zero, dividend: zero, total: zero };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function moscowDate(value: Date): string {
|
function moscowDate(value: Date): string {
|
||||||
@@ -214,7 +226,11 @@ function moscowDate(value: Date): string {
|
|||||||
|
|
||||||
export {
|
export {
|
||||||
type AccountIncomePageViewModel,
|
type AccountIncomePageViewModel,
|
||||||
|
formatDraftDate,
|
||||||
|
type IncomeForm,
|
||||||
isDate,
|
isDate,
|
||||||
|
moscowDate,
|
||||||
|
parseDraftDate,
|
||||||
toIncomeDisplayModel,
|
toIncomeDisplayModel,
|
||||||
useAccountIncomePageViewModel,
|
useAccountIncomePageViewModel,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,52 +2,62 @@ import {
|
|||||||
Alert,
|
Alert,
|
||||||
Button,
|
Button,
|
||||||
Group,
|
Group,
|
||||||
|
Loader,
|
||||||
Stack,
|
Stack,
|
||||||
Text,
|
Text,
|
||||||
TextInput,
|
|
||||||
Title,
|
Title,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
|
import { FormProvider } from "react-hook-form";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { StateView } from "@/shared/ui";
|
import { StateView } from "@/shared/ui";
|
||||||
|
import classes from "../AccountIncomePage.module.css";
|
||||||
import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
|
import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
|
||||||
import { IncomeBreakdown } from "./IncomeBreakdown.view";
|
|
||||||
import { IncomeComparisons } from "./IncomeComparisons.view";
|
import { IncomeComparisons } from "./IncomeComparisons.view";
|
||||||
import { IncomeForecast } from "./IncomeForecast.view";
|
import { IncomePayments } from "./IncomePayments.view";
|
||||||
|
import { IncomePeriodForm } from "./IncomePeriodForm.view";
|
||||||
import { IncomeSummary } from "./IncomeSummary.view";
|
import { IncomeSummary } from "./IncomeSummary.view";
|
||||||
import { IncomeTrend } from "./IncomeTrend.view";
|
|
||||||
|
|
||||||
type LoadedProps = Extract<AccountIncomePageViewModel, { state: "loaded" }>;
|
type LoadedProps = Extract<AccountIncomePageViewModel, { state: "loaded" }>;
|
||||||
|
|
||||||
const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
|
const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
|
||||||
const { analytics, display, form, forecast, onSubmit, onReset } = props;
|
const {
|
||||||
|
analytics,
|
||||||
|
display,
|
||||||
|
form,
|
||||||
|
refreshing,
|
||||||
|
refreshError,
|
||||||
|
retry,
|
||||||
|
onSubmit,
|
||||||
|
onReset,
|
||||||
|
} = props;
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
<Stack maw={960} gap="lg">
|
<Stack maw={960} gap="lg" className={classes.page}>
|
||||||
<Title order={1}>{t("income.title")}</Title>
|
<Title order={1}>{t("income.title")}</Title>
|
||||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
<FormProvider {...form}>
|
||||||
<Group align="end">
|
<IncomePeriodForm
|
||||||
<TextInput
|
key={props.formRevision}
|
||||||
error={form.formState.errors.from?.message}
|
onSubmit={form.handleSubmit(onSubmit)}
|
||||||
label={t("income.from")}
|
onReset={onReset}
|
||||||
type="date"
|
/>
|
||||||
{...form.register("from")}
|
</FormProvider>
|
||||||
/>
|
{refreshing ? (
|
||||||
<TextInput
|
<Group gap="xs" role="status" aria-label={t("income.refreshing")}>
|
||||||
error={form.formState.errors.to?.message}
|
<Loader size="sm" />
|
||||||
label={t("income.to")}
|
<Text>{t("income.refreshing")}</Text>
|
||||||
type="date"
|
|
||||||
{...form.register("to")}
|
|
||||||
/>
|
|
||||||
<Button type="submit">{t("income.apply")}</Button>
|
|
||||||
<Button onClick={onReset} variant="subtle">
|
|
||||||
{t("income.reset")}
|
|
||||||
</Button>
|
|
||||||
</Group>
|
</Group>
|
||||||
</form>
|
) : null}
|
||||||
<Text c="dimmed">
|
{refreshError ? (
|
||||||
{analytics.period.from} — {analytics.period.to}
|
<Alert color="orange">
|
||||||
</Text>
|
<Stack gap="sm">
|
||||||
|
<Text>{t("income.refreshError")}</Text>
|
||||||
|
<Button onClick={retry} variant="default">
|
||||||
|
{t("income.retry")}
|
||||||
|
</Button>
|
||||||
|
</Stack>
|
||||||
|
</Alert>
|
||||||
|
) : null}
|
||||||
{analytics.totalsByCurrency.length ? (
|
{analytics.totalsByCurrency.length ? (
|
||||||
<IncomeSummary totals={analytics.totalsByCurrency} />
|
<IncomeSummary totals={analytics.totalsByCurrency} />
|
||||||
) : (
|
) : (
|
||||||
@@ -58,9 +68,7 @@ const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
|
|||||||
)}
|
)}
|
||||||
<Alert color="blue">{t("income.taxBoundary")}</Alert>
|
<Alert color="blue">{t("income.taxBoundary")}</Alert>
|
||||||
<IncomeComparisons analytics={analytics} />
|
<IncomeComparisons analytics={analytics} />
|
||||||
<IncomeTrend trend={display.trend} />
|
<IncomePayments entries={display.entries} />
|
||||||
<IncomeBreakdown instruments={display.instruments} />
|
|
||||||
<IncomeForecast forecast={forecast} />
|
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,15 +1,31 @@
|
|||||||
import { Skeleton } from "@mantine/core";
|
import { Paper, Skeleton, Stack } from "@mantine/core";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { LoadingSkeleton } from "@/shared/ui";
|
import { LoadingSkeleton } from "@/shared/ui";
|
||||||
|
import classes from "../AccountIncomePage.module.css";
|
||||||
|
|
||||||
const AccountIncomePageLoading: FC = () => {
|
const AccountIncomePageLoading: FC = () => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
<LoadingSkeleton label={t("states.loadingTitle")}>
|
<LoadingSkeleton label={t("states.loadingTitle")}>
|
||||||
<Skeleton height={32} width="40%" />
|
<Stack maw={960} gap="lg">
|
||||||
<Skeleton height={120} radius="md" />
|
<Skeleton height={32} width="40%" />
|
||||||
<Skeleton height={260} radius="md" />
|
<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>
|
</LoadingSkeleton>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,54 +0,0 @@
|
|||||||
import { Accordion, Stack, Text, Title } from "@mantine/core";
|
|
||||||
import type { FC } from "react";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { LedgerEntryRow } from "@/entities/broker-operation";
|
|
||||||
import { formatMoney } from "@/shared/lib";
|
|
||||||
import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
|
|
||||||
|
|
||||||
type LoadedProps = Extract<AccountIncomePageViewModel, { state: "loaded" }>;
|
|
||||||
type IncomeBreakdownProps = {
|
|
||||||
instruments: LoadedProps["display"]["instruments"];
|
|
||||||
};
|
|
||||||
|
|
||||||
const IncomeBreakdown: FC<IncomeBreakdownProps> = (props) => {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
return (
|
|
||||||
<Stack>
|
|
||||||
<Title order={2}>{t("income.instruments")}</Title>
|
|
||||||
<Accordion>
|
|
||||||
{props.instruments.map((instrument) => {
|
|
||||||
const occurrences = new Map<string, number>();
|
|
||||||
return (
|
|
||||||
<Accordion.Item key={instrument.key} value={instrument.key}>
|
|
||||||
<Accordion.Control>
|
|
||||||
{instrument.displayName} · {formatMoney(instrument.total)} ·{" "}
|
|
||||||
{instrument.receiptCount}
|
|
||||||
</Accordion.Control>
|
|
||||||
<Accordion.Panel>
|
|
||||||
<Text size="sm">
|
|
||||||
{t("income.coupon")}: {formatMoney(instrument.coupon)} ·{" "}
|
|
||||||
{t("income.dividend")}: {formatMoney(instrument.dividend)}
|
|
||||||
</Text>
|
|
||||||
<Stack mt="sm">
|
|
||||||
{instrument.entries.map((entry) => {
|
|
||||||
// Distinguish repeated IDs and reset image fallback when its source changes.
|
|
||||||
const occurrence = occurrences.get(entry.id) ?? 0;
|
|
||||||
occurrences.set(entry.id, occurrence + 1);
|
|
||||||
const key = JSON.stringify([
|
|
||||||
entry.id,
|
|
||||||
occurrence,
|
|
||||||
entry.logoName,
|
|
||||||
]);
|
|
||||||
return <LedgerEntryRow key={key} operation={entry} />;
|
|
||||||
})}
|
|
||||||
</Stack>
|
|
||||||
</Accordion.Panel>
|
|
||||||
</Accordion.Item>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Accordion>
|
|
||||||
</Stack>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export { IncomeBreakdown };
|
|
||||||
@@ -40,7 +40,7 @@ const IncomeComparisons: FC<IncomeComparisonsProps> = (props) => {
|
|||||||
const Comparison: FC<ComparisonProps> = (props) => {
|
const Comparison: FC<ComparisonProps> = (props) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
<Paper p="sm" withBorder>
|
<Paper p="sm" radius="md" withBorder>
|
||||||
<Text fw={700}>{props.title}</Text>
|
<Text fw={700}>{props.title}</Text>
|
||||||
{props.values.map((value) => (
|
{props.values.map((value) => (
|
||||||
<Stack gap={2} key={value.currency}>
|
<Stack gap={2} key={value.currency}>
|
||||||
|
|||||||
@@ -1,68 +0,0 @@
|
|||||||
import { Alert, Button, Paper, Stack, Text, Title } from "@mantine/core";
|
|
||||||
import type { FC } from "react";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { Link } from "react-router";
|
|
||||||
import type { BrokerageEvent } from "@/entities/brokerage-event";
|
|
||||||
import { formatMoney } from "@/shared/lib";
|
|
||||||
import { StateView } from "@/shared/ui";
|
|
||||||
import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
|
|
||||||
|
|
||||||
type LoadedProps = Extract<AccountIncomePageViewModel, { state: "loaded" }>;
|
|
||||||
type IncomeForecastProps = { forecast: LoadedProps["forecast"] };
|
|
||||||
type ForecastEventProps = { event: BrokerageEvent };
|
|
||||||
|
|
||||||
const IncomeForecast: FC<IncomeForecastProps> = (props) => {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
if (props.forecast.state === "loading")
|
|
||||||
return <Text c="dimmed">{t("income.forecastLoading")}</Text>;
|
|
||||||
if (props.forecast.state === "error")
|
|
||||||
return (
|
|
||||||
<StateView
|
|
||||||
error
|
|
||||||
title={t("income.forecastError")}
|
|
||||||
text={t("income.errorText")}
|
|
||||||
action={
|
|
||||||
<Button onClick={props.forecast.retry}>{t("income.retry")}</Button>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
if (props.forecast.state === "empty")
|
|
||||||
return (
|
|
||||||
<StateView
|
|
||||||
title={t("income.forecastTitle")}
|
|
||||||
text={t("income.forecastEmpty")}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
if (props.forecast.state !== "loaded") return null;
|
|
||||||
return (
|
|
||||||
<Stack>
|
|
||||||
<Title order={2}>{t("income.forecastTitle")}</Title>
|
|
||||||
<Alert color="yellow">{t("income.forecastWarning")}</Alert>
|
|
||||||
{props.forecast.totals.map((total) => (
|
|
||||||
<Text key={total.currency} fw={700}>
|
|
||||||
{formatMoney(total)}
|
|
||||||
</Text>
|
|
||||||
))}
|
|
||||||
{props.forecast.events.map((event) => (
|
|
||||||
<ForecastEvent
|
|
||||||
event={event}
|
|
||||||
key={`${event.type}-${event.date}-${event.ticker}`}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
<Button component={Link} to="../events" variant="subtle">
|
|
||||||
{t("events.open")}
|
|
||||||
</Button>
|
|
||||||
</Stack>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const ForecastEvent: FC<ForecastEventProps> = (props) => (
|
|
||||||
<Paper p="sm" withBorder>
|
|
||||||
<Text fw={700}>{props.event.displayName}</Text>
|
|
||||||
<Text size="sm">
|
|
||||||
{props.event.date} · {formatMoney(props.event.projectedAmount)}
|
|
||||||
</Text>
|
|
||||||
</Paper>
|
|
||||||
);
|
|
||||||
|
|
||||||
export { IncomeForecast };
|
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { Stack, Title } from "@mantine/core";
|
||||||
|
import type { FC } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { LedgerEntryRow } from "@/entities/broker-operation";
|
||||||
|
import classes from "../AccountIncomePage.module.css";
|
||||||
|
import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
|
||||||
|
|
||||||
|
type LoadedProps = Extract<AccountIncomePageViewModel, { state: "loaded" }>;
|
||||||
|
type IncomePaymentsProps = { entries: LoadedProps["display"]["entries"] };
|
||||||
|
|
||||||
|
const IncomePayments: FC<IncomePaymentsProps> = (props) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<Stack component="section" aria-label={t("income.payments")}>
|
||||||
|
<Title order={2}>{t("income.payments")}</Title>
|
||||||
|
<Stack component="ul" gap="sm" className={classes.entries}>
|
||||||
|
{props.entries.map(({ key, operation }) => (
|
||||||
|
<li key={key}>
|
||||||
|
<LedgerEntryRow operation={operation} />
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { IncomePayments };
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import { Button, Paper, Stack, Text } from "@mantine/core";
|
||||||
|
import { DateInput } from "@mantine/dates";
|
||||||
|
import type { FC, FormEventHandler } from "react";
|
||||||
|
import { Controller, useFormContext, useWatch } from "react-hook-form";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import classes from "../AccountIncomePage.module.css";
|
||||||
|
import {
|
||||||
|
formatDraftDate,
|
||||||
|
type IncomeForm,
|
||||||
|
moscowDate,
|
||||||
|
parseDraftDate,
|
||||||
|
} from "../AccountIncomePage.vm";
|
||||||
|
|
||||||
|
type IncomePeriodFormProps = {
|
||||||
|
onSubmit: FormEventHandler<HTMLFormElement>;
|
||||||
|
onReset: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const IncomePeriodForm: FC<IncomePeriodFormProps> = (props) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const {
|
||||||
|
control,
|
||||||
|
formState: { isSubmitting },
|
||||||
|
} = useFormContext<IncomeForm>();
|
||||||
|
const [from, to] = useWatch({ control, name: ["from", "to"] });
|
||||||
|
const today = moscowDate(new Date());
|
||||||
|
const start = parseDraftDate(from);
|
||||||
|
const end = parseDraftDate(to);
|
||||||
|
return (
|
||||||
|
<Paper
|
||||||
|
component="form"
|
||||||
|
onSubmit={props.onSubmit}
|
||||||
|
p="md"
|
||||||
|
radius="md"
|
||||||
|
withBorder
|
||||||
|
>
|
||||||
|
<Stack gap="sm">
|
||||||
|
<Text fw={700}>{t("income.period")}</Text>
|
||||||
|
<div className={classes.fields}>
|
||||||
|
{(["from", "to"] as const).map((name) => (
|
||||||
|
<Controller
|
||||||
|
key={name}
|
||||||
|
name={name}
|
||||||
|
control={control}
|
||||||
|
render={({ field, fieldState }) => (
|
||||||
|
<DateInput
|
||||||
|
ref={field.ref}
|
||||||
|
label={t(`income.${name}`)}
|
||||||
|
placeholder={t("income.datePlaceholder")}
|
||||||
|
valueFormat="DD.MM.YYYY"
|
||||||
|
value={parseDraftDate(field.value)}
|
||||||
|
dateParser={parseDraftDate}
|
||||||
|
fixOnBlur={false}
|
||||||
|
popoverProps={{ middlewares: { shift: { crossAxis: true } } }}
|
||||||
|
onInput={(event) => field.onChange(event.currentTarget.value)}
|
||||||
|
onChange={(value) =>
|
||||||
|
field.onChange(value ? formatDraftDate(value) : "")
|
||||||
|
}
|
||||||
|
onBlur={(event) => {
|
||||||
|
field.onChange(event.currentTarget.value);
|
||||||
|
field.onBlur();
|
||||||
|
}}
|
||||||
|
minDate={
|
||||||
|
name === "to" && start && start <= today ? start : undefined
|
||||||
|
}
|
||||||
|
maxDate={name === "from" && end && end <= today ? end : today}
|
||||||
|
error={fieldState.error?.message}
|
||||||
|
disabled={isSubmitting}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className={classes.actions}>
|
||||||
|
<Button type="submit" loading={isSubmitting}>
|
||||||
|
{t("income.apply")}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
onClick={props.onReset}
|
||||||
|
disabled={isSubmitting}
|
||||||
|
variant="default"
|
||||||
|
>
|
||||||
|
{t("income.reset")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</Stack>
|
||||||
|
</Paper>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { IncomePeriodForm };
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Paper, Stack, Text } from "@mantine/core";
|
import { Paper, Stack, Text, Title } from "@mantine/core";
|
||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import type { IncomeAnalytics } from "@/entities/income";
|
import type { IncomeAnalytics } from "@/entities/income";
|
||||||
@@ -10,8 +10,9 @@ const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
<Stack>
|
<Stack>
|
||||||
|
<Title order={2}>{t("income.summaryTitle")}</Title>
|
||||||
{props.totals.map((total) => (
|
{props.totals.map((total) => (
|
||||||
<Paper key={total.currency} p="md" withBorder>
|
<Paper key={total.currency} p="md" radius="md" withBorder>
|
||||||
<Text fw={700}>{formatMoney(total.total)}</Text>
|
<Text fw={700}>{formatMoney(total.total)}</Text>
|
||||||
<Text c="dimmed" size="sm">
|
<Text c="dimmed" size="sm">
|
||||||
{t("income.coupon")}: {formatMoney(total.coupon)} ·{" "}
|
{t("income.coupon")}: {formatMoney(total.coupon)} ·{" "}
|
||||||
|
|||||||
@@ -1,107 +0,0 @@
|
|||||||
import { SegmentedControl, Stack, Text, Title } from "@mantine/core";
|
|
||||||
import type { FC } from "react";
|
|
||||||
import { useState } from "react";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { formatMoney } from "@/shared/lib";
|
|
||||||
import styles from "../AccountIncomePage.module.css";
|
|
||||||
import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
|
|
||||||
|
|
||||||
type LoadedProps = Extract<AccountIncomePageViewModel, { state: "loaded" }>;
|
|
||||||
type IncomeTrendProps = { trend: LoadedProps["display"]["trend"] };
|
|
||||||
|
|
||||||
const IncomeTrend: FC<IncomeTrendProps> = (props) => {
|
|
||||||
const currencies = props.trend.map(({ currency }) => currency);
|
|
||||||
const [currency, setCurrency] = useState(currencies[0] ?? "");
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const buckets =
|
|
||||||
props.trend.find((item) => item.currency === currency)?.buckets ?? [];
|
|
||||||
const values = buckets.map((bucket) => ({
|
|
||||||
...bucket,
|
|
||||||
coupon: Number(bucket.total.coupon.value),
|
|
||||||
dividend: Number(bucket.total.dividend.value),
|
|
||||||
}));
|
|
||||||
const scale = Math.max(
|
|
||||||
1,
|
|
||||||
...values.map((value) =>
|
|
||||||
Math.max(
|
|
||||||
positive(value.coupon) + positive(value.dividend),
|
|
||||||
negative(value.coupon) + negative(value.dividend),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return (
|
|
||||||
<Stack>
|
|
||||||
<Title order={2}>{t("income.trend")}</Title>
|
|
||||||
{currencies.length > 1 ? (
|
|
||||||
<SegmentedControl
|
|
||||||
aria-label={t("income.currency")}
|
|
||||||
data={currencies}
|
|
||||||
onChange={setCurrency}
|
|
||||||
value={currency}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
<div aria-hidden="true" className={styles.trendChart}>
|
|
||||||
{values.map((value) => (
|
|
||||||
<div className={styles.trendColumn} key={value.period.from}>
|
|
||||||
<span className={styles.baseline} />
|
|
||||||
<div className={styles.positiveStack}>
|
|
||||||
{value.coupon > 0 ? (
|
|
||||||
<span
|
|
||||||
className={styles.coupon}
|
|
||||||
data-testid={`trend-positive-coupon-${value.period.from}`}
|
|
||||||
style={{ flexBasis: chartHeight(value.coupon, scale) }}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
{value.dividend > 0 ? (
|
|
||||||
<span
|
|
||||||
className={styles.dividend}
|
|
||||||
data-testid={`trend-positive-dividend-${value.period.from}`}
|
|
||||||
style={{ flexBasis: chartHeight(value.dividend, scale) }}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
<div className={styles.negativeStack}>
|
|
||||||
{value.coupon < 0 ? (
|
|
||||||
<span
|
|
||||||
className={styles.coupon}
|
|
||||||
data-testid={`trend-negative-coupon-${value.period.from}`}
|
|
||||||
style={{ flexBasis: chartHeight(value.coupon, scale) }}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
{value.dividend < 0 ? (
|
|
||||||
<span
|
|
||||||
className={styles.dividend}
|
|
||||||
data-testid={`trend-negative-dividend-${value.period.from}`}
|
|
||||||
style={{ flexBasis: chartHeight(value.dividend, scale) }}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<Stack gap={2}>
|
|
||||||
{buckets.map((bucket) => (
|
|
||||||
<Text key={bucket.period.from} size="sm">
|
|
||||||
{bucket.period.from} — {bucket.period.to}: {t("income.coupon")}{" "}
|
|
||||||
{formatMoney(bucket.total.coupon)}, {t("income.dividend")}{" "}
|
|
||||||
{formatMoney(bucket.total.dividend)}
|
|
||||||
</Text>
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
</Stack>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
function positive(value: number): number {
|
|
||||||
return Math.max(0, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
function negative(value: number): number {
|
|
||||||
return Math.max(0, -value);
|
|
||||||
}
|
|
||||||
|
|
||||||
function chartHeight(value: number, scale: number): string {
|
|
||||||
return `${(Math.abs(value) / scale) * 100}%`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export { IncomeTrend };
|
|
||||||
@@ -175,22 +175,20 @@ const ru = {
|
|||||||
compared: "Сравниваемый период",
|
compared: "Сравниваемый период",
|
||||||
difference: "Разница",
|
difference: "Разница",
|
||||||
total: "Итого",
|
total: "Итого",
|
||||||
trend: "Динамика",
|
payments: "Выплаты",
|
||||||
currency: "Валюта графика",
|
|
||||||
instruments: "По инструментам",
|
|
||||||
emptyTitle: "Купоны и дивиденды не найдены",
|
emptyTitle: "Купоны и дивиденды не найдены",
|
||||||
emptyText: "За выбранный период подходящих исполненных выплат нет.",
|
emptyText: "За выбранный период подходящих исполненных выплат нет.",
|
||||||
errorTitle: "Не удалось рассчитать пассивный доход",
|
errorTitle: "Не удалось рассчитать пассивный доход",
|
||||||
errorText: "Попробуйте загрузить результат еще раз.",
|
errorText: "Попробуйте загрузить результат еще раз.",
|
||||||
retry: "Повторить",
|
retry: "Повторить",
|
||||||
forecastTitle: "Ближайший прогноз",
|
period: "Период",
|
||||||
forecastLoading: "Загрузка прогноза",
|
datePlaceholder: "ДД.ММ.ГГГГ",
|
||||||
forecastError: "Не удалось загрузить прогноз",
|
refreshing: "Обновляем пассивный доход",
|
||||||
forecastEmpty: "Ближайших купонов и дивидендов не найдено.",
|
refreshError:
|
||||||
forecastWarning:
|
"Не удалось обновить пассивный доход. Показан последний загруженный результат.",
|
||||||
"Это известный прогноз, а не гарантированное поступление.",
|
|
||||||
validation: {
|
validation: {
|
||||||
date: "Введите существующую дату.",
|
date: "Введите существующую дату в формате ДД.ММ.ГГГГ.",
|
||||||
|
future: "Дата не может быть позже сегодняшнего дня.",
|
||||||
period:
|
period:
|
||||||
"Укажите корректный период без будущих дат: начало не позже окончания.",
|
"Укажите корректный период без будущих дат: начало не позже окончания.",
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in New Issue
Block a user