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
+146 -103
View File
@@ -6,6 +6,7 @@ import { MemoryRouter, Route, Routes, useLocation } from "react-router";
import { describe, expect, it, vi } from "vitest";
import { configureAuthClient } from "@/shared/api";
import { createTestQueryClient } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server";
import { BondPage } from "./BondPage";
@@ -92,127 +93,145 @@ function setup(
http.get("*/api/v1/bonds/:uid", () =>
options.failBond
? HttpResponse.json({ code: "NOT_FOUND" }, { status: 404 })
: HttpResponse.json(resolved),
: HttpResponse.json(resource(resolved)),
),
http.get("*/api/v1/bonds/by-ticker/:ticker", ({ request }) => {
requests.push(new URL(request.url));
return options.ambiguousTicker
? HttpResponse.json({ code: "BOND_TICKER_AMBIGUOUS" }, { status: 409 })
: HttpResponse.json(resolved);
: HttpResponse.json(resource(resolved));
}),
http.get("*/api/v1/bonds/:uid/:section", ({ params, request }) => {
requests.push(new URL(request.url));
if (params.section === "metrics")
return HttpResponse.json({
creditRating:
options.ratingState === "missing" ||
options.ratingState === "unavailable"
? null
: {
agency: "NCR",
value: options.ratingState === "withdrawn" ? null : "AAA.ru",
status:
options.ratingState === "withdrawn"
? "withdrawn"
: "active",
date: "2026-04-17",
sourceUrl: "https://ratings.ru/ratings/issues/123/",
observedAt: quote.observedAt,
},
coupon: money("32.88"),
couponDate: "2026-10-27",
couponType: "COUPON_TYPE_FLOATING",
couponPeriodDays: 90,
couponYieldPercent: "27.18",
couponYieldPriceAt: quote.priceAt,
effectiveYield: {
value: "15.6262",
pricePercent: "53.384",
date: "2030-05-15",
dateType: "MATDATE",
tradeAt: quote.priceAt,
},
unavailable: options.ratingState === "unavailable" ? ["rating"] : [],
observedAt: quote.observedAt,
});
return HttpResponse.json(
resource({
creditRating:
options.ratingState === "missing" ||
options.ratingState === "unavailable"
? null
: {
agency: "NCR",
value:
options.ratingState === "withdrawn" ? null : "AAA.ru",
status:
options.ratingState === "withdrawn"
? "withdrawn"
: "active",
date: "2026-04-17",
sourceUrl: "https://ratings.ru/ratings/issues/123/",
observedAt: quote.observedAt,
},
coupon: money("32.88"),
couponDate: "2026-10-27",
couponType: "COUPON_TYPE_FLOATING",
couponPeriodDays: 90,
couponYieldPercent: "27.18",
couponYieldPriceAt: quote.priceAt,
effectiveYield: {
value: "15.6262",
pricePercent: "53.384",
date: "2030-05-15",
dateType: "MATDATE",
tradeAt: quote.priceAt,
},
unavailable:
options.ratingState === "unavailable" ? ["rating"] : [],
observedAt: quote.observedAt,
}),
);
if (params.section === "quote")
return failQuote
? HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 })
: HttpResponse.json(quote);
: HttpResponse.json(resource(quote));
if (params.section === "position")
return HttpResponse.json(
options.noPosition
? { ...position, quantity: "0", accounts: [] }
: position,
resource(
options.noPosition
? { ...position, quantity: "0", accounts: [] }
: position,
),
);
if (params.section === "candles")
return HttpResponse.json({
candles: [
{ time: "2026-09-09T00:00:00Z", close: "99.25", isComplete: true },
],
currency: null,
historyFrom: null,
observedAt: quote.observedAt,
});
return HttpResponse.json(
resource({
candles: [
{
time: "2026-09-09T00:00:00Z",
close: "99.25",
isComplete: true,
},
],
currency: null,
historyFrom: null,
observedAt: quote.observedAt,
}),
);
if (options.failCoupons)
return HttpResponse.json(
{ code: "TBANK_UNAVAILABLE" },
{ status: 503 },
);
return HttpResponse.json({
coupons: [
{
perBond: money("32.88"),
recordDate: "2026-10-13",
number: "1",
couponType: "COUPON_TYPE_FLOATING",
periodDays: 90,
paymentDate: "2026-10-27",
timing: "upcoming",
estimatedAmount: options.noPosition ? null : money("328.8"),
},
{
perBond: money("20"),
recordDate: "2025-10-13",
paymentDate: null,
number: "2",
couponType: null,
periodDays: null,
timing: "past",
estimatedAmount: null,
},
],
from: "2021-09-10",
to: "2027-09-10",
observedAt: quote.observedAt,
positionAt: null,
estimateUnavailable: false,
positionIsStale: false,
});
return HttpResponse.json(
resource({
coupons: [
{
perBond: money("32.88"),
recordDate: "2026-10-13",
number: "1",
couponType: "COUPON_TYPE_FLOATING",
periodDays: 90,
paymentDate: "2026-10-27",
timing: "upcoming",
estimatedAmount: options.noPosition ? null : money("328.8"),
},
{
perBond: money("20"),
recordDate: "2025-10-13",
paymentDate: null,
number: "2",
couponType: null,
periodDays: null,
timing: "past",
estimatedAmount: null,
},
],
from: "2021-09-10",
to: "2027-09-10",
observedAt: quote.observedAt,
positionAt: null,
estimateUnavailable: false,
positionIsStale: false,
}),
);
}),
http.get("*/api/v1/brokerage-accounts/all/operations", ({ request }) => {
const url = new URL(request.url);
requests.push(url);
const next = url.searchParams.has("cursor");
return HttpResponse.json({
accountId: "all",
observedAt: quote.observedAt,
hasNext: !next,
nextCursor: next ? null : "next",
items: [
{
id: next ? "sold" : "dividend",
occurredAt: next ? "2022-01-02T10:00:00Z" : "2025-01-02T10:00:00Z",
type: next ? "OPERATION_TYPE_SELL" : "OPERATION_TYPE_COUPON",
category: next ? "trade" : "income",
description: "",
account: { id: "main", name: "Основной" },
payment: money("200"),
quantity: next ? "2" : null,
price: next ? money("100") : null,
},
],
});
return HttpResponse.json(
resource({
accountId: "all",
observedAt: quote.observedAt,
hasNext: !next,
nextCursor: next ? null : "next",
items: [
{
id: next ? "sold" : "dividend",
occurredAt: next
? "2022-01-02T10:00:00Z"
: "2025-01-02T10:00:00Z",
type: next ? "OPERATION_TYPE_SELL" : "OPERATION_TYPE_COUPON",
category: next ? "trade" : "income",
description: "",
account: { id: "main", name: "Основной" },
payment: money("200"),
quantity: next ? "2" : null,
price: next ? money("100") : null,
},
],
}),
);
}),
);
configureAuthClient({
@@ -300,9 +319,11 @@ describe("bond page", () => {
it("keeps market content and sold-position history when coupons fail", async () => {
setup({ noPosition: true, failCoupons: true });
await screen.findByText("98,125 %");
expect(await screen.findByRole("alert")).toHaveTextContent(
"Не удалось загрузить этот раздел",
);
expect(
(await screen.findByText(/Не удалось загрузить этот раздел/)).closest(
'[role="status"]',
),
).toHaveAttribute("aria-live", "polite");
expect(
screen.queryByRole("heading", { name: "Моя позиция" }),
).not.toBeInTheDocument();
@@ -311,14 +332,36 @@ describe("bond page", () => {
).toBeVisible();
});
it("preserves cached quote on refresh failure", async () => {
const controls = setup();
const scopes: unknown[] = [];
server.use(
http.post("*/api/v1/tbank-sync", async ({ request }) => {
scopes.push(await request.json());
return HttpResponse.json(
{ code: "TBANK_UNAVAILABLE" },
{ status: 503 },
);
}),
);
const controls = setup({ path: `/bonds/${uid}?period=year&events=trades` });
await screen.findByText("98,125 %");
controls.failQuote();
fireEvent.click(screen.getByRole("button", { name: "Обновить цену" }));
expect(await screen.findByRole("alert")).toHaveTextContent(
"последние полученные",
);
fireEvent.click(screen.getByRole("button", { name: "Обновить" }));
expect(
(await screen.findByText(/последние полученные/)).closest(
'[role="status"]',
),
).toHaveAttribute("aria-live", "polite");
expect(screen.getByText("98,125 %")).toBeVisible();
expect(scopes).toEqual([
{
screen: "bond",
instrumentUid: uid,
accountId: "all",
candlePeriod: "year",
categories: ["trade"],
limit: 20,
},
]);
});
it("offers search for an ambiguous or missing instrument without loading personal data", async () => {
const { requests } = setup({ path: "/bonds/SAME", ambiguousTicker: true });
+8 -9
View File
@@ -55,13 +55,10 @@ const BondPageView: FC<BondPageViewProps> = (props) => {
</div>
<Button
variant="subtle"
onClick={() => {
vm.bondState.retry();
vm.quoteState.retry();
vm.metricsState.retry();
}}
onClick={vm.refresh}
disabled={vm.refreshing}
>
{t("stock.refreshPrice")}
{t("investment.refresh")}
</Button>
</Group>
<Group mt="md" gap="xs">
@@ -80,8 +77,8 @@ const BondPageView: FC<BondPageViewProps> = (props) => {
</Badge>
) : null}
</Group>
{vm.bondState.error || vm.quoteState.error ? (
<Alert role="alert" color="orange" mt="md">
{vm.refreshError || vm.bondState.error || vm.quoteState.error ? (
<Alert role="status" aria-live="polite" color="orange" mt="md">
{t(vm.quote ? "accounts.refreshError" : "stock.sectionError")}
</Alert>
) : null}
@@ -322,7 +319,9 @@ const BondPageView: FC<BondPageViewProps> = (props) => {
{vm.coupons ? (
<Stack gap="md">
{vm.coupons.estimateUnavailable || vm.coupons.positionIsStale ? (
<Alert color="orange">{t("stock.estimateUnavailable")}</Alert>
<Alert color="orange" role="status" aria-live="polite">
{t("stock.estimateUnavailable")}
</Alert>
) : null}
{vm.upcoming.length ? (
vm.upcoming.map((coupon) => (
+26 -8
View File
@@ -16,6 +16,7 @@ import {
useBrokerageOperations,
} from "@/entities/broker-operation";
import { section } from "@/features/instrument-details";
import { useScreenSync } from "@/features/tbank-connection";
import { apiErrorCode } from "@/shared/api";
import { formatDate, instrumentLogoUrl } from "@/shared/lib";
@@ -58,6 +59,17 @@ function useBondPageVm() {
...firstPage,
cursor: cursors.at(-1),
});
const sync = useScreenSync(
{
screen: "bond",
instrumentUid: uid,
candlePeriod: period,
accountId: "all",
categories: categories[filter],
limit: 20,
},
[bond, quote, candles, position, metrics, coupons, operations],
);
const setParam = (key: string, value: string) => {
const next = new URLSearchParams(params);
next.set(key, value);
@@ -70,7 +82,7 @@ function useBondPageVm() {
queryKey: brokerageOperationsQueryOptions("all", firstPage).queryKey,
exact: true,
});
} else void operations.refetch();
} else void sync.refresh();
};
const chartData =
candles.data?.candles.map((candle) => ({
@@ -79,31 +91,34 @@ function useBondPageVm() {
price: Number(candle.close),
})) ?? [];
return {
refresh: sync.refresh,
refreshing: sync.refreshing,
refreshError: sync.transportError || sync.sourceError,
canonicalTo:
bond.data?.slug && bond.data.slug !== bondId
? `/bonds/${encodeURIComponent(bond.data.slug)}${params.size ? `?${params.toString()}` : ""}`
: null,
bond: bond.data,
bondState: section(bond),
bondState: section(bond, uid ? sync.refresh : () => bond.refetch()),
code: apiErrorCode(bond.error),
logoSrc: instrumentLogoUrl(bond.data?.logoName),
metrics: metrics.data,
metricsState: section(metrics),
metricsState: section(metrics, sync.refresh),
quote: quote.data,
quoteState: section(quote),
quoteState: section(quote, sync.refresh),
candles: candles.data,
chartData,
priceRows: chartData.toReversed(),
candlesState: section(candles),
candlesState: section(candles, sync.refresh),
period,
setPeriod: (value: string) => setParam("period", value),
averageLine: null,
hasIncompleteCandle:
candles.data?.candles.some((candle) => !candle.isComplete) ?? false,
position: position.data,
positionState: section(position),
positionState: section(position, sync.refresh),
coupons: coupons.data,
couponsState: section(coupons),
couponsState: section(coupons, sync.refresh),
upcoming:
coupons.data?.coupons
.filter((event) => event.timing === "upcoming")
@@ -121,7 +136,10 @@ function useBondPageVm() {
),
) ?? [],
operations: operations.data,
operationsState: { ...section(operations), retry: retryOperations },
operationsState: {
...section(operations, sync.refresh),
retry: retryOperations,
},
eventRows:
operations.data?.items.map((item) => ({
...item,