fix: preserve cached data during refresh failures
This commit is contained in:
+1
-1
@@ -4,6 +4,6 @@
|
|||||||
|
|
||||||
Во время submit все действия формы блокируются. Ошибки Zod отображаются у поля; ошибки сети сохраняют введённые значения и показываются отдельным `Alert`.
|
Во время submit все действия формы блокируются. Ошибки Zod отображаются у поля; ошибки сети сохраняют введённые значения и показываются отдельным `Alert`.
|
||||||
|
|
||||||
Запросные экраны выбирают состояние в порядке loading, error, empty, loaded. Состояния имеют отдельные компоненты, если повторяются или содержат самостоятельную разметку.
|
Запросные экраны без успешных данных выбирают состояние в порядке loading, error, empty, loaded. Если query уже содержит данные, они остаются видимыми при фоновом refetch и его ошибке: рядом показываются неблокирующий progress и локальное предупреждение с retry. Такое состояние называется Client Cached Snapshot; оно не заменяет доменное server-side stale/fallback состояние.
|
||||||
|
|
||||||
Для finance-экранов container вызывает query hooks, VM выбирает состояние и передает только presentation props в Loading/Error/Empty/Loaded view. Known API errors, retry и stale snapshot остаются local views, а непойманные route errors обрабатывает общий route-keyed ErrorBoundary.
|
Для finance-экранов container вызывает query hooks, VM выбирает состояние и передает только presentation props в Loading/Error/Empty/Loaded view. Known API errors, retry и stale snapshot остаются local views, а непойманные route errors обрабатывает общий route-keyed ErrorBoundary.
|
||||||
|
|||||||
@@ -34,4 +34,58 @@ describe("AuthProvider", () => {
|
|||||||
|
|
||||||
expect(authorization).toBe("Bearer restored-token");
|
expect(authorization).toBe("Bearer restored-token");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("settles unauthenticated and clears cached data when cold-start refresh has a transport error", async () => {
|
||||||
|
server.use(http.post("*/api/v1/auth/refresh", () => HttpResponse.error()));
|
||||||
|
const queryClient = new QueryClient();
|
||||||
|
queryClient.setQueryData(["cached-query"], { value: "stale" });
|
||||||
|
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<AuthProvider>{children}</AuthProvider>
|
||||||
|
</QueryClientProvider>
|
||||||
|
);
|
||||||
|
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||||
|
|
||||||
|
await waitFor(() => expect(result.current.ready).toBe(true));
|
||||||
|
|
||||||
|
expect(result.current.user).toBeNull();
|
||||||
|
expect(result.current.accessToken).toBeNull();
|
||||||
|
expect(queryClient.getQueryData(["cached-query"])).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the original protected 401 when serialized refresh has a transport error", async () => {
|
||||||
|
let refreshCalls = 0;
|
||||||
|
server.use(
|
||||||
|
http.post("*/api/v1/auth/refresh", () => {
|
||||||
|
refreshCalls += 1;
|
||||||
|
return refreshCalls === 1
|
||||||
|
? HttpResponse.json({
|
||||||
|
accessToken: "restored-token",
|
||||||
|
user: { id: "user-1", email: "user@example.com" },
|
||||||
|
})
|
||||||
|
: HttpResponse.error();
|
||||||
|
}),
|
||||||
|
http.get("*/api/v1/brokerage-accounts", () =>
|
||||||
|
HttpResponse.json({ code: "UNAUTHORIZED" }, { status: 401 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const queryClient = new QueryClient();
|
||||||
|
queryClient.setQueryData(["cached-query"], { value: "stale" });
|
||||||
|
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<AuthProvider>{children}</AuthProvider>
|
||||||
|
</QueryClientProvider>
|
||||||
|
);
|
||||||
|
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(result.current.accessToken).toBe("restored-token"),
|
||||||
|
);
|
||||||
|
const response = await apiClient.GET("/api/v1/brokerage-accounts");
|
||||||
|
|
||||||
|
expect(response.response.status).toBe(401);
|
||||||
|
await waitFor(() => expect(result.current.user).toBeNull());
|
||||||
|
expect(result.current.accessToken).toBeNull();
|
||||||
|
expect(queryClient.getQueryData(["cached-query"])).toBeUndefined();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,12 @@
|
|||||||
import { useQueryClient } from "@tanstack/react-query";
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
import { createContext, useContext, useEffect, useRef, useState } from "react";
|
import {
|
||||||
|
createContext,
|
||||||
|
useCallback,
|
||||||
|
useContext,
|
||||||
|
useEffect,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
} from "react";
|
||||||
import { apiClient, configureAuthClient } from "@/shared/api";
|
import { apiClient, configureAuthClient } from "@/shared/api";
|
||||||
import type { paths } from "@/shared/api/generated/schema";
|
import type { paths } from "@/shared/api/generated/schema";
|
||||||
|
|
||||||
@@ -41,40 +48,52 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|||||||
const [ready, setReady] = useState(false);
|
const [ready, setReady] = useState(false);
|
||||||
|
|
||||||
const refreshPromise = useRef<Promise<boolean> | null>(null);
|
const refreshPromise = useRef<Promise<boolean> | null>(null);
|
||||||
|
const applyAuthentication = useCallback((authentication: Authentication) => {
|
||||||
|
setUser(authentication.user);
|
||||||
|
setAccessToken(authentication.accessToken);
|
||||||
|
accessTokenRef.current = authentication.accessToken;
|
||||||
|
}, []);
|
||||||
|
const clearSession = useCallback(() => {
|
||||||
|
setUser(null);
|
||||||
|
setAccessToken(null);
|
||||||
|
accessTokenRef.current = null;
|
||||||
|
queryClient.clear();
|
||||||
|
}, [queryClient]);
|
||||||
|
|
||||||
async function refresh(): Promise<boolean> {
|
const refresh = useCallback(async (): Promise<boolean> => {
|
||||||
if (refreshPromise.current) return refreshPromise.current;
|
if (refreshPromise.current) return refreshPromise.current;
|
||||||
refreshPromise.current = (async () => {
|
refreshPromise.current = (async () => {
|
||||||
const run = async () => {
|
const run = async () => {
|
||||||
const { data } = await apiClient.POST("/api/v1/auth/refresh");
|
try {
|
||||||
if (!data) return false;
|
const { data } = await apiClient.POST("/api/v1/auth/refresh");
|
||||||
const authentication = data as Authentication;
|
if (!data) {
|
||||||
setUser(authentication.user);
|
clearSession();
|
||||||
setAccessToken(authentication.accessToken);
|
return false;
|
||||||
accessTokenRef.current = authentication.accessToken;
|
}
|
||||||
return true;
|
applyAuthentication(data as Authentication);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
clearSession();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
return "locks" in navigator
|
try {
|
||||||
? navigator.locks.request("wealth-ledger-refresh", run)
|
return "locks" in navigator
|
||||||
: run();
|
? navigator.locks.request("wealth-ledger-refresh", run)
|
||||||
|
: run();
|
||||||
|
} catch {
|
||||||
|
clearSession();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
})().finally(() => {
|
})().finally(() => {
|
||||||
refreshPromise.current = null;
|
refreshPromise.current = null;
|
||||||
});
|
});
|
||||||
return refreshPromise.current;
|
return refreshPromise.current;
|
||||||
}
|
}, [applyAuthentication, clearSession]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void apiClient
|
void refresh().finally(() => setReady(true));
|
||||||
.POST("/api/v1/auth/refresh")
|
}, [refresh]);
|
||||||
.then(({ data }) => {
|
|
||||||
if (!data) return;
|
|
||||||
const authentication = data as Authentication;
|
|
||||||
setUser(authentication.user);
|
|
||||||
setAccessToken(authentication.accessToken);
|
|
||||||
accessTokenRef.current = authentication.accessToken;
|
|
||||||
})
|
|
||||||
.finally(() => setReady(true));
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
async function authenticate(
|
async function authenticate(
|
||||||
path: "/api/v1/auth/login" | "/api/v1/auth/register",
|
path: "/api/v1/auth/login" | "/api/v1/auth/register",
|
||||||
@@ -82,19 +101,14 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|||||||
password: string,
|
password: string,
|
||||||
) {
|
) {
|
||||||
const authentication = await request(path, email, password);
|
const authentication = await request(path, email, password);
|
||||||
setUser(authentication.user);
|
applyAuthentication(authentication);
|
||||||
setAccessToken(authentication.accessToken);
|
|
||||||
accessTokenRef.current = authentication.accessToken;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function logout() {
|
async function logout() {
|
||||||
try {
|
try {
|
||||||
await apiClient.POST("/api/v1/auth/logout");
|
await apiClient.POST("/api/v1/auth/logout");
|
||||||
} finally {
|
} finally {
|
||||||
setUser(null);
|
clearSession();
|
||||||
setAccessToken(null);
|
|
||||||
accessTokenRef.current = null;
|
|
||||||
queryClient.clear();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,12 +116,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|||||||
configureAuthClient({
|
configureAuthClient({
|
||||||
accessToken: () => accessTokenRef.current,
|
accessToken: () => accessTokenRef.current,
|
||||||
refresh,
|
refresh,
|
||||||
clear: () => {
|
clear: clearSession,
|
||||||
setUser(null);
|
|
||||||
setAccessToken(null);
|
|
||||||
accessTokenRef.current = null;
|
|
||||||
queryClient.clear();
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
return () => configureAuthClient(null);
|
return () => configureAuthClient(null);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,17 +2,22 @@ import { MantineProvider } from "@mantine/core";
|
|||||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
import { cleanup, render, screen, waitFor } from "@testing-library/react";
|
import { cleanup, render, screen, waitFor } from "@testing-library/react";
|
||||||
import { HttpResponse, http } from "msw";
|
import { HttpResponse, http } from "msw";
|
||||||
import { MemoryRouter } from "react-router";
|
import { MemoryRouter, Route, Routes } from "react-router";
|
||||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
import type { Portfolio } from "@/entities/portfolio";
|
import type { Portfolio } from "@/entities/portfolio";
|
||||||
import { server } from "@/test/server";
|
import { server } from "@/test/server";
|
||||||
import {
|
import {
|
||||||
|
AccountPage,
|
||||||
AccountPageEmpty,
|
AccountPageEmpty,
|
||||||
AccountPageError,
|
AccountPageError,
|
||||||
AccountPageLoaded,
|
AccountPageLoaded,
|
||||||
AccountPageLoading,
|
AccountPageLoading,
|
||||||
} from "./AccountPage";
|
} from "./AccountPage";
|
||||||
|
|
||||||
|
vi.mock("@/features/auth", () => ({
|
||||||
|
useAuth: () => ({ accessToken: "test-token" }),
|
||||||
|
}));
|
||||||
|
|
||||||
function renderPage(ui: React.ReactNode) {
|
function renderPage(ui: React.ReactNode) {
|
||||||
return render(
|
return render(
|
||||||
<QueryClientProvider client={new QueryClient()}>
|
<QueryClientProvider client={new QueryClient()}>
|
||||||
@@ -23,6 +28,20 @@ function renderPage(ui: React.ReactNode) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function renderAccountRoute(queryClient: QueryClient) {
|
||||||
|
return render(
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<MantineProvider>
|
||||||
|
<MemoryRouter initialEntries={["/accounts/account-1"]}>
|
||||||
|
<Routes>
|
||||||
|
<Route path="/accounts/:accountId" element={<AccountPage />} />
|
||||||
|
</Routes>
|
||||||
|
</MemoryRouter>
|
||||||
|
</MantineProvider>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const portfolio: Portfolio = {
|
const portfolio: Portfolio = {
|
||||||
lastSuccessfulAt: "2026-08-13T10:00:00Z",
|
lastSuccessfulAt: "2026-08-13T10:00:00Z",
|
||||||
isStale: true,
|
isStale: true,
|
||||||
@@ -169,4 +188,68 @@ describe("AccountPage states", () => {
|
|||||||
);
|
);
|
||||||
expect(screen.getByText("Вторая")).toBeInTheDocument();
|
expect(screen.getByText("Вторая")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("keeps the cached portfolio visible with distinct server and refresh warnings", async () => {
|
||||||
|
let requestCount = 0;
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () => {
|
||||||
|
requestCount += 1;
|
||||||
|
if (requestCount === 1) return HttpResponse.json(portfolio);
|
||||||
|
return HttpResponse.json(
|
||||||
|
{ code: "TBANK_UNAVAILABLE" },
|
||||||
|
{ status: 503 },
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const queryClient = new QueryClient();
|
||||||
|
renderAccountRoute(queryClient);
|
||||||
|
|
||||||
|
await screen.findByText("Вторая");
|
||||||
|
void queryClient.invalidateQueries({
|
||||||
|
queryKey: ["get", "/api/v1/brokerage-accounts/{accountId}/portfolio"],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(
|
||||||
|
await screen.findByText(
|
||||||
|
"Не удалось обновить портфель. Показан последний полученный снимок.",
|
||||||
|
),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
expect(
|
||||||
|
screen.getByText(
|
||||||
|
"T-Bank временно недоступен. Показан последний успешный снимок.",
|
||||||
|
),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Вторая")).toBeInTheDocument();
|
||||||
|
screen.getByRole("button", { name: "Повторить" }).click();
|
||||||
|
await waitFor(() => expect(requestCount).toBe(3));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the cached portfolio visible during a background refresh", async () => {
|
||||||
|
let requestCount = 0;
|
||||||
|
let resolveRefresh: ((response: Response) => void) | undefined;
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () => {
|
||||||
|
requestCount += 1;
|
||||||
|
if (requestCount === 1) return HttpResponse.json(portfolio);
|
||||||
|
return new Promise<Response>((resolve) => {
|
||||||
|
resolveRefresh = resolve;
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const queryClient = new QueryClient();
|
||||||
|
renderAccountRoute(queryClient);
|
||||||
|
|
||||||
|
await screen.findByText("Вторая");
|
||||||
|
void queryClient.invalidateQueries({
|
||||||
|
queryKey: ["get", "/api/v1/brokerage-accounts/{accountId}/portfolio"],
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitFor(() => expect(requestCount).toBe(2));
|
||||||
|
expect(screen.getByText("Вторая")).toBeInTheDocument();
|
||||||
|
expect(
|
||||||
|
screen.getByRole("status", { name: "Обновляем портфель" }),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
|
||||||
|
resolveRefresh?.(HttpResponse.json(portfolio));
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -16,6 +16,9 @@ export function AccountPage() {
|
|||||||
account={viewModel.account}
|
account={viewModel.account}
|
||||||
accountId={viewModel.accountId}
|
accountId={viewModel.accountId}
|
||||||
accessToken={viewModel.accessToken}
|
accessToken={viewModel.accessToken}
|
||||||
|
refreshing={viewModel.refreshing}
|
||||||
|
refreshError={viewModel.refreshError}
|
||||||
|
retry={viewModel.retry}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
return (
|
return (
|
||||||
@@ -24,6 +27,9 @@ export function AccountPage() {
|
|||||||
accountId={viewModel.accountId}
|
accountId={viewModel.accountId}
|
||||||
accessToken={viewModel.accessToken}
|
accessToken={viewModel.accessToken}
|
||||||
portfolio={viewModel.portfolio}
|
portfolio={viewModel.portfolio}
|
||||||
|
refreshing={viewModel.refreshing}
|
||||||
|
refreshError={viewModel.refreshError}
|
||||||
|
retry={viewModel.retry}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import {
|
|||||||
Button,
|
Button,
|
||||||
Card,
|
Card,
|
||||||
Group,
|
Group,
|
||||||
|
Loader,
|
||||||
Paper,
|
Paper,
|
||||||
SimpleGrid,
|
SimpleGrid,
|
||||||
Stack,
|
Stack,
|
||||||
@@ -93,15 +94,26 @@ export function AccountPageEmpty({
|
|||||||
account,
|
account,
|
||||||
accountId,
|
accountId,
|
||||||
accessToken = null,
|
accessToken = null,
|
||||||
|
refreshing = false,
|
||||||
|
refreshError = false,
|
||||||
|
retry,
|
||||||
}: {
|
}: {
|
||||||
account?: BrokerageAccount;
|
account?: BrokerageAccount;
|
||||||
accountId?: string;
|
accountId?: string;
|
||||||
accessToken?: string | null;
|
accessToken?: string | null;
|
||||||
|
refreshing?: boolean;
|
||||||
|
refreshError?: boolean;
|
||||||
|
retry?: () => void;
|
||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
<Stack>
|
<Stack>
|
||||||
<AccountHeading account={account} />
|
<AccountHeading account={account} />
|
||||||
|
<PortfolioRefreshState
|
||||||
|
refreshing={refreshing}
|
||||||
|
refreshError={refreshError}
|
||||||
|
retry={retry}
|
||||||
|
/>
|
||||||
<StateView
|
<StateView
|
||||||
title={t("portfolio.emptyTitle")}
|
title={t("portfolio.emptyTitle")}
|
||||||
text={t("portfolio.emptyText")}
|
text={t("portfolio.emptyText")}
|
||||||
@@ -116,11 +128,17 @@ export function AccountPageLoaded({
|
|||||||
accountId,
|
accountId,
|
||||||
accessToken,
|
accessToken,
|
||||||
portfolio,
|
portfolio,
|
||||||
|
refreshing = false,
|
||||||
|
refreshError = false,
|
||||||
|
retry,
|
||||||
}: {
|
}: {
|
||||||
account?: BrokerageAccount;
|
account?: BrokerageAccount;
|
||||||
accountId?: string;
|
accountId?: string;
|
||||||
accessToken?: string | null;
|
accessToken?: string | null;
|
||||||
portfolio: Portfolio;
|
portfolio: Portfolio;
|
||||||
|
refreshing?: boolean;
|
||||||
|
refreshError?: boolean;
|
||||||
|
retry?: () => void;
|
||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const stocks = portfolio.positions.filter((p) => p.type === "STOCK");
|
const stocks = portfolio.positions.filter((p) => p.type === "STOCK");
|
||||||
@@ -140,6 +158,11 @@ export function AccountPageLoaded({
|
|||||||
return (
|
return (
|
||||||
<Stack className={classes.page} gap="lg">
|
<Stack className={classes.page} gap="lg">
|
||||||
<AccountHeading account={account} />
|
<AccountHeading account={account} />
|
||||||
|
<PortfolioRefreshState
|
||||||
|
refreshing={refreshing}
|
||||||
|
refreshError={refreshError}
|
||||||
|
retry={retry}
|
||||||
|
/>
|
||||||
{portfolio.isStale ? (
|
{portfolio.isStale ? (
|
||||||
<Alert color="blue">{t("portfolio.staleWarning")}</Alert>
|
<Alert color="blue">{t("portfolio.staleWarning")}</Alert>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -197,6 +220,40 @@ export function AccountPageLoaded({
|
|||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
function PortfolioRefreshState({
|
||||||
|
refreshing,
|
||||||
|
refreshError,
|
||||||
|
retry,
|
||||||
|
}: {
|
||||||
|
refreshing: boolean;
|
||||||
|
refreshError: boolean;
|
||||||
|
retry?: () => void;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
if (!refreshing && !refreshError) return null;
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{refreshing ? (
|
||||||
|
<Group gap="xs" role="status" aria-label={t("portfolio.refreshing")}>
|
||||||
|
<Loader size="sm" />
|
||||||
|
<Text c="dimmed" size="sm">
|
||||||
|
{t("portfolio.refreshing")}
|
||||||
|
</Text>
|
||||||
|
</Group>
|
||||||
|
) : null}
|
||||||
|
{refreshError ? (
|
||||||
|
<Alert color="orange">
|
||||||
|
<Stack gap="sm">
|
||||||
|
<Text>{t("portfolio.refreshError")}</Text>
|
||||||
|
<Button onClick={retry} variant="light">
|
||||||
|
{t("accounts.retry")}
|
||||||
|
</Button>
|
||||||
|
</Stack>
|
||||||
|
</Alert>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
function RecentOperations({
|
function RecentOperations({
|
||||||
accountId,
|
accountId,
|
||||||
accessToken,
|
accessToken,
|
||||||
|
|||||||
@@ -14,21 +14,34 @@ export function useAccountPageViewModel() {
|
|||||||
const account = useQueryClient()
|
const account = useQueryClient()
|
||||||
.getQueryData<BrokerageAccount[]>(brokerageAccountsQueryKey)
|
.getQueryData<BrokerageAccount[]>(brokerageAccountsQueryKey)
|
||||||
?.find((item) => item.id === accountId);
|
?.find((item) => item.id === accountId);
|
||||||
if (portfolio.isError)
|
if (!portfolio.data) {
|
||||||
return {
|
if (portfolio.isError)
|
||||||
state: "error" as const,
|
return {
|
||||||
code: portfolioErrorCode(portfolio.error),
|
state: "error" as const,
|
||||||
retry: () => portfolio.refetch(),
|
code: portfolioErrorCode(portfolio.error),
|
||||||
};
|
retry: () => portfolio.refetch(),
|
||||||
if (portfolio.isFetching || !portfolio.data)
|
};
|
||||||
return { state: "loading" as const };
|
return { state: "loading" as const };
|
||||||
|
}
|
||||||
|
const refresh = {
|
||||||
|
refreshing: portfolio.isFetching,
|
||||||
|
refreshError: portfolio.isError,
|
||||||
|
retry: () => portfolio.refetch(),
|
||||||
|
};
|
||||||
if (!portfolio.data.positions.length && !portfolio.data.cashBalances.length)
|
if (!portfolio.data.positions.length && !portfolio.data.cashBalances.length)
|
||||||
return { state: "empty" as const, account, accountId, accessToken };
|
return {
|
||||||
|
state: "empty" as const,
|
||||||
|
account,
|
||||||
|
accountId,
|
||||||
|
accessToken,
|
||||||
|
...refresh,
|
||||||
|
};
|
||||||
return {
|
return {
|
||||||
state: "loaded" as const,
|
state: "loaded" as const,
|
||||||
account,
|
account,
|
||||||
accountId,
|
accountId,
|
||||||
accessToken,
|
accessToken,
|
||||||
portfolio: portfolio.data,
|
portfolio: portfolio.data,
|
||||||
|
...refresh,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
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 { MemoryRouter } from "react-router";
|
||||||
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { brokerageAccountsQueryKey } from "@/entities/brokerage-account";
|
||||||
|
import { server } from "@/test/server";
|
||||||
|
import { AccountsPage } from "./AccountsPage";
|
||||||
|
|
||||||
|
vi.mock("@/features/auth", () => ({
|
||||||
|
useAuth: () => ({ accessToken: "test-token" }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const account = {
|
||||||
|
id: "account-1",
|
||||||
|
name: "Основной",
|
||||||
|
type: "BROKERAGE",
|
||||||
|
openedOn: "2026-01-01",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
function renderPage(queryClient: QueryClient) {
|
||||||
|
return render(
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<MantineProvider>
|
||||||
|
<MemoryRouter>
|
||||||
|
<AccountsPage />
|
||||||
|
</MemoryRouter>
|
||||||
|
</MantineProvider>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("AccountsPage", () => {
|
||||||
|
afterEach(cleanup);
|
||||||
|
|
||||||
|
it("keeps the cached account list visible during a background refresh", async () => {
|
||||||
|
let requestCount = 0;
|
||||||
|
let resolveRefresh: ((response: Response) => void) | undefined;
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/brokerage-accounts", () => {
|
||||||
|
requestCount += 1;
|
||||||
|
if (requestCount === 1) return HttpResponse.json([account]);
|
||||||
|
return new Promise<Response>((resolve) => {
|
||||||
|
resolveRefresh = resolve;
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const queryClient = new QueryClient();
|
||||||
|
renderPage(queryClient);
|
||||||
|
|
||||||
|
await screen.findByText(account.name);
|
||||||
|
void queryClient.invalidateQueries({
|
||||||
|
queryKey: brokerageAccountsQueryKey,
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitFor(() => expect(requestCount).toBe(2));
|
||||||
|
expect(screen.getByText(account.name)).toBeInTheDocument();
|
||||||
|
expect(
|
||||||
|
screen.getByRole("status", { name: "Обновляем данные" }),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
|
||||||
|
resolveRefresh?.(HttpResponse.json([account]));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the cached account list and offers retry after a refresh error", async () => {
|
||||||
|
let requestCount = 0;
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/brokerage-accounts", () => {
|
||||||
|
requestCount += 1;
|
||||||
|
if (requestCount === 1) return HttpResponse.json([account]);
|
||||||
|
if (requestCount === 2)
|
||||||
|
return HttpResponse.json(
|
||||||
|
{ code: "TBANK_UNAVAILABLE" },
|
||||||
|
{ status: 503 },
|
||||||
|
);
|
||||||
|
return HttpResponse.json([account]);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const queryClient = new QueryClient();
|
||||||
|
renderPage(queryClient);
|
||||||
|
|
||||||
|
await screen.findByText(account.name);
|
||||||
|
void queryClient.invalidateQueries({
|
||||||
|
queryKey: brokerageAccountsQueryKey,
|
||||||
|
});
|
||||||
|
|
||||||
|
const warning = await screen.findByText(
|
||||||
|
"Не удалось обновить данные. Показаны последние полученные.",
|
||||||
|
);
|
||||||
|
expect(warning).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(account.name)).toBeInTheDocument();
|
||||||
|
|
||||||
|
screen.getByRole("button", { name: "Повторить" }).click();
|
||||||
|
await waitFor(() => expect(requestCount).toBe(3));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps a cached empty account list visible after a refresh error", async () => {
|
||||||
|
let requestCount = 0;
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/brokerage-accounts", () => {
|
||||||
|
requestCount += 1;
|
||||||
|
if (requestCount === 1) return HttpResponse.json([]);
|
||||||
|
return HttpResponse.json(
|
||||||
|
{ code: "TBANK_UNAVAILABLE" },
|
||||||
|
{ status: 503 },
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const queryClient = new QueryClient();
|
||||||
|
renderPage(queryClient);
|
||||||
|
|
||||||
|
await screen.findByText("Нет инвестиционных счетов");
|
||||||
|
void queryClient.invalidateQueries({
|
||||||
|
queryKey: brokerageAccountsQueryKey,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(
|
||||||
|
await screen.findByText(
|
||||||
|
"Не удалось обновить данные. Показаны последние полученные.",
|
||||||
|
),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Нет инвестиционных счетов")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -10,8 +10,22 @@ export function AccountsPage() {
|
|||||||
const viewModel = useAccountsPageViewModel();
|
const viewModel = useAccountsPageViewModel();
|
||||||
if (viewModel.state === "loading") return <AccountsPageLoading />;
|
if (viewModel.state === "loading") return <AccountsPageLoading />;
|
||||||
if (viewModel.state === "error") return <AccountsPageError {...viewModel} />;
|
if (viewModel.state === "error") return <AccountsPageError {...viewModel} />;
|
||||||
if (viewModel.state === "empty") return <AccountsPageEmpty />;
|
if (viewModel.state === "empty")
|
||||||
return <AccountsPageLoaded accounts={viewModel.accounts} />;
|
return (
|
||||||
|
<AccountsPageEmpty
|
||||||
|
refreshing={viewModel.refreshing}
|
||||||
|
refreshError={viewModel.refreshError}
|
||||||
|
retry={viewModel.retry}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<AccountsPageLoaded
|
||||||
|
accounts={viewModel.accounts}
|
||||||
|
refreshing={viewModel.refreshing}
|
||||||
|
refreshError={viewModel.refreshError}
|
||||||
|
retry={viewModel.retry}
|
||||||
|
/>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
|
|||||||
@@ -1,4 +1,12 @@
|
|||||||
import { Button, Stack, Title } from "@mantine/core";
|
import {
|
||||||
|
Alert,
|
||||||
|
Button,
|
||||||
|
Group,
|
||||||
|
Loader,
|
||||||
|
Stack,
|
||||||
|
Text,
|
||||||
|
Title,
|
||||||
|
} from "@mantine/core";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
import type { BrokerageAccount } from "@/entities/brokerage-account";
|
import type { BrokerageAccount } from "@/entities/brokerage-account";
|
||||||
@@ -71,26 +79,87 @@ export function AccountsPageError({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function AccountsPageEmpty() {
|
export function AccountsPageEmpty({
|
||||||
|
refreshing = false,
|
||||||
|
refreshError = false,
|
||||||
|
retry,
|
||||||
|
}: {
|
||||||
|
refreshing?: boolean;
|
||||||
|
refreshError?: boolean;
|
||||||
|
retry?: () => void;
|
||||||
|
}) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
<StateView
|
<Stack>
|
||||||
title={t("accounts.emptyTitle")}
|
<AccountsRefreshState
|
||||||
text={t("accounts.emptyText")}
|
refreshing={refreshing}
|
||||||
/>
|
refreshError={refreshError}
|
||||||
|
retry={retry}
|
||||||
|
/>
|
||||||
|
<StateView
|
||||||
|
title={t("accounts.emptyTitle")}
|
||||||
|
text={t("accounts.emptyText")}
|
||||||
|
/>
|
||||||
|
</Stack>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function AccountsPageLoaded({
|
export function AccountsPageLoaded({
|
||||||
accounts,
|
accounts,
|
||||||
|
refreshing = false,
|
||||||
|
refreshError = false,
|
||||||
|
retry,
|
||||||
}: {
|
}: {
|
||||||
accounts: BrokerageAccount[];
|
accounts: BrokerageAccount[];
|
||||||
|
refreshing?: boolean;
|
||||||
|
refreshError?: boolean;
|
||||||
|
retry?: () => void;
|
||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
<Stack>
|
<Stack>
|
||||||
<Title order={1}>{t("accounts.title")}</Title>
|
<Title order={1}>{t("accounts.title")}</Title>
|
||||||
|
<AccountsRefreshState
|
||||||
|
refreshing={refreshing}
|
||||||
|
refreshError={refreshError}
|
||||||
|
retry={retry}
|
||||||
|
/>
|
||||||
<BrokerageAccountList accounts={accounts} />
|
<BrokerageAccountList accounts={accounts} />
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function AccountsRefreshState({
|
||||||
|
refreshing,
|
||||||
|
refreshError,
|
||||||
|
retry,
|
||||||
|
}: {
|
||||||
|
refreshing: boolean;
|
||||||
|
refreshError: boolean;
|
||||||
|
retry?: () => void;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
if (!refreshing && !refreshError) return null;
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{refreshing ? (
|
||||||
|
<Group gap="xs" role="status" aria-label={t("accounts.refreshing")}>
|
||||||
|
<Loader size="sm" />
|
||||||
|
<Text c="dimmed" size="sm">
|
||||||
|
{t("accounts.refreshing")}
|
||||||
|
</Text>
|
||||||
|
</Group>
|
||||||
|
) : null}
|
||||||
|
{refreshError ? (
|
||||||
|
<Alert color="orange">
|
||||||
|
<Stack gap="sm">
|
||||||
|
<Text>{t("accounts.refreshError")}</Text>
|
||||||
|
<Button onClick={retry} variant="light">
|
||||||
|
{t("accounts.retry")}
|
||||||
|
</Button>
|
||||||
|
</Stack>
|
||||||
|
</Alert>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,13 +4,27 @@ import { useAuth } from "@/features/auth";
|
|||||||
export function useAccountsPageViewModel() {
|
export function useAccountsPageViewModel() {
|
||||||
const { accessToken } = useAuth();
|
const { accessToken } = useAuth();
|
||||||
const accounts = useBrokerageAccounts(accessToken);
|
const accounts = useBrokerageAccounts(accessToken);
|
||||||
if (accounts.isFetching) return { state: "loading" as const };
|
if (!accounts.data) {
|
||||||
if (accounts.isError)
|
if (accounts.isFetching) return { state: "loading" as const };
|
||||||
|
if (accounts.isError)
|
||||||
|
return {
|
||||||
|
state: "error" as const,
|
||||||
|
code: errorCode(accounts.error),
|
||||||
|
retry: () => accounts.refetch(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!accounts.data?.length)
|
||||||
return {
|
return {
|
||||||
state: "error" as const,
|
state: "empty" as const,
|
||||||
code: errorCode(accounts.error),
|
refreshing: accounts.isFetching,
|
||||||
|
refreshError: accounts.isError,
|
||||||
retry: () => accounts.refetch(),
|
retry: () => accounts.refetch(),
|
||||||
};
|
};
|
||||||
if (!accounts.data?.length) return { state: "empty" as const };
|
return {
|
||||||
return { state: "loaded" as const, accounts: accounts.data };
|
state: "loaded" as const,
|
||||||
|
accounts: accounts.data,
|
||||||
|
refreshing: accounts.isFetching,
|
||||||
|
refreshError: accounts.isError,
|
||||||
|
retry: () => accounts.refetch(),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,6 +41,9 @@ export const ru = {
|
|||||||
unavailableTitle: "T-Bank временно недоступен",
|
unavailableTitle: "T-Bank временно недоступен",
|
||||||
unavailableText:
|
unavailableText:
|
||||||
"Попробуйте загрузить счета еще раз или проверьте подключение.",
|
"Попробуйте загрузить счета еще раз или проверьте подключение.",
|
||||||
|
refreshing: "Обновляем данные",
|
||||||
|
refreshError:
|
||||||
|
"Не удалось обновить данные. Показаны последние полученные.",
|
||||||
retry: "Повторить",
|
retry: "Повторить",
|
||||||
types: {
|
types: {
|
||||||
BROKERAGE: "Брокерский счет",
|
BROKERAGE: "Брокерский счет",
|
||||||
@@ -61,6 +64,9 @@ export const ru = {
|
|||||||
back: "К счетам",
|
back: "К счетам",
|
||||||
staleWarning:
|
staleWarning:
|
||||||
"T-Bank временно недоступен. Показан последний успешный снимок.",
|
"T-Bank временно недоступен. Показан последний успешный снимок.",
|
||||||
|
refreshing: "Обновляем портфель",
|
||||||
|
refreshError:
|
||||||
|
"Не удалось обновить портфель. Показан последний полученный снимок.",
|
||||||
updatedAt: "Данные получены {{date}}",
|
updatedAt: "Данные получены {{date}}",
|
||||||
positions: "Позиции",
|
positions: "Позиции",
|
||||||
stocks: "Акции",
|
stocks: "Акции",
|
||||||
|
|||||||
Reference in New Issue
Block a user