feat: show persisted investment data and sync state
Consume the provided resource-envelope API snapshot. Preserve financial snapshots during refresh, observe synchronization without importing, and fence late responses across account and connection changes.
This commit is contained in:
@@ -5,6 +5,7 @@ import type { FC, PropsWithChildren } from "react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { apiClient, apiQueryClient, useAuthenticatedQuery } from "@/shared/api";
|
||||
import { createTestQueryClient } from "@/test/query";
|
||||
import { resource } from "@/test/resource";
|
||||
import { server } from "@/test/server";
|
||||
import { AuthProvider, useAuth } from "./auth";
|
||||
|
||||
@@ -24,7 +25,7 @@ describe("AuthProvider", () => {
|
||||
),
|
||||
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
||||
authorization = request.headers.get("Authorization");
|
||||
return HttpResponse.json([]);
|
||||
return HttpResponse.json(resource([]));
|
||||
}),
|
||||
);
|
||||
const queryClient = createTestQueryClient();
|
||||
|
||||
@@ -143,8 +143,8 @@ const AuthProvider: FC<PropsWithChildren> = (props) => {
|
||||
refresh,
|
||||
clear: clearSession,
|
||||
});
|
||||
return () => configureAuthClient(null);
|
||||
});
|
||||
useEffect(() => () => configureAuthClient(null), []);
|
||||
|
||||
return (
|
||||
<AuthContext
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { resource } from "@/test/resource";
|
||||
import { section } from "./section";
|
||||
|
||||
describe("instrument source and transport presentation", () => {
|
||||
it.each(["missing", "partial", "complete"] as const)(
|
||||
"keeps %s separate from successful transport",
|
||||
(availability) => {
|
||||
const data = availability === "missing" ? undefined : { rows: [] };
|
||||
const state = section({
|
||||
data,
|
||||
meta: resource(data, { availability }).meta,
|
||||
isError: false,
|
||||
isFetching: false,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
expect(state.loading).toBe(availability === "missing");
|
||||
expect(state.partial).toBe(availability === "partial");
|
||||
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();
|
||||
const meta = resource([], {
|
||||
sync: { id: "work", state: "failed", errorCode: "TBANK_UNAVAILABLE" },
|
||||
}).meta;
|
||||
const state = section(
|
||||
{ data: [], meta, isError: false, isFetching: false, refetch },
|
||||
retry,
|
||||
);
|
||||
expect(state).toMatchObject({
|
||||
hasData: true,
|
||||
loading: false,
|
||||
error: true,
|
||||
refreshing: false,
|
||||
lastSuccessfulAt: meta.lastSuccessfulAt,
|
||||
});
|
||||
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,
|
||||
meta: resource(null, {
|
||||
sync: { id: "work", state: "failed", errorCode: "TBANK_UNAVAILABLE" },
|
||||
}).meta,
|
||||
isError: false,
|
||||
isFetching: false,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
expect(state).toMatchObject({
|
||||
hasData: false,
|
||||
loading: false,
|
||||
error: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,23 +1,44 @@
|
||||
import type { paths } from "@/shared/api";
|
||||
|
||||
type Meta =
|
||||
paths["/api/v1/tbank-sync/{id}"]["get"]["responses"][200]["content"]["application/json"]["resources"][number];
|
||||
type SectionState = {
|
||||
stale?: boolean;
|
||||
sourceError?: boolean;
|
||||
partial?: boolean;
|
||||
lastSuccessfulAt?: string | null;
|
||||
hasData: boolean;
|
||||
loading: boolean;
|
||||
error: boolean;
|
||||
refreshing: boolean;
|
||||
retry: () => void;
|
||||
};
|
||||
function section(query: {
|
||||
data: unknown;
|
||||
isError: boolean;
|
||||
isFetching: boolean;
|
||||
refetch: () => unknown;
|
||||
}): SectionState {
|
||||
function section(
|
||||
query: {
|
||||
data: unknown;
|
||||
meta?: Meta;
|
||||
isError: boolean;
|
||||
isFetching: boolean;
|
||||
refetch: () => unknown;
|
||||
},
|
||||
retry?: () => unknown,
|
||||
): SectionState {
|
||||
const error = query.isError || query.meta?.sync.state === "failed";
|
||||
return {
|
||||
stale: query.meta?.freshness === "stale",
|
||||
sourceError: query.meta?.sync.state === "failed",
|
||||
partial: query.meta?.availability === "partial",
|
||||
lastSuccessfulAt: query.meta?.lastSuccessfulAt,
|
||||
hasData: Boolean(query.data),
|
||||
loading: !query.data && !query.isError,
|
||||
error: query.isError,
|
||||
refreshing: Boolean(query.data) && query.isFetching,
|
||||
loading: !query.data && !error,
|
||||
error,
|
||||
refreshing:
|
||||
Boolean(query.data) &&
|
||||
(query.isFetching ||
|
||||
query.meta?.sync.state === "running" ||
|
||||
query.meta?.sync.state === "queued"),
|
||||
retry: () => {
|
||||
void query.refetch();
|
||||
void (retry ?? query.refetch)();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,10 +2,12 @@ import type { BrokerageOperation } from "@/entities/broker-operation";
|
||||
import type { paths } from "@/shared/api";
|
||||
import type { SectionState } from "./section";
|
||||
|
||||
type Position =
|
||||
paths["/api/v1/stocks/{uid}/position"]["get"]["responses"][200]["content"]["application/json"];
|
||||
type Candles =
|
||||
paths["/api/v1/stocks/{uid}/candles"]["get"]["responses"][200]["content"]["application/json"];
|
||||
type Position = NonNullable<
|
||||
paths["/api/v1/stocks/{uid}/position"]["get"]["responses"][200]["content"]["application/json"]["data"]
|
||||
>;
|
||||
type Candles = NonNullable<
|
||||
paths["/api/v1/stocks/{uid}/candles"]["get"]["responses"][200]["content"]["application/json"]["data"]
|
||||
>;
|
||||
type ChartRow = Candles["candles"][number] & { date: string; price: number };
|
||||
type InstrumentPositionVm = {
|
||||
position?: Position;
|
||||
|
||||
@@ -177,7 +177,13 @@ const InstrumentChart: FC<InstrumentChartProps> = (props) => {
|
||||
</Accordion>
|
||||
</>
|
||||
) : (
|
||||
<Text c="dimmed">{t("stock.noCandles")}</Text>
|
||||
<Text c="dimmed">
|
||||
{t(
|
||||
vm.candlesState.partial
|
||||
? "investment.partial"
|
||||
: "stock.noCandles",
|
||||
)}
|
||||
</Text>
|
||||
)
|
||||
) : null}
|
||||
</InstrumentSection>
|
||||
|
||||
@@ -60,7 +60,11 @@ const InstrumentEvents: FC<InstrumentEventsProps> = (props) => {
|
||||
</Stack>
|
||||
) : (
|
||||
<Text c="dimmed" py="lg">
|
||||
{t("stock.noOperations")}
|
||||
{t(
|
||||
vm.operationsState.partial
|
||||
? "investment.partial"
|
||||
: "stock.noOperations",
|
||||
)}
|
||||
</Text>
|
||||
)}
|
||||
<Group justify="space-between" mt="md">
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||
import type { FC, PropsWithChildren, ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { formatSnapshotTime } from "@/shared/lib";
|
||||
import type { SectionState } from "../model/section";
|
||||
import classes from "./InstrumentDetails.module.css";
|
||||
|
||||
@@ -38,20 +39,40 @@ const InstrumentSection: FC<InstrumentSectionProps> = (props) => {
|
||||
</Title>
|
||||
{props.controls}
|
||||
</Group>
|
||||
{props.state.stale ? (
|
||||
<Text size="xs">{t("investment.stale")}</Text>
|
||||
) : null}
|
||||
{props.state.partial ? (
|
||||
<Text role="status">{t("investment.partial")}</Text>
|
||||
) : null}
|
||||
{props.state.lastSuccessfulAt ? (
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("investment.sourceTime", {
|
||||
date: formatSnapshotTime(props.state.lastSuccessfulAt),
|
||||
})}
|
||||
</Text>
|
||||
) : null}
|
||||
{props.state.refreshing ? (
|
||||
<Text role="status" size="xs" c="dimmed">
|
||||
{t("accounts.refreshing")}
|
||||
</Text>
|
||||
) : null}
|
||||
{props.state.error ? (
|
||||
<Alert color="orange" mb="sm" role="alert">
|
||||
<Alert color="orange" mb="sm" role="status" aria-live="polite">
|
||||
<Group justify="space-between">
|
||||
<Text size="sm">
|
||||
{props.state.hasData
|
||||
? t("accounts.refreshError")
|
||||
: t("stock.sectionError")}
|
||||
{props.state.sourceError
|
||||
? t("investment.syncFailed")
|
||||
: props.state.hasData
|
||||
? t("accounts.refreshError")
|
||||
: t("stock.sectionError")}
|
||||
</Text>
|
||||
<Button size="xs" variant="default" onClick={props.state.retry}>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="default"
|
||||
onClick={props.state.retry}
|
||||
disabled={props.state.refreshing}
|
||||
>
|
||||
{t("accounts.retry")}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
@@ -1 +1,7 @@
|
||||
export { useScreenSync } from "./model/screen-sync";
|
||||
export {
|
||||
type InvestmentScreen,
|
||||
useTbankSync,
|
||||
useTbankSyncStatus,
|
||||
} from "./model/sync";
|
||||
export { TbankConnectionSection } from "./ui/TbankConnectionSection/TbankConnectionSection";
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
import { apiQueryClient, type paths } from "@/shared/api";
|
||||
import {
|
||||
apiQueryClient,
|
||||
invalidateApiRequests,
|
||||
type paths,
|
||||
} from "@/shared/api";
|
||||
|
||||
type TbankConnectionStatus =
|
||||
paths["/api/v1/tbank-connection"]["get"]["responses"][200]["content"]["application/json"];
|
||||
@@ -15,6 +19,13 @@ function commitTbankConnectionBoundary(
|
||||
queryClient: QueryClient,
|
||||
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"),
|
||||
);
|
||||
queryClient.setQueryData(tbankConnectionQueryKey, status);
|
||||
void queryClient.resetQueries({
|
||||
predicate: ({ queryKey }) => {
|
||||
@@ -22,7 +33,8 @@ function commitTbankConnectionBoundary(
|
||||
return (
|
||||
method === "get" &&
|
||||
typeof path === "string" &&
|
||||
(path === "/api/v1/bonds" ||
|
||||
(path.startsWith("/api/v1/tbank-sync") ||
|
||||
path === "/api/v1/bonds" ||
|
||||
path.startsWith("/api/v1/bonds/") ||
|
||||
path === "/api/v1/stocks" ||
|
||||
path.startsWith("/api/v1/stocks/") ||
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import { HttpResponse, http } from "msw";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { useBrokerageAccounts } from "@/entities/brokerage-account";
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createQueryWrapper } from "@/test/query";
|
||||
import { resource } from "@/test/resource";
|
||||
import { server } from "@/test/server";
|
||||
import { useScreenSync } from "../index";
|
||||
|
||||
function auth() {
|
||||
configureAuthClient({
|
||||
accessToken: () => "synthetic",
|
||||
refresh: async () => true,
|
||||
clear: vi.fn(),
|
||||
});
|
||||
}
|
||||
describe("page-owned screen synchronization", () => {
|
||||
it("posts only its scope once and observes completion without importing again", async () => {
|
||||
auth();
|
||||
const modes: (string | null)[] = [];
|
||||
const bodies: unknown[] = [];
|
||||
let completed = false;
|
||||
let polls = 0;
|
||||
const meta = () =>
|
||||
resource([], { stateVersion: completed ? "2" : "1" }).meta;
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
||||
modes.push(new URL(request.url).searchParams.get("sync"));
|
||||
return HttpResponse.json(resource([], meta()));
|
||||
}),
|
||||
http.post("*/api/v1/tbank-sync", async ({ request }) => {
|
||||
bodies.push(await request.json());
|
||||
completed = true;
|
||||
return HttpResponse.json(
|
||||
{
|
||||
id: "screen",
|
||||
scope: { screen: "accounts" },
|
||||
now: "2026-09-25T00:00:00Z",
|
||||
},
|
||||
{ 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()],
|
||||
});
|
||||
}),
|
||||
);
|
||||
const { result, unmount } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
return {
|
||||
accounts,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts]),
|
||||
};
|
||||
},
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
await waitFor(() => expect(result.current.accounts.data).toEqual([]));
|
||||
await act(async () => {
|
||||
await Promise.all([
|
||||
result.current.sync.refresh(),
|
||||
result.current.sync.refresh(),
|
||||
]);
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current.accounts.meta?.stateVersion).toBe("2"),
|
||||
);
|
||||
expect(bodies).toEqual([{ screen: "accounts" }]);
|
||||
expect(modes).toEqual([null, "observe"]);
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
await act(() => vi.advanceTimersByTimeAsync(120000));
|
||||
expect(polls).toBe(1);
|
||||
expect(modes).toEqual([null, "observe"]);
|
||||
unmount();
|
||||
await vi.advanceTimersByTimeAsync(120000);
|
||||
expect(polls).toBe(1);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
it.each(["leave", "logout"])(
|
||||
"publishes completed empty coverage while history runs, then stops on %s",
|
||||
async (boundary) => {
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
try {
|
||||
auth();
|
||||
let completed = false;
|
||||
let polls = 0;
|
||||
const modes: (string | null)[] = [];
|
||||
const snapshot = () =>
|
||||
resource(completed ? [] : null, {
|
||||
stateVersion: completed ? "covered" : "initial",
|
||||
sync: { id: "history", state: "running", errorCode: null },
|
||||
});
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
||||
modes.push(new URL(request.url).searchParams.get("sync"));
|
||||
return HttpResponse.json(snapshot());
|
||||
}),
|
||||
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],
|
||||
});
|
||||
}),
|
||||
);
|
||||
const { result, unmount } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
return {
|
||||
accounts,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts]),
|
||||
};
|
||||
},
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(result.current.accounts.meta?.sync.id).toBe("history"),
|
||||
);
|
||||
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);
|
||||
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));
|
||||
});
|
||||
expect(modes).toEqual([null, "observe"]);
|
||||
if (boundary === "leave") unmount();
|
||||
else await act(() => configureAuthClient(null));
|
||||
const stopped = polls;
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1100));
|
||||
});
|
||||
expect(polls).toBe(stopped);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("clears private snapshots when status confirms access loss", async () => {
|
||||
auth();
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", () =>
|
||||
HttpResponse.json(
|
||||
resource([], {
|
||||
sync: { id: "revoked", state: "running", errorCode: null },
|
||||
}),
|
||||
),
|
||||
),
|
||||
http.get("*/api/v1/tbank-sync/:id", () =>
|
||||
HttpResponse.json({ code: "INVALID_TBANK_TOKEN" }, { status: 400 }),
|
||||
),
|
||||
);
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
return {
|
||||
accounts,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts]),
|
||||
};
|
||||
},
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
await waitFor(() => expect(result.current.accounts.isError).toBe(true));
|
||||
expect(result.current.accounts.data).toBeUndefined();
|
||||
});
|
||||
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;
|
||||
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;
|
||||
return HttpResponse.json(
|
||||
resource(observed ? [] : null, {
|
||||
resourceKey: "projection",
|
||||
dependencies: [
|
||||
{ ...dependency, stateVersion: observed ? "covered" : "initial" },
|
||||
],
|
||||
}),
|
||||
);
|
||||
}),
|
||||
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" }],
|
||||
}),
|
||||
),
|
||||
);
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
useScreenSync({ screen: "accounts" }, [accounts]);
|
||||
return accounts;
|
||||
},
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
await waitFor(() => expect(result.current.data).toEqual([]));
|
||||
expect(modes).toEqual([null, "observe"]);
|
||||
});
|
||||
|
||||
it("preserves a fresh snapshot and timestamp after a failed force", async () => {
|
||||
auth();
|
||||
const saved = resource([], { lastSuccessfulAt: "2026-09-25T01:00:00Z" });
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", () => HttpResponse.json(saved)),
|
||||
http.post("*/api/v1/tbank-sync", () =>
|
||||
HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }),
|
||||
),
|
||||
);
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
return {
|
||||
accounts,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts]),
|
||||
};
|
||||
},
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
await waitFor(() => expect(result.current.accounts.data).toEqual([]));
|
||||
await act(() => result.current.sync.refresh());
|
||||
await waitFor(() => expect(result.current.sync.transportError).toBe(true));
|
||||
expect(result.current.accounts.meta).toEqual(saved.meta);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
apiErrorCode,
|
||||
apiQueryClient,
|
||||
invalidateResourceAccess,
|
||||
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 ScreenResource = {
|
||||
meta?: ResourceMeta;
|
||||
observe: (version?: string) => Promise<unknown>;
|
||||
};
|
||||
const STATUS_INTERVAL_MS = 1000;
|
||||
|
||||
function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
|
||||
const mutation = useTbankSync();
|
||||
const client = useQueryClient();
|
||||
const denied = useRef(new Set<unknown>());
|
||||
const scopeKey = JSON.stringify(scope);
|
||||
const [requested, setRequested] = useState<{
|
||||
scope: string;
|
||||
id: string;
|
||||
} | null>(null);
|
||||
const requestInFlight = useRef<string | null>(null);
|
||||
const currentScope = useRef(scopeKey);
|
||||
currentScope.current = scopeKey;
|
||||
const currentMutation = JSON.stringify(mutation.variables?.body) === scopeKey;
|
||||
const observed = useRef(new Map<string, string>());
|
||||
const ids = [
|
||||
...new Set([
|
||||
...(requested?.scope === scopeKey ? [requested.id] : []),
|
||||
...resources
|
||||
.flatMap(({ meta }) =>
|
||||
meta ? [meta, ...(meta.dependencies ?? [])] : [],
|
||||
)
|
||||
.flatMap((meta) =>
|
||||
meta?.sync.id &&
|
||||
(meta.sync.state === "running" || meta.sync.state === "queued")
|
||||
? [meta.sync.id]
|
||||
: [],
|
||||
),
|
||||
]),
|
||||
];
|
||||
const statuses = useAuthenticatedQueries(
|
||||
ids.map((id) => ({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/tbank-sync/{id}", {
|
||||
params: { path: { id } },
|
||||
}),
|
||||
retry: false,
|
||||
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,
|
||||
})),
|
||||
);
|
||||
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);
|
||||
}
|
||||
}
|
||||
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 ?? []) {
|
||||
latest.set(meta.resourceKey, meta);
|
||||
for (const dependency of meta.dependencies ?? [])
|
||||
latest.set(dependency.resourceKey, dependency);
|
||||
}
|
||||
for (const resource of resources) {
|
||||
if (!resource.meta) 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);
|
||||
}
|
||||
}, [client, statuses, resources]);
|
||||
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 refresh = async () => {
|
||||
if (requestInFlight.current === scopeKey || refreshing) return;
|
||||
requestInFlight.current = scopeKey;
|
||||
try {
|
||||
const accepted = await mutation.mutateAsync({ body: scope });
|
||||
if (
|
||||
currentScope.current === scopeKey &&
|
||||
requestInFlight.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;
|
||||
}
|
||||
};
|
||||
return {
|
||||
refresh,
|
||||
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"),
|
||||
};
|
||||
}
|
||||
|
||||
export { useScreenSync };
|
||||
@@ -0,0 +1,114 @@
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import { HttpResponse, http } 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,
|
||||
useTbankSyncStatus,
|
||||
} from "../index";
|
||||
import { commitTbankConnectionBoundary } from "./connection-boundary";
|
||||
|
||||
describe("sync connection and session boundaries", () => {
|
||||
it.each(["connection", "session"])(
|
||||
"discards pending status and mutation after %s changes",
|
||||
async (boundary) => {
|
||||
let generation = 0;
|
||||
configureAuthClient({
|
||||
generation: () => generation,
|
||||
accessToken: () => "synthetic",
|
||||
refresh: async () => true,
|
||||
clear: vi.fn(),
|
||||
});
|
||||
let release!: () => void;
|
||||
const blocked = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const accepted = {
|
||||
id: "work",
|
||||
scope: { screen: "accounts" },
|
||||
now: "2026-09-25T12:00:00Z",
|
||||
};
|
||||
let started = 0;
|
||||
let changed = false;
|
||||
server.use(
|
||||
http.post("*/api/v1/tbank-sync", async () => {
|
||||
started += 1;
|
||||
await blocked;
|
||||
return HttpResponse.json(accepted, { status: 202 });
|
||||
}),
|
||||
http.get("*/api/v1/tbank-sync/:id", async () => {
|
||||
const now = changed ? "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: [],
|
||||
});
|
||||
}),
|
||||
);
|
||||
const { wrapper, queryClient } = createQueryWrapper();
|
||||
const published: string[] = [];
|
||||
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
|
||||
if (event.query.queryKey[1] === "/api/v1/tbank-sync/{id}") {
|
||||
const data = event.query.state.data as { now?: string } | undefined;
|
||||
if (data?.now) published.push(data.now);
|
||||
}
|
||||
});
|
||||
const { result } = renderHook(
|
||||
() => ({
|
||||
mutation: useTbankSync(),
|
||||
status: useTbankSyncStatus("work"),
|
||||
}),
|
||||
{ wrapper },
|
||||
);
|
||||
const screen: InvestmentScreen = { screen: "accounts" };
|
||||
let mutation!: Promise<unknown>;
|
||||
act(() => {
|
||||
mutation = result.current.mutation.mutateAsync({ body: screen });
|
||||
});
|
||||
const discarded = expect(mutation).rejects.toMatchObject({
|
||||
name: "AbortError",
|
||||
});
|
||||
await waitFor(() => expect(started).toBe(2));
|
||||
await act(async () => {
|
||||
changed = true;
|
||||
if (boundary === "connection")
|
||||
commitTbankConnectionBoundary(queryClient, {
|
||||
connected: false,
|
||||
connectedAt: null,
|
||||
});
|
||||
else {
|
||||
generation += 1;
|
||||
queryClient.clear();
|
||||
}
|
||||
release();
|
||||
await blocked;
|
||||
});
|
||||
await discarded;
|
||||
expect(result.current.mutation.data).toBeUndefined();
|
||||
const key = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/tbank-sync/{id}",
|
||||
{ params: { path: { id: "work" } } },
|
||||
).queryKey;
|
||||
// A new request may start after a successful connection boundary; an old result cannot win it.
|
||||
if (boundary === "session")
|
||||
expect(queryClient.getQueryData(key)).toBeUndefined();
|
||||
else
|
||||
await waitFor(() =>
|
||||
expect(queryClient.getQueryData(key)).toMatchObject({
|
||||
now: "2026-09-25T12:01:00Z",
|
||||
}),
|
||||
);
|
||||
expect(published).not.toContain(accepted.now);
|
||||
unsubscribe();
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import {
|
||||
apiQueryClient,
|
||||
type paths,
|
||||
useAuthenticatedQuery,
|
||||
} from "@/shared/api";
|
||||
|
||||
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) {
|
||||
return useAuthenticatedQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/tbank-sync/{id}", {
|
||||
params: { path: { id: id ?? "" } },
|
||||
}),
|
||||
enabled: Boolean(id),
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
export { type InvestmentScreen, useTbankSync, useTbankSyncStatus };
|
||||
Reference in New Issue
Block a user