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
@@ -3,6 +3,7 @@ import { HttpResponse, http } from "msw";
import { describe, expect, it, vi } from "vitest";
import { configureAuthClient } from "@/shared/api";
import { createQueryWrapper } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server";
import { useBrokerageAccounts } from "./useBrokerageAccounts";
@@ -15,14 +16,16 @@ describe("useBrokerageAccounts", () => {
});
server.use(
http.get("*/api/v1/brokerage-accounts", () =>
HttpResponse.json([
{
id: "account-1",
name: "Основной",
type: "BROKERAGE",
openedOn: "2024-08-13",
},
]),
HttpResponse.json(
resource([
{
id: "account-1",
name: "Основной",
type: "BROKERAGE",
openedOn: "2024-08-13",
},
]),
),
),
);
@@ -52,14 +55,16 @@ describe("useBrokerageAccounts", () => {
http.get("*/api/v1/brokerage-accounts", () => {
calls += 1;
return calls === 1
? HttpResponse.json([
{
id: "account-1",
name: "Основной",
type: "BROKERAGE",
openedOn: "2024-08-13",
},
])
? HttpResponse.json(
resource([
{
id: "account-1",
name: "Основной",
type: "BROKERAGE",
openedOn: "2024-08-13",
},
]),
)
: HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 });
}),
);
@@ -1,19 +1,17 @@
import {
apiQueryClient,
type paths,
useAuthenticatedQuery,
} from "@/shared/api";
import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
const brokerageAccountsQueryOptions = () =>
apiQueryClient.queryOptions("get", "/api/v1/brokerage-accounts");
const brokerageAccountsQueryKey = brokerageAccountsQueryOptions().queryKey;
type BrokerageAccount =
paths["/api/v1/brokerage-accounts"]["get"]["responses"][200]["content"]["application/json"][number];
type BrokerageAccount = NonNullable<
paths["/api/v1/brokerage-accounts"]["get"]["responses"][200]["content"]["application/json"]["data"]
>[number];
function useBrokerageAccounts() {
return useAuthenticatedQuery({
return useResourceQuery({
meta: { accessGroup: "brokerage" },
...brokerageAccountsQueryOptions(),
staleTime: 60_000,
});
@@ -1,10 +1,18 @@
import type { BrokerageAccount } from "../api/useBrokerageAccounts";
import type {
BrokerageAccount,
useBrokerageAccounts,
} from "../api/useBrokerageAccounts";
type Money = NonNullable<
BrokerageAccount["portfolioSummary"]
>["totalsByCurrency"][number];
type BrokerageAccountCard = {
source?: NonNullable<
ReturnType<typeof useBrokerageAccounts>["meta"]
>["dependencies"] extends (infer T)[] | undefined
? T
: never;
account: BrokerageAccount;
positionCounts: { stocks: number; bonds: number } | null;
summary:
@@ -19,11 +27,19 @@ function accountTypeKey(type: BrokerageAccount["type"]) {
function brokerageAccountCards(
accounts: BrokerageAccount[],
dependencies: NonNullable<
ReturnType<typeof useBrokerageAccounts>["meta"]
>["dependencies"] = [],
): BrokerageAccountCard[] {
return accounts.map((account) => {
const source = dependencies.find(
(item) =>
item.resourceKey === `portfolio/${encodeURIComponent(account.id)}`,
);
const summary = account.portfolioSummary;
if (!summary)
return {
source,
account,
positionCounts: null,
summary: { state: "unavailable" },
@@ -33,8 +49,9 @@ function brokerageAccountCards(
bonds: summary.bondPositionCount,
};
if (!summary.totalsByCurrency.length)
return { account, positionCounts, summary: { state: "empty" } };
return { source, account, positionCounts, summary: { state: "empty" } };
return {
source,
account,
positionCounts,
summary: {
@@ -185,3 +185,44 @@ export const LargeValues: Story = {
]),
},
};
export const IndependentFreshness: Story = {
name: "Независимая свежесть и ошибка сводок",
args: {
accounts: brokerageAccountCards(
[
syntheticAccount,
{
...syntheticAccount,
id: "waiting",
name: "Новый счёт",
portfolioSummary: null,
},
],
[
{
resourceKey: "portfolio/storybook-account",
dataRevision: "1",
stateVersion: "failed",
availability: "complete",
freshness: "stale",
lastSuccessfulAt: "2026-09-24T10:30:00Z",
sync: {
id: "failed",
state: "failed",
errorCode: "TBANK_UNAVAILABLE",
},
},
{
resourceKey: "portfolio/waiting",
dataRevision: "0",
stateVersion: "waiting",
availability: "missing",
freshness: "unknown",
lastSuccessfulAt: null,
sync: { id: "waiting", state: "running", errorCode: null },
},
],
),
},
};
@@ -2,6 +2,7 @@ import { MantineProvider } from "@mantine/core";
import { render, screen, within } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { describe, expect, it } from "vitest";
import { resource } from "@/test/resource";
import { brokerageAccountCards } from "../../model/display";
import { BrokerageAccountList } from "./BrokerageAccountList";
@@ -84,3 +85,42 @@ describe("BrokerageAccountList", () => {
).not.toBeInTheDocument();
});
});
it("shows portfolio summary freshness independently for each account", () => {
const accounts = brokerageAccountCards(
["fresh", "stale"].map((id) => ({
id,
name: id,
type: "BROKERAGE" as const,
openedOn: null,
portfolioSummary: {
stockPositionCount: 1,
bondPositionCount: 0,
totalsByCurrency: [{ currency: "RUB", value: "10" }],
},
})),
[
resource(null, { resourceKey: "portfolio/fresh", freshness: "fresh" })
.meta,
resource(null, { resourceKey: "portfolio/stale", freshness: "stale" })
.meta,
],
);
render(
<MantineProvider>
<MemoryRouter>
<BrokerageAccountList accounts={accounts} />
</MemoryRouter>
</MantineProvider>,
);
expect(
within(screen.getByRole("link", { name: /stale/ })).getByText(
"Данные требуют обновления",
),
).toBeVisible();
expect(
within(screen.getByRole("link", { name: /fresh/ })).queryByText(
"Данные требуют обновления",
),
).not.toBeInTheDocument();
});
@@ -2,7 +2,7 @@ import { Card, Group, SimpleGrid, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { formatDate, formatMoney } from "@/shared/lib";
import { formatDate, formatMoney, formatSnapshotTime } from "@/shared/lib";
import type { BrokerageAccountCard } from "../../model/display";
import { accountTypeKey } from "../../model/display";
import classes from "./BrokerageAccountList.module.css";
@@ -52,8 +52,8 @@ const BrokerageAccountList: FC<BrokerageAccountListProps> = (props) => {
const { t } = useTranslation();
return (
<SimpleGrid className={classes.list} cols={{ base: 1, lg: 2 }} spacing="lg">
{accounts.map(({ account, summary, positionCounts }) => (
<SimpleGrid className={classes.list} cols={1} spacing="lg">
{accounts.map(({ account, summary, positionCounts, source }) => (
<Card
component={Link}
to={`/accounts/${account.id}`}
@@ -92,6 +92,25 @@ const BrokerageAccountList: FC<BrokerageAccountListProps> = (props) => {
{t("accounts.currentValue")}
</Text>
<BrokerageAccountSummary summary={summary} />
{source?.lastSuccessfulAt ? (
<Text size="xs" c="dimmed">
{t("investment.sourceTime", {
date: formatSnapshotTime(source.lastSuccessfulAt),
})}
</Text>
) : null}
{source?.sync.state === "running" ||
source?.sync.state === "queued" ? (
<Text size="xs" role="status">
{t("accounts.refreshing")}
</Text>
) : null}
{source?.sync.state === "failed" ? (
<Text size="xs">{t("accounts.refreshError")}</Text>
) : null}
{source?.freshness === "stale" ? (
<Text size="xs">{t("investment.stale")}</Text>
) : null}
</Stack>
{positionCounts ? (
<dl className={classes.positions}>