feat(account): offer retry after exhausted portfolio reads (WealthLedger/frontend#55)

This commit is contained in:
2026-11-03 08:35:13 +03:00
parent 1a9199a92b
commit 3a01a3a5bc
7 changed files with 152 additions and 10 deletions
@@ -60,6 +60,10 @@ function configureTestAuth() {
}); });
} }
// Automatic read retries wait 1s + 2s before the failure is final.
const RETRIES_EXHAUSTED_MS = 6000;
const TEST_MS = 10_000;
function renderAccountRoute(queryClient: QueryClient, accountId = "account-1") { function renderAccountRoute(queryClient: QueryClient, accountId = "account-1") {
configureTestAuth(); configureTestAuth();
@@ -1255,6 +1259,110 @@ describe("AccountPage states", () => {
expect(screen.getByText("Вторая")).toBeInTheDocument(); expect(screen.getByText("Вторая")).toBeInTheDocument();
}); });
it(
"keeps cached totals, then warns and retries the same portfolio GET",
{ timeout: TEST_MS },
async () => {
let isFailing = false;
let requests = 0;
server.use(
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () => {
requests += 1;
if (isFailing)
return HttpResponse.json(
{ code: "TBANK_UNAVAILABLE" },
{ status: 503 },
);
return HttpResponse.json(resource(
requests === 1
? portfolio
: { ...portfolio, totalsByCurrency: [{ currency: "RUB", value: "999" }] },
{ resourceKey: "portfolio" },
));
}),
);
const queryClient = createTestQueryClient();
renderAccountRoute(queryClient);
await screen.findByText("Вторая");
expect(screen.queryByRole("button", { name: "Повторить" }))
.not.toBeInTheDocument();
isFailing = true;
void queryClient.invalidateQueries({
queryKey: portfolioQueryOptions("account-1").queryKey,
});
const retry = await screen.findByRole(
"button",
{ name: "Повторить" },
{ timeout: RETRIES_EXHAUSTED_MS },
);
expect(screen.getByText("Не удалось обновить данные")).toBeInTheDocument();
expect(screen.getByText("Вторая")).toBeInTheDocument();
expect(screen.getByText("1 234,5 ₽")).toBeInTheDocument();
// One cached read plus the three automatic attempts.
expect(requests).toBe(4);
isFailing = false;
fireEvent.click(retry);
expect(await screen.findByText("999 ₽")).toBeInTheDocument();
expect(requests).toBe(5);
expect(screen.queryByText("Не удалось обновить данные"))
.not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Повторить" }))
.not.toBeInTheDocument();
},
);
it(
"offers retry after an initial temporary failure and recovers in place",
{ timeout: TEST_MS },
async () => {
let isFailing = true;
let requests = 0;
server.use(
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () => {
requests += 1;
return isFailing
? HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 })
: HttpResponse.json(resource(portfolio, { resourceKey: "portfolio" }));
}),
);
renderAccountRoute(createTestQueryClient());
const retry = await screen.findByRole(
"button",
{ name: "Повторить" },
{ timeout: RETRIES_EXHAUSTED_MS },
);
expect(requests).toBe(3);
isFailing = false;
fireEvent.click(retry);
expect(await screen.findByText("Вторая")).toBeInTheDocument();
expect(requests).toBe(4);
},
);
it.each(["NOT_FOUND", "UNAUTHORIZED"])(
"does not offer a plain retry for %s after a cached portfolio",
async (code) => {
server.use(
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
HttpResponse.json({ code }, { status: code === "NOT_FOUND" ? 404 : 401 })),
);
renderAccountRoute(createTestQueryClient());
await waitFor(() =>
expect(screen.queryByRole("heading", { name: "Загрузка" })).not.toBeInTheDocument());
expect(screen.queryByRole("button", { name: "Повторить" })).not.toBeInTheDocument();
},
);
it.each([503])( it.each([503])(
"preserves totals quietly through refresh error %i and success", "preserves totals quietly through refresh error %i and success",
async (status) => { async (status) => {
@@ -16,6 +16,7 @@ const AccountPage: FC = () => {
account={viewModel.account} account={viewModel.account}
accountId={viewModel.accountId} accountId={viewModel.accountId}
incomeSummary={viewModel.incomeSummary} incomeSummary={viewModel.incomeSummary}
readRetry={viewModel.readRetry}
recentEvents={viewModel.recentEvents} recentEvents={viewModel.recentEvents}
recentOperations={viewModel.recentOperations} recentOperations={viewModel.recentOperations}
source={viewModel.source} source={viewModel.source}
@@ -35,6 +36,7 @@ const AccountPage: FC = () => {
partial={viewModel.partial} partial={viewModel.partial}
portfolio={viewModel.portfolio} portfolio={viewModel.portfolio}
positionSections={viewModel.positionSections} positionSections={viewModel.positionSections}
readRetry={viewModel.readRetry}
recentEvents={viewModel.recentEvents} recentEvents={viewModel.recentEvents}
recentOperations={viewModel.recentOperations} recentOperations={viewModel.recentOperations}
slice={viewModel.slice} slice={viewModel.slice}
@@ -16,7 +16,7 @@ import {
import { useIncomeSummary } from "@/entities/income"; import { useIncomeSummary } from "@/entities/income";
import { usePortfolio } from "@/entities/portfolio"; import { usePortfolio } from "@/entities/portfolio";
import { useScreenSync } from "@/features/tbank-connection"; import { useScreenSync } from "@/features/tbank-connection";
import { apiErrorCode, isBrokerageAccessLoss } from "@/shared/api"; import { apiErrorCode, isBrokerageAccessLoss, readRetry } from "@/shared/api";
import { useInitialAvailability } from "@/shared/lib"; import { useInitialAvailability } from "@/shared/lib";
import { import {
@@ -45,6 +45,7 @@ type AccountPageContent = {
accountId?: string; accountId?: string;
incomeSummary: AccountPageIncomeSummary; incomeSummary: AccountPageIncomeSummary;
partial?: boolean; partial?: boolean;
readRetry: AccountPageReadRetry;
recentEvents: AccountPageRecentEvents; recentEvents: AccountPageRecentEvents;
recentOperations: AccountPageRecentOperations; recentOperations: AccountPageRecentOperations;
source?: InvestmentResourceMeta; source?: InvestmentResourceMeta;
@@ -68,10 +69,12 @@ type AccountPageLoadedViewModel = AccountPageContent & {
unrealizedReturns: Portfolio["totalsByCurrency"]; unrealizedReturns: Portfolio["totalsByCurrency"];
}; };
type AccountPageReadRetry = ReturnType<typeof readRetry>;
type AccountPageViewModel type AccountPageViewModel
= | AccountPageEmptyViewModel = | AccountPageEmptyViewModel
| AccountPageLoadedViewModel | AccountPageLoadedViewModel
| { code?: string; state: "error" } | { code?: string; readRetry: AccountPageReadRetry; state: "error" }
| { state: "loading" }; | { state: "loading" };
function useAccountPageViewModel(): AccountPageViewModel { function useAccountPageViewModel(): AccountPageViewModel {
@@ -113,6 +116,8 @@ function useAccountPageViewModel(): AccountPageViewModel {
]); ]);
const code = apiErrorCode(portfolio.error); const code = apiErrorCode(portfolio.error);
// The portfolio drives this screen; the retry repeats only its GET.
const retry = readRetry([portfolio]);
const isAccessFailure = isBrokerageAccessLoss(code); const isAccessFailure = isBrokerageAccessLoss(code);
const availability = useInitialAvailability({ const availability = useInitialAvailability({
@@ -122,12 +127,13 @@ function useAccountPageViewModel(): AccountPageViewModel {
isFetching: portfolio.isFetching, isFetching: portfolio.isFetching,
}); });
if (isAccessFailure) return { code, state: "error" as const }; if (isAccessFailure)
return { code, readRetry: retry, state: "error" as const };
if (!portfolio.data) if (!portfolio.data)
return { return availability === "unavailable"
state: availability === "unavailable" ? "error" : "loading", ? { code, readRetry: retry, state: "error" as const }
} as const; : { state: "loading" as const };
const account = accounts.data?.find(item => item.id === accountId); const account = accounts.data?.find(item => item.id === accountId);
const recentOperations = toRecentOperations(accountId, operations); const recentOperations = toRecentOperations(accountId, operations);
@@ -144,6 +150,7 @@ function useAccountPageViewModel(): AccountPageViewModel {
account, account,
accountId, accountId,
incomeSummary, incomeSummary,
readRetry: retry,
recentEvents, recentEvents,
recentOperations, recentOperations,
source: portfolio.meta, source: portfolio.meta,
@@ -181,6 +188,7 @@ function useAccountPageViewModel(): AccountPageViewModel {
partial: isPartial, partial: isPartial,
portfolio: portfolio.data, portfolio: portfolio.data,
positionSections: toAccountPagePositionSections(portfolio.data), positionSections: toAccountPagePositionSections(portfolio.data),
readRetry: retry,
recentEvents, recentEvents,
recentOperations, recentOperations,
slice: current.slice, slice: current.slice,
@@ -8,7 +8,7 @@ import type { BrokerageAccount } from "@/entities/brokerage-account";
import type { InvestmentResourceMeta } from "@/shared/api"; import type { InvestmentResourceMeta } from "@/shared/api";
import { BrokerageEventsPreview } from "@/entities/brokerage-event"; import { BrokerageEventsPreview } from "@/entities/brokerage-event";
import { SourceSyncStatus } from "@/shared/ui"; import { ReadRetry, type ReadRetryProps, SourceSyncStatus } from "@/shared/ui";
import { PortfolioStructure } from "@/widgets/portfolio-structure"; import { PortfolioStructure } from "@/widgets/portfolio-structure";
import type { import type {
@@ -25,6 +25,7 @@ type AccountPageEmptyProps = {
account?: BrokerageAccount; account?: BrokerageAccount;
accountId?: string; accountId?: string;
incomeSummary?: AccountPageIncomeSummary; incomeSummary?: AccountPageIncomeSummary;
readRetry?: ReadRetryProps;
recentEvents: AccountPageRecentEvents; recentEvents: AccountPageRecentEvents;
recentOperations: AccountPageRecentOperations; recentOperations: AccountPageRecentOperations;
source?: InvestmentResourceMeta; source?: InvestmentResourceMeta;
@@ -49,6 +50,8 @@ const AccountPageEmpty: FC<AccountPageEmptyProps> = (props) => {
stale={props.source?.freshness === "stale"} stale={props.source?.freshness === "stale"}
/> />
{!!props.readRetry && <ReadRetry {...props.readRetry} />}
<StateView text={text} title={t("portfolio.emptyTitle")} /> <StateView text={text} title={t("portfolio.emptyTitle")} />
<PortfolioStructure <PortfolioStructure
@@ -6,8 +6,12 @@ import { useTranslation } from "react-i18next";
import { Link } from "react-router"; import { Link } from "react-router";
import { ApiErrorCode, isApiErrorCode } from "@/shared/api"; import { ApiErrorCode, isApiErrorCode } from "@/shared/api";
import { ReadRetryButton, type ReadRetryProps } from "@/shared/ui";
type AccountPageErrorProps = { code?: string }; type AccountPageErrorProps = {
code?: string;
readRetry?: ReadRetryProps;
};
const AccountPageError: FC<AccountPageErrorProps> = (props) => { const AccountPageError: FC<AccountPageErrorProps> = (props) => {
const { code } = props; const { code } = props;
@@ -43,8 +47,18 @@ const AccountPageError: FC<AccountPageErrorProps> = (props) => {
/> />
); );
const retry = props.readRetry?.exhausted
? (
<ReadRetryButton
onRetry={props.readRetry.onRetry}
retrying={props.readRetry.retrying}
/>
)
: undefined;
return ( return (
<StateView <StateView
action={retry}
text={t("states.unavailableText")} text={t("states.unavailableText")}
title={t("states.unavailableTitle")} title={t("states.unavailableTitle")}
/> />
@@ -15,7 +15,7 @@ import type { InvestmentResourceMeta } from "@/shared/api";
import { BrokerageEventsPreview } from "@/entities/brokerage-event"; import { BrokerageEventsPreview } from "@/entities/brokerage-event";
import { formatMoney } from "@/shared/lib"; import { formatMoney } from "@/shared/lib";
import { SourceSyncStatus } from "@/shared/ui"; import { ReadRetry, type ReadRetryProps, SourceSyncStatus } from "@/shared/ui";
import { PortfolioStructure } from "@/widgets/portfolio-structure"; import { PortfolioStructure } from "@/widgets/portfolio-structure";
import type { Concentration as ConcentrationModel, Slice } from "../../../model/concentration"; import type { Concentration as ConcentrationModel, Slice } from "../../../model/concentration";
@@ -46,6 +46,7 @@ type AccountPageLoadedProps = {
partial?: boolean; partial?: boolean;
portfolio: Portfolio; portfolio: Portfolio;
positionSections: AccountPagePositionSection[]; positionSections: AccountPagePositionSection[];
readRetry?: ReadRetryProps;
recentEvents: AccountPageRecentEvents; recentEvents: AccountPageRecentEvents;
recentOperations: AccountPageRecentOperations; recentOperations: AccountPageRecentOperations;
slice: Slice; slice: Slice;
@@ -86,6 +87,8 @@ const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
stale={props.source?.freshness === "stale"} stale={props.source?.freshness === "stale"}
/> />
{!!props.readRetry && <ReadRetry {...props.readRetry} />}
{props.partial {props.partial
? tab !== "concentration" && ( ? tab !== "concentration" && (
<Alert role="status">{t("investment.partial")}</Alert> <Alert role="status">{t("investment.partial")}</Alert>
+5 -1
View File
@@ -5,5 +5,9 @@ export {
EntryGroupTotal, EntryGroupTotal,
} from "./EntryGroup/EntryGroup"; } from "./EntryGroup/EntryGroup";
export { PayoutCard } from "./PayoutCard/PayoutCard"; export { PayoutCard } from "./PayoutCard/PayoutCard";
export { ReadRetry, ReadRetryButton } from "./ReadRetry/ReadRetry"; export {
ReadRetry,
ReadRetryButton,
type ReadRetryProps,
} from "./ReadRetry/ReadRetry";
export { SourceSyncStatus } from "./SourceSyncStatus/SourceSyncStatus"; export { SourceSyncStatus } from "./SourceSyncStatus/SourceSyncStatus";