chore: finish frontend ESLint migration #18

Enable every plugin recommended preset and replace Biome with ESLint formatting.

Preserve API contracts and JSX whitespace; verify source, tests, builds and tooling.
This commit is contained in:
2026-09-28 16:36:40 +03:00
committed by ksv741
parent 57630102e4
commit 72d7835227
253 changed files with 10059 additions and 8864 deletions
@@ -1,12 +1,13 @@
import type { QueryClient } from "@tanstack/react-query";
import {
apiQueryClient,
invalidateApiRequests,
type paths,
} from "@/shared/api";
type TbankConnectionStatus =
paths["/api/v1/tbank-connection"]["get"]["responses"][200]["content"]["application/json"];
type TbankConnectionStatus
= paths["/api/v1/tbank-connection"]["get"]["responses"][200]["content"]["application/json"];
const brokerageAccountsPath = "/api/v1/brokerage-accounts";
@@ -20,26 +21,26 @@ function commitTbankConnectionBoundary(
status: TbankConnectionStatus,
) {
invalidateApiRequests(
(path) =>
path.startsWith("/api/v1/brokerage-accounts") ||
path.startsWith("/api/v1/stocks") ||
path.startsWith("/api/v1/bonds") ||
path.startsWith("/api/v1/tbank-sync"),
path =>
path.startsWith("/api/v1/brokerage-accounts")
|| path.startsWith("/api/v1/stocks")
|| path.startsWith("/api/v1/bonds")
|| path.startsWith("/api/v1/tbank-sync"),
);
queryClient.setQueryData(tbankConnectionQueryKey, status);
void queryClient.resetQueries({
predicate: ({ queryKey }) => {
const [method, path] = queryKey;
return (
method === "get" &&
typeof path === "string" &&
(path.startsWith("/api/v1/tbank-sync") ||
path === "/api/v1/bonds" ||
path.startsWith("/api/v1/bonds/") ||
path === "/api/v1/stocks" ||
path.startsWith("/api/v1/stocks/") ||
path === brokerageAccountsPath ||
path.startsWith(`${brokerageAccountsPath}/`))
method === "get"
&& typeof path === "string"
&& (path.startsWith("/api/v1/tbank-sync")
|| path === "/api/v1/bonds"
|| path.startsWith("/api/v1/bonds/")
|| path === "/api/v1/stocks"
|| path.startsWith("/api/v1/stocks/")
|| path === brokerageAccountsPath
|| path.startsWith(`${brokerageAccountsPath}/`))
);
},
});
@@ -47,6 +48,6 @@ function commitTbankConnectionBoundary(
export {
commitTbankConnectionBoundary,
type TbankConnectionStatus,
tbankConnectionQueryOptions,
type TbankConnectionStatus,
};
@@ -1,41 +1,41 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { http, HttpResponse } from "msw";
import { describe, expect, it, vi } from "vitest";
import { useBrokerageAccounts } from "@/entities/brokerage-account";
import { useStockQuote } from "@/entities/stock";
import { configureAuthClient, invalidateResourceAccess } from "@/shared/api";
import { createQueryWrapper } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server";
import { useScreenSync } from "../index";
import { commitTbankConnectionBoundary } from "./connection-boundary";
function auth() {
configureAuthClient({
accessToken: () => "synthetic",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
}
describe("page-owned screen synchronization", () => {
it("ignores a late sync acceptance after the account scope changes", async () => {
auth();
let release!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
const { promise: blocked, resolve: release } = Promise.withResolvers<void>();
const posted: string[] = [];
const polled: string[] = [];
server.use(
http.post("*/api/v1/tbank-sync", async ({ request }) => {
const scope = (await request.json()) as {
screen: "account";
accountId: string;
screen: "account";
};
posted.push(scope.accountId);
await blocked;
return HttpResponse.json(
{ id: scope.accountId, scope, now: "2026-09-25T00:00:00Z" },
{ id: scope.accountId, now: "2026-09-25T00:00:00Z", scope },
{ status: 202 },
);
}),
@@ -43,13 +43,13 @@ describe("page-owned screen synchronization", () => {
polled.push(String(params.id));
return HttpResponse.json({
id: params.id,
state: "succeeded",
resources: [],
state: "succeeded",
});
}),
);
const { result, rerender } = renderHook(
({ accountId }) => useScreenSync({ screen: "account", accountId }, []),
const { rerender, result } = renderHook(
({ accountId }) => useScreenSync({ accountId, screen: "account" }, []),
{
initialProps: { accountId: "old" },
wrapper: createQueryWrapper().wrapper,
@@ -73,13 +73,13 @@ describe("page-owned screen synchronization", () => {
"retries a failed GET without forcing the source (cached=%s)",
async (cached) => {
auth();
const modes: (string | null)[] = [];
let unavailable = !cached;
const modes: (null | string)[] = [];
let isUnavailable = !cached;
let posts = 0;
server.use(
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
modes.push(new URL(request.url).searchParams.get("sync"));
return unavailable
return isUnavailable
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
: HttpResponse.json(
resource([], { stateVersion: String(modes.length) }),
@@ -90,7 +90,7 @@ describe("page-owned screen synchronization", () => {
return new HttpResponse(null, { status: 500 });
}),
);
const { wrapper, queryClient } = createQueryWrapper();
const { queryClient, wrapper } = createQueryWrapper();
const { result } = renderHook(
() => {
const accounts = useBrokerageAccounts();
@@ -105,20 +105,21 @@ describe("page-owned screen synchronization", () => {
);
if (cached) {
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.isSuccess).toBe(true),
);
unavailable = true;
isUnavailable = true;
await act(() => result.current.accounts.refetch());
}
await waitFor(() => expect(result.current.accounts.isError).toBe(true));
unavailable = false;
isUnavailable = false;
await act(() => result.current.sync.retry());
await waitFor(() => expect(result.current.accounts.isSuccess).toBe(true));
expect(result.current.accounts.meta?.stateVersion).toBe(
cached ? "3" : "2",
);
expect(modes).toEqual(
cached ? [null, null, "observe"] : [null, "observe"],
cached ? [null, /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null, "observe"] : [null, "observe"],
);
expect(posts).toBe(0);
expect(result.current.disabled.data).toBeUndefined();
@@ -139,26 +140,24 @@ describe("page-owned screen synchronization", () => {
"discards recovery after %s changes (HTTP already pending=%s)",
async (boundary, pending) => {
auth();
let release!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
let recovering = false;
let changed = false;
const { promise: blocked, resolve: release } = Promise.withResolvers<void>();
let isRecovering = false;
let isChanged = false;
server.use(
http.get("*/api/v1/brokerage-accounts", async ({ request }) => {
if (boundary === "connection" && changed && !request.signal.aborted)
if (boundary === "connection" && isChanged && !request.signal.aborted)
return HttpResponse.json(resource([], { stateVersion: "current" }));
if (!new URL(request.url).searchParams.has("sync"))
return changed
return isChanged
? HttpResponse.json(resource([], { stateVersion: "current" }))
: HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 });
recovering = true;
isRecovering = true;
await blocked;
return HttpResponse.json(resource([], { stateVersion: "old" }));
}),
);
const { wrapper, queryClient } = createQueryWrapper();
const { queryClient, wrapper } = createQueryWrapper();
const published: unknown[] = [];
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
if (event.type === "updated" && event.action.type === "success")
@@ -179,29 +178,42 @@ describe("page-owned screen synchronization", () => {
act(() => {
recovery = result.current.sync.retry();
});
if (pending) await waitFor(() => expect(recovering).toBe(true));
// 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 () => {
changed = true;
if (boundary === "logout") {
configureAuthClient(null);
queryClient.clear();
} else if (boundary === "session") {
auth();
queryClient.clear();
} else if (boundary === "access") {
invalidateResourceAccess(queryClient, "brokerage", {
code: "FORBIDDEN",
});
} else
commitTbankConnectionBoundary(queryClient, {
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?.stateVersion).toBe("current"),
);
expect(published).not.toContainEqual(
@@ -216,7 +228,7 @@ describe("page-owned screen synchronization", () => {
"recovers an initial GET failure after forced sync without metadata (status retry=%s)",
async (retryStatus) => {
auth();
const modes: (string | null)[] = [];
const modes: (null | string)[] = [];
let polls = 0;
server.use(
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
@@ -234,12 +246,12 @@ describe("page-owned screen synchronization", () => {
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
: HttpResponse.json({
id: "recover",
state: "succeeded",
resources: [resource([]).meta],
state: "succeeded",
});
}),
);
const { wrapper, queryClient } = createQueryWrapper();
const { queryClient, wrapper } = createQueryWrapper();
const { result } = renderHook(
() => {
const accounts = useBrokerageAccounts();
@@ -256,12 +268,14 @@ describe("page-owned screen synchronization", () => {
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),
);
await act(() => result.current.sync.retry());
}
await waitFor(() => expect(result.current.accounts.isSuccess).toBe(true));
expect(result.current.accounts.data).toEqual([]);
// eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response.
expect(modes).toEqual([null, "observe"]);
expect(
queryClient
@@ -272,12 +286,12 @@ describe("page-owned screen synchronization", () => {
);
it("posts only its scope once and observes completion without importing again", async () => {
auth();
const modes: (string | null)[] = [];
const modes: (null | string)[] = [];
const bodies: unknown[] = [];
let completed = false;
let isCompleted = false;
let polls = 0;
const meta = () =>
resource([], { stateVersion: completed ? "2" : "1" }).meta;
resource([], { stateVersion: isCompleted ? "2" : "1" }).meta;
server.use(
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
modes.push(new URL(request.url).searchParams.get("sync"));
@@ -285,27 +299,29 @@ describe("page-owned screen synchronization", () => {
}),
http.post("*/api/v1/tbank-sync", async ({ request }) => {
bodies.push(await request.json());
completed = true;
isCompleted = true;
return HttpResponse.json(
{
id: "screen",
scope: { screen: "accounts" },
now: "2026-09-25T00:00:00Z",
scope: { screen: "accounts" },
},
{ status: 202 },
);
}),
http.get("*/api/v1/tbank-sync/:id", () => {
polls++;
return HttpResponse.json({
id: "screen",
scope: { screen: "accounts" },
now: "2026-09-25T00:00:00Z",
state: "succeeded",
errorCode: null,
progress: { total: 1, completed: 1, discovering: false },
resources: [meta()],
});
return HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
errorCode: null,
id: "screen",
now: "2026-09-25T00:00:00Z",
progress: { completed: 1, discovering: false, total: 1 },
resources: [meta()],
scope: { screen: "accounts" },
state: "succeeded",
}
/* eslint-enable unicorn/no-null */));
}),
);
const { result, unmount } = renderHook(
@@ -329,16 +345,19 @@ describe("page-owned screen synchronization", () => {
expect(result.current.accounts.meta?.stateVersion).toBe("2"),
);
expect(bodies).toEqual([{ screen: "accounts" }]);
// eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response.
expect(modes).toEqual([null, "observe"]);
vi.useFakeTimers();
try {
await act(() => vi.advanceTimersByTimeAsync(120000));
await act(() => vi.advanceTimersByTimeAsync(120_000));
expect(polls).toBe(1);
// eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response.
expect(modes).toEqual([null, "observe"]);
unmount();
await vi.advanceTimersByTimeAsync(120000);
await vi.advanceTimersByTimeAsync(120_000);
expect(polls).toBe(1);
} finally {
}
finally {
vi.useRealTimers();
}
});
@@ -348,14 +367,16 @@ describe("page-owned screen synchronization", () => {
vi.useFakeTimers({ toFake: ["Date"] });
try {
auth();
let completed = false;
let isCompleted = false;
let polls = 0;
const modes: (string | null)[] = [];
const modes: (null | string)[] = [];
const snapshot = () =>
resource(completed ? [] : null, {
stateVersion: completed ? "covered" : "initial",
sync: { id: "history", state: "running", errorCode: null },
});
resource(isCompleted ? [] : /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null, (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
stateVersion: isCompleted ? "covered" : "initial",
sync: { errorCode: null, id: "history", state: "running" },
}
/* eslint-enable unicorn/no-null */));
server.use(
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
modes.push(new URL(request.url).searchParams.get("sync"));
@@ -363,19 +384,21 @@ describe("page-owned screen synchronization", () => {
}),
http.get("*/api/v1/tbank-sync/:id", () => {
polls++;
return HttpResponse.json({
id: "history",
scope: null,
now: "2026-09-25T00:00:00Z",
state: "running",
errorCode: null,
progress: {
total: 2,
completed: completed ? 1 : 0,
discovering: true,
},
resources: [snapshot().meta],
});
return HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
errorCode: null,
id: "history",
now: "2026-09-25T00:00:00Z",
progress: {
completed: isCompleted ? 1 : 0,
discovering: true,
total: 2,
},
resources: [snapshot().meta],
scope: null,
state: "running",
}
/* eslint-enable unicorn/no-null */));
}),
);
const { result, unmount } = renderHook(
@@ -394,24 +417,26 @@ describe("page-owned screen synchronization", () => {
await waitFor(() => expect(polls).toBeGreaterThan(0));
expect(result.current.sync.refreshing).toBe(true);
expect(result.current.accounts.data).toBeUndefined();
completed = true;
vi.setSystemTime(Date.now() + 61000);
isCompleted = true;
vi.setSystemTime(Date.now() + 61_000);
await waitFor(() => expect(result.current.accounts.data).toEqual([]), {
timeout: 3000,
});
expect(result.current.sync.refreshing).toBe(true);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 1100));
await new Promise(resolve => setTimeout(resolve, 1100));
});
// eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response.
expect(modes).toEqual([null, "observe"]);
if (boundary === "leave") unmount();
else act(() => configureAuthClient(null));
else act(() => configureAuthClient());
const stopped = polls;
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 1100));
await new Promise(resolve => setTimeout(resolve, 1100));
});
expect(polls).toBe(stopped);
} finally {
}
finally {
vi.useRealTimers();
}
},
@@ -422,9 +447,11 @@ describe("page-owned screen synchronization", () => {
server.use(
http.get("*/api/v1/brokerage-accounts", () =>
HttpResponse.json(
resource([], {
sync: { id: "revoked", state: "running", errorCode: null },
}),
resource([], (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
sync: { errorCode: null, id: "revoked", state: "running" },
}
/* eslint-enable unicorn/no-null */)),
),
),
http.get("*/api/v1/tbank-sync/:id", () =>
@@ -446,41 +473,45 @@ describe("page-owned screen synchronization", () => {
});
it("observes a projection when only its dependency reports new coverage", async () => {
auth();
let observed = false;
const modes: (string | null)[] = [];
const dependency = resource([], {
resourceKey: "operations",
stateVersion: observed ? "covered" : "initial",
sync: {
id: "dependency",
state: observed ? "idle" : "running",
errorCode: null,
},
}).meta;
let isObserved = false;
const modes: (null | string)[] = [];
const dependency = resource([], (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
resourceKey: "operations",
stateVersion: isObserved ? "covered" : "initial",
sync: {
errorCode: null,
id: "dependency",
state: isObserved ? "idle" : "running",
},
}
/* eslint-enable unicorn/no-null */)).meta;
server.use(
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
const mode = new URL(request.url).searchParams.get("sync");
modes.push(mode);
if (mode) observed = true;
if (mode) isObserved = true;
return HttpResponse.json(
resource(observed ? [] : null, {
resourceKey: "projection",
resource(isObserved ? [] : /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null, {
dependencies: [
{ ...dependency, stateVersion: observed ? "covered" : "initial" },
{ ...dependency, stateVersion: isObserved ? "covered" : "initial" },
],
resourceKey: "projection",
}),
);
}),
http.get("*/api/v1/tbank-sync/:id", () =>
HttpResponse.json({
id: "dependency",
scope: null,
now: "2026-09-25T00:00:00Z",
state: "succeeded",
errorCode: null,
progress: { total: 1, completed: 1, discovering: false },
resources: [{ ...dependency, stateVersion: "covered" }],
}),
HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
errorCode: null,
id: "dependency",
now: "2026-09-25T00:00:00Z",
progress: { completed: 1, discovering: false, total: 1 },
resources: [{ ...dependency, stateVersion: "covered" }],
scope: null,
state: "succeeded",
}
/* eslint-enable unicorn/no-null */)),
),
);
const { result } = renderHook(
@@ -492,6 +523,7 @@ describe("page-owned screen synchronization", () => {
{ wrapper: createQueryWrapper().wrapper },
);
await waitFor(() => expect(result.current.data).toEqual([]));
// eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response.
expect(modes).toEqual([null, "observe"]);
});
+117 -107
View File
@@ -1,5 +1,6 @@
import { type QueryKey, useQueryClient } from "@tanstack/react-query";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import {
apiErrorCode,
apiQueryClient,
@@ -7,37 +8,74 @@ import {
type paths,
useAuthenticatedQueries,
} from "@/shared/api";
import { type InvestmentScreen, useTbankSync } from "./sync";
type ResourceMeta =
paths["/api/v1/tbank-sync/{id}"]["get"]["responses"][200]["content"]["application/json"]["resources"][number];
type ResourceMeta
= paths["/api/v1/tbank-sync/{id}"]["get"]["responses"][200]["content"]["application/json"]["resources"][number];
type ScreenResource = {
queryKey: QueryKey;
meta?: ResourceMeta;
transport: {
status: "pending" | "success" | "error";
fetchStatus: "idle" | "fetching" | "paused";
};
observe: (version?: string) => Promise<unknown>;
queryKey: QueryKey;
transport: {
fetchStatus: "fetching" | "idle" | "paused";
status: "error" | "pending" | "success";
};
};
const STATUS_INTERVAL_MS = 1000;
function observeResource(
resource: ScreenResource,
latest: Map<string, ResourceMeta>,
completedId: string | undefined,
observed: Map<string, string>,
) {
if (!resource.meta) {
if (!completedId || resource.transport.fetchStatus !== "idle") return;
const key = `query:${JSON.stringify(resource.queryKey)}`;
if (observed.get(key) === completedId) return;
observed.set(key, completedId);
void resource.observe().catch(() => {});
return;
}
const changed = [
resource.meta,
...(resource.meta.dependencies ?? []),
].flatMap((current) => {
const notified = latest.get(current.resourceKey);
return notified && notified.stateVersion !== current.stateVersion
? [notified]
: [];
});
if (changed.length === 0) return;
const notification = JSON.stringify(
changed.map(meta => [meta.resourceKey, meta.stateVersion]),
);
if (observed.get(resource.meta.resourceKey) === notification)
return;
observed.set(resource.meta.resourceKey, notification);
const own = changed.find(
meta => meta.resourceKey === resource.meta?.resourceKey,
);
void resource.observe(own?.stateVersion).catch(() => {});
}
function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
const mutation = useTbankSync();
const client = useQueryClient();
const denied = useRef(new Set<unknown>());
const deniedRef = useRef(new Set<unknown>());
const scopeKey = JSON.stringify(scope);
const [requested, setRequested] = useState<{
scope: string;
const [requested, setRequested] = useState<null | {
id: string;
} | null>(null);
const requestInFlight = useRef<string | null>(null);
const currentScope = useRef(scopeKey);
scope: string;
}>(null);
const requestInFlightRef = useRef<null | string>(null);
const currentScopeRef = useRef(scopeKey);
useLayoutEffect(() => {
currentScope.current = scopeKey;
currentScopeRef.current = scopeKey;
}, [scopeKey]);
const currentMutation = JSON.stringify(mutation.variables?.body) === scopeKey;
const observed = useRef(new Map<string, string>());
const isCurrentMutation = JSON.stringify(mutation.variables?.body) === scopeKey;
const observedRef = useRef(new Map<string, string>());
const ids = [
...new Set([
...(requested?.scope === scopeKey ? [requested.id] : []),
@@ -45,139 +83,111 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
.flatMap(({ meta }) =>
meta ? [meta, ...(meta.dependencies ?? [])] : [],
)
.flatMap((meta) =>
meta?.sync.id &&
(meta.sync.state === "running" || meta.sync.state === "queued")
.flatMap(meta =>
meta?.sync.id
&& (meta.sync.state === "running" || meta.sync.state === "queued")
? [meta.sync.id]
: [],
),
]),
];
const statuses = useAuthenticatedQueries(
ids.map((id) => ({
ids.map(id => ({
...apiQueryClient.queryOptions("get", "/api/v1/tbank-sync/{id}", {
params: { path: { id } },
}),
retry: false,
refetchInterval: (query: {
state: { data?: { state: string }; error: unknown };
}) =>
!(query.state.error || (query.state.data && query.state.data.state !== "running")) && STATUS_INTERVAL_MS,
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchInterval: (query: {
state: { error: unknown; data?: { state: string } };
}) =>
query.state.error ||
(query.state.data && query.state.data.state !== "running")
? false
: STATUS_INTERVAL_MS,
retry: false,
})),
);
useEffect(() => {
for (const status of statuses) {
if (status.error && !denied.current.has(status.error)) {
denied.current.add(status.error);
if (apiErrorCode(status.error) !== "NOT_FOUND")
invalidateResourceAccess(client, "brokerage", status.error);
if (!status.error || deniedRef.current.has(status.error)) {
continue;
}
deniedRef.current.add(status.error);
if (apiErrorCode(status.error) !== "NOT_FOUND")
invalidateResourceAccess(client, "brokerage", status.error);
}
const latest = new Map<string, ResourceMeta>();
for (const status of [...statuses].sort(
(a, b) => a.dataUpdatedAt - b.dataUpdatedAt,
))
for (const meta of status.data?.resources ?? []) {
const orderedStatuses = statuses.toSorted((a, b) => a.dataUpdatedAt - b.dataUpdatedAt);
for (const status of orderedStatuses) {
const statusResources = status.data?.resources ?? [];
for (const meta of statusResources) {
latest.set(meta.resourceKey, meta);
for (const dependency of meta.dependencies ?? [])
const dependencies = meta.dependencies ?? [];
for (const dependency of dependencies)
latest.set(dependency.resourceKey, dependency);
}
for (const resource of resources) {
if (!resource.meta) {
if (resource.transport.fetchStatus !== "idle") continue;
const completed = statuses.find(
(status) =>
requested?.scope === scopeKey &&
status.data?.id === requested.id &&
status.data.state !== "running",
)?.data;
const key = `query:${JSON.stringify(resource.queryKey)}`;
if (completed && observed.current.get(key) !== completed.id) {
observed.current.set(key, completed.id);
void resource.observe().catch(() => undefined);
}
continue;
}
const changed = [
resource.meta,
...(resource.meta.dependencies ?? []),
].flatMap((current) => {
const notified = latest.get(current.resourceKey);
return notified && notified.stateVersion !== current.stateVersion
? [notified]
: [];
});
if (!changed.length) continue;
const notification = JSON.stringify(
changed.map((meta) => [meta.resourceKey, meta.stateVersion]),
);
if (observed.current.get(resource.meta.resourceKey) === notification)
continue;
observed.current.set(resource.meta.resourceKey, notification);
const own = changed.find(
(meta) => meta.resourceKey === resource.meta?.resourceKey,
);
void resource.observe(own?.stateVersion).catch(() => undefined);
}
const completed = statuses.find(status => requested?.scope === scopeKey
&& status.data?.id === requested.id && status.data.state !== "running")?.data;
for (const resource of resources) observeResource(resource, latest, completed?.id, observedRef.current);
}, [client, statuses, resources, requested, scopeKey]);
const refreshing =
(currentMutation && mutation.isPending) ||
statuses.some(
(status) => !status.isError && status.data?.state === "running",
) ||
resources.some(({ meta }) => {
const status = statuses[ids.indexOf(meta?.sync.id ?? "")];
return (
!status?.isError &&
(!status?.data || status.data.state === "running") &&
(meta?.sync.state === "running" || meta?.sync.state === "queued")
);
});
const isRefreshing
= (isCurrentMutation && mutation.isPending)
|| statuses.some(
status => !status.isError && status.data?.state === "running",
)
|| resources.some(({ meta }) => {
const status = statuses[ids.indexOf(meta?.sync.id ?? "")];
return (
!status?.isError
&& (!status?.data || status.data.state === "running")
&& (meta?.sync.state === "running" || meta?.sync.state === "queued")
);
});
const refresh = async () => {
if (requestInFlight.current === scopeKey || refreshing) return;
requestInFlight.current = scopeKey;
if (isRefreshing || requestInFlightRef.current === scopeKey) return;
requestInFlightRef.current = scopeKey;
try {
const accepted = await mutation.mutateAsync({ body: scope });
if (
currentScope.current === scopeKey &&
requestInFlight.current === scopeKey
currentScopeRef.current === scopeKey
&& requestInFlightRef.current === scopeKey
)
setRequested({ scope: scopeKey, id: accepted.id });
} catch {
/* The mutation retains the transport error for presentation. */
} finally {
if (requestInFlight.current === scopeKey) requestInFlight.current = null;
setRequested({ id: accepted.id, scope: scopeKey });
}
catch {
/*
The mutation retains the transport error for presentation.
*/
}
finally {
if (requestInFlightRef.current === scopeKey) requestInFlightRef.current = /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null;
}
};
// Retry failed HTTP reads without asking the source to import again.
// A source failure (or explicit refresh with no read error) still needs a sync.
const retry = async () => {
const failed = resources.filter(
(resource) => resource.transport.status === "error",
resource => resource.transport.status === "error",
);
const failedStatuses = statuses.filter((status) => status.isError);
if (failed.length || failedStatuses.length) {
const failedStatuses = statuses.filter(status => status.isError);
if (failed.length > 0 || failedStatuses.length > 0) {
await Promise.allSettled([
...failed.map((resource) => resource.observe()),
...failedStatuses.map((status) => status.refetch()),
...failed.map(resource => resource.observe()),
...failedStatuses.map(status => status.refetch()),
]);
} else await refresh();
}
else await refresh();
};
return {
refresh,
refreshing: isRefreshing,
retry,
refreshing,
transportError:
(currentMutation && mutation.isError) ||
statuses.some((status) => status.isError),
sourceError:
statuses.some((status) => status.data?.state === "failed") ||
resources.some(({ meta }) => meta?.sync.state === "failed"),
statuses.some(status => status.data?.state === "failed")
|| resources.some(({ meta }) => meta?.sync.state === "failed"),
transportError:
(isCurrentMutation && mutation.isError)
|| statuses.some(status => status.isError),
};
}
@@ -1,9 +1,11 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { http, HttpResponse } from "msw";
import { describe, expect, it, vi } from "vitest";
import { apiQueryClient, configureAuthClient } from "@/shared/api";
import { createQueryWrapper } from "@/test/query";
import { server } from "@/test/server";
import {
type InvestmentScreen,
useTbankSync,
@@ -17,22 +19,20 @@ describe("sync connection and session boundaries", () => {
async (boundary) => {
let generation = 0;
configureAuthClient({
generation: () => generation,
accessToken: () => "synthetic",
refresh: async () => true,
clear: vi.fn(),
generation: () => generation,
refresh: () => Promise.resolve(true),
});
let release!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
const { promise: blocked, resolve: release } = Promise.withResolvers<void>();
const accepted = {
id: "work",
scope: { screen: "accounts" },
now: "2026-09-25T12:00:00Z",
scope: { screen: "accounts" },
};
let started = 0;
let changed = false;
let isChanged = false;
server.use(
http.post("*/api/v1/tbank-sync", async () => {
started += 1;
@@ -40,29 +40,31 @@ describe("sync connection and session boundaries", () => {
return HttpResponse.json(accepted, { status: 202 });
}),
http.get("*/api/v1/tbank-sync/:id", async () => {
const now = changed ? "2026-09-25T12:01:00Z" : accepted.now;
const now = isChanged ? "2026-09-25T12:01:00Z" : accepted.now;
started += 1;
await blocked;
return HttpResponse.json({
...accepted,
now,
state: "succeeded",
errorCode: null,
progress: { total: 1, completed: 1, discovering: false },
resources: [],
});
return HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
...accepted,
errorCode: null,
now,
progress: { completed: 1, discovering: false, total: 1 },
resources: [],
state: "succeeded",
}
/* eslint-enable unicorn/no-null */));
}),
);
const { wrapper, queryClient } = createQueryWrapper();
const { queryClient, wrapper } = createQueryWrapper();
const published: string[] = [];
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
if (
(event.query.queryKey as readonly unknown[])[1] ===
"/api/v1/tbank-sync/{id}"
) {
const data = event.query.state.data as { now?: string } | undefined;
if (data?.now) published.push(data.now);
if ((event.query.queryKey as readonly unknown[])[1]
!== "/api/v1/tbank-sync/{id}") {
return;
}
const data = event.query.state.data as undefined | { now?: string };
if (data?.now) published.push(data.now);
});
const { result } = renderHook(
() => ({
@@ -82,12 +84,14 @@ describe("sync connection and session boundaries", () => {
});
await waitFor(() => expect(started).toBe(2));
await act(async () => {
changed = true;
isChanged = true;
if (boundary === "connection")
commitTbankConnectionBoundary(queryClient, {
connected: false,
connectedAt: null,
});
commitTbankConnectionBoundary(queryClient, (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
connected: false,
connectedAt: null,
}
/* eslint-enable unicorn/no-null */));
else {
generation += 1;
queryClient.clear();
@@ -104,9 +108,11 @@ describe("sync connection and session boundaries", () => {
).queryKey;
// A new request may start after a successful connection boundary; an old result cannot win it.
if (boundary === "session")
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
expect(queryClient.getQueryData(key)).toBeUndefined();
else
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(queryClient.getQueryData(key)).toMatchObject({
now: "2026-09-25T12:01:00Z",
}),
+3 -3
View File
@@ -4,14 +4,14 @@ import {
useAuthenticatedQuery,
} from "@/shared/api";
type InvestmentScreen =
paths["/api/v1/tbank-sync"]["post"]["requestBody"]["content"]["application/json"];
type InvestmentScreen
= paths["/api/v1/tbank-sync"]["post"]["requestBody"]["content"]["application/json"];
function useTbankSync() {
return apiQueryClient.useMutation("post", "/api/v1/tbank-sync", {
retry: false,
});
}
function useTbankSyncStatus(id: string | null) {
function useTbankSyncStatus(id: null | string) {
return useAuthenticatedQuery({
...apiQueryClient.queryOptions("get", "/api/v1/tbank-sync/{id}", {
params: { path: { id: id ?? "" } },