feat: show persisted investment data and sync state

Consume the provided resource-envelope API snapshot. Preserve financial snapshots during
refresh, observe synchronization without importing, and fence late responses across
account and connection changes.
This commit is contained in:
2026-09-26 21:22:49 +03:00
parent b987fd8e78
commit 4e5f564fa1
81 changed files with 4714 additions and 1420 deletions
@@ -1,3 +1,4 @@
import { resource } from "@/test/resource";
import "dayjs/locale/ru";
import { MantineProvider } from "@mantine/core";
import { DatesProvider } from "@mantine/dates";
@@ -154,7 +155,7 @@ describe("AccountIncomePage", () => {
"*/api/v1/brokerage-accounts/:accountId/income-analytics",
({ request }) => {
requested.push(new URL(request.url).search);
return HttpResponse.json(analytics);
return HttpResponse.json(resource(analytics));
},
),
);
@@ -236,7 +237,7 @@ describe("AccountIncomePage", () => {
};
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json(response),
HttpResponse.json(resource(response)),
),
);
renderPage();
@@ -284,7 +285,7 @@ describe("AccountIncomePage", () => {
])("shows a local error for %s", async (_name, response) => {
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json(response),
HttpResponse.json(resource(response)),
),
);
renderPage();
@@ -299,13 +300,15 @@ describe("AccountIncomePage", () => {
it("accepts an empty analytics response", async () => {
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json({
...analytics,
totalsByCurrency: [],
buckets: [],
instruments: [],
entries: [],
}),
HttpResponse.json(
resource({
...analytics,
totalsByCurrency: [],
buckets: [],
instruments: [],
entries: [],
}),
),
),
);
renderPage();
@@ -347,7 +350,7 @@ describe("AccountIncomePage", () => {
};
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json(response),
HttpResponse.json(resource(response)),
),
);
renderPage();
@@ -369,13 +372,15 @@ describe("AccountIncomePage", () => {
const eventsRequest = vi.fn(() => new HttpResponse(null, { status: 503 }));
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json({
...analytics,
yearComparison: {
period: { from: "2025-08-01", to: "2025-08-27" },
totalsByCurrency: [comparison("RUB")],
},
}),
HttpResponse.json(
resource({
...analytics,
yearComparison: {
period: { from: "2025-08-01", to: "2025-08-27" },
totalsByCurrency: [comparison("RUB")],
},
}),
),
),
http.get("*/api/v1/brokerage-accounts/account-1/events", eventsRequest),
);
@@ -392,13 +397,16 @@ describe("AccountIncomePage", () => {
expect(screen.queryByText("Динамика")).not.toBeInTheDocument();
expect(eventsRequest).not.toHaveBeenCalled();
expect(screen.getByRole("region", { name: "Выплаты" })).toBeInTheDocument();
const selected = screen.getByRole("region", {
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();
expect(screen.queryByText(/Предыдущий период/)).not.toBeInTheDocument();
expect(
screen.getByRole("heading", { name: "Предыдущий период" }),
).toBeVisible();
expect(screen.queryByText("Выбранный период")).not.toBeInTheDocument();
expect(screen.queryByText("Сравниваемый период")).not.toBeInTheDocument();
expect(
@@ -409,7 +417,7 @@ describe("AccountIncomePage", () => {
for (const amount of ["10 ₽", "2 ₽", "12 ₽"]) {
expect(within(selected).getByText(amount)).toBeInTheDocument();
}
const difference = screen.getByRole("region", { name: "Разница" });
const difference = within(year).getByRole("region", { name: "Разница" });
for (const amount of ["+9 ₽", "+2 ₽", "+11 ₽"]) {
expect(within(difference).getByText(amount)).toBeInTheDocument();
}
@@ -425,7 +433,18 @@ describe("AccountIncomePage", () => {
it("shows the unavailable year state without falling back to the previous period", async () => {
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json(analytics),
HttpResponse.json(
resource(analytics, {
dependencies: [
resource(analytics).meta,
resource(analytics).meta,
{
...resource(null).meta,
unavailableReason: "CALENDAR_OR_ACCOUNT_HISTORY",
},
],
}),
),
),
);
renderPage();
@@ -433,9 +452,11 @@ describe("AccountIncomePage", () => {
await screen.findByText("Сравнение с годом ранее недоступно."),
).toBeInTheDocument();
expect(
screen.queryByRole("region", { name: "Разница" }),
screen.queryByRole("region", { name: "Годом ранее" }),
).not.toBeInTheDocument();
expect(screen.queryByText(/Предыдущий период/)).not.toBeInTheDocument();
expect(
screen.getByRole("region", { name: "Предыдущий период" }),
).toBeVisible();
});
it("shows a recoverable realized error", async () => {
@@ -537,13 +558,15 @@ function respondWithRequestedPeriod(requests: string[]) {
({ 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"),
},
});
return HttpResponse.json(
resource({
...analytics,
period: {
from: url.searchParams.get("from"),
to: url.searchParams.get("to"),
},
}),
);
},
),
);
@@ -669,7 +692,32 @@ describe("income period and snapshot boundary", () => {
await screen.findByText(/Показан последний загруженный результат/),
).toBeInTheDocument();
expect(screen.getByRole("region", { name: "Выплаты" })).toBeVisible();
respondWithRequestedPeriod([]);
server.use(
http.post("*/api/v1/tbank-sync", () =>
HttpResponse.json(
{
id: "income",
scope: { screen: "income", accountId: "account-1" },
now: "2026-09-25T00:00:00Z",
},
{ status: 202 },
),
),
http.get("*/api/v1/tbank-sync/:id", () =>
HttpResponse.json({
id: "income",
scope: null,
now: "2026-09-25T00:00:00Z",
state: "succeeded",
errorCode: null,
progress: { total: 1, completed: 1, discovering: false },
resources: [resource(null, { stateVersion: "2" }).meta],
}),
),
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json(resource(analytics, { stateVersion: "2" })),
),
);
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
await waitFor(() =>
expect(
@@ -694,10 +742,12 @@ describe("income period and snapshot boundary", () => {
"*/api/v1/brokerage-accounts/account-1/income-analytics",
async () => {
await pending;
return HttpResponse.json({
...analytics,
period: { from: "2026-08-02", to: "2026-08-27" },
});
return HttpResponse.json(
resource({
...analytics,
period: { from: "2026-08-02", to: "2026-08-27" },
}),
);
},
),
);
@@ -778,3 +828,64 @@ describe("income period and snapshot boundary", () => {
expect(screen.getAllByText("Купон")).toHaveLength(6);
});
});
it("shows selected income before comparison coverage without inventing a zero baseline", async () => {
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json(
resource({ ...analytics, previous: null, yearComparison: null }),
),
),
);
renderPage();
expect(await screen.findByRole("region", { name: "Выплаты" })).toBeVisible();
expect(
screen.queryByRole("region", { name: "Год назад" }),
).not.toBeInTheDocument();
expect(screen.getAllByText("12 ₽").length).toBeGreaterThan(0);
expect(
screen.getAllByText("Период сравнения ещё не загружен полностью."),
).toHaveLength(2);
expect(
screen.queryByText("Сравнение с годом ранее недоступно."),
).not.toBeInTheDocument();
expect(
screen.queryByRole("region", { name: "Разница" }),
).not.toBeInTheDocument();
expect(screen.getByLabelText("Период")).toBeVisible();
});
it("keeps complete previous comparison while year source failed without inventing its amounts", async () => {
server.use(
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json(
resource(analytics, {
dependencies: [
resource(analytics).meta,
resource(analytics).meta,
{
...resource(null).meta,
sync: {
id: null,
state: "failed",
errorCode: "TBANK_UNAVAILABLE",
},
},
],
}),
),
),
);
renderPage();
expect(
await screen.findByRole("region", { name: "Предыдущий период" }),
).toBeVisible();
expect(
screen.getByText(
"Не удалось загрузить период сравнения. Повторите обновление.",
),
).toBeVisible();
expect(
screen.queryByRole("region", { name: "Годом ранее" }),
).not.toBeInTheDocument();
});
@@ -4,6 +4,7 @@ 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 {
@@ -17,7 +18,16 @@ import {
const ISO_MONTH_LENGTH = 7;
type IncomeMeta = ReturnType<typeof useIncomeAnalytics>["meta"];
type ComparisonNotice =
| "comparisonPending"
| "comparisonFailed"
| "yearUnavailable";
type IncomeDisplayModel = {
previousComparison: IncomeDisplayModel["comparison"];
previousNotice: ComparisonNotice;
yearNotice: ComparisonNotice;
entries: { key: string; operation: IncomeAnalytics["entries"][number] }[];
comparison: {
selectedPeriod: string;
@@ -38,6 +48,9 @@ type AccountIncomePageViewModel =
analytics: IncomeAnalytics;
display: IncomeDisplayModel;
formRevision: number;
sourceError?: boolean;
lastSuccessfulAt?: string | null;
partial?: boolean;
refreshing: boolean;
refreshError: boolean;
retry: () => void;
@@ -90,6 +103,10 @@ const useAccountIncomePageViewModel = (
});
const [formRevision, setFormRevision] = useState(0);
const analytics = useIncomeAnalytics(accountId, period);
const sync = useScreenSync(
{ screen: "income", accountId, from: period.from, to: period.to },
[analytics],
);
useEffect(() => {
if (!validPeriod(requested)) setSearchParams(period, { replace: true });
@@ -112,21 +129,30 @@ const useAccountIncomePageViewModel = (
setSearchParams(next, { replace: true });
};
if (analytics.isLoading || !analytics.data) {
if (analytics.isError)
return { state: "error", retry: () => analytics.refetch(), period };
if (analytics.isError || analytics.meta?.sync.state === "failed")
return { state: "error", retry: sync.refresh, period };
return { state: "loading" };
}
const display = toIncomeDisplayModel(analytics.data);
const display = toIncomeDisplayModel(analytics.data, analytics.meta);
if (!display)
return { state: "error", retry: () => analytics.refetch(), period };
return {
state: "error",
retry: () => {
void analytics.observe();
},
period,
};
return {
state: "loaded",
analytics: analytics.data,
display,
formRevision,
refreshing: analytics.isFetching,
refreshError: analytics.isError,
retry: () => analytics.refetch(),
sourceError: sync.sourceError,
lastSuccessfulAt: analytics.meta?.lastSuccessfulAt,
partial: analytics.meta?.availability !== "complete",
refreshing: analytics.isFetching || sync.refreshing,
refreshError: analytics.isError || sync.sourceError || sync.transportError,
retry: sync.refresh,
form,
onSubmit,
onReset,
@@ -157,6 +183,7 @@ function validPeriod(period: IncomePeriod): period is IncomePeriod {
function toIncomeDisplayModel(
analytics: IncomeAnalytics,
meta?: IncomeMeta,
): IncomeDisplayModel | null {
const instruments = new Map<
string,
@@ -209,33 +236,53 @@ function toIncomeDisplayModel(
if (instrument.includedCount !== instrument.receiptCount) return null;
}
// The income endpoint returns selected, previous and year dependencies in order.
const [, previous, year] = meta?.dependencies ?? [];
return {
entries,
comparison: analytics.yearComparison
? {
selectedPeriod: formatComparisonPeriod(analytics.period),
comparedPeriod: formatComparisonPeriod(
analytics.yearComparison.period,
),
values: analytics.yearComparison.totalsByCurrency.map((value) => ({
...value,
percentages: {
total: formatIncomeChange(
value.difference.total.value,
value.compared.total.value,
),
coupon: formatIncomeChange(
value.difference.coupon.value,
value.compared.coupon.value,
),
dividend: formatIncomeChange(
value.difference.dividend.value,
value.compared.dividend.value,
),
},
})),
}
: null,
previousComparison: comparisonDisplay(analytics.period, analytics.previous),
comparison: comparisonDisplay(analytics.period, analytics.yearComparison),
previousNotice: comparisonNotice(previous),
yearNotice: comparisonNotice(year),
};
}
function comparisonNotice(
dependency:
| NonNullable<NonNullable<IncomeMeta>["dependencies"]>[number]
| undefined,
): ComparisonNotice {
if (dependency?.unavailableReason) return "yearUnavailable";
return dependency?.sync.state === "failed"
? "comparisonFailed"
: "comparisonPending";
}
function comparisonDisplay(
period: IncomePeriod,
comparison: IncomeAnalytics["yearComparison"],
): IncomeDisplayModel["comparison"] {
if (!comparison) return null;
return {
selectedPeriod: formatComparisonPeriod(period),
comparedPeriod: formatComparisonPeriod(comparison.period),
values: comparison.totalsByCurrency.map((value) => ({
...value,
percentages: {
total: formatIncomeChange(
value.difference.total.value,
value.compared.total.value,
),
coupon: formatIncomeChange(
value.difference.coupon.value,
value.compared.coupon.value,
),
dividend: formatIncomeChange(
value.difference.dividend.value,
value.compared.dividend.value,
),
},
})),
};
}
@@ -11,6 +11,7 @@ import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { FormProvider } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { formatSnapshotTime } from "@/shared/lib";
import classes from "../AccountIncomePage.module.css";
import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
import { IncomeComparisons } from "./IncomeComparisons.view";
@@ -34,7 +35,17 @@ const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
const { t } = useTranslation();
return (
<Stack gap="lg" className={classes.page}>
{props.lastSuccessfulAt ? (
<Text size="xs" c="dimmed">
{t("investment.sourceTime", {
date: formatSnapshotTime(props.lastSuccessfulAt),
})}
</Text>
) : null}
<Title order={1}>{t("income.title")}</Title>
<Button onClick={retry} disabled={refreshing} w="fit-content">
{t("investment.refresh")}
</Button>
<FormProvider {...form}>
<IncomePeriodForm
key={props.formRevision}
@@ -49,16 +60,24 @@ const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
</Group>
) : null}
{refreshError ? (
<Alert color="orange">
<Alert color="orange" role="status" aria-live="polite">
<Stack gap="sm">
<Text>{t("income.refreshError")}</Text>
<Text>
{t(
props.sourceError
? "investment.syncFailed"
: "income.refreshError",
)}
</Text>
<Button onClick={retry} variant="default">
{t("income.retry")}
</Button>
</Stack>
</Alert>
) : null}
{analytics.totalsByCurrency.length ? (
{props.partial ? (
<Alert role="status">{t("investment.partial")}</Alert>
) : analytics.totalsByCurrency.length ? (
<IncomeSummary totals={analytics.totalsByCurrency} />
) : (
<StateView
@@ -67,7 +86,16 @@ const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
/>
)}
<Alert color="blue">{t("income.taxBoundary")}</Alert>
<IncomeComparisons comparison={display.comparison} />
<IncomeComparisons
title={t("income.previousPeriod")}
comparison={display.previousComparison}
notice={t(`income.${display.previousNotice}`)}
/>
<IncomeComparisons
title={t("income.yearAgo")}
comparison={display.comparison}
notice={t(`income.${display.yearNotice}`)}
/>
<IncomePayments entries={display.entries} />
</Stack>
);
@@ -5,8 +5,14 @@ import { formatMoney } from "@/shared/lib";
import classes from "../AccountIncomePage.module.css";
import type { IncomeDisplayModel } from "../AccountIncomePage.vm";
type IncomeComparisonsProps = { comparison: IncomeDisplayModel["comparison"] };
type ComparisonProps = NonNullable<IncomeDisplayModel["comparison"]>;
type IncomeComparisonsProps = {
comparison: IncomeDisplayModel["comparison"];
title: string;
notice: string;
};
type ComparisonProps = NonNullable<IncomeDisplayModel["comparison"]> & {
title: string;
};
type ComparisonValuesProps = {
kind: "selected" | "compared" | "difference";
label: string;
@@ -15,16 +21,15 @@ type ComparisonValuesProps = {
};
const IncomeComparisons: FC<IncomeComparisonsProps> = (props) => {
const { t } = useTranslation();
return (
<Stack>
<Title order={2}>{t("income.yearAgo")}</Title>
<Title order={2}>{props.title}</Title>
{props.comparison ? (
<Comparison {...props.comparison} />
<Comparison {...props.comparison} title={props.title} />
) : (
<Paper p="sm" radius="md" className={classes.comparisonNotice}>
<Text size="sm" c="gray.7">
{t("income.yearUnavailable")}
<Text size="sm" c="gray.7" role="status" aria-live="polite">
{props.notice}
</Text>
</Paper>
)}
@@ -35,7 +40,7 @@ const IncomeComparisons: FC<IncomeComparisonsProps> = (props) => {
const Comparison: FC<ComparisonProps> = (props) => {
const { t } = useTranslation();
return (
<section aria-label={t("income.yearAgo")} className={classes.comparison}>
<section aria-label={props.title} className={classes.comparison}>
<Stack gap="md">
{props.values.map((value) => (
<Stack