feat: add quiet reading with rare confirmations
Part of the quiet-user-feedback change; docs and specs land in their own repositories.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resource } from "@/test/resource";
|
||||
|
||||
@@ -13,9 +13,7 @@ describe("instrument source and transport presentation", () => {
|
||||
const state = section({
|
||||
data,
|
||||
isError: false,
|
||||
isFetching: false,
|
||||
meta: resource(data, { availability }).meta,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
expect(state.loading).toBe(availability === "missing");
|
||||
@@ -23,39 +21,40 @@ describe("instrument source and transport presentation", () => {
|
||||
expect(state.hasData).toBe(availability !== "missing");
|
||||
},
|
||||
);
|
||||
it("preserves a full fresh source and timestamp when force fails, while offering scoped retry", () => {
|
||||
const retry = vi.fn();
|
||||
const refetch = vi.fn();
|
||||
it("preserves empty successful data instead of treating it as missing", () => {
|
||||
const state = section({
|
||||
data: [],
|
||||
isError: false,
|
||||
meta: resource([]).meta,
|
||||
});
|
||||
|
||||
expect(state).toMatchObject({
|
||||
error: false,
|
||||
hasData: true,
|
||||
loading: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves a full source when force fails", () => {
|
||||
const meta = resource([], {
|
||||
sync: { errorCode: "TBANK_UNAVAILABLE", id: "work", state: "failed" },
|
||||
}).meta;
|
||||
|
||||
const state = section(
|
||||
{ data: [], isError: false, isFetching: false, meta, refetch },
|
||||
retry,
|
||||
);
|
||||
const state = section({ data: [], isError: false, meta });
|
||||
|
||||
expect(state).toMatchObject({
|
||||
error: true,
|
||||
hasData: true,
|
||||
lastSuccessfulAt: meta.lastSuccessfulAt,
|
||||
loading: false,
|
||||
refreshing: false,
|
||||
});
|
||||
state.retry();
|
||||
expect(retry).toHaveBeenCalledOnce();
|
||||
expect(refetch).not.toHaveBeenCalled();
|
||||
});
|
||||
it("shows source failure without a false loading or empty result", () => {
|
||||
const state = section({
|
||||
data: undefined,
|
||||
isError: false,
|
||||
isFetching: false,
|
||||
meta: resource(null, {
|
||||
sync: { errorCode: "TBANK_UNAVAILABLE", id: "work", state: "failed" },
|
||||
}).meta,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
expect(state).toMatchObject({
|
||||
|
||||
@@ -3,43 +3,27 @@ import type { InvestmentResourceMeta } from "@/shared/api";
|
||||
type SectionState = {
|
||||
error: boolean;
|
||||
hasData: boolean;
|
||||
lastSuccessfulAt?: null | string;
|
||||
loading: boolean;
|
||||
partial?: boolean;
|
||||
refreshing: boolean;
|
||||
retry: () => void;
|
||||
sourceError?: boolean;
|
||||
stale?: boolean;
|
||||
};
|
||||
|
||||
function section(
|
||||
query: {
|
||||
data: unknown;
|
||||
isError: boolean;
|
||||
isFetching: boolean;
|
||||
meta?: InvestmentResourceMeta;
|
||||
refetch: () => unknown;
|
||||
},
|
||||
retry?: () => unknown,
|
||||
): SectionState {
|
||||
function hasSectionData(data: unknown) {
|
||||
return data !== undefined;
|
||||
}
|
||||
|
||||
function section(query: {
|
||||
data: unknown;
|
||||
isError: boolean;
|
||||
meta?: InvestmentResourceMeta;
|
||||
}): SectionState {
|
||||
const isError = query.isError || query.meta?.sync.state === "failed";
|
||||
const hasData = hasSectionData(query.data);
|
||||
|
||||
return {
|
||||
error: isError,
|
||||
hasData: Boolean(query.data),
|
||||
lastSuccessfulAt: query.meta?.lastSuccessfulAt,
|
||||
loading: !query.data && !isError,
|
||||
hasData,
|
||||
loading: !hasData && !isError,
|
||||
partial: query.meta?.availability === "partial",
|
||||
refreshing:
|
||||
Boolean(query.data)
|
||||
&& (query.isFetching
|
||||
|| query.meta?.sync.state === "running"
|
||||
),
|
||||
retry: () => {
|
||||
void (retry ?? query.refetch)();
|
||||
},
|
||||
sourceError: query.meta?.sync.state === "failed",
|
||||
stale: query.meta?.freshness === "stale",
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@ const InstrumentEvents: FC<InstrumentEventsProps> = (props) => {
|
||||
|
||||
<Group justify="space-between" mt="md">
|
||||
<Button
|
||||
disabled={!vm.hasPrevious || vm.operationsState.refreshing}
|
||||
disabled={!vm.hasPrevious}
|
||||
onClick={vm.onPrevious}
|
||||
variant="default"
|
||||
>
|
||||
@@ -94,7 +94,7 @@ const InstrumentEvents: FC<InstrumentEventsProps> = (props) => {
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
disabled={!vm.operations.hasNext || vm.operationsState.refreshing}
|
||||
disabled={!vm.operations.hasNext}
|
||||
onClick={vm.onNext}
|
||||
variant="default"
|
||||
>
|
||||
|
||||
@@ -1,21 +1,17 @@
|
||||
import type { FC, PropsWithChildren, ReactNode } from "react";
|
||||
|
||||
import { Avatar, Button, Group, Paper, Text, Title } from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Avatar, Group, Paper, Text, Title } from "@mantine/core";
|
||||
|
||||
import classes from "./InstrumentHeader.module.css";
|
||||
|
||||
type InstrumentHeaderProps = PropsWithChildren<{
|
||||
logoSrc: null | string;
|
||||
name: string;
|
||||
onRefresh: () => void;
|
||||
refreshing: boolean;
|
||||
subtitle: ReactNode;
|
||||
}>;
|
||||
|
||||
const InstrumentHeader: FC<InstrumentHeaderProps> = (props) => {
|
||||
const { children, logoSrc, name, onRefresh, refreshing, subtitle } = props;
|
||||
const { t } = useTranslation();
|
||||
const { children, logoSrc, name, subtitle } = props;
|
||||
|
||||
return (
|
||||
<Paper className={classes.header} component="header" withBorder>
|
||||
@@ -31,10 +27,6 @@ const InstrumentHeader: FC<InstrumentHeaderProps> = (props) => {
|
||||
<Text c="dimmed" size="sm">{subtitle}</Text>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button disabled={refreshing} onClick={onRefresh} variant="subtle">
|
||||
{t("investment.refresh")}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
{children}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { Anchor, Button, Skeleton, Stack, Text, Title } from "@mantine/core";
|
||||
import { Anchor, Skeleton, Stack, Text, Title } from "@mantine/core";
|
||||
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
@@ -11,11 +11,10 @@ type InstrumentPageStateProps = {
|
||||
code?: string;
|
||||
kind: "bond" | "stock";
|
||||
loading: boolean;
|
||||
retry: () => void;
|
||||
};
|
||||
|
||||
const InstrumentPageState: FC<InstrumentPageStateProps> = (props) => {
|
||||
const { code, kind, loading, retry } = props;
|
||||
const { code, kind, loading } = props;
|
||||
const { t } = useTranslation();
|
||||
if (loading) return (
|
||||
<LoadingSkeleton label={t(`${kind}.loading`)}>
|
||||
@@ -55,10 +54,6 @@ const InstrumentPageState: FC<InstrumentPageStateProps> = (props) => {
|
||||
<Anchor component={Link} to="/settings">
|
||||
{t("accounts.openSettings")}
|
||||
</Anchor>
|
||||
|
||||
<Button onClick={retry} variant="default">
|
||||
{t("accounts.retry")}
|
||||
</Button>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -2,7 +2,6 @@ import type { FC, PropsWithChildren, ReactNode } from "react";
|
||||
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Group,
|
||||
Paper,
|
||||
Skeleton,
|
||||
@@ -13,8 +12,6 @@ import {
|
||||
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { SourceSyncStatus } from "@/shared/ui";
|
||||
|
||||
import type { SectionState } from "../model/section";
|
||||
|
||||
import classes from "./InstrumentDetails.module.css";
|
||||
@@ -33,10 +30,6 @@ type InstrumentSectionProps = PropsWithChildren<{
|
||||
const InstrumentSection: FC<InstrumentSectionProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const readError = t(
|
||||
props.state.hasData ? "accounts.refreshError" : "stock.sectionError",
|
||||
);
|
||||
|
||||
const sectionClassName = props.embedded
|
||||
? classes.embeddedSection
|
||||
: classes.section;
|
||||
@@ -80,35 +73,11 @@ const InstrumentSection: FC<InstrumentSectionProps> = (props) => {
|
||||
{props.controls}
|
||||
</Group>
|
||||
|
||||
<SourceSyncStatus
|
||||
lastSuccessfulAt={props.state.lastSuccessfulAt}
|
||||
stale={props.state.stale}
|
||||
/>
|
||||
|
||||
{!!props.state.partial && <Text role="status">{t("investment.partial")}</Text>}
|
||||
|
||||
{!!props.state.refreshing && (
|
||||
<Text c="dimmed" role="status" size="xs">
|
||||
{t("accounts.refreshing")}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
{!!props.state.error && (
|
||||
{!!(props.state.error && !props.state.hasData) && (
|
||||
<Alert aria-live="polite" color="orange" mb="sm" role="status">
|
||||
<Group justify="space-between">
|
||||
<Text size="sm">
|
||||
{props.state.sourceError ? t("investment.syncFailed") : readError}
|
||||
</Text>
|
||||
|
||||
<Button
|
||||
disabled={props.state.refreshing}
|
||||
onClick={props.state.retry}
|
||||
size="xs"
|
||||
variant="default"
|
||||
>
|
||||
{t("accounts.retry")}
|
||||
</Button>
|
||||
</Group>
|
||||
<Text size="sm">{t("stock.sectionError")}</Text>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { ComponentProps } from "react";
|
||||
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
@@ -16,8 +16,6 @@ it("keeps cached results on failure, hides them during a new search and distingu
|
||||
partial: false,
|
||||
query: "SBER",
|
||||
ready: true,
|
||||
refreshing: false,
|
||||
retry: vi.fn(),
|
||||
};
|
||||
|
||||
const cached = [<a href="/stocks/SBER" key="SBER">Сбербанк</a>];
|
||||
@@ -44,8 +42,7 @@ it("keeps cached results on failure, hides them during a new search and distingu
|
||||
expect(
|
||||
screen.getByRole("link", { name: "Открыть настройки T-Bank" }),
|
||||
).toHaveAttribute("href", "/settings");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
|
||||
expect(vm.retry).toHaveBeenCalledOnce();
|
||||
expect(screen.queryByRole("button", { name: "Повторить" })).not.toBeInTheDocument();
|
||||
|
||||
rerender(view({ loading: true, ready: false }));
|
||||
expect(screen.queryByRole("link", { name: "Сбербанк" })).not.toBeInTheDocument();
|
||||
|
||||
@@ -3,7 +3,6 @@ import type { ChangeEvent, FC, ReactNode } from "react";
|
||||
import {
|
||||
Alert,
|
||||
Anchor,
|
||||
Button,
|
||||
Skeleton,
|
||||
Stack,
|
||||
Text,
|
||||
@@ -28,8 +27,6 @@ type InstrumentSearchProps = {
|
||||
partial: boolean;
|
||||
query: string;
|
||||
ready: boolean;
|
||||
refreshing: boolean;
|
||||
retry: () => void;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -77,14 +74,6 @@ const InstrumentSearch: FC<InstrumentSearchProps> = (props) => {
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
disabled={vm.refreshing || !vm.canSearch}
|
||||
onClick={vm.retry}
|
||||
w="fit-content"
|
||||
>
|
||||
{t("investment.refresh")}
|
||||
</Button>
|
||||
|
||||
{!!vm.partial && <Alert role="status">{t("investment.partial")}</Alert>}
|
||||
|
||||
<TextInput
|
||||
@@ -114,9 +103,6 @@ const InstrumentSearch: FC<InstrumentSearchProps> = (props) => {
|
||||
{t("accounts.openSettings")}
|
||||
</Anchor>
|
||||
|
||||
<Button onClick={vm.retry} variant="default">
|
||||
{t("accounts.retry")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@@ -78,7 +78,7 @@ describe("page-owned screen synchronization", () => {
|
||||
expect(posted).toEqual(["old", "new"]);
|
||||
});
|
||||
it.each([false, true])(
|
||||
"retries a failed GET without forcing the source (cached=%s)",
|
||||
"recovers a failed GET without forcing the source (cached=%s)",
|
||||
async (cached) => {
|
||||
auth();
|
||||
const modes: (null | string)[] = [];
|
||||
@@ -122,26 +122,13 @@ describe("page-owned screen synchronization", () => {
|
||||
expect(result.current.accounts.isSuccess).toBe(true),
|
||||
);
|
||||
isUnavailable = true;
|
||||
await act(() => result.current.accounts.refetch());
|
||||
void result.current.accounts.refetch();
|
||||
}
|
||||
|
||||
await waitFor(() => expect(result.current.accounts.isError).toBe(true));
|
||||
isUnavailable = false;
|
||||
await act(() => result.current.sync.retry());
|
||||
await waitFor(() => expect(result.current.accounts.isSuccess).toBe(true));
|
||||
expect(result.current.accounts.meta?.dataRevision).toBe(
|
||||
cached ? "3" : "2",
|
||||
);
|
||||
expect(modes).toEqual(
|
||||
cached
|
||||
? [
|
||||
null,
|
||||
null,
|
||||
"observe",
|
||||
]
|
||||
: [null, "observe"],
|
||||
);
|
||||
expect(posts).toBe(0);
|
||||
expect(modes.every(mode => mode === null)).toBe(true);
|
||||
expect(result.current.disabled.data).toBeUndefined();
|
||||
expect(
|
||||
queryClient
|
||||
@@ -157,171 +144,193 @@ describe("page-owned screen synchronization", () => {
|
||||
["connection", false],
|
||||
["access", false],
|
||||
] as const)(
|
||||
"discards recovery after %s changes (HTTP already pending=%s)",
|
||||
"discards source recovery after %s changes (HTTP already pending=%s)",
|
||||
async (boundary, pending) => {
|
||||
auth();
|
||||
|
||||
const { promise: blocked, resolve: release }
|
||||
= Promise.withResolvers<void>();
|
||||
|
||||
let isRecovering = false;
|
||||
let recoveryRequests = 0;
|
||||
let isChanged = false;
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", async ({ request }) => {
|
||||
if (boundary === "connection" && isChanged && !request.signal.aborted)
|
||||
return HttpResponse.json(resource([], { dataRevision: "current" }));
|
||||
if (!new URL(request.url).searchParams.has("sync"))
|
||||
return isChanged
|
||||
? HttpResponse.json(resource([], { dataRevision: "current" }))
|
||||
: HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 });
|
||||
isRecovering = true;
|
||||
await blocked;
|
||||
|
||||
return HttpResponse.json(resource([], { dataRevision: "old" }));
|
||||
}),
|
||||
);
|
||||
const { queryClient, wrapper } = createQueryWrapper();
|
||||
const published: unknown[] = [];
|
||||
try {
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", async () => {
|
||||
if (isChanged)
|
||||
return HttpResponse.json(
|
||||
resource([], { dataRevision: "current" }),
|
||||
);
|
||||
|
||||
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
|
||||
if (event.type === "updated" && event.action.type === "success")
|
||||
published.push(event.query.state.data);
|
||||
});
|
||||
if (recoveryRequests > 0) {
|
||||
recoveryRequests += 1;
|
||||
await blocked;
|
||||
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
return HttpResponse.json(resource([], { dataRevision: "old" }));
|
||||
}
|
||||
|
||||
return {
|
||||
accounts,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts]),
|
||||
};
|
||||
},
|
||||
{ wrapper },
|
||||
);
|
||||
recoveryRequests += 1;
|
||||
|
||||
await waitFor(() => expect(result.current.accounts.isError).toBe(true));
|
||||
let recovery!: Promise<void>;
|
||||
act(() => {
|
||||
recovery = result.current.sync.retry();
|
||||
});
|
||||
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
|
||||
if (pending) await waitFor(() => expect(isRecovering).toBe(true));
|
||||
await act(async () => {
|
||||
isChanged = true;
|
||||
|
||||
switch (boundary) {
|
||||
case "access": {
|
||||
invalidateResourceAccess(queryClient, "brokerage", {
|
||||
code: "FORBIDDEN",
|
||||
});
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case "logout": {
|
||||
configureAuthClient();
|
||||
queryClient.clear();
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case "session": {
|
||||
auth();
|
||||
queryClient.clear();
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case "connection": {
|
||||
commitTbankConnectionBoundary(queryClient, {
|
||||
connected: true,
|
||||
connectedAt: "2026-09-27T00:00:00Z",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
release();
|
||||
await recovery;
|
||||
});
|
||||
if (boundary === "connection")
|
||||
await waitFor(() =>
|
||||
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
|
||||
expect(result.current.accounts.meta?.dataRevision).toBe("current"),
|
||||
return HttpResponse.json(
|
||||
resource(null, {
|
||||
sync: {
|
||||
errorCode: "TBANK_UNAVAILABLE",
|
||||
id: "failed",
|
||||
state: "failed",
|
||||
},
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
expect(published).not.toContainEqual(
|
||||
expect.objectContaining({
|
||||
meta: expect.objectContaining({ dataRevision: "old" }) as unknown,
|
||||
}),
|
||||
);
|
||||
unsubscribe();
|
||||
const { queryClient, wrapper } = createQueryWrapper();
|
||||
const published: unknown[] = [];
|
||||
|
||||
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
|
||||
if (event.type === "updated" && event.action.type === "success")
|
||||
published.push(event.query.state.data);
|
||||
});
|
||||
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
|
||||
return {
|
||||
accounts,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts]),
|
||||
};
|
||||
},
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.accounts.meta?.sync.state).toBe("failed"),
|
||||
);
|
||||
vi.useFakeTimers();
|
||||
if (pending)
|
||||
await act(() => vi.advanceTimersByTimeAsync(5000));
|
||||
expect(recoveryRequests).toBeGreaterThanOrEqual(1);
|
||||
|
||||
await act(async () => {
|
||||
isChanged = true;
|
||||
|
||||
switch (boundary) {
|
||||
case "access": {
|
||||
invalidateResourceAccess(queryClient, "brokerage", {
|
||||
code: "FORBIDDEN",
|
||||
});
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case "logout": {
|
||||
configureAuthClient();
|
||||
queryClient.clear();
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case "session": {
|
||||
auth();
|
||||
queryClient.clear();
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case "connection": {
|
||||
commitTbankConnectionBoundary(queryClient, {
|
||||
connected: true,
|
||||
connectedAt: "2026-09-27T00:00:00Z",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
release();
|
||||
if (!pending) await vi.advanceTimersByTimeAsync(5000);
|
||||
});
|
||||
vi.useRealTimers();
|
||||
if (boundary === "connection" && !pending)
|
||||
await waitFor(() =>
|
||||
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
|
||||
expect(result.current.accounts.meta?.dataRevision).toBe("current"),
|
||||
);
|
||||
expect(published).not.toContainEqual(
|
||||
expect.objectContaining({
|
||||
meta: expect.objectContaining({ dataRevision: "old" }) as unknown,
|
||||
}),
|
||||
);
|
||||
unsubscribe();
|
||||
}
|
||||
finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
},
|
||||
);
|
||||
it.each([false, true])(
|
||||
"recovers an initial GET failure after forced sync without metadata (status retry=%s)",
|
||||
"recovers an initial GET failure without forced sync (status retry=%s)",
|
||||
async (retryStatus) => {
|
||||
auth();
|
||||
const modes: (null | string)[] = [];
|
||||
let posts = 0;
|
||||
let polls = 0;
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
||||
modes.push(new URL(request.url).searchParams.get("sync"));
|
||||
|
||||
return modes.length === 1
|
||||
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
|
||||
: HttpResponse.json(resource([]));
|
||||
}),
|
||||
http.post("*/api/v1/tbank-sync", () =>
|
||||
HttpResponse.json({ id: "recover" }, { status: 202 }),
|
||||
),
|
||||
http.get("*/api/v1/tbank-sync/:id", () => {
|
||||
polls += 1;
|
||||
try {
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
||||
modes.push(new URL(request.url).searchParams.get("sync"));
|
||||
|
||||
return retryStatus && polls === 1
|
||||
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
|
||||
: HttpResponse.json({
|
||||
id: "recover",
|
||||
state: "succeeded",
|
||||
});
|
||||
}),
|
||||
);
|
||||
const { queryClient, wrapper } = createQueryWrapper();
|
||||
return modes.length === 1
|
||||
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
|
||||
: HttpResponse.json(resource([]));
|
||||
}),
|
||||
http.post("*/api/v1/tbank-sync", () => {
|
||||
posts += 1;
|
||||
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
const disabled = useStockQuote("");
|
||||
return HttpResponse.json({ id: "recover" }, { status: 202 });
|
||||
}),
|
||||
http.get("*/api/v1/tbank-sync/:id", () => {
|
||||
polls += 1;
|
||||
|
||||
return {
|
||||
accounts,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts, disabled]),
|
||||
};
|
||||
},
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
await waitFor(() => expect(result.current.accounts.isError).toBe(true));
|
||||
expect(result.current.accounts.meta).toBeUndefined();
|
||||
await act(() => result.current.sync.refresh());
|
||||
|
||||
if (retryStatus) {
|
||||
await waitFor(() =>
|
||||
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
|
||||
expect(result.current.sync.transportError).toBe(true),
|
||||
return retryStatus && polls === 1
|
||||
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
|
||||
: HttpResponse.json({
|
||||
id: "recover",
|
||||
state: "succeeded",
|
||||
});
|
||||
}),
|
||||
);
|
||||
await act(() => result.current.sync.retry());
|
||||
const { queryClient, wrapper } = createQueryWrapper();
|
||||
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
const disabled = useStockQuote("");
|
||||
|
||||
return {
|
||||
accounts,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts, disabled]),
|
||||
};
|
||||
},
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
await waitFor(
|
||||
() => expect(result.current.accounts.isSuccess).toBe(true),
|
||||
{ timeout: 3000 },
|
||||
);
|
||||
expect(result.current.accounts.data).toEqual([]);
|
||||
|
||||
expect(modes).toEqual([null, null]);
|
||||
expect(posts).toBe(0);
|
||||
expect(polls).toBe(0);
|
||||
expect(
|
||||
queryClient
|
||||
.getQueryCache()
|
||||
.findAll({ queryKey: ["get", "/api/v1/brokerage-accounts"] }),
|
||||
).toHaveLength(1);
|
||||
}
|
||||
finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
|
||||
await waitFor(() => expect(result.current.accounts.isSuccess).toBe(true));
|
||||
expect(result.current.accounts.data).toEqual([]);
|
||||
|
||||
expect(modes[0]).toBeNull();
|
||||
expect(modes.slice(1).every(mode => mode === "observe")).toBe(true);
|
||||
expect(
|
||||
queryClient
|
||||
.getQueryCache()
|
||||
.findAll({ queryKey: ["get", "/api/v1/brokerage-accounts"] }),
|
||||
).toHaveLength(1);
|
||||
},
|
||||
);
|
||||
it("posts only its scope once and observes completion without importing again", async () => {
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { type QueryKey, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
focusManager,
|
||||
onlineManager,
|
||||
type QueryKey,
|
||||
useQueryClient,
|
||||
} from "@tanstack/react-query";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
import {
|
||||
@@ -21,9 +26,39 @@ type ScreenResource = {
|
||||
meta?: InvestmentResourceMeta;
|
||||
observe: () => Promise<unknown>;
|
||||
queryKey: QueryKey;
|
||||
refetch: () => Promise<unknown>;
|
||||
};
|
||||
|
||||
const STATUS_INTERVAL_MS = 1000;
|
||||
const FIRST_SOURCE_RECOVERY_DELAY_MS = 5000;
|
||||
const SECOND_SOURCE_RECOVERY_DELAY_MS = 15_000;
|
||||
|
||||
function requiresSourceRecovery(meta?: InvestmentResourceMeta): boolean {
|
||||
if (!meta || meta.unavailableReason) return false;
|
||||
|
||||
return ["cancelled", "failed"].includes(meta.sync.state)
|
||||
|| meta.availability === "missing"
|
||||
|| meta.freshness === "stale"
|
||||
|| (meta.dependencies ?? []).some(dependency =>
|
||||
requiresSourceRecovery(dependency),
|
||||
);
|
||||
}
|
||||
|
||||
function sourceRecoveryDelay(attempt: number): number | undefined {
|
||||
switch (attempt) {
|
||||
case 0: {
|
||||
return FIRST_SOURCE_RECOVERY_DELAY_MS;
|
||||
}
|
||||
|
||||
case 1: {
|
||||
return SECOND_SOURCE_RECOVERY_DELAY_MS;
|
||||
}
|
||||
|
||||
default: {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
|
||||
const mutation = apiQueryClient.useMutation("post", "/api/v1/tbank-sync", {
|
||||
@@ -35,6 +70,9 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
|
||||
const scopeKey = JSON.stringify(scope);
|
||||
|
||||
const requestInFlightRef = useRef<null | string>(null);
|
||||
const lifecycleRecoveryRef = useRef(new Set<string>());
|
||||
const sourceRecoveryRef = useRef(new Map<string, number>());
|
||||
const sourceTimersRef = useRef(new Set<ReturnType<typeof setTimeout>>());
|
||||
|
||||
const isCurrentMutation
|
||||
= JSON.stringify(mutation.variables?.body) === scopeKey;
|
||||
@@ -110,6 +148,73 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
|
||||
void resource.observe().catch(() => {});
|
||||
}, [client, statuses, resources, scopeKey]);
|
||||
|
||||
useEffect(() => {
|
||||
const timers = sourceTimersRef.current;
|
||||
const attempts = sourceRecoveryRef.current;
|
||||
|
||||
return () => {
|
||||
for (const timer of timers) clearTimeout(timer);
|
||||
timers.clear();
|
||||
attempts.clear();
|
||||
};
|
||||
}, [scopeKey]);
|
||||
|
||||
useEffect(() => {
|
||||
for (const resource of resources) {
|
||||
if (
|
||||
!requiresSourceRecovery(resource.meta)
|
||||
|| resource.isFetching
|
||||
) continue;
|
||||
|
||||
const key = JSON.stringify([scopeKey, resource.queryKey]);
|
||||
const attempt = sourceRecoveryRef.current.get(key) ?? 0;
|
||||
const delay = sourceRecoveryDelay(attempt);
|
||||
if (delay === undefined) continue;
|
||||
|
||||
sourceRecoveryRef.current.set(key, attempt + 1);
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
sourceTimersRef.current.delete(timer);
|
||||
void resource.refetch().catch(() => {});
|
||||
}, delay);
|
||||
|
||||
sourceTimersRef.current.add(timer);
|
||||
}
|
||||
}, [resources, scopeKey]);
|
||||
|
||||
useEffect(() => {
|
||||
const recover = () => {
|
||||
for (const resource of resources) {
|
||||
if (
|
||||
!requiresSourceRecovery(resource.meta)
|
||||
|| resource.isFetching
|
||||
) continue;
|
||||
|
||||
const key = JSON.stringify([scopeKey, resource.queryKey]);
|
||||
if (lifecycleRecoveryRef.current.has(key)) continue;
|
||||
|
||||
sourceRecoveryRef.current.delete(key);
|
||||
lifecycleRecoveryRef.current.add(key);
|
||||
void resource.refetch()
|
||||
.catch(() => {})
|
||||
.finally(() => lifecycleRecoveryRef.current.delete(key));
|
||||
}
|
||||
};
|
||||
|
||||
const unsubscribeFocus = focusManager.subscribe((focused) => {
|
||||
if (focused) recover();
|
||||
});
|
||||
|
||||
const unsubscribeOnline = onlineManager.subscribe((online) => {
|
||||
if (online) recover();
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubscribeFocus();
|
||||
unsubscribeOnline();
|
||||
};
|
||||
}, [resources, scopeKey]);
|
||||
|
||||
const isRefreshing
|
||||
= (isCurrentMutation && mutation.isPending)
|
||||
|| statuses.some(
|
||||
|
||||
+11
-11
@@ -127,9 +127,11 @@ describe("TbankConnectionSection", () => {
|
||||
const token = screen.getByLabelText("Token T-Bank");
|
||||
fireEvent.change(token, { target: { value: "replacement-draft" } });
|
||||
finishRefetch?.();
|
||||
expect(
|
||||
await screen.findByText(/Не удалось обновить статус подключения/),
|
||||
).toBeVisible();
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.queryByText(/Не удалось обновить статус подключения/),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByLabelText("Token T-Bank")).toBe(token);
|
||||
expect(token).toHaveValue("replacement-draft");
|
||||
expect(screen.getByText("Подключено с 14.08.2026")).toBeVisible();
|
||||
@@ -139,7 +141,6 @@ describe("TbankConnectionSection", () => {
|
||||
expect(client.getQueryData(portfolioQueryKey)).toEqual({
|
||||
source: "previous-connection",
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
|
||||
await waitFor(() => expect(reads).toBe(2));
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
@@ -164,13 +165,12 @@ describe("TbankConnectionSection", () => {
|
||||
}),
|
||||
);
|
||||
renderSection(createTestQueryClient());
|
||||
expect(
|
||||
await screen.findByText(/Не удалось загрузить статус подключения/),
|
||||
).toBeVisible();
|
||||
expect(screen.queryByLabelText("Token T-Bank")).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
|
||||
expect(await screen.findByLabelText("Token T-Bank")).toBeVisible();
|
||||
expect(reads).toBe(2);
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.queryByText(/Не удалось загрузить статус подключения/),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
expect(reads).toBe(1);
|
||||
});
|
||||
it("commits connection status and resets the complete brokerage query subtree after connecting", async () => {
|
||||
const client = seededClient();
|
||||
|
||||
+7
@@ -1,3 +1,4 @@
|
||||
import { notifications } from "@mantine/notifications";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
@@ -32,6 +33,12 @@ function useTbankConnectionSectionLoadedVm(status: TbankConnectionStatus) {
|
||||
onSuccess: (data) => {
|
||||
commitTbankConnectionBoundary(queryClient, data);
|
||||
reset();
|
||||
|
||||
if (status.connected && data.connected)
|
||||
notifications.show({
|
||||
id: "tbank-token-replaced-" + crypto.randomUUID(),
|
||||
message: t("tbank.tokenReplaced"),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user