fix: stabilize frontend query cache contracts
This commit is contained in:
@@ -42,14 +42,13 @@ export function useBrokerageOperations(
|
||||
) {
|
||||
const params = brokerageOperationsQueryParams(query);
|
||||
return useQuery({
|
||||
queryKey: ["brokerage-operations", accountId ?? "", params] as const,
|
||||
enabled: Boolean(accountId && accessToken),
|
||||
staleTime: 30_000,
|
||||
retry: false,
|
||||
...apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/brokerage-accounts/{accountId}/operations",
|
||||
{ params: { path: { accountId: accountId ?? "" }, query: params } },
|
||||
),
|
||||
enabled: Boolean(accountId && accessToken),
|
||||
staleTime: 30_000,
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2,17 +2,20 @@ import { useQuery } from "@tanstack/react-query";
|
||||
import { apiQueryClient } from "@/shared/api";
|
||||
import type { paths } from "@/shared/api/generated/schema";
|
||||
|
||||
export const brokerageAccountsQueryKey = ["brokerage-accounts"] as const;
|
||||
const brokerageAccountsQueryOptions = () =>
|
||||
apiQueryClient.queryOptions("get", "/api/v1/brokerage-accounts");
|
||||
|
||||
export const brokerageAccountsQueryKey =
|
||||
brokerageAccountsQueryOptions().queryKey;
|
||||
|
||||
export type BrokerageAccount =
|
||||
paths["/api/v1/brokerage-accounts"]["get"]["responses"][200]["content"]["application/json"][number];
|
||||
|
||||
export function useBrokerageAccounts(accessToken: string | null) {
|
||||
return useQuery({
|
||||
queryKey: brokerageAccountsQueryKey,
|
||||
...brokerageAccountsQueryOptions(),
|
||||
enabled: Boolean(accessToken),
|
||||
staleTime: 60_000,
|
||||
retry: false,
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/brokerage-accounts"),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -12,14 +12,13 @@ export function useBrokerageEvents(
|
||||
accessToken: string | null,
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ["brokerage-events", accountId ?? ""] as const,
|
||||
enabled: Boolean(accountId && accessToken),
|
||||
staleTime: 30_000,
|
||||
retry: false,
|
||||
...apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/brokerage-accounts/{accountId}/events",
|
||||
{ params: { path: { accountId: accountId ?? "" } } },
|
||||
),
|
||||
enabled: Boolean(accountId && accessToken),
|
||||
staleTime: 30_000,
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2,9 +2,6 @@ import { useQuery } from "@tanstack/react-query";
|
||||
import { apiQueryClient } from "@/shared/api";
|
||||
import type { paths } from "@/shared/api/generated/schema";
|
||||
|
||||
const portfolioQueryKey = (accountId: string) =>
|
||||
["portfolio", accountId] as const;
|
||||
|
||||
const portfolioQueryPolicy = {
|
||||
staleTime: 30_000,
|
||||
retry: false,
|
||||
@@ -18,13 +15,12 @@ export function usePortfolio(
|
||||
accessToken: string | null,
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: portfolioQueryKey(accountId ?? ""),
|
||||
enabled: Boolean(accountId && accessToken),
|
||||
...portfolioQueryPolicy,
|
||||
...apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/brokerage-accounts/{accountId}/portfolio",
|
||||
{ params: { path: { accountId: accountId ?? "" } } },
|
||||
),
|
||||
enabled: Boolean(accountId && accessToken),
|
||||
...portfolioQueryPolicy,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import {
|
||||
cleanup,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
} from "@testing-library/react";
|
||||
import { HttpResponse, http } from "msw";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { apiQueryClient } from "@/shared/api";
|
||||
import { server } from "@/test/server";
|
||||
import { TbankConnectionSection } from "./TbankConnectionSection";
|
||||
|
||||
vi.mock("@/features/auth", () => ({
|
||||
useAuth: () => ({ accessToken: "test-token" }),
|
||||
}));
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
const brokerageAccountsQueryKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/brokerage-accounts",
|
||||
).queryKey;
|
||||
|
||||
function renderSection(client: QueryClient) {
|
||||
return render(
|
||||
<MantineProvider>
|
||||
<QueryClientProvider client={client}>
|
||||
<TbankConnectionSection />
|
||||
</QueryClientProvider>
|
||||
</MantineProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
function seededClient() {
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
client.setQueryData(brokerageAccountsQueryKey, [
|
||||
{
|
||||
id: "account-1",
|
||||
name: "Основной счет",
|
||||
type: "BROKERAGE",
|
||||
openedOn: null,
|
||||
},
|
||||
]);
|
||||
return client;
|
||||
}
|
||||
|
||||
describe("TbankConnectionSection", () => {
|
||||
it("updates the generated status cache and invalidates accounts after connecting", async () => {
|
||||
const client = seededClient();
|
||||
renderSection(client);
|
||||
|
||||
await screen.findByText("Не подключено");
|
||||
fireEvent.change(screen.getByLabelText("Token T-Bank"), {
|
||||
target: { value: "replacement-token" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Подключить" }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Заменить token" }),
|
||||
).toBeInTheDocument(),
|
||||
);
|
||||
expect(client.getQueryState(brokerageAccountsQueryKey)?.isInvalidated).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("updates the generated status cache and invalidates accounts after deleting", async () => {
|
||||
server.use(
|
||||
http.get("*/api/v1/tbank-connection", () =>
|
||||
HttpResponse.json({
|
||||
connected: true,
|
||||
connectedAt: "2026-08-14T00:00:00Z",
|
||||
}),
|
||||
),
|
||||
);
|
||||
const client = seededClient();
|
||||
renderSection(client);
|
||||
|
||||
fireEvent.click(
|
||||
await screen.findByRole("button", { name: "Удалить подключение" }),
|
||||
);
|
||||
fireEvent.click(await screen.findByRole("button", { name: /^Удалить$/ }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Подключить" }),
|
||||
).toBeInTheDocument(),
|
||||
);
|
||||
expect(client.getQueryState(brokerageAccountsQueryKey)?.isInvalidated).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -17,7 +17,10 @@ import {
|
||||
TbankConnectionError,
|
||||
TbankConnectionLoading,
|
||||
} from "./TbankConnectionSection.view";
|
||||
import { useTbankConnectionViewModel } from "./TbankConnectionSection.vm";
|
||||
import {
|
||||
tbankConnectionQueryKey,
|
||||
useTbankConnectionViewModel,
|
||||
} from "./TbankConnectionSection.vm";
|
||||
|
||||
type Status =
|
||||
paths["/api/v1/tbank-connection"]["get"]["responses"][200]["content"]["application/json"];
|
||||
@@ -49,18 +52,18 @@ function TbankConnectionSectionLoaded({ status }: { status: Status }) {
|
||||
} = useForm<{ token: string }>();
|
||||
const update = apiQueryClient.useMutation("put", "/api/v1/tbank-connection", {
|
||||
onSuccess: (data) => {
|
||||
queryClient.setQueryData(["tbank-connection"], data);
|
||||
queryClient.setQueryData(tbankConnectionQueryKey, data);
|
||||
queryClient.invalidateQueries({ queryKey: brokerageAccountsQueryKey });
|
||||
reset();
|
||||
},
|
||||
onError: (error) => setRequestError(errorCode(error)),
|
||||
onError: (error) => setRequestError(errorCode(error) ?? "REQUEST_ERROR"),
|
||||
});
|
||||
const remove = apiQueryClient.useMutation(
|
||||
"delete",
|
||||
"/api/v1/tbank-connection",
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.setQueryData<Status>(["tbank-connection"], {
|
||||
queryClient.setQueryData<Status>(tbankConnectionQueryKey, {
|
||||
connected: false,
|
||||
connectedAt: null,
|
||||
});
|
||||
|
||||
@@ -2,12 +2,16 @@ import { useQuery } from "@tanstack/react-query";
|
||||
import { useAuth } from "@/features/auth";
|
||||
import { apiQueryClient } from "@/shared/api";
|
||||
|
||||
const tbankConnectionQueryOptions = () =>
|
||||
apiQueryClient.queryOptions("get", "/api/v1/tbank-connection");
|
||||
|
||||
export const tbankConnectionQueryKey = tbankConnectionQueryOptions().queryKey;
|
||||
|
||||
export function useTbankConnectionViewModel() {
|
||||
const { accessToken } = useAuth();
|
||||
const status = useQuery({
|
||||
queryKey: ["tbank-connection"],
|
||||
...tbankConnectionQueryOptions(),
|
||||
enabled: Boolean(accessToken),
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/tbank-connection"),
|
||||
});
|
||||
if (status.isPending) return { state: "loading" as const };
|
||||
if (status.isError)
|
||||
|
||||
@@ -16,6 +16,7 @@ export function AccountEventsPage() {
|
||||
if (events.isLoading) return <AccountEventsPageLoading />;
|
||||
if (events.isError)
|
||||
return <AccountEventsPageError retry={() => events.refetch()} />;
|
||||
if (!events.data) return <AccountEventsPageLoading />;
|
||||
if (!events.data.events.length) return <AccountEventsPageEmpty />;
|
||||
return <AccountEventsPageLoaded events={events.data.events} />;
|
||||
}
|
||||
|
||||
@@ -68,6 +68,16 @@ export function AccountOperationsPage() {
|
||||
}
|
||||
/>
|
||||
);
|
||||
if (!operations.data)
|
||||
return (
|
||||
<StateView
|
||||
loading
|
||||
title={t("states.loadingTitle")}
|
||||
text={t("states.loadingText")}
|
||||
/>
|
||||
);
|
||||
const { data } = operations;
|
||||
const nextCursor = data.nextCursor;
|
||||
return (
|
||||
<Stack maw={960} gap="lg">
|
||||
<Title order={1}>{t("ledger.title")}</Title>
|
||||
@@ -109,8 +119,8 @@ export function AccountOperationsPage() {
|
||||
))}
|
||||
</Group>
|
||||
</Checkbox.Group>
|
||||
{operations.data.items.length ? (
|
||||
operations.data.items.map((operation) => (
|
||||
{data.items.length ? (
|
||||
data.items.map((operation) => (
|
||||
<OperationRow key={operation.id} operation={operation} />
|
||||
))
|
||||
) : (
|
||||
@@ -119,7 +129,7 @@ export function AccountOperationsPage() {
|
||||
text={t("ledger.emptyText")}
|
||||
/>
|
||||
)}
|
||||
{operations.data.hasNext || cursors.length ? (
|
||||
{data.hasNext || cursors.length ? (
|
||||
<Group justify="space-between">
|
||||
<Button
|
||||
disabled={!cursors.length}
|
||||
@@ -128,11 +138,10 @@ export function AccountOperationsPage() {
|
||||
{t("ledger.previous")}
|
||||
</Button>
|
||||
<Button
|
||||
disabled={!operations.data.hasNext || !operations.data.nextCursor}
|
||||
onClick={() =>
|
||||
operations.data.nextCursor &&
|
||||
setCursors((value) => [...value, operations.data.nextCursor])
|
||||
}
|
||||
disabled={!data.hasNext || !nextCursor}
|
||||
onClick={() => {
|
||||
if (nextCursor) setCursors((value) => [...value, nextCursor]);
|
||||
}}
|
||||
>
|
||||
{t("ledger.next")}
|
||||
</Button>
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useParams } from "react-router";
|
||||
import type { BrokerageAccount } from "@/entities/brokerage-account";
|
||||
import {
|
||||
type BrokerageAccount,
|
||||
brokerageAccountsQueryKey,
|
||||
} from "@/entities/brokerage-account";
|
||||
import { portfolioErrorCode, usePortfolio } from "@/entities/portfolio";
|
||||
import { useAuth } from "@/features/auth";
|
||||
|
||||
const accountsQueryKey = ["brokerage-accounts"] as const;
|
||||
|
||||
export function useAccountPageViewModel() {
|
||||
const { accountId } = useParams();
|
||||
const { accessToken } = useAuth();
|
||||
const portfolio = usePortfolio(accountId, accessToken);
|
||||
const account = useQueryClient()
|
||||
.getQueryData<BrokerageAccount[]>(accountsQueryKey)
|
||||
.getQueryData<BrokerageAccount[]>(brokerageAccountsQueryKey)
|
||||
?.find((item) => item.id === accountId);
|
||||
if (portfolio.isError)
|
||||
return {
|
||||
|
||||
Reference in New Issue
Block a user