refactor: enforce frontend view model boundaries
This commit is contained in:
@@ -31,6 +31,7 @@ function commitTbankConnectionBoundary(
|
||||
void queryClient.resetQueries({
|
||||
predicate: ({ queryKey }) => {
|
||||
const [method, path] = queryKey;
|
||||
|
||||
return (
|
||||
method === "get"
|
||||
&& typeof path === "string"
|
||||
|
||||
@@ -19,11 +19,14 @@ function auth() {
|
||||
refresh: () => Promise.resolve(true),
|
||||
});
|
||||
}
|
||||
|
||||
describe("page-owned screen synchronization", () => {
|
||||
it("ignores a late sync acceptance after the account scope changes", async () => {
|
||||
auth();
|
||||
|
||||
const { promise: blocked, resolve: release } = Promise.withResolvers<void>();
|
||||
const { promise: blocked, resolve: release }
|
||||
= Promise.withResolvers<void>();
|
||||
|
||||
const posted: string[] = [];
|
||||
const polled: string[] = [];
|
||||
server.use(
|
||||
@@ -32,8 +35,10 @@ describe("page-owned screen synchronization", () => {
|
||||
accountId: string;
|
||||
screen: "account";
|
||||
};
|
||||
|
||||
posted.push(scope.accountId);
|
||||
await blocked;
|
||||
|
||||
return HttpResponse.json(
|
||||
{ id: scope.accountId, now: "2026-09-25T00:00:00Z", scope },
|
||||
{ status: 202 },
|
||||
@@ -41,6 +46,7 @@ describe("page-owned screen synchronization", () => {
|
||||
}),
|
||||
http.get("*/api/v1/tbank-sync/:id", ({ params }) => {
|
||||
polled.push(String(params.id));
|
||||
|
||||
return HttpResponse.json({
|
||||
id: params.id,
|
||||
resources: [],
|
||||
@@ -48,6 +54,7 @@ describe("page-owned screen synchronization", () => {
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const { rerender, result } = renderHook(
|
||||
({ accountId }) => useScreenSync({ accountId, screen: "account" }, []),
|
||||
{
|
||||
@@ -55,6 +62,7 @@ describe("page-owned screen synchronization", () => {
|
||||
wrapper: createQueryWrapper().wrapper,
|
||||
},
|
||||
);
|
||||
|
||||
let pending!: Promise<void>;
|
||||
act(() => {
|
||||
pending = result.current.refresh();
|
||||
@@ -79,6 +87,7 @@ describe("page-owned screen synchronization", () => {
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
||||
modes.push(new URL(request.url).searchParams.get("sync"));
|
||||
|
||||
return isUnavailable
|
||||
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
|
||||
: HttpResponse.json(
|
||||
@@ -87,14 +96,17 @@ describe("page-owned screen synchronization", () => {
|
||||
}),
|
||||
http.post("*/api/v1/tbank-sync", () => {
|
||||
posts += 1;
|
||||
|
||||
return new HttpResponse(null, { status: 500 });
|
||||
}),
|
||||
);
|
||||
const { queryClient, wrapper } = createQueryWrapper();
|
||||
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
const disabled = useStockQuote("");
|
||||
|
||||
return {
|
||||
accounts,
|
||||
disabled,
|
||||
@@ -103,6 +115,7 @@ describe("page-owned screen synchronization", () => {
|
||||
},
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
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.
|
||||
@@ -111,6 +124,7 @@ describe("page-owned screen synchronization", () => {
|
||||
isUnavailable = true;
|
||||
await act(() => result.current.accounts.refetch());
|
||||
}
|
||||
|
||||
await waitFor(() => expect(result.current.accounts.isError).toBe(true));
|
||||
isUnavailable = false;
|
||||
await act(() => result.current.sync.retry());
|
||||
@@ -119,7 +133,14 @@ describe("page-owned screen synchronization", () => {
|
||||
cached ? "3" : "2",
|
||||
);
|
||||
expect(modes).toEqual(
|
||||
cached ? [null, /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null, "observe"] : [null, "observe"],
|
||||
cached
|
||||
? [
|
||||
null, // eslint-disable-line unicorn/no-null -- Preserve explicit null in the API fixture.
|
||||
// eslint-disable-next-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
|
||||
null,
|
||||
"observe",
|
||||
]
|
||||
: [null, "observe"], // eslint-disable-line unicorn/no-null -- Preserve explicit null in the API fixture.
|
||||
);
|
||||
expect(posts).toBe(0);
|
||||
expect(result.current.disabled.data).toBeUndefined();
|
||||
@@ -141,7 +162,9 @@ describe("page-owned screen synchronization", () => {
|
||||
async (boundary, pending) => {
|
||||
auth();
|
||||
|
||||
const { promise: blocked, resolve: release } = Promise.withResolvers<void>();
|
||||
const { promise: blocked, resolve: release }
|
||||
= Promise.withResolvers<void>();
|
||||
|
||||
let isRecovering = false;
|
||||
let isChanged = false;
|
||||
server.use(
|
||||
@@ -154,18 +177,22 @@ describe("page-owned screen synchronization", () => {
|
||||
: HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 });
|
||||
isRecovering = true;
|
||||
await blocked;
|
||||
|
||||
return HttpResponse.json(resource([], { stateVersion: "old" }));
|
||||
}),
|
||||
);
|
||||
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]),
|
||||
@@ -173,6 +200,7 @@ describe("page-owned screen synchronization", () => {
|
||||
},
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
await waitFor(() => expect(result.current.accounts.isError).toBe(true));
|
||||
let recovery!: Promise<void>;
|
||||
act(() => {
|
||||
@@ -182,6 +210,7 @@ describe("page-owned screen synchronization", () => {
|
||||
if (pending) await waitFor(() => expect(isRecovering).toBe(true));
|
||||
await act(async () => {
|
||||
isChanged = true;
|
||||
|
||||
switch (boundary) {
|
||||
case "access": {
|
||||
invalidateResourceAccess(queryClient, "brokerage", {
|
||||
@@ -190,24 +219,29 @@ describe("page-owned screen synchronization", () => {
|
||||
|
||||
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",
|
||||
});
|
||||
|
||||
case "connection": {
|
||||
commitTbankConnectionBoundary(queryClient, {
|
||||
connected: true,
|
||||
connectedAt: "2026-09-27T00:00:00Z",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
release();
|
||||
await recovery;
|
||||
});
|
||||
@@ -233,6 +267,7 @@ describe("page-owned screen synchronization", () => {
|
||||
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([]));
|
||||
@@ -242,6 +277,7 @@ describe("page-owned screen synchronization", () => {
|
||||
),
|
||||
http.get("*/api/v1/tbank-sync/:id", () => {
|
||||
polls += 1;
|
||||
|
||||
return retryStatus && polls === 1
|
||||
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
|
||||
: HttpResponse.json({
|
||||
@@ -252,10 +288,12 @@ describe("page-owned screen synchronization", () => {
|
||||
}),
|
||||
);
|
||||
const { queryClient, wrapper } = createQueryWrapper();
|
||||
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
const disabled = useStockQuote("");
|
||||
|
||||
return {
|
||||
accounts,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts, disabled]),
|
||||
@@ -263,9 +301,11 @@ describe("page-owned screen synchronization", () => {
|
||||
},
|
||||
{ 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.
|
||||
@@ -273,6 +313,7 @@ describe("page-owned screen synchronization", () => {
|
||||
);
|
||||
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.
|
||||
@@ -290,16 +331,20 @@ describe("page-owned screen synchronization", () => {
|
||||
const bodies: unknown[] = [];
|
||||
let isCompleted = false;
|
||||
let polls = 0;
|
||||
|
||||
const 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"));
|
||||
|
||||
return HttpResponse.json(resource([], meta()));
|
||||
}),
|
||||
http.post("*/api/v1/tbank-sync", async ({ request }) => {
|
||||
bodies.push(await request.json());
|
||||
isCompleted = true;
|
||||
|
||||
return HttpResponse.json(
|
||||
{
|
||||
id: "screen",
|
||||
@@ -311,7 +356,10 @@ describe("page-owned screen synchronization", () => {
|
||||
}),
|
||||
http.get("*/api/v1/tbank-sync/:id", () => {
|
||||
polls++;
|
||||
return HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
return HttpResponse.json(
|
||||
{
|
||||
errorCode: null,
|
||||
id: "screen",
|
||||
@@ -320,13 +368,16 @@ describe("page-owned screen synchronization", () => {
|
||||
resources: [meta()],
|
||||
scope: { screen: "accounts" },
|
||||
state: "succeeded",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */));
|
||||
},
|
||||
/* eslint-enable unicorn/no-null */
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const { result, unmount } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
|
||||
return {
|
||||
accounts,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts]),
|
||||
@@ -334,6 +385,7 @@ describe("page-owned screen synchronization", () => {
|
||||
},
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
|
||||
await waitFor(() => expect(result.current.accounts.data).toEqual([]));
|
||||
await act(async () => {
|
||||
await Promise.all([
|
||||
@@ -348,6 +400,7 @@ describe("page-owned screen synchronization", () => {
|
||||
// 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(120_000));
|
||||
expect(polls).toBe(1);
|
||||
@@ -365,26 +418,36 @@ describe("page-owned screen synchronization", () => {
|
||||
"publishes completed empty coverage while history runs, then stops on %s",
|
||||
async (boundary) => {
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
|
||||
try {
|
||||
auth();
|
||||
let isCompleted = false;
|
||||
let polls = 0;
|
||||
const modes: (null | string)[] = [];
|
||||
|
||||
const snapshot = () =>
|
||||
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. */
|
||||
resource(
|
||||
isCompleted
|
||||
? []
|
||||
: null, // eslint-disable-line unicorn/no-null -- Preserve the nullable API fixture.
|
||||
{
|
||||
stateVersion: isCompleted ? "covered" : "initial",
|
||||
sync: { errorCode: null, id: "history", state: "running" },
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */));
|
||||
sync: { errorCode: null, id: "history", state: "running" }, // eslint-disable-line unicorn/no-null -- Preserve explicit null in the API fixture.
|
||||
},
|
||||
);
|
||||
|
||||
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((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
return HttpResponse.json(
|
||||
{
|
||||
errorCode: null,
|
||||
id: "history",
|
||||
@@ -397,13 +460,16 @@ describe("page-owned screen synchronization", () => {
|
||||
resources: [snapshot().meta],
|
||||
scope: null,
|
||||
state: "running",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */));
|
||||
},
|
||||
/* eslint-enable unicorn/no-null */
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const { result, unmount } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
|
||||
return {
|
||||
accounts,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts]),
|
||||
@@ -411,6 +477,7 @@ describe("page-owned screen synchronization", () => {
|
||||
},
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.accounts.meta?.sync.id).toBe("history"),
|
||||
);
|
||||
@@ -447,20 +514,25 @@ describe("page-owned screen synchronization", () => {
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", () =>
|
||||
HttpResponse.json(
|
||||
resource([], (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
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 */)),
|
||||
},
|
||||
/* eslint-enable unicorn/no-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]),
|
||||
@@ -468,6 +540,7 @@ describe("page-owned screen synchronization", () => {
|
||||
},
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
|
||||
await waitFor(() => expect(result.current.accounts.isError).toBe(true));
|
||||
expect(result.current.accounts.data).toBeUndefined();
|
||||
});
|
||||
@@ -475,7 +548,10 @@ describe("page-owned screen synchronization", () => {
|
||||
auth();
|
||||
let isObserved = false;
|
||||
const modes: (null | string)[] = [];
|
||||
const dependency = resource([], (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
const dependency = resource(
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
[],
|
||||
{
|
||||
resourceKey: "operations",
|
||||
stateVersion: isObserved ? "covered" : "initial",
|
||||
@@ -484,24 +560,36 @@ describe("page-owned screen synchronization", () => {
|
||||
id: "dependency",
|
||||
state: isObserved ? "idle" : "running",
|
||||
},
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */)).meta;
|
||||
},
|
||||
/* 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) isObserved = true;
|
||||
|
||||
return HttpResponse.json(
|
||||
resource(isObserved ? [] : /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null, {
|
||||
dependencies: [
|
||||
{ ...dependency, stateVersion: isObserved ? "covered" : "initial" },
|
||||
],
|
||||
resourceKey: "projection",
|
||||
}),
|
||||
resource(
|
||||
isObserved
|
||||
? []
|
||||
: null, // eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
|
||||
{
|
||||
dependencies: [
|
||||
{
|
||||
...dependency,
|
||||
stateVersion: isObserved ? "covered" : "initial",
|
||||
},
|
||||
],
|
||||
resourceKey: "projection",
|
||||
},
|
||||
),
|
||||
);
|
||||
}),
|
||||
http.get("*/api/v1/tbank-sync/:id", () =>
|
||||
HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
HttpResponse.json(
|
||||
{
|
||||
errorCode: null,
|
||||
id: "dependency",
|
||||
@@ -510,18 +598,22 @@ describe("page-owned screen synchronization", () => {
|
||||
resources: [{ ...dependency, stateVersion: "covered" }],
|
||||
scope: null,
|
||||
state: "succeeded",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */)),
|
||||
},
|
||||
/* eslint-enable unicorn/no-null */
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
useScreenSync({ screen: "accounts" }, [accounts]);
|
||||
|
||||
return accounts;
|
||||
},
|
||||
{ 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"]);
|
||||
@@ -536,9 +628,11 @@ describe("page-owned screen synchronization", () => {
|
||||
HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }),
|
||||
),
|
||||
);
|
||||
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
|
||||
return {
|
||||
accounts,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts]),
|
||||
@@ -546,6 +640,7 @@ describe("page-owned screen synchronization", () => {
|
||||
},
|
||||
{ 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));
|
||||
|
||||
@@ -15,15 +15,21 @@ 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>;
|
||||
queryKey: QueryKey;
|
||||
transport: {
|
||||
fetchStatus: "fetching" | "idle" | "paused";
|
||||
status: "error" | "pending" | "success";
|
||||
fetchStatus: "fetching"
|
||||
| "idle"
|
||||
| "paused";
|
||||
status: "error"
|
||||
| "pending"
|
||||
| "success";
|
||||
};
|
||||
};
|
||||
|
||||
const STATUS_INTERVAL_MS = 1000;
|
||||
|
||||
function observeResource(
|
||||
@@ -38,27 +44,34 @@ function observeResource(
|
||||
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;
|
||||
|
||||
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(() => {});
|
||||
}
|
||||
|
||||
@@ -67,17 +80,24 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
|
||||
const client = useQueryClient();
|
||||
const deniedRef = useRef(new Set<unknown>());
|
||||
const scopeKey = JSON.stringify(scope);
|
||||
const [requested, setRequested] = useState<null | {
|
||||
id: string;
|
||||
scope: string;
|
||||
}>(null);
|
||||
|
||||
const [requested, setRequested] = useState<null
|
||||
| {
|
||||
id: string;
|
||||
scope: string;
|
||||
}>(null);
|
||||
|
||||
const requestInFlightRef = useRef<null | string>(null);
|
||||
const currentScopeRef = useRef(scopeKey);
|
||||
useLayoutEffect(() => {
|
||||
currentScopeRef.current = scopeKey;
|
||||
}, [scopeKey]);
|
||||
const isCurrentMutation = JSON.stringify(mutation.variables?.body) === scopeKey;
|
||||
|
||||
const isCurrentMutation
|
||||
= JSON.stringify(mutation.variables?.body) === scopeKey;
|
||||
|
||||
const observedRef = useRef(new Map<string, string>());
|
||||
|
||||
const ids = [
|
||||
...new Set([
|
||||
...(requested?.scope === scopeKey ? [requested.id] : []),
|
||||
@@ -93,6 +113,7 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
|
||||
),
|
||||
]),
|
||||
];
|
||||
|
||||
const statuses = useAuthenticatedQueries(
|
||||
ids.map(id => ({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/tbank-sync/{id}", {
|
||||
@@ -101,12 +122,16 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
|
||||
refetchInterval: (query: {
|
||||
state: { data?: { state: string }; error: unknown };
|
||||
}) =>
|
||||
!(query.state.error || (query.state.data && query.state.data.state !== "running")) && STATUS_INTERVAL_MS,
|
||||
!(
|
||||
query.state.error
|
||||
|| (query.state.data && query.state.data.state !== "running")
|
||||
) && STATUS_INTERVAL_MS,
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
retry: false,
|
||||
})),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
for (const status of statuses) {
|
||||
if (!status.error || deniedRef.current.has(status.error)) {
|
||||
@@ -117,10 +142,16 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
|
||||
if (!isApiErrorCode(apiErrorCode(status.error), ApiErrorCode.NotFound))
|
||||
invalidateResourceAccess(client, "brokerage", status.error);
|
||||
}
|
||||
|
||||
const latest = new Map<string, ResourceMeta>();
|
||||
const orderedStatuses = statuses.toSorted((a, b) => a.dataUpdatedAt - b.dataUpdatedAt);
|
||||
|
||||
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);
|
||||
const dependencies = meta.dependencies ?? [];
|
||||
@@ -128,10 +159,18 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
|
||||
latest.set(dependency.resourceKey, dependency);
|
||||
}
|
||||
}
|
||||
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);
|
||||
|
||||
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 isRefreshing
|
||||
= (isCurrentMutation && mutation.isPending)
|
||||
|| statuses.some(
|
||||
@@ -139,15 +178,18 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
|
||||
)
|
||||
|| 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 (isRefreshing || requestInFlightRef.current === scopeKey) return;
|
||||
requestInFlightRef.current = scopeKey;
|
||||
|
||||
try {
|
||||
const accepted = await mutation.mutateAsync({ body: scope });
|
||||
if (
|
||||
@@ -162,15 +204,20 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
|
||||
*/
|
||||
}
|
||||
finally {
|
||||
if (requestInFlightRef.current === scopeKey) requestInFlightRef.current = /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null;
|
||||
if (requestInFlightRef.current === scopeKey)
|
||||
requestInFlightRef.current
|
||||
// eslint-disable-next-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",
|
||||
);
|
||||
|
||||
const failedStatuses = statuses.filter(status => status.isError);
|
||||
if (failed.length > 0 || failedStatuses.length > 0) {
|
||||
await Promise.allSettled([
|
||||
@@ -180,6 +227,7 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
|
||||
}
|
||||
else await refresh();
|
||||
};
|
||||
|
||||
return {
|
||||
refresh,
|
||||
refreshing: isRefreshing,
|
||||
|
||||
@@ -25,25 +25,32 @@ describe("sync connection and session boundaries", () => {
|
||||
refresh: () => Promise.resolve(true),
|
||||
});
|
||||
|
||||
const { promise: blocked, resolve: release } = Promise.withResolvers<void>();
|
||||
const { promise: blocked, resolve: release }
|
||||
= Promise.withResolvers<void>();
|
||||
|
||||
const accepted = {
|
||||
id: "work",
|
||||
now: "2026-09-25T12:00:00Z",
|
||||
scope: { screen: "accounts" },
|
||||
};
|
||||
|
||||
let started = 0;
|
||||
let isChanged = 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 = isChanged ? "2026-09-25T12:01:00Z" : accepted.now;
|
||||
started += 1;
|
||||
await blocked;
|
||||
return HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
return HttpResponse.json(
|
||||
{
|
||||
...accepted,
|
||||
errorCode: null,
|
||||
@@ -51,21 +58,26 @@ describe("sync connection and session boundaries", () => {
|
||||
progress: { completed: 1, discovering: false, total: 1 },
|
||||
resources: [],
|
||||
state: "succeeded",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */));
|
||||
},
|
||||
/* eslint-enable unicorn/no-null */
|
||||
);
|
||||
}),
|
||||
);
|
||||
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}") {
|
||||
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(
|
||||
() => ({
|
||||
mutation: useTbankSync(),
|
||||
@@ -73,39 +85,49 @@ describe("sync connection and session boundaries", () => {
|
||||
}),
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
const screen: InvestmentScreen = { screen: "accounts" };
|
||||
let mutation!: Promise<unknown>;
|
||||
act(() => {
|
||||
mutation = result.current.mutation.mutateAsync({ body: screen });
|
||||
});
|
||||
|
||||
// eslint-disable-next-line vitest/valid-expect -- Attach rejection handling before releasing the request; the assertion is awaited below.
|
||||
const discarded = expect(mutation).rejects.toMatchObject({
|
||||
name: "AbortError",
|
||||
});
|
||||
|
||||
await waitFor(() => expect(started).toBe(2));
|
||||
await act(async () => {
|
||||
isChanged = true;
|
||||
|
||||
if (boundary === "connection")
|
||||
commitTbankConnectionBoundary(queryClient, (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
commitTbankConnectionBoundary(
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
queryClient,
|
||||
{
|
||||
connected: false,
|
||||
connectedAt: null,
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */));
|
||||
},
|
||||
/* eslint-enable unicorn/no-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")
|
||||
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
|
||||
|
||||
@@ -6,11 +6,13 @@ import {
|
||||
|
||||
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: null | string) {
|
||||
return useAuthenticatedQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/tbank-sync/{id}", {
|
||||
|
||||
+40
-14
@@ -21,26 +21,31 @@ const brokerageAccountsQueryKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/brokerage-accounts",
|
||||
).queryKey;
|
||||
|
||||
const portfolioQueryKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/brokerage-accounts/{accountId}/portfolio",
|
||||
{ params: { path: { accountId: "account-1" } } },
|
||||
).queryKey;
|
||||
|
||||
const operationsQueryKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/brokerage-accounts/{accountId}/operations",
|
||||
{ params: { path: { accountId: "account-1" } } },
|
||||
).queryKey;
|
||||
|
||||
const stockQueryKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/stocks/{uid}/position",
|
||||
{ params: { path: { uid: "e6123145-9665-43e0-8413-cd61b8aa9b13" } } },
|
||||
).queryKey;
|
||||
|
||||
const bondQueryKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/bonds/{uid}/position",
|
||||
{ params: { path: { uid: "e6123145-9665-43e0-8413-cd61b8aa9b13" } } },
|
||||
).queryKey;
|
||||
|
||||
const bankCardsQueryKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/bank-cards",
|
||||
@@ -48,6 +53,7 @@ const bankCardsQueryKey = apiQueryClient.queryOptions(
|
||||
params: { query: { includeArchived: "false" } },
|
||||
},
|
||||
).queryKey;
|
||||
|
||||
const unrelatedQueryKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/auth/me",
|
||||
@@ -59,6 +65,7 @@ function renderSection(client: QueryClient) {
|
||||
clear: vi.fn(),
|
||||
refresh: () => Promise.resolve(true),
|
||||
});
|
||||
|
||||
return render(
|
||||
<MantineProvider>
|
||||
<QueryClientProvider client={client}>
|
||||
@@ -70,21 +77,22 @@ function renderSection(client: QueryClient) {
|
||||
|
||||
function seededClient() {
|
||||
const client = createTestQueryClient();
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
client.setQueryData(brokerageAccountsQueryKey, [
|
||||
(/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
id: "account-1",
|
||||
name: "Основной счет",
|
||||
openedOn: null,
|
||||
type: "BROKERAGE",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */),
|
||||
{
|
||||
id: "account-1",
|
||||
name: "Основной счет",
|
||||
openedOn: null,
|
||||
type: "BROKERAGE",
|
||||
},
|
||||
/* eslint-enable unicorn/no-null */
|
||||
]);
|
||||
client.setQueryData(portfolioQueryKey, { source: "previous-connection" });
|
||||
client.setQueryData(stockQueryKey, { source: "previous-connection" });
|
||||
client.setQueryData(bondQueryKey, { source: "previous-connection" });
|
||||
client.setQueryData(unrelatedQueryKey, { id: "user-1" });
|
||||
client.setQueryData(bankCardsQueryKey, [{ id: "bank-card-1" }]);
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
@@ -92,18 +100,23 @@ describe("TbankConnectionSection", () => {
|
||||
it("preserves cached status and a draft entered during a delayed failed refetch", async () => {
|
||||
const status = { connected: true, connectedAt: "2026-08-14T00:00:00Z" };
|
||||
|
||||
const { promise: response, resolve: finishRefetch } = Promise.withResolvers<void>();
|
||||
const { promise: response, resolve: finishRefetch }
|
||||
= Promise.withResolvers<void>();
|
||||
|
||||
let reads = 0;
|
||||
server.use(
|
||||
http.get("*/api/v1/tbank-connection", async () => {
|
||||
reads += 1;
|
||||
|
||||
if (reads === 1) {
|
||||
await response;
|
||||
|
||||
return HttpResponse.json(
|
||||
{ code: "TBANK_UNAVAILABLE" },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
return HttpResponse.json(status);
|
||||
}),
|
||||
);
|
||||
@@ -141,11 +154,14 @@ describe("TbankConnectionSection", () => {
|
||||
server.use(
|
||||
http.get("*/api/v1/tbank-connection", () => {
|
||||
reads += 1;
|
||||
|
||||
return reads === 1
|
||||
? HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 })
|
||||
: HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{ connected: false, connectedAt: null }
|
||||
/* eslint-enable unicorn/no-null */));
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
: HttpResponse.json(
|
||||
{ connected: false, connectedAt: null },
|
||||
/* eslint-enable unicorn/no-null */
|
||||
);
|
||||
}),
|
||||
);
|
||||
renderSection(createTestQueryClient());
|
||||
@@ -244,19 +260,24 @@ describe("TbankConnectionSection", () => {
|
||||
const client = seededClient();
|
||||
|
||||
let isAborted = false;
|
||||
const { promise: previousResponse, resolve: finishPrevious } = Promise.withResolvers<{ source: string }>();
|
||||
|
||||
const { promise: previousResponse, resolve: finishPrevious }
|
||||
= Promise.withResolvers<{ source: string }>();
|
||||
|
||||
const previousRequest = client
|
||||
.query({
|
||||
queryFn: ({ signal }) => {
|
||||
signal.addEventListener("abort", () => {
|
||||
isAborted = true;
|
||||
});
|
||||
|
||||
return previousResponse;
|
||||
},
|
||||
queryKey: operationsQueryKey,
|
||||
})
|
||||
// eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering.
|
||||
.catch(() => {});
|
||||
|
||||
renderSection(client);
|
||||
|
||||
await screen.findByText("Не подключено");
|
||||
@@ -302,7 +323,9 @@ describe("TbankConnectionSection", () => {
|
||||
it("keeps DELETE recovery inside the dialog and preserves cache until successful retry", async () => {
|
||||
let deletes = 0;
|
||||
|
||||
const { promise: response, resolve: finishDelete } = Promise.withResolvers<void>();
|
||||
const { promise: response, resolve: finishDelete }
|
||||
= Promise.withResolvers<void>();
|
||||
|
||||
server.use(
|
||||
http.get("*/api/v1/tbank-connection", () =>
|
||||
HttpResponse.json({
|
||||
@@ -313,6 +336,7 @@ describe("TbankConnectionSection", () => {
|
||||
http.delete("*/api/v1/tbank-connection", async () => {
|
||||
deletes += 1;
|
||||
if (deletes === 1) await response;
|
||||
|
||||
return deletes === 1
|
||||
? HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 })
|
||||
: new HttpResponse(null, { status: 204 });
|
||||
@@ -324,9 +348,11 @@ describe("TbankConnectionSection", () => {
|
||||
fireEvent.click(
|
||||
await screen.findByRole("button", { name: "Удалить подключение" }),
|
||||
);
|
||||
|
||||
const dialog = await screen.findByRole("dialog", {
|
||||
name: "Удалить подключение?",
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
// eslint-disable-next-line testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
|
||||
expect(dialog.contains(document.activeElement)).toBe(true),
|
||||
|
||||
@@ -10,7 +10,14 @@ import { TbankConnectionSectionLoaded } from "./TbankConnectionSectionLoaded";
|
||||
const TbankConnectionSection: FC = () => {
|
||||
const viewModel = useTbankConnectionViewModel();
|
||||
if (viewModel.state === "loading") return <TbankConnectionLoading />;
|
||||
return viewModel.state === "error" ? <TbankConnectionError retry={viewModel.retry} /> : <TbankConnectionSectionLoaded {...viewModel} />;
|
||||
|
||||
return viewModel.state === "error"
|
||||
? (
|
||||
<TbankConnectionError retry={viewModel.retry} />
|
||||
)
|
||||
: (
|
||||
<TbankConnectionSectionLoaded {...viewModel} />
|
||||
);
|
||||
};
|
||||
|
||||
export { TbankConnectionSection };
|
||||
|
||||
+2
@@ -10,11 +10,13 @@ import {
|
||||
describe("TbankConnectionSection state views", () => {
|
||||
it("renders loading and retries a status error", () => {
|
||||
const retry = vi.fn();
|
||||
|
||||
const { rerender } = render(
|
||||
<MantineProvider>
|
||||
<TbankConnectionLoading />
|
||||
</MantineProvider>,
|
||||
);
|
||||
|
||||
expect(screen.getByRole("status", { name: "Загрузка" })).toHaveAttribute(
|
||||
"aria-busy",
|
||||
"true",
|
||||
|
||||
+1
@@ -14,6 +14,7 @@ const TbankConnectionLoading: FC = () => {
|
||||
return (
|
||||
<LoadingSkeleton label={t("states.loadingTitle")}>
|
||||
<Skeleton height={20} width="45%" />
|
||||
|
||||
<Skeleton height={36} radius="sm" width={140} />
|
||||
</LoadingSkeleton>
|
||||
);
|
||||
|
||||
+5
-1
@@ -6,9 +6,13 @@ function useTbankConnectionViewModel() {
|
||||
const status = useAuthenticatedQuery({
|
||||
...tbankConnectionQueryOptions(),
|
||||
});
|
||||
|
||||
if (!status.data) {
|
||||
return status.isPending ? { state: "loading" as const } : { retry: () => status.refetch(), state: "error" as const };
|
||||
return status.isPending
|
||||
? { state: "loading" as const }
|
||||
: { retry: () => status.refetch(), state: "error" as const };
|
||||
}
|
||||
|
||||
return {
|
||||
refreshError: status.isError,
|
||||
refreshing: status.isFetching,
|
||||
|
||||
+39
-64
@@ -8,19 +8,11 @@ import {
|
||||
Stack,
|
||||
Text,
|
||||
} from "@mantine/core";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { ApiErrorCode, apiErrorCode, apiQueryClient, isApiErrorCode } from "@/shared/api";
|
||||
import { ApiErrorCode, isApiErrorCode } from "@/shared/api";
|
||||
|
||||
import {
|
||||
commitTbankConnectionBoundary,
|
||||
type TbankConnectionStatus,
|
||||
} from "../../model/connection-boundary";
|
||||
|
||||
enum ConnectionErrorCode { RequestFailed = "REQUEST_ERROR" }
|
||||
import { type TbankConnectionStatus } from "../../model/connection-boundary";
|
||||
import { useTbankConnectionSectionLoadedVm } from "./TbankConnectionSectionLoaded.vm";
|
||||
|
||||
type TbankConnectionSectionLoadedProps = {
|
||||
refreshError: boolean;
|
||||
@@ -32,48 +24,29 @@ type TbankConnectionSectionLoadedProps = {
|
||||
const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
|
||||
props,
|
||||
) => {
|
||||
const { status } = props;
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const [isDeleteOpened, setIsDeleteOpened] = useState(false);
|
||||
const removalButtonRef = useRef<HTMLButtonElement>(null);
|
||||
const [requestError, setRequestError] = useState<null | string>(null);
|
||||
const {
|
||||
formState: { errors },
|
||||
handleSubmit,
|
||||
errors,
|
||||
isConnected,
|
||||
isDeleteOpened,
|
||||
isPending,
|
||||
onCloseDisconnect,
|
||||
onConfirmDisconnect,
|
||||
onOpenDisconnect,
|
||||
onSubmit,
|
||||
register,
|
||||
reset,
|
||||
} = useForm<{ token: string }>();
|
||||
const update = apiQueryClient.useMutation("put", "/api/v1/tbank-connection", {
|
||||
onError: error => setRequestError(apiErrorCode(error) ?? ConnectionErrorCode.RequestFailed),
|
||||
onSuccess: (data) => {
|
||||
commitTbankConnectionBoundary(queryClient, data);
|
||||
reset();
|
||||
},
|
||||
});
|
||||
const remove = apiQueryClient.useMutation(
|
||||
"delete",
|
||||
"/api/v1/tbank-connection",
|
||||
{
|
||||
onSuccess: () => {
|
||||
commitTbankConnectionBoundary(queryClient, {
|
||||
connected: false,
|
||||
connectedAt: /* eslint-disable-line unicorn/no-null -- The disconnected API snapshot requires a null connection timestamp. */ null,
|
||||
});
|
||||
setIsDeleteOpened(false);
|
||||
},
|
||||
},
|
||||
);
|
||||
const unavailableMessage = isApiErrorCode(requestError, ApiErrorCode.TbankUnavailable) ? "tbank.unavailable" : "tbank.requestError";
|
||||
const isPending = update.isPending || remove.isPending;
|
||||
const isConnected = status.connected;
|
||||
useEffect(() => {
|
||||
if (isDeleteOpened && remove.isError) removalButtonRef.current?.focus();
|
||||
}, [isDeleteOpened, remove.isError]);
|
||||
removalButtonRef,
|
||||
remove,
|
||||
requestError,
|
||||
status,
|
||||
t,
|
||||
unavailableMessage,
|
||||
update,
|
||||
} = useTbankConnectionSectionLoadedVm(props);
|
||||
|
||||
return (
|
||||
<Stack mt="xl">
|
||||
<Text fw={600}>{t("tbank.title")}</Text>
|
||||
|
||||
<Text size="sm">
|
||||
{isConnected
|
||||
? t("tbank.connected", {
|
||||
@@ -83,18 +56,22 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
|
||||
})
|
||||
: t("tbank.disconnected")}
|
||||
</Text>
|
||||
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("tbank.hint")}
|
||||
</Text>
|
||||
|
||||
{props.refreshing && (
|
||||
<Text c="dimmed" role="status" size="sm">
|
||||
{t("tbank.refreshing")}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
{props.refreshError && (
|
||||
<Alert aria-live="polite" color="orange" role="status">
|
||||
<Stack gap="sm">
|
||||
<Text>{t("tbank.refreshError")}</Text>
|
||||
|
||||
<Button
|
||||
disabled={props.refreshing || isPending}
|
||||
onClick={props.retry}
|
||||
@@ -105,12 +82,8 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
|
||||
</Stack>
|
||||
</Alert>
|
||||
)}
|
||||
<form
|
||||
onSubmit={handleSubmit(({ token }) => {
|
||||
setRequestError(null);
|
||||
update.mutate({ body: { token } });
|
||||
})}
|
||||
>
|
||||
|
||||
<form onSubmit={onSubmit}>
|
||||
<fieldset disabled={isPending}>
|
||||
<Stack>
|
||||
<PasswordInput
|
||||
@@ -118,6 +91,7 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
|
||||
{...register("token", { required: t("tbank.tokenRequired") })}
|
||||
error={errors.token?.message}
|
||||
/>
|
||||
|
||||
{requestError && (
|
||||
<Alert color="red">
|
||||
{t(
|
||||
@@ -127,42 +101,43 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
|
||||
)}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Button loading={update.isPending} type="submit">
|
||||
{t(isConnected ? "tbank.replace" : "tbank.connect")}
|
||||
</Button>
|
||||
|
||||
{isConnected && (
|
||||
<Button
|
||||
color="red"
|
||||
onClick={() => {
|
||||
remove.reset();
|
||||
setIsDeleteOpened(true);
|
||||
}}
|
||||
variant="outline"
|
||||
>
|
||||
<Button color="red" onClick={onOpenDisconnect} variant="outline">
|
||||
{t("tbank.delete")}
|
||||
</Button>
|
||||
)}
|
||||
</Stack>
|
||||
</fieldset>
|
||||
</form>
|
||||
|
||||
<Modal
|
||||
closeButtonProps={{ "aria-label": t("tbank.close"), "disabled": isPending }}
|
||||
closeButtonProps={{
|
||||
"aria-label": t("tbank.close"),
|
||||
"disabled": isPending,
|
||||
}}
|
||||
closeOnClickOutside={!isPending}
|
||||
closeOnEscape={!isPending}
|
||||
onClose={() => !isPending && setIsDeleteOpened(false)}
|
||||
onClose={onCloseDisconnect}
|
||||
opened={isDeleteOpened}
|
||||
title={t("tbank.deleteTitle")}
|
||||
>
|
||||
<Stack>
|
||||
<Text>{t("tbank.deleteText")}</Text>
|
||||
|
||||
{remove.isError && (
|
||||
<Alert color="red">{t("tbank.requestError")}</Alert>
|
||||
)}
|
||||
|
||||
<Button
|
||||
color="red"
|
||||
disabled={isPending}
|
||||
loading={remove.isPending}
|
||||
onClick={() => remove.mutate({})}
|
||||
onClick={onConfirmDisconnect}
|
||||
ref={removalButtonRef}
|
||||
>
|
||||
{t("tbank.deleteConfirm")}
|
||||
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import {
|
||||
ApiErrorCode,
|
||||
apiErrorCode,
|
||||
apiQueryClient,
|
||||
isApiErrorCode,
|
||||
} from "@/shared/api";
|
||||
|
||||
import {
|
||||
commitTbankConnectionBoundary,
|
||||
type TbankConnectionStatus,
|
||||
} from "../../model/connection-boundary";
|
||||
enum ConnectionErrorCode {
|
||||
RequestFailed = "REQUEST_ERROR",
|
||||
}
|
||||
|
||||
type TbankConnectionSectionLoadedProps = {
|
||||
refreshError: boolean;
|
||||
refreshing: boolean;
|
||||
retry: () => void;
|
||||
status: TbankConnectionStatus;
|
||||
};
|
||||
|
||||
function useTbankConnectionSectionLoadedVm(
|
||||
props: TbankConnectionSectionLoadedProps,
|
||||
) {
|
||||
const { status } = props;
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const [isDeleteOpened, setIsDeleteOpened] = useState(false);
|
||||
const removalButtonRef = useRef<HTMLButtonElement>(null);
|
||||
const [requestError, setRequestError] = useState<null | string>(null);
|
||||
|
||||
const {
|
||||
formState: { errors },
|
||||
handleSubmit,
|
||||
register,
|
||||
reset,
|
||||
} = useForm<{ token: string }>();
|
||||
|
||||
const update = apiQueryClient.useMutation("put", "/api/v1/tbank-connection", {
|
||||
onError: error =>
|
||||
setRequestError(apiErrorCode(error) ?? ConnectionErrorCode.RequestFailed),
|
||||
onSuccess: (data) => {
|
||||
commitTbankConnectionBoundary(queryClient, data);
|
||||
reset();
|
||||
},
|
||||
});
|
||||
|
||||
const remove = apiQueryClient.useMutation(
|
||||
"delete",
|
||||
"/api/v1/tbank-connection",
|
||||
{
|
||||
onSuccess: () => {
|
||||
commitTbankConnectionBoundary(queryClient, {
|
||||
connected: false,
|
||||
connectedAt:
|
||||
// eslint-disable-next-line unicorn/no-null -- The disconnected API snapshot requires a null connection timestamp.
|
||||
null,
|
||||
});
|
||||
setIsDeleteOpened(false);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const unavailableMessage = isApiErrorCode(
|
||||
requestError,
|
||||
ApiErrorCode.TbankUnavailable,
|
||||
)
|
||||
? "tbank.unavailable"
|
||||
: "tbank.requestError";
|
||||
|
||||
const isPending = update.isPending || remove.isPending;
|
||||
const isConnected = status.connected;
|
||||
useEffect(() => {
|
||||
if (isDeleteOpened && remove.isError) removalButtonRef.current?.focus();
|
||||
}, [isDeleteOpened, remove.isError]);
|
||||
|
||||
const onSubmit = handleSubmit(({ token }) => {
|
||||
setRequestError(null);
|
||||
update.mutate({ body: { token } });
|
||||
});
|
||||
|
||||
const onOpenDisconnect = () => {
|
||||
remove.reset();
|
||||
setIsDeleteOpened(true);
|
||||
};
|
||||
|
||||
const onCloseDisconnect = () => !isPending && setIsDeleteOpened(false);
|
||||
const onConfirmDisconnect = () => remove.mutate({});
|
||||
|
||||
return {
|
||||
errors,
|
||||
isConnected,
|
||||
isDeleteOpened,
|
||||
isPending,
|
||||
onCloseDisconnect,
|
||||
onConfirmDisconnect,
|
||||
onOpenDisconnect,
|
||||
onSubmit,
|
||||
register,
|
||||
removalButtonRef,
|
||||
remove,
|
||||
requestError,
|
||||
status,
|
||||
t,
|
||||
unavailableMessage,
|
||||
update,
|
||||
};
|
||||
}
|
||||
|
||||
export { useTbankConnectionSectionLoadedVm };
|
||||
Reference in New Issue
Block a user