refactor: centralize frontend auth query gating

This commit is contained in:
2026-08-25 14:29:41 +03:00
parent fff36f252a
commit 268acdf2e1
24 changed files with 352 additions and 82 deletions
@@ -8,9 +8,6 @@ import { AccountEventsPage } from "./AccountEventsPage";
vi.mock("@/entities/brokerage-event", () => ({
useBrokerageEvents: vi.fn(),
}));
vi.mock("@/features/auth", () => ({
useAuth: () => ({ accessToken: "token" }),
}));
const query = vi.mocked(useBrokerageEvents);
@@ -6,13 +6,11 @@ import {
useBrokerageEvents,
} from "@/entities/brokerage-event";
import { formatMoney } from "@/entities/portfolio";
import { useAuth } from "@/features/auth";
import { StateView } from "@/shared/ui";
export function AccountEventsPage() {
const { accountId } = useParams();
const { accessToken } = useAuth();
const events = useBrokerageEvents(accountId, accessToken);
const events = useBrokerageEvents(accountId);
if (events.isLoading) return <AccountEventsPageLoading />;
if (events.isError)
return <AccountEventsPageError retry={() => events.refetch()} />;
@@ -3,15 +3,12 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { MemoryRouter, Route, Routes } from "react-router";
import { describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { BrokerageOperation } from "@/entities/broker-operation";
import { configureAuthClient } from "@/shared/api";
import { server } from "@/test/server";
import { AccountOperationsPage, OperationRow } from "./AccountOperationsPage";
vi.mock("@/features/auth", () => ({
useAuth: () => ({ accessToken: "token" }),
}));
const operation: BrokerageOperation = {
id: "operation-1",
occurredAt: "2026-08-14T10:00:00Z",
@@ -29,6 +26,14 @@ const operation: BrokerageOperation = {
commission: { currency: "RUB", value: "1" },
};
function configureTestAuth() {
configureAuthClient({
accessToken: () => "token",
refresh: async () => true,
clear: vi.fn(),
});
}
describe("OperationRow", () => {
it("marks cashless operations without rendering operation details", () => {
render(
@@ -49,7 +54,10 @@ describe("OperationRow", () => {
});
describe("AccountOperationsPage", () => {
afterEach(() => configureAuthClient(null));
it("resets cursor pagination when filters change", async () => {
configureTestAuth();
const searches: string[] = [];
server.use(
http.get(
@@ -96,6 +104,7 @@ describe("AccountOperationsPage", () => {
});
it("renders an error state", async () => {
configureTestAuth();
server.use(
http.get("*/api/v1/brokerage-accounts/:accountId/operations", () =>
HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }),
@@ -18,7 +18,6 @@ import {
useBrokerageOperations,
} from "@/entities/broker-operation";
import { formatMoney, formatSnapshotTime } from "@/entities/portfolio";
import { useAuth } from "@/features/auth";
import { StateView } from "@/shared/ui";
function dateStart(value: string) {
@@ -31,14 +30,13 @@ function dateEnd(value: string) {
export function AccountOperationsPage() {
const { accountId } = useParams();
const { accessToken } = useAuth();
const { t } = useTranslation();
const [from, setFrom] = useState("");
const [to, setTo] = useState("");
const [categories, setCategories] = useState<OperationCategory[]>([]);
const [cursors, setCursors] = useState<string[]>([]);
const cursor = cursors.at(-1);
const operations = useBrokerageOperations(accountId, accessToken, {
const operations = useBrokerageOperations(accountId, {
from: dateStart(from),
to: dateEnd(to),
...(categories.length ? { categories } : {}),
+14 -5
View File
@@ -5,6 +5,7 @@ import { HttpResponse, http } from "msw";
import { MemoryRouter, Route, Routes } from "react-router";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { Portfolio } from "@/entities/portfolio";
import { configureAuthClient } from "@/shared/api";
import { server } from "@/test/server";
import {
AccountPage,
@@ -19,10 +20,6 @@ import type {
} from "./AccountPage.vm";
import { toAccountPagePositionSections } from "./AccountPage.vm";
vi.mock("@/features/auth", () => ({
useAuth: () => ({ accessToken: "test-token" }),
}));
function renderPage(ui: React.ReactNode) {
return render(
<QueryClientProvider client={new QueryClient()}>
@@ -33,7 +30,16 @@ function renderPage(ui: React.ReactNode) {
);
}
function configureTestAuth() {
configureAuthClient({
accessToken: () => "test-token",
refresh: async () => true,
clear: vi.fn(),
});
}
function renderAccountRoute(queryClient: QueryClient) {
configureTestAuth();
return render(
<QueryClientProvider client={queryClient}>
<MantineProvider>
@@ -105,7 +111,10 @@ function emptyProps() {
}
describe("AccountPage states", () => {
afterEach(cleanup);
afterEach(() => {
configureAuthClient(null);
cleanup();
});
it("renders loading and empty states", () => {
renderPage(<AccountPageLoading />);
expect(screen.getByRole("status")).toBeInTheDocument();
+15 -5
View File
@@ -4,15 +4,12 @@ import { renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import type { ReactNode } from "react";
import { MemoryRouter, Route, Routes } from "react-router";
import { describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { Portfolio } from "@/entities/portfolio";
import { configureAuthClient } from "@/shared/api";
import { server } from "@/test/server";
import { useAccountPageViewModel } from "./AccountPage.vm";
vi.mock("@/features/auth", () => ({
useAuth: () => ({ accessToken: "test-token" }),
}));
const portfolio: Portfolio = {
lastSuccessfulAt: "2026-08-13T10:00:00Z",
isStale: true,
@@ -55,6 +52,14 @@ const portfolio: Portfolio = {
cashBalances: [{ currency: "USD", value: "1" }],
};
function configureTestAuth() {
configureAuthClient({
accessToken: () => "test-token",
refresh: async () => true,
clear: vi.fn(),
});
}
function wrapper({ children }: { children: ReactNode }) {
return (
<QueryClientProvider client={new QueryClient()}>
@@ -121,7 +126,10 @@ function mockLoadedAccountPage() {
}
describe("useAccountPageViewModel", () => {
afterEach(() => configureAuthClient(null));
it("prepares grouped position sections with derived display data", async () => {
configureTestAuth();
mockLoadedAccountPage();
const { result } = renderHook(() => useAccountPageViewModel(), { wrapper });
@@ -175,6 +183,7 @@ describe("useAccountPageViewModel", () => {
});
it("prepares recent operations and events state for presentation views", async () => {
configureTestAuth();
mockLoadedAccountPage();
const { result } = renderHook(() => useAccountPageViewModel(), { wrapper });
@@ -207,6 +216,7 @@ describe("useAccountPageViewModel", () => {
});
it("keeps recent errors isolated in the ViewModel presentation state", async () => {
configureTestAuth();
server.use(
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
HttpResponse.json(portfolio),
+3 -5
View File
@@ -18,7 +18,6 @@ import {
portfolioErrorCode,
usePortfolio,
} from "@/entities/portfolio";
import { useAuth } from "@/features/auth";
type PositionSectionKind = "stocks" | "bonds" | "other";
type AccountPageReturnTone = "positive" | "negative";
@@ -86,12 +85,11 @@ export type AccountPageViewModel =
export function useAccountPageViewModel(): AccountPageViewModel {
const { accountId } = useParams();
const { accessToken } = useAuth();
const portfolio = usePortfolio(accountId, accessToken);
const operations = useBrokerageOperations(accountId, accessToken, {
const portfolio = usePortfolio(accountId);
const operations = useBrokerageOperations(accountId, {
limit: 5,
});
const events = useBrokerageEvents(accountId, accessToken);
const events = useBrokerageEvents(accountId);
const account = useQueryClient()
.getQueryData<BrokerageAccount[]>(brokerageAccountsQueryKey)
?.find((item) => item.id === accountId);
+14 -5
View File
@@ -5,13 +5,10 @@ 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 { configureAuthClient } from "@/shared/api";
import { server } from "@/test/server";
import { AccountsPage } from "./AccountsPage";
vi.mock("@/features/auth", () => ({
useAuth: () => ({ accessToken: "test-token" }),
}));
const account = {
id: "account-1",
name: "Основной",
@@ -19,7 +16,16 @@ const account = {
openedOn: "2026-01-01",
} as const;
function configureTestAuth() {
configureAuthClient({
accessToken: () => "test-token",
refresh: async () => true,
clear: vi.fn(),
});
}
function renderPage(queryClient: QueryClient) {
configureTestAuth();
return render(
<QueryClientProvider client={queryClient}>
<MantineProvider>
@@ -32,7 +38,10 @@ function renderPage(queryClient: QueryClient) {
}
describe("AccountsPage", () => {
afterEach(cleanup);
afterEach(() => {
configureAuthClient(null);
cleanup();
});
it("keeps the cached account list visible during a background refresh", async () => {
let requestCount = 0;
+1 -3
View File
@@ -1,9 +1,7 @@
import { errorCode, useBrokerageAccounts } from "@/entities/brokerage-account";
import { useAuth } from "@/features/auth";
export function useAccountsPageViewModel() {
const { accessToken } = useAuth();
const accounts = useBrokerageAccounts(accessToken);
const accounts = useBrokerageAccounts();
if (!accounts.data) {
if (accounts.isFetching) return { state: "loading" as const };
if (accounts.isError)