feat(income): add account income analytics

This commit is contained in:
2026-08-28 01:25:52 +03:00
parent 71a214d7ad
commit 9364568202
18 changed files with 1746 additions and 7 deletions
+1
View File
@@ -0,0 +1 @@
export { AccountIncomePage } from "./ui/AccountIncomePage";
@@ -0,0 +1,51 @@
.trendChart {
align-items: stretch;
display: flex;
gap: var(--mantine-spacing-xs);
height: 160px;
overflow-x: auto;
padding: 0 var(--mantine-spacing-xs);
}
.trendColumn {
flex: 1 0 32px;
min-width: 32px;
position: relative;
}
.baseline {
background: var(--mantine-color-gray-4);
height: 1px;
left: 0;
position: absolute;
right: 0;
top: 50%;
}
.positiveStack,
.negativeStack {
display: flex;
left: 25%;
position: absolute;
right: 25%;
}
.positiveStack {
bottom: 50%;
flex-direction: column-reverse;
top: 0;
}
.negativeStack {
bottom: 0;
flex-direction: column;
top: 50%;
}
.coupon {
background: var(--mantine-color-blue-5);
}
.dividend {
background: var(--mantine-color-grape-5);
}
@@ -0,0 +1,234 @@
import { MantineProvider } from "@mantine/core";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { cleanup, render, screen, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import type { FC, PropsWithChildren } from "react";
import { MemoryRouter, Route, Routes } from "react-router";
import { afterEach, describe, expect, it, vi } from "vitest";
import { configureAuthClient } from "@/shared/api";
import { server } from "@/test/server";
import { AccountIncomePage } from "./AccountIncomePage";
const analytics = {
accountId: "account-1",
period: { from: "2026-08-01", to: "2026-08-27" },
calculatedAt: "2026-08-27T00:00:00Z",
totalsByCurrency: [summary("RUB", "10", "2")],
previous: {
period: { from: "2026-07-01", to: "2026-07-31" },
totalsByCurrency: [comparison("RUB")],
},
yearComparison: null,
bucketGranularity: "day",
buckets: [
{
period: { from: "2026-08-01", to: "2026-08-01" },
totalsByCurrency: [summary("RUB", "10", "2")],
},
],
instruments: [
{
key: "figi:FIGI:RUB",
figi: "FIGI",
instrumentUid: null,
ticker: "BOND",
instrumentType: "bond",
displayName: "BOND",
coupon: money("RUB", "10"),
dividend: money("RUB", "2"),
total: money("RUB", "12"),
receiptCount: 1,
},
],
entries: [entry()],
};
function money(currency: string, value: string) {
return { currency, value };
}
function summary(currency: string, coupon: string, dividend: string) {
return {
currency,
coupon: money(currency, coupon),
dividend: money(currency, dividend),
total: money(currency, String(Number(coupon) + Number(dividend))),
};
}
function comparison(currency: string) {
return {
currency,
selected: summary(currency, "10", "2"),
compared: summary(currency, "1", "0"),
difference: summary(currency, "9", "2"),
};
}
function entry() {
return {
id: "coupon-1",
occurredAt: "2026-08-01T12:00:00Z",
type: "OPERATION_TYPE_COUPON",
category: "income",
description: "Купон",
figi: "FIGI",
instrumentUid: null,
ticker: "BOND",
instrumentType: "bond",
logoName: null,
payment: money("RUB", "10"),
quantity: null,
price: null,
accruedInterest: null,
commission: null,
};
}
function renderPage() {
configureAuthClient({
accessToken: () => "token",
refresh: async () => true,
clear: vi.fn(),
});
const Wrapper: FC<PropsWithChildren> = (props) => (
<MantineProvider>
<QueryClientProvider client={new QueryClient()}>
{props.children}
</QueryClientProvider>
</MantineProvider>
);
return render(
<Wrapper>
<MemoryRouter
initialEntries={[
"/accounts/account-1/income?from=2026-08-01&to=2026-08-27",
]}
>
<Routes>
<Route
path="/accounts/:accountId/income"
element={<AccountIncomePage />}
/>
<Route path="/accounts/:accountId/events" element={<h1>Events</h1>} />
</Routes>
</MemoryRouter>
</Wrapper>,
);
}
describe("AccountIncomePage", () => {
afterEach(() => {
cleanup();
configureAuthClient(null);
});
it("renders realized analytics, drill-down, and the independent forecast", async () => {
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json(analytics),
),
http.get("*/api/v1/brokerage-accounts/account-1/events", () =>
HttpResponse.json({
accountId: "account-1",
calculatedAt: "2026-08-27T00:00:00Z",
incomeTotalsByCurrency: [money("RUB", "3")],
events: [
{
type: "coupon",
date: "2026-08-28",
dateKind: "event",
figi: "FIGI",
instrumentUid: null,
ticker: "BOND",
displayName: "BOND",
projectedAmount: money("RUB", "3"),
},
],
}),
),
);
renderPage();
await waitFor(() =>
expect(
screen.getByRole("heading", { name: "Пассивный доход" }),
).toBeInTheDocument(),
);
expect(
screen.getByText("Налоговые операции не включены в этот результат."),
).toBeInTheDocument();
expect(screen.getByText("Ближайший прогноз")).toBeInTheDocument();
expect(screen.getByText("BOND · 12 ₽ · 1")).toBeInTheDocument();
expect(
screen.getByText(
"Выбранный период: Купоны 10 ₽ · Дивиденды 2 ₽ · Итого 12 ₽",
),
).toBeInTheDocument();
expect(
screen.getByText("Разница: Купоны 9 ₽ · Дивиденды 2 ₽ · Итого 11 ₽"),
).toBeInTheDocument();
});
it("renders an empty trend bucket as zero money", async () => {
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json({
...analytics,
buckets: [
...analytics.buckets,
{
period: { from: "2026-08-02", to: "2026-08-02" },
totalsByCurrency: [],
},
],
}),
),
);
renderPage();
await waitFor(() =>
expect(
screen.getByText("2026-08-02 — 2026-08-02: Купоны 0 ₽, Дивиденды 0 ₽"),
).toBeInTheDocument(),
);
});
it("renders signed coupon and dividend segments on opposite baseline sides", async () => {
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json({
...analytics,
buckets: [
{
period: { from: "2026-08-01", to: "2026-08-01" },
totalsByCurrency: [summary("RUB", "-10", "2")],
},
],
}),
),
);
renderPage();
await waitFor(() => {
expect(
screen.getByTestId("trend-negative-coupon-2026-08-01"),
).toBeInTheDocument();
expect(
screen.getByTestId("trend-positive-dividend-2026-08-01"),
).toBeInTheDocument();
});
});
it("shows a recoverable realized error", async () => {
server.use(
http.get(
"*/api/v1/brokerage-accounts/account-1/income-analytics",
() => new HttpResponse(null, { status: 503 }),
),
);
renderPage();
await waitFor(() =>
expect(
screen.getByRole("button", { name: "Повторить" }),
).toBeInTheDocument(),
);
});
});
@@ -0,0 +1,17 @@
import type { FC } from "react";
import {
AccountIncomePageError,
AccountIncomePageLoaded,
AccountIncomePageLoading,
} from "./AccountIncomePage.view";
import { useAccountIncomePageViewModel } from "./AccountIncomePage.vm";
const AccountIncomePage: FC = () => {
const viewModel = useAccountIncomePageViewModel();
if (viewModel.state === "loading") return <AccountIncomePageLoading />;
if (viewModel.state === "error")
return <AccountIncomePageError {...viewModel} />;
return <AccountIncomePageLoaded {...viewModel} />;
};
export { AccountIncomePage };
@@ -0,0 +1,388 @@
import {
Accordion,
Alert,
Button,
Group,
Paper,
SegmentedControl,
Skeleton,
Stack,
Text,
TextInput,
Title,
} from "@mantine/core";
import type { FC } from "react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { LedgerEntryRow } from "@/entities/broker-operation";
import type { BrokerageEvent } from "@/entities/brokerage-event";
import type { IncomeAnalytics } from "@/entities/income";
import { formatMoney } from "@/entities/portfolio";
import { LoadingSkeleton, StateView } from "@/shared/ui";
import styles from "./AccountIncomePage.module.css";
import type { AccountIncomePageViewModel } from "./AccountIncomePage.vm";
type LoadedProps = Extract<AccountIncomePageViewModel, { state: "loaded" }>;
type ErrorProps = Extract<AccountIncomePageViewModel, { state: "error" }>;
const AccountIncomePageLoading: FC = () => {
const { t } = useTranslation();
return (
<LoadingSkeleton label={t("states.loadingTitle")}>
<Skeleton height={32} width="40%" />
<Skeleton height={120} radius="md" />
<Skeleton height={260} radius="md" />
</LoadingSkeleton>
);
};
const AccountIncomePageError: FC<ErrorProps> = (props) => {
const { t } = useTranslation();
return (
<StateView
error
title={t("income.errorTitle")}
text={t("income.errorText")}
action={<Button onClick={props.retry}>{t("income.retry")}</Button>}
/>
);
};
const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
const { analytics, form, forecast, onSubmit, onReset } = props;
const { t } = useTranslation();
return (
<Stack maw={960} gap="lg">
<Title order={1}>{t("income.title")}</Title>
<form onSubmit={form.handleSubmit(onSubmit)}>
<Group align="end">
<TextInput
error={form.formState.errors.from?.message}
label={t("income.from")}
type="date"
{...form.register("from")}
/>
<TextInput
error={form.formState.errors.to?.message}
label={t("income.to")}
type="date"
{...form.register("to")}
/>
<Button type="submit">{t("income.apply")}</Button>
<Button onClick={onReset} variant="subtle">
{t("income.reset")}
</Button>
</Group>
</form>
<Text c="dimmed">
{analytics.period.from} — {analytics.period.to}
</Text>
{analytics.totalsByCurrency.length ? (
<IncomeSummary totals={analytics.totalsByCurrency} />
) : (
<StateView
title={t("income.emptyTitle")}
text={t("income.emptyText")}
/>
)}
<Alert color="blue">{t("income.taxBoundary")}</Alert>
<IncomeComparisons analytics={analytics} />
<IncomeTrend analytics={analytics} />
<IncomeBreakdown analytics={analytics} />
<IncomeForecast forecast={forecast} />
</Stack>
);
};
const IncomeSummary: FC<{ totals: IncomeAnalytics["totalsByCurrency"] }> = (
props,
) => {
const { t } = useTranslation();
return (
<Stack>
{props.totals.map((total) => (
<Paper key={total.currency} p="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)}
</Text>
</Paper>
))}
</Stack>
);
};
const IncomeComparisons: FC<{ analytics: IncomeAnalytics }> = (props) => {
const { t } = useTranslation();
return (
<Stack>
<Title order={2}>{t("income.comparisons")}</Title>
<Comparison
title={t("income.previous", {
from: props.analytics.previous.period.from,
to: props.analytics.previous.period.to,
})}
values={props.analytics.previous.totalsByCurrency}
/>
{props.analytics.yearComparison ? (
<Comparison
title={t("income.yearAgo", {
from: props.analytics.yearComparison.period.from,
to: props.analytics.yearComparison.period.to,
})}
values={props.analytics.yearComparison.totalsByCurrency}
/>
) : (
<Text c="dimmed">{t("income.yearUnavailable")}</Text>
)}
</Stack>
);
};
const Comparison: FC<{
title: string;
values: IncomeAnalytics["previous"]["totalsByCurrency"];
}> = (props) => {
const { t } = useTranslation();
return (
<Paper p="sm" withBorder>
<Text fw={700}>{props.title}</Text>
{props.values.map((value) => (
<Stack gap={2} key={value.currency}>
<Text size="sm">{value.currency}</Text>
<Text size="sm">
{t("income.selected")}: {t("income.coupon")}{" "}
{formatMoney(value.selected.coupon)} · {t("income.dividend")}{" "}
{formatMoney(value.selected.dividend)} · {t("income.total")}{" "}
{formatMoney(value.selected.total)}
</Text>
<Text size="sm">
{t("income.compared")}: {t("income.coupon")}{" "}
{formatMoney(value.compared.coupon)} · {t("income.dividend")}{" "}
{formatMoney(value.compared.dividend)} · {t("income.total")}{" "}
{formatMoney(value.compared.total)}
</Text>
<Text size="sm">
{t("income.difference")}: {t("income.coupon")}{" "}
{formatMoney(value.difference.coupon)} · {t("income.dividend")}{" "}
{formatMoney(value.difference.dividend)} · {t("income.total")}{" "}
{formatMoney(value.difference.total)}
</Text>
</Stack>
))}
</Paper>
);
};
const IncomeTrend: FC<{ analytics: IncomeAnalytics }> = (props) => {
const currencies = props.analytics.totalsByCurrency.map(
(total) => total.currency,
);
const [currency, setCurrency] = useState(currencies[0] ?? "");
const { t } = useTranslation();
const buckets = props.analytics.buckets.map((bucket) => ({
period: bucket.period,
total:
bucket.totalsByCurrency.find((item) => item.currency === currency) ??
zeroSummary(currency),
}));
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 ?? null)}, {t("income.dividend")}{" "}
{formatMoney(bucket.total?.dividend ?? null)}
</Text>
))}
</Stack>
</Stack>
);
};
const IncomeBreakdown: FC<{ analytics: IncomeAnalytics }> = (props) => {
const { t } = useTranslation();
return (
<Stack>
<Title order={2}>{t("income.instruments")}</Title>
<Accordion>
{props.analytics.instruments.map((instrument) => (
<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">
{props.analytics.entries
.filter((entry) => entryKey(entry) === instrument.key)
.map((entry) => (
<LedgerEntryRow key={entry.id} operation={entry} />
))}
</Stack>
</Accordion.Panel>
</Accordion.Item>
))}
</Accordion>
</Stack>
);
};
const IncomeForecast: FC<{ forecast: LoadedProps["forecast"] }> = (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<{ event: BrokerageEvent }> = (props) => (
<Paper p="sm" withBorder>
<Text fw={700}>{props.event.displayName}</Text>
<Text size="sm">
{props.event.date} · {formatMoney(props.event.projectedAmount)}
</Text>
</Paper>
);
function entryKey(entry: IncomeAnalytics["entries"][number]): string {
const base = entry.instrumentUid
? `uid:${entry.instrumentUid}`
: entry.figi
? `figi:${entry.figi}`
: entry.ticker || entry.instrumentType
? `ticker:${entry.ticker ?? ""}:${entry.instrumentType ?? ""}`
: `operation:${entry.id}`;
return `${base}:${entry.payment?.currency ?? ""}`;
}
function zeroSummary(
currency: string,
): IncomeAnalytics["totalsByCurrency"][number] {
const zero = { currency, value: "0" };
return { currency, coupon: zero, dividend: zero, total: zero };
}
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 {
AccountIncomePageError,
AccountIncomePageLoaded,
AccountIncomePageLoading,
};
@@ -0,0 +1,147 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect, useMemo } from "react";
import { useForm } from "react-hook-form";
import { useParams, useSearchParams } from "react-router";
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 { validationMessage } from "@/shared/i18n";
type IncomePeriod = { from: string; to: string };
type IncomeForm = IncomePeriod;
type IncomeForecast =
| { state: "loading" | "empty" }
| { state: "error"; retry: () => void }
| {
state: "loaded";
totals: { currency: string; value: string }[];
events: BrokerageEvent[];
};
type AccountIncomePageViewModel =
| { state: "loading" }
| { state: "error"; retry: () => void; period: IncomePeriod }
| {
state: "loaded";
analytics: IncomeAnalytics;
forecast: IncomeForecast;
form: ReturnType<typeof useForm<IncomeForm>>;
onReset: () => void;
onSubmit: (values: IncomeForm) => void;
};
const datePattern = /^\d{4}-\d{2}-\d{2}$/;
const incomeFormSchema = z
.object({
from: z
.string()
.refine(isDate, validationMessage("income.validation.date")),
to: z.string().refine(isDate, validationMessage("income.validation.date")),
})
.refine(validPeriod, {
path: ["to"],
...validationMessage("income.validation.period")({}),
});
const useAccountIncomePageViewModel = (): AccountIncomePageViewModel => {
const { accountId } = useParams();
const [searchParams, setSearchParams] = useSearchParams();
const requested = useMemo(
() => ({
from: searchParams.get("from") ?? "",
to: searchParams.get("to") ?? "",
}),
[searchParams],
);
const period = useMemo(
() => (validPeriod(requested) ? requested : defaultPeriod()),
[requested],
);
const form = useForm<IncomeForm>({
defaultValues: period,
resolver: zodResolver(incomeFormSchema),
});
const analytics = useIncomeAnalytics(accountId, period);
const events = useBrokerageEvents(accountId);
useEffect(() => {
if (!validPeriod(requested)) setSearchParams(period, { replace: true });
}, [period, requested, setSearchParams]);
useEffect(() => form.reset(period), [form, period]);
const onSubmit = (values: IncomeForm) => setSearchParams(values);
const onReset = () => setSearchParams(defaultPeriod(), { replace: true });
if (analytics.isLoading || !analytics.data) {
if (analytics.isError)
return { state: "error", retry: () => analytics.refetch(), period };
return { state: "loading" };
}
return {
state: "loaded",
analytics: analytics.data,
forecast: toForecast(events),
form,
onSubmit,
onReset,
};
};
function toForecast(
events: ReturnType<typeof useBrokerageEvents>,
): IncomeForecast {
if (events.isLoading) return { state: "loading" };
if (events.isError) return { state: "error", retry: () => events.refetch() };
const response = events.data;
const upcoming =
response?.events.filter(
(event) => event.type === "coupon" || event.type === "dividend",
) ?? [];
if (!response || !upcoming.length) return { state: "empty" };
return {
state: "loaded",
totals: response.incomeTotalsByCurrency,
events: upcoming.slice(0, 3),
};
}
function defaultPeriod(): IncomePeriod {
const today = moscowDate(new Date());
return { from: `${today.slice(0, 7)}-01`, to: today };
}
function validPeriod(period: IncomePeriod): period is IncomePeriod {
if (!isDate(period.from) || !isDate(period.to)) return false;
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, 10) === period.from &&
to.toISOString().slice(0, 10) === period.to &&
from <= to &&
to <= today &&
(to.valueOf() - from.valueOf()) / 86_400_000 + 1 <= 366
);
}
function isDate(value: string): boolean {
return (
datePattern.test(value) &&
new Date(`${value}T00:00:00Z`).toISOString().slice(0, 10) === value
);
}
function moscowDate(value: Date): string {
const parts = new Intl.DateTimeFormat("en-CA", {
timeZone: "Europe/Moscow",
year: "numeric",
month: "2-digit",
day: "2-digit",
}).formatToParts(value);
const part = (type: string) =>
parts.find((item) => item.type === type)?.value;
return `${part("year")}-${part("month")}-${part("day")}`;
}
export { type AccountIncomePageViewModel, useAccountIncomePageViewModel };
+2
View File
@@ -20,6 +20,7 @@ const AccountPage: FC = () => {
retry={viewModel.retry}
recentOperations={viewModel.recentOperations}
recentEvents={viewModel.recentEvents}
incomeSummary={viewModel.incomeSummary}
/>
);
return (
@@ -32,6 +33,7 @@ const AccountPage: FC = () => {
retry={viewModel.retry}
recentOperations={viewModel.recentOperations}
recentEvents={viewModel.recentEvents}
incomeSummary={viewModel.incomeSummary}
/>
);
};
+14
View File
@@ -8,6 +8,7 @@ import { formatSnapshotTime } from "@/entities/portfolio";
import { LoadingSkeleton, StateView } from "@/shared/ui";
import classes from "./AccountPage.module.css";
import type {
AccountPageIncomeSummary,
AccountPagePositionSection,
AccountPageRecentEvents,
AccountPageRecentOperations,
@@ -15,6 +16,7 @@ import type {
import {
AccountHeading,
CashBalances,
IncomeSummary,
PortfolioRefreshState,
PortfolioTotals,
PositionSection,
@@ -34,6 +36,7 @@ type AccountPageEmptyProps = {
retry?: () => void;
recentOperations: AccountPageRecentOperations;
recentEvents: AccountPageRecentEvents;
incomeSummary?: AccountPageIncomeSummary;
};
type AccountPageLoadedProps = {
@@ -45,6 +48,7 @@ type AccountPageLoadedProps = {
retry?: () => void;
recentOperations: AccountPageRecentOperations;
recentEvents: AccountPageRecentEvents;
incomeSummary?: AccountPageIncomeSummary;
};
const AccountPageLoading: FC = () => {
@@ -117,6 +121,7 @@ const AccountPageEmpty: FC<AccountPageEmptyProps> = (props) => {
retry,
recentOperations,
recentEvents,
incomeSummary,
} = props;
const { t } = useTranslation();
@@ -134,6 +139,7 @@ const AccountPageEmpty: FC<AccountPageEmptyProps> = (props) => {
/>
<RecentOperations operations={recentOperations} />
<RecentEvents events={recentEvents} />
{incomeSummary ? <IncomeSummary {...incomeSummary} /> : null}
</Stack>
);
};
@@ -148,6 +154,7 @@ const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
retry,
recentOperations,
recentEvents,
incomeSummary,
} = props;
const { t } = useTranslation();
@@ -175,6 +182,7 @@ const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
"cash",
"recentOperations",
"recentEvents",
"incomeSummary",
]}
classNames={{
control: classes.accordionControl,
@@ -211,6 +219,12 @@ const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
<RecentEvents events={recentEvents} />
</Accordion.Panel>
</Accordion.Item>
<Accordion.Item value="incomeSummary">
<Accordion.Control>{t("income.summaryTitle")}</Accordion.Control>
<Accordion.Panel>
{incomeSummary ? <IncomeSummary {...incomeSummary} /> : null}
</Accordion.Panel>
</Accordion.Item>
</Accordion>
</Stack>
);
+24
View File
@@ -10,6 +10,7 @@ import {
type BrokerageEvent,
useBrokerageEvents,
} from "@/entities/brokerage-event";
import { type IncomeSummary, useIncomeSummary } from "@/entities/income";
import type { Portfolio } from "@/entities/portfolio";
import {
formatMoney,
@@ -57,6 +58,11 @@ type AccountPageRecentEvents =
items: BrokerageEvent[];
};
type AccountPageIncomeSummary =
| { state: "loading" | "empty"; to: string }
| { state: "error"; to: string; retry: () => void }
| { state: "loaded"; to: string; summary: IncomeSummary };
type AccountPageContent = {
account?: BrokerageAccount;
accountId?: string;
@@ -65,6 +71,7 @@ type AccountPageContent = {
retry: () => void;
recentOperations: AccountPageRecentOperations;
recentEvents: AccountPageRecentEvents;
incomeSummary: AccountPageIncomeSummary;
};
type AccountPageLoadedViewModel = AccountPageContent & {
@@ -90,11 +97,13 @@ function useAccountPageViewModel(): AccountPageViewModel {
limit: 5,
});
const events = useBrokerageEvents(accountId);
const income = useIncomeSummary(accountId);
const account = useQueryClient()
.getQueryData<BrokerageAccount[]>(brokerageAccountsQueryKey)
?.find((item) => item.id === accountId);
const recentOperations = toRecentOperations(accountId, operations);
const recentEvents = toRecentEvents(accountId, events);
const incomeSummary = toIncomeSummary(accountId, income);
if (!portfolio.data) {
if (portfolio.isError)
return {
@@ -116,6 +125,7 @@ function useAccountPageViewModel(): AccountPageViewModel {
accountId,
recentOperations,
recentEvents,
incomeSummary,
...refresh,
};
return {
@@ -126,10 +136,23 @@ function useAccountPageViewModel(): AccountPageViewModel {
positionSections: toAccountPagePositionSections(portfolio.data),
recentOperations,
recentEvents,
incomeSummary,
...refresh,
};
}
function toIncomeSummary(
accountId: string | undefined,
income: ReturnType<typeof useIncomeSummary>,
): AccountPageIncomeSummary {
const to = `/accounts/${accountId}/income`;
if (income.isLoading) return { state: "loading", to };
if (income.isError)
return { state: "error", to, retry: () => income.refetch() };
if (!income.data?.totalsByCurrency.length) return { state: "empty", to };
return { state: "loaded", to, summary: income.data };
}
function toRecentOperations(
accountId: string | undefined,
operations: ReturnType<typeof useBrokerageOperations>,
@@ -223,6 +246,7 @@ function toPosition(
}
export {
type AccountPageIncomeSummary,
type AccountPagePosition,
type AccountPagePositionSection,
type AccountPageRecentEvents,
@@ -0,0 +1,57 @@
import { Button, Paper, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import type { IncomeSummary as IncomeSummaryData } from "@/entities/income";
import { formatMoney } from "@/entities/portfolio";
import { StateView } from "@/shared/ui";
type IncomeSummaryProps =
| { state: "loading"; to: string }
| { state: "error"; to: string; retry: () => void }
| { state: "empty"; to: string }
| { state: "loaded"; to: string; summary: IncomeSummaryData };
const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
const { t } = useTranslation();
if (props.state === "loading")
return <Text c="dimmed">{t("income.summaryLoading")}</Text>;
if (props.state === "error")
return (
<StateView
error
title={t("income.summaryError")}
text={t("income.errorText")}
action={
<Button onClick={props.retry}>{t("income.summaryRetry")}</Button>
}
/>
);
if (props.state === "empty")
return (
<Stack gap="xs">
<Text c="dimmed">{t("income.summaryEmpty")}</Text>
<Button component={Link} to={props.to} variant="subtle">
{t("income.open")}
</Button>
</Stack>
);
return (
<Stack gap="xs">
{props.summary.totalsByCurrency.map((total) => (
<Paper key={total.currency} p="sm" 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)}
</Text>
</Paper>
))}
<Button component={Link} to={props.to} variant="subtle">
{t("income.open")}
</Button>
</Stack>
);
};
export { IncomeSummary };
+1
View File
@@ -1,5 +1,6 @@
export { AccountHeading } from "./AccountHeading.view";
export { CashBalances } from "./CashBalances.view";
export { IncomeSummary } from "./IncomeSummary.view";
export { PortfolioRefreshState } from "./PortfolioRefreshState.view";
export { PortfolioTotals } from "./PortfolioTotals.view";
export { PositionSection } from "./PositionSection.view";