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
+11 -10
View File
@@ -1,23 +1,24 @@
import { createContext, useContext } from "react";
import { createContext, use } from "react";
import type { paths } from "@/shared/api";
type User =
paths["/api/v1/auth/me"]["get"]["responses"][200]["content"]["application/json"];
type AuthContextValue = {
user: User | null;
accessToken: string | null;
ready: boolean;
accessToken: string | undefined;
login: (email: string, password: string) => Promise<void>;
register: (email: string, password: string) => Promise<void>;
logout: () => Promise<void>;
ready: boolean;
refresh: () => Promise<boolean>;
register: (email: string, password: string) => Promise<void>;
user: undefined | User;
};
const AuthContext = createContext<AuthContextValue | null>(null);
type User
= paths["/api/v1/auth/me"]["get"]["responses"][200]["content"]["application/json"];
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
function useAuth() {
const context = useContext(AuthContext);
const context = use(AuthContext);
if (!context) throw new Error("AuthProvider is required");
return context;
}
export { AuthContext, type User, useAuth };
export { AuthContext, useAuth, type User };
+50 -81
View File
@@ -1,12 +1,15 @@
import type { FC, PropsWithChildren } from "react";
import { QueryClientProvider, useQueryClient } from "@tanstack/react-query";
import { act, renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import type { FC, PropsWithChildren } from "react";
import { http, HttpResponse } from "msw";
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 } from "./auth";
import { useAuth } from "./auth-context";
@@ -14,14 +17,22 @@ const bankCardsKey = apiQueryClient.queryOptions("get", "/api/v1/bank-cards", {
params: { query: { includeArchived: "false" } },
}).queryKey;
function createAuthWrapper(queryClient: ReturnType<typeof createTestQueryClient>): FC<PropsWithChildren> {
return props => (
<QueryClientProvider client={queryClient}>
<AuthProvider>{props.children}</AuthProvider>
</QueryClientProvider>
);
}
describe("AuthProvider", () => {
it("authorizes requests after restoring the initial session", async () => {
let authorization: string | null = null;
let authorization: null | string = /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null;
server.use(
http.post("*/api/v1/auth/refresh", () =>
HttpResponse.json({
accessToken: "restored-token",
user: { id: "user-1", email: "user@example.com" },
user: { email: "user@example.com", id: "user-1" },
}),
),
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
@@ -30,16 +41,8 @@ describe("AuthProvider", () => {
}),
);
const queryClient = createTestQueryClient();
const wrapper: FC<PropsWithChildren> = (props) => {
const { children } = props;
return (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
};
const { result, rerender } = renderHook(
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
const { rerender, result } = renderHook(
() => ({ ...useAuth(), queryClient: useQueryClient() }),
{ wrapper },
);
@@ -61,21 +64,13 @@ describe("AuthProvider", () => {
const queryClient = createTestQueryClient();
queryClient.setQueryData(["cached-query"], { value: "stale" });
queryClient.setQueryData(bankCardsKey, [{ id: "bank-card-1" }]);
const wrapper: FC<PropsWithChildren> = (props) => {
const { children } = props;
return (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
};
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(result.current.ready).toBe(true));
expect(result.current.user).toBeNull();
expect(result.current.accessToken).toBeNull();
expect(result.current.user).toBeUndefined();
expect(result.current.accessToken).toBeUndefined();
expect(queryClient.getQueryData(["cached-query"])).toBeUndefined();
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
});
@@ -88,7 +83,7 @@ describe("AuthProvider", () => {
return refreshCalls === 1
? HttpResponse.json({
accessToken: "restored-token",
user: { id: "user-1", email: "user@example.com" },
user: { email: "user@example.com", id: "user-1" },
})
: HttpResponse.error();
}),
@@ -99,15 +94,7 @@ describe("AuthProvider", () => {
const queryClient = createTestQueryClient();
queryClient.setQueryData(["cached-query"], { value: "stale" });
queryClient.setQueryData(bankCardsKey, [{ id: "bank-card-1" }]);
const wrapper: FC<PropsWithChildren> = (props) => {
const { children } = props;
return (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
};
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() =>
@@ -116,8 +103,8 @@ describe("AuthProvider", () => {
const response = await apiClient.GET("/api/v1/brokerage-accounts");
expect(response.response.status).toBe(401);
await waitFor(() => expect(result.current.user).toBeNull());
expect(result.current.accessToken).toBeNull();
await waitFor(() => expect(result.current.user).toBeUndefined());
expect(result.current.accessToken).toBeUndefined();
expect(queryClient.getQueryData(["cached-query"])).toBeUndefined();
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
});
@@ -127,7 +114,7 @@ describe("AuthProvider", () => {
http.post("*/api/v1/auth/refresh", () =>
HttpResponse.json({
accessToken: "test-token",
user: { id: "user-1", email: "user@example.com" },
user: { email: "user@example.com", id: "user-1" },
}),
),
);
@@ -147,14 +134,7 @@ describe("AuthProvider", () => {
});
queryClient.setQueryData(portfolioKey, { source: "current-connection" });
queryClient.setQueryData(bankCardsKey, [{ id: "bank-card-1" }]);
const wrapper: FC<PropsWithChildren> = (props) => {
const { children } = props;
return (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
};
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(result.current.accessToken).toBe("test-token"));
@@ -163,8 +143,8 @@ describe("AuthProvider", () => {
]);
await act(() => result.current.logout());
expect(result.current.user).toBeNull();
expect(result.current.accessToken).toBeNull();
expect(result.current.user).toBeUndefined();
expect(result.current.accessToken).toBeUndefined();
expect(queryClient.getQueryData(statusKey)).toBeUndefined();
expect(queryClient.getQueryData(portfolioKey)).toBeUndefined();
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
@@ -177,10 +157,7 @@ describe("AuthProvider", () => {
])(
"serializes late refresh (failure=%s, login=%s)",
async (failure, loginAfterLogout) => {
let release!: () => void;
const pending = new Promise<void>((resolve) => {
release = resolve;
});
const { promise: pending, resolve: release } = Promise.withResolvers<void>();
let calls = 0;
const order: string[] = [];
server.use(
@@ -194,7 +171,7 @@ describe("AuthProvider", () => {
? HttpResponse.error()
: HttpResponse.json({
accessToken: "a",
user: { id: "a", email: "a@example.com" },
user: { email: "a@example.com", id: "a" },
});
}),
http.post("*/api/v1/auth/logout", () => {
@@ -205,7 +182,7 @@ describe("AuthProvider", () => {
order.push("login-cookie");
return HttpResponse.json({
accessToken: "b",
user: { id: "b", email: "b@example.com" },
user: { email: "b@example.com", id: "b" },
});
}),
http.get("*/api/v1/brokerage-accounts", () =>
@@ -213,22 +190,20 @@ describe("AuthProvider", () => {
),
);
const queryClient = createTestQueryClient();
const wrapper: FC<PropsWithChildren> = ({ children }) => (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(result.current.ready).toBe(true));
const oldRequest = apiClient
.GET("/api/v1/brokerage-accounts")
.catch(() => null);
// eslint-disable-next-line unicorn/prefer-await -- Attach rejection handling before releasing the deliberately pending query.
.catch(() => {});
await waitFor(() => expect(order).toContain("refresh-start"));
let logout!: Promise<void>;
act(() => {
logout = result.current.logout();
});
await waitFor(() => expect(result.current.user).toBeNull());
await waitFor(() => expect(result.current.user).toBeUndefined());
let login!: Promise<void>;
act(() => {
login = loginAfterLogout
@@ -239,8 +214,8 @@ describe("AuthProvider", () => {
release();
await Promise.all([oldRequest, logout, login]);
});
expect(result.current.user?.id ?? null).toBe(
loginAfterLogout ? "b" : null,
expect(result.current.user?.id ?? /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null).toBe(
loginAfterLogout ? "b" : /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null,
);
expect(order).toEqual([
"refresh-start",
@@ -257,16 +232,12 @@ describe("AuthProvider", () => {
http.post("*/api/v1/auth/refresh", () =>
HttpResponse.json({
accessToken: identity,
user: { id: identity, email: `${identity}@example.com` },
user: { email: `${identity}@example.com`, id: identity },
}),
),
);
const queryClient = createTestQueryClient();
const wrapper: FC<PropsWithChildren> = ({ children }) => (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(result.current.ready).toBe(true));
queryClient.setQueryData(bankCardsKey, [{ id: "a-card" }]);
@@ -274,14 +245,16 @@ describe("AuthProvider", () => {
expect(queryClient.getQueryData(bankCardsKey)).toEqual([{ id: "a-card" }]);
let release!: (value: string) => void;
const pending = queryClient
.fetchQuery({
.query({
queryFn: () => {
const deferred = Promise.withResolvers<string>();
release = deferred.resolve;
return deferred.promise;
},
queryKey: ["pending-finance"],
queryFn: () =>
new Promise<string>((resolve) => {
release = resolve;
}),
})
.catch(() => null);
// eslint-disable-next-line unicorn/prefer-await -- Attach rejection handling before releasing the deliberately pending query.
.catch(() => {});
identity = "b";
await act(() => result.current.refresh());
release("a-data");
@@ -296,7 +269,7 @@ describe("AuthProvider", () => {
http.post("*/api/v1/auth/refresh", () =>
HttpResponse.json({
accessToken: identity,
user: { id: identity, email: `${identity}@example.com` },
user: { email: `${identity}@example.com`, id: identity },
}),
),
http.get("*/api/v1/bank-cards", () =>
@@ -304,11 +277,7 @@ describe("AuthProvider", () => {
),
);
const queryClient = createTestQueryClient();
const wrapper: FC<PropsWithChildren> = (props) => (
<QueryClientProvider client={queryClient}>
<AuthProvider>{props.children}</AuthProvider>
</QueryClientProvider>
);
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
const { result } = renderHook(
() => ({
auth: useAuth(),
+46 -39
View File
@@ -1,13 +1,16 @@
import { useQueryClient } from "@tanstack/react-query";
import type { FC, PropsWithChildren } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useRef, useState } from "react";
import { apiClient, configureAuthClient, type paths } from "@/shared/api";
import { AuthContext, type User } from "./auth-context";
type Authentication =
paths["/api/v1/auth/login"]["post"]["responses"][200]["content"]["application/json"];
type Credentials =
paths["/api/v1/auth/login"]["post"]["requestBody"]["content"]["application/json"];
type Authentication
= paths["/api/v1/auth/login"]["post"]["responses"][200]["content"]["application/json"];
type Credentials
= paths["/api/v1/auth/login"]["post"]["requestBody"]["content"]["application/json"];
async function request(
path: "/api/v1/auth/login" | "/api/v1/auth/register",
email: string,
@@ -24,32 +27,34 @@ async function request(
const AuthProvider: FC<PropsWithChildren> = (props) => {
const { children } = props;
const queryClient = useQueryClient();
const [user, setUser] = useState<User | null>(null);
const [accessToken, setAccessToken] = useState<string | null>(null);
const accessTokenRef = useRef<string | null>(null);
const [user, setUser] = useState<undefined | User>(undefined);
const [accessToken, setAccessToken] = useState<string | undefined>(undefined);
const accessTokenRef = useRef<string | undefined>(undefined);
const [ready, setReady] = useState(false);
const generation = useRef(0);
const userRef = useRef<User | null>(null);
const authQueue = useRef<Promise<unknown>>(Promise.resolve());
const refreshPromise = useRef<Promise<boolean> | null>(null);
const generationRef = useRef(0);
const userRef = useRef<undefined | User>(undefined);
const authQueueRef = useRef<Promise<unknown>>(Promise.resolve());
const refreshPromiseRef = useRef<Promise<boolean> | undefined>(undefined);
// Cookie-writing requests share ordering, including across tabs with Web Locks.
const serialize = useCallback(<T,>(run: () => Promise<T>): Promise<T> => {
const next = authQueue.current.then(async () =>
// eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering.
const next = authQueueRef.current.then(async () =>
"locks" in navigator
? navigator.locks.request("wealth-ledger-refresh", run)
: run(),
);
authQueue.current = next.catch(() => undefined);
// eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering.
authQueueRef.current = next.catch(() => {});
return next;
}, []);
const applyAuthentication = useCallback(
(authentication: Authentication) => {
const changedIdentity =
userRef.current && userRef.current.id !== authentication.user.id;
const changedIdentity
= userRef.current && userRef.current.id !== authentication.user.id;
accessTokenRef.current = authentication.accessToken;
if (changedIdentity) {
generation.current += 1;
generationRef.current += 1;
queryClient.removeQueries({ type: "inactive" });
queryClient.getMutationCache().clear();
void queryClient.resetQueries();
@@ -61,36 +66,38 @@ const AuthProvider: FC<PropsWithChildren> = (props) => {
[queryClient],
);
const clearSession = useCallback(() => {
generation.current += 1;
userRef.current = null;
setUser(null);
setAccessToken(null);
accessTokenRef.current = null;
generationRef.current += 1;
userRef.current = undefined;
setUser(undefined);
setAccessToken(undefined);
accessTokenRef.current = undefined;
queryClient.clear();
}, [queryClient]);
const refresh = useCallback((): Promise<boolean> => {
if (refreshPromise.current) return refreshPromise.current;
const started = generation.current;
if (refreshPromiseRef.current) return refreshPromiseRef.current;
const started = generationRef.current;
const pending = serialize(async () => {
if (started !== generation.current) return false;
if (started !== generationRef.current) return false;
try {
const { data } = await apiClient.POST("/api/v1/auth/refresh");
if (started !== generation.current) return false;
if (started !== generationRef.current) return false;
if (!data) {
clearSession();
return false;
}
applyAuthentication(data);
return true;
} catch {
if (started === generation.current) clearSession();
}
catch {
if (started === generationRef.current) clearSession();
return false;
}
// eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering.
}).finally(() => {
if (refreshPromise.current === pending) refreshPromise.current = null;
if (refreshPromiseRef.current === pending) refreshPromiseRef.current = undefined;
});
refreshPromise.current = pending;
refreshPromiseRef.current = pending;
return pending;
}, [applyAuthentication, clearSession, serialize]);
@@ -104,10 +111,10 @@ const AuthProvider: FC<PropsWithChildren> = (props) => {
password: string,
) {
clearSession();
const started = generation.current;
const started = generationRef.current;
await serialize(async () => {
const authentication = await request(path, email, password);
if (started === generation.current) applyAuthentication(authentication);
if (started === generationRef.current) applyAuthentication(authentication);
});
}
@@ -121,25 +128,25 @@ const AuthProvider: FC<PropsWithChildren> = (props) => {
useEffect(() => {
configureAuthClient({
accessToken: () => accessTokenRef.current,
generation: () => generation.current,
refresh,
clear: clearSession,
generation: () => generationRef.current,
refresh,
});
});
useEffect(() => () => configureAuthClient(null), []);
useEffect(() => () => configureAuthClient(), []);
return (
<AuthContext
value={{
user,
accessToken,
ready,
login: (email, password) =>
authenticate("/api/v1/auth/login", email, password),
logout,
ready,
refresh,
register: (email, password) =>
authenticate("/api/v1/auth/register", email, password),
logout,
refresh,
user,
}}
>
{children}
+16 -12
View File
@@ -1,6 +1,9 @@
import { z } from "zod";
import { validationMessage } from "@/shared/i18n";
const EMAIL_PART_COUNT = 2;
const ASCII_SPACE = 32;
const ASCII_DELETE = 127;
const MAX_EMAIL_LENGTH = 254;
@@ -8,10 +11,11 @@ const MIN_PASSWORD_BYTES = 12;
const MAX_PASSWORD_BYTES = 72;
function isEmailCharacterInvalid(character: string): boolean {
const codePoint = character.codePointAt(0);
return (
/\s/.test(character) ||
character.charCodeAt(0) < ASCII_SPACE ||
character.charCodeAt(0) === ASCII_DELETE
/\s/.test(character)
|| (codePoint !== undefined && codePoint < ASCII_SPACE)
|| codePoint === ASCII_DELETE
);
}
@@ -21,18 +25,18 @@ const email = z
.toLowerCase()
.max(MAX_EMAIL_LENGTH)
.refine(
(value) =>
value.split("@").length === 2 &&
value.split("@").every(Boolean) &&
!value.split("").some(isEmailCharacterInvalid),
value =>
value.split("@").length === EMAIL_PART_COUNT
&& value.split("@").every(Boolean)
&& value.split("").every(element => !isEmailCharacterInvalid(element)),
{ error: validationMessage("auth.validation.invalidEmail") },
);
const password = z
.string()
.refine(
(value) =>
new TextEncoder().encode(value).length >= MIN_PASSWORD_BYTES &&
new TextEncoder().encode(value).length <= MAX_PASSWORD_BYTES,
value =>
new TextEncoder().encode(value).length >= MIN_PASSWORD_BYTES
&& new TextEncoder().encode(value).length <= MAX_PASSWORD_BYTES,
{ error: validationMessage("auth.validation.invalidPasswordLength") },
);
@@ -42,10 +46,10 @@ const loginSchema = z.object({
passwordConfirmation: z.string().optional(),
});
const registerSchema = loginSchema.refine(
(value) => value.password === value.passwordConfirmation,
value => value.password === value.passwordConfirmation,
{
path: ["passwordConfirmation"],
error: validationMessage("auth.validation.passwordsDoNotMatch"),
path: ["passwordConfirmation"],
},
);
@@ -2,6 +2,7 @@ import { MantineProvider } from "@mantine/core";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { describe, expect, it, vi } from "vitest";
import { AuthForm } from "./AuthForm";
describe("AuthForm", () => {
@@ -10,7 +11,7 @@ describe("AuthForm", () => {
render(
<MantineProvider>
<MemoryRouter>
<AuthForm register onSubmit={onSubmit} />
<AuthForm onSubmit={onSubmit} register />
</MemoryRouter>
</MantineProvider>,
);
+9 -6
View File
@@ -1,10 +1,12 @@
import type { FC } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { Alert, Button, PasswordInput, Stack, TextInput } from "@mantine/core";
import type { FC } from "react";
import { useState } from "react";
import { FormProvider, type Resolver, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import {
type AuthFormValues,
loginSchema,
@@ -13,12 +15,12 @@ import {
import classes from "./AuthForm.module.css";
type AuthFormProps = {
register?: true;
onSubmit: (email: string, password: string) => Promise<void>;
register?: true;
};
const AuthForm: FC<AuthFormProps> = (props) => {
const { register, onSubmit } = props;
const { onSubmit, register } = props;
const { t } = useTranslation();
const schema = register ? registerSchema : loginSchema;
const methods = useForm<AuthFormValues>({
@@ -27,7 +29,7 @@ const AuthForm: FC<AuthFormProps> = (props) => {
const {
formState: { errors, isSubmitting },
} = methods;
const [submitError, setSubmitError] = useState<string | null>(null);
const [submitError, setSubmitError] = useState<null | string>(null);
return (
<FormProvider {...methods}>
<form
@@ -35,7 +37,8 @@ const AuthForm: FC<AuthFormProps> = (props) => {
setSubmitError(null);
try {
await onSubmit(values.email, values.password);
} catch {
}
catch {
setSubmitError(t("auth.requestError"));
}
})}
@@ -60,7 +63,7 @@ const AuthForm: FC<AuthFormProps> = (props) => {
/>
)}
{submitError && <Alert color="red">{submitError}</Alert>}
<Button type="submit" loading={isSubmitting}>
<Button loading={isSubmitting} type="submit">
{t(register ? "auth.register" : "auth.login")}
</Button>
<Button
@@ -1,5 +1,7 @@
import { Paper, Stack, Title } from "@mantine/core";
import type { FC, PropsWithChildren } from "react";
import { Paper, Stack, Title } from "@mantine/core";
import classes from "./AuthPageLayout.module.css";
type AuthPageLayoutProps = PropsWithChildren<{ title: string }>;
+4 -2
View File
@@ -1,5 +1,7 @@
import type { FC } from "react";
import { useLocation, useNavigate } from "react-router";
import { useAuth } from "../model/auth-context";
import { AuthForm } from "./AuthForm/AuthForm";
@@ -7,8 +9,8 @@ const LoginForm: FC = () => {
const { login } = useAuth();
const navigate = useNavigate();
const location = useLocation();
const returnTo =
(location.state as { returnTo?: string } | null)?.returnTo ?? "/accounts";
const returnTo
= (location.state as null | { returnTo?: string })?.returnTo ?? "/accounts";
return (
<AuthForm
+5 -3
View File
@@ -1,5 +1,7 @@
import type { FC } from "react";
import { useLocation, useNavigate } from "react-router";
import { useAuth } from "../model/auth-context";
import { AuthForm } from "./AuthForm/AuthForm";
@@ -7,16 +9,16 @@ const RegisterForm: FC = () => {
const { register } = useAuth();
const navigate = useNavigate();
const location = useLocation();
const returnTo =
(location.state as { returnTo?: string } | null)?.returnTo ?? "/accounts";
const returnTo
= (location.state as null | { returnTo?: string })?.returnTo ?? "/accounts";
return (
<AuthForm
register
onSubmit={async (email, password) => {
await register(email, password);
await navigate(returnTo, { replace: true });
}}
register
/>
);
};
@@ -1,5 +1,7 @@
import { describe, expect, it, vi } from "vitest";
import { resource } from "@/test/resource";
import { section } from "./section";
describe("instrument source and transport presentation", () => {
@@ -9,9 +11,9 @@ describe("instrument source and transport presentation", () => {
const data = availability === "missing" ? undefined : { rows: [] };
const state = section({
data,
meta: resource(data, { availability }).meta,
isError: false,
isFetching: false,
meta: resource(data, { availability }).meta,
refetch: vi.fn(),
});
expect(state.loading).toBe(availability === "missing");
@@ -23,37 +25,39 @@ describe("instrument source and transport presentation", () => {
const retry = vi.fn();
const refetch = vi.fn();
const meta = resource([], {
sync: { id: "work", state: "failed", errorCode: "TBANK_UNAVAILABLE" },
sync: { errorCode: "TBANK_UNAVAILABLE", id: "work", state: "failed" },
}).meta;
const state = section(
{ data: [], meta, isError: false, isFetching: false, refetch },
{ data: [], isError: false, isFetching: false, meta, refetch },
retry,
);
expect(state).toMatchObject({
hasData: true,
loading: false,
error: true,
refreshing: false,
hasData: true,
lastSuccessfulAt: meta.lastSuccessfulAt,
loading: false,
refreshing: false,
});
state.retry();
expect(retry).toHaveBeenCalledOnce();
expect(refetch).not.toHaveBeenCalled();
});
it("shows source failure without a false loading or empty result", () => {
const state = section({
data: undefined,
meta: resource(null, {
sync: { id: "work", state: "failed", errorCode: "TBANK_UNAVAILABLE" },
}).meta,
isError: false,
isFetching: false,
refetch: vi.fn(),
});
const state = section((
{
data: undefined,
isError: false,
isFetching: false,
meta: resource(null, {
sync: { errorCode: "TBANK_UNAVAILABLE", id: "work", state: "failed" },
}).meta,
refetch: vi.fn(),
}
));
expect(state).toMatchObject({
error: true,
hasData: false,
loading: false,
error: true,
});
});
});
@@ -1,46 +1,46 @@
import type { paths } from "@/shared/api";
type Meta =
paths["/api/v1/tbank-sync/{id}"]["get"]["responses"][200]["content"]["application/json"]["resources"][number];
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;
hasData: boolean;
lastSuccessfulAt?: null | string;
loading: boolean;
partial?: boolean;
refreshing: boolean;
retry: () => void;
sourceError?: boolean;
stale?: boolean;
};
function section(
query: {
data: unknown;
meta?: Meta;
isError: boolean;
isFetching: boolean;
meta?: Meta;
refetch: () => unknown;
},
retry?: () => unknown,
): SectionState {
const error = query.isError || query.meta?.sync.state === "failed";
const isError = 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,
error: isError,
hasData: Boolean(query.data),
loading: !query.data && !error,
error,
lastSuccessfulAt: query.meta?.lastSuccessfulAt,
loading: !query.data && !isError,
partial: query.meta?.availability === "partial",
refreshing:
Boolean(query.data) &&
(query.isFetching ||
query.meta?.sync.state === "running" ||
query.meta?.sync.state === "queued"),
Boolean(query.data)
&& (query.isFetching
|| query.meta?.sync.state === "running"
|| query.meta?.sync.state === "queued"),
retry: () => {
void (retry ?? query.refetch)();
},
sourceError: query.meta?.sync.state === "failed",
stale: query.meta?.freshness === "stale",
};
}
export { type SectionState, section };
export { section, type SectionState };
+25 -24
View File
@@ -1,38 +1,39 @@
import type { BrokerageOperation } from "@/entities/broker-operation";
import type { paths } from "@/shared/api";
import type { SectionState } from "./section";
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 InstrumentChartVm = {
averageLine: null | number;
candles?: Candles;
candlesState: SectionState;
chartData: ChartRow[];
hasIncompleteCandle: boolean;
period: string;
position?: Position;
priceRows: ChartRow[];
setPeriod: (value: string) => void;
};
type InstrumentEventsVm = {
eventRows: BrokerageOperation[];
filter: string;
hasPrevious: boolean;
onNext: () => void;
onPrevious: () => void;
operations?: { hasNext: boolean };
operationsState: SectionState;
setFilter: (value: string) => void;
};
type InstrumentPositionVm = {
position?: Position;
positionState: SectionState;
};
type InstrumentChartVm = {
candles?: Candles;
candlesState: SectionState;
chartData: ChartRow[];
priceRows: ChartRow[];
period: string;
setPeriod: (value: string) => void;
averageLine: number | null;
hasIncompleteCandle: boolean;
position?: Position;
};
type InstrumentEventsVm = {
operations?: { hasNext: boolean };
operationsState: SectionState;
filter: string;
setFilter: (value: string) => void;
eventRows: BrokerageOperation[];
hasPrevious: boolean;
onPrevious: () => void;
onNext: () => void;
};
type Position = NonNullable<
paths["/api/v1/stocks/{uid}/position"]["get"]["responses"][200]["content"]["application/json"]["data"]
>;
export type { InstrumentChartVm, InstrumentEventsVm, InstrumentPositionVm };
@@ -1,5 +1,6 @@
import { useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import {
brokerageOperationsQueryOptions,
type OperationCategory,
@@ -14,37 +15,38 @@ function useInstrumentOperations(
) {
const scope = `${uid}:${filter}`;
const [pagination, setPagination] = useState<{
scope: string;
cursors: string[];
}>({ scope, cursors: [] });
scope: string;
}>({ cursors: [], scope });
const cursors = pagination.scope === scope ? pagination.cursors : [];
const client = useQueryClient();
const firstPage = { instrumentUid: uid, categories, limit: 20 };
const firstPage = { categories, instrumentUid: uid, limit: 20 };
const operations = useBrokerageOperations(uid ? "all" : undefined, {
...firstPage,
cursor: cursors.at(-1),
});
const retry = (retryScreen: () => unknown) => {
if (apiErrorCode(operations.error) === "INVALID_OPERATIONS_CURSOR") {
setPagination({ scope, cursors: [] });
setPagination({ cursors: [], scope });
void client.invalidateQueries({
queryKey: brokerageOperationsQueryOptions("all", firstPage).queryKey,
exact: true,
queryKey: brokerageOperationsQueryOptions("all", firstPage).queryKey,
});
} else void retryScreen();
}
else void retryScreen();
};
return {
operations,
retry,
hasPrevious: cursors.length > 0,
onPrevious: () => setPagination({ scope, cursors: cursors.slice(0, -1) }),
onNext: () => {
if (operations.data?.nextCursor)
setPagination({
scope,
cursors: [...cursors, operations.data.nextCursor],
scope,
});
},
onPrevious: () => setPagination({ cursors: cursors.slice(0, -1), scope }),
operations,
retry,
};
}
@@ -1,3 +1,5 @@
import type { FC } from "react";
import { AreaChart } from "@mantine/charts";
import {
Accordion,
@@ -7,185 +9,187 @@ import {
Table,
Text,
} from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { formatDecimal, formatMoney } from "@/shared/lib";
import type { InstrumentChartVm } from "../model/types";
import classes from "./InstrumentDetails.module.css";
import { InstrumentSection } from "./InstrumentSection.view";
type InstrumentChartProps = { vm: InstrumentChartVm; priceUnit?: "percent" };
type InstrumentChartProps = { priceUnit?: "percent"; vm: InstrumentChartVm };
const InstrumentChart: FC<InstrumentChartProps> = (props) => {
const { vm } = props;
const { t } = useTranslation();
const priceLabel = (value: string) => {
if (props.priceUnit === "percent") return `${formatDecimal(value)} %`;
const currency = vm.candles?.currency;
return formatMoney(currency ? { currency, value } : undefined);
};
return (
<InstrumentSection
title={t("stock.chart")}
state={vm.candlesState}
large
controls={
controls={(
<div className={classes.controls}>
<SegmentedControl
aria-label={t("stock.period")}
value={vm.period}
onChange={vm.setPeriod}
data={["month", "halfYear", "year", "all"].map((value) => ({
value,
data={["month", "halfYear", "year", "all"].map(value => ({
label: t(`stock.periods.${value}`),
value,
}))}
onChange={vm.setPeriod}
value={vm.period}
/>
</div>
}
)}
large
state={vm.candlesState}
title={t("stock.chart")}
>
{vm.candles ? (
vm.chartData.length ? (
<>
<AreaChart
h={310}
data={vm.chartData}
dataKey="date"
series={[
{ name: "price", color: "blue.6", label: t("stock.price") },
]}
curveType="linear"
withDots={vm.chartData.length === 1}
withGradient
gridAxis="y"
tickLine="none"
tooltipAnimationDuration={0}
areaProps={{ isAnimationActive: false }}
yAxisProps={{ domain: ["auto", "auto"], width: 64 }}
referenceLines={
vm.averageLine === null
? []
: [
{
y: vm.averageLine,
ifOverflow: "extendDomain",
color: "orange.7",
label: t("stock.averageLine"),
},
]
}
valueFormatter={(value) =>
new Intl.NumberFormat("ru-RU", {
maximumFractionDigits: 4,
}).format(value)
}
aria-label={t(
props.priceUnit === "percent"
? "bond.chartLabel"
: "stock.chartLabel",
{
currency:
{!!(vm.candles) && ((
vm.chartData.length > 0
? (
<>
<AreaChart
areaProps={{ isAnimationActive: false }}
aria-label={t(
props.priceUnit === "percent"
? "bond.chartLabel"
: "stock.chartLabel",
{
currency:
props.priceUnit === "percent"
? t("bond.percentOfNominal")
: (vm.candles.currency ?? ""),
},
)}
/>
<Text size="xs" c="dimmed" mt="sm">
{t(
props.priceUnit === "percent"
? "bond.chartNote"
: "stock.chartNote",
)}
</Text>
{vm.hasIncompleteCandle ? (
<Text size="xs" c="dimmed">
{t("stock.incomplete")}
</Text>
) : null}
{vm.averageLine !== null ? (
<Text size="sm" mt="xs">
{t("stock.averageLine")}:{" "}
{formatMoney(vm.position?.averagePurchasePrice ?? null)}
</Text>
) : null}
<Accordion
className={classes.priceTable}
variant="contained"
radius="md"
>
<Accordion.Item value="prices">
<Accordion.Control>
<Text fw={600}>{t("stock.priceTable")}</Text>
<Text size="xs" c="dimmed">
{t("stock.priceTableHint", { count: vm.chartData.length })}
},
)}
curveType="linear"
data={vm.chartData}
dataKey="date"
gridAxis="y"
h={310}
referenceLines={
vm.averageLine === null
? []
: [
{
color: "orange.7",
ifOverflow: "extendDomain",
label: t("stock.averageLine"),
y: vm.averageLine,
},
]
}
series={[
{ color: "blue.6", label: t("stock.price"), name: "price" },
]}
tickLine="none"
tooltipAnimationDuration={0}
valueFormatter={value =>
new Intl.NumberFormat("ru-RU", {
maximumFractionDigits: 4,
}).format(value)}
withDots={vm.chartData.length === 1}
withGradient
yAxisProps={{ domain: ["auto", "auto"], width: 64 }}
/>
<Text c="dimmed" mt="sm" size="xs">
{t(
props.priceUnit === "percent"
? "bond.chartNote"
: "stock.chartNote",
)}
</Text>
{!!(vm.hasIncompleteCandle) && ((
<Text c="dimmed" size="xs">
{t("stock.incomplete")}
</Text>
</Accordion.Control>
<Accordion.Panel>
<ScrollArea.Autosize
mah={360}
type="auto"
viewportProps={{
tabIndex: 0,
role: "region",
"aria-label": t("stock.priceTable"),
}}
>
<Table
striped
highlightOnHover
stickyHeader
verticalSpacing="sm"
horizontalSpacing="md"
>
<Table.Thead>
<Table.Tr>
<Table.Th>{t("stock.date")}</Table.Th>
<Table.Th>{t("stock.price")}</Table.Th>
<Table.Th>{t("stock.candle")}</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{vm.priceRows.map((candle) => (
<Table.Tr key={candle.time}>
<Table.Td>{candle.date}</Table.Td>
<Table.Td>
{props.priceUnit === "percent"
? `${formatDecimal(candle.close)} %`
: formatMoney(
vm.candles?.currency
? {
value: candle.close,
currency: vm.candles.currency,
}
: null,
)}
</Table.Td>
<Table.Td>
<Badge
variant="light"
color={candle.isComplete ? "gray" : "blue"}
size="sm"
>
{t(
candle.isComplete
? "stock.complete"
: "stock.forming",
)}
</Badge>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
</ScrollArea.Autosize>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
</>
) : (
<Text c="dimmed">
{t(
vm.candlesState.partial
? "investment.partial"
: "stock.noCandles",
)}
</Text>
)
) : null}
))}
{vm.averageLine !== null && ((
<Text mt="xs" size="sm">
{t("stock.averageLine")}
:
{" "}
{formatMoney(vm.position?.averagePurchasePrice)}
</Text>
))}
<Accordion
className={classes.priceTable}
radius="md"
variant="contained"
>
<Accordion.Item value="prices">
<Accordion.Control>
<Text fw={600}>{t("stock.priceTable")}</Text>
<Text c="dimmed" size="xs">
{t("stock.priceTableHint", { count: vm.chartData.length })}
</Text>
</Accordion.Control>
<Accordion.Panel>
<ScrollArea.Autosize
mah={360}
type="auto"
viewportProps={{
"aria-label": t("stock.priceTable"),
"role": "region",
"tabIndex": 0,
}}
>
<Table
highlightOnHover
horizontalSpacing="md"
stickyHeader
striped
verticalSpacing="sm"
>
<Table.Thead>
<Table.Tr>
<Table.Th>{t("stock.date")}</Table.Th>
<Table.Th>{t("stock.price")}</Table.Th>
<Table.Th>{t("stock.candle")}</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{vm.priceRows.map(candle => (
<Table.Tr key={candle.time}>
<Table.Td>{candle.date}</Table.Td>
<Table.Td>
{priceLabel(candle.close)}
</Table.Td>
<Table.Td>
<Badge
color={candle.isComplete ? "gray" : "blue"}
size="sm"
variant="light"
>
{t(
candle.isComplete
? "stock.complete"
: "stock.forming",
)}
</Badge>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
</ScrollArea.Autosize>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
</>
)
: (
<Text c="dimmed">
{t(
vm.candlesState.partial
? "investment.partial"
: "stock.noCandles",
)}
</Text>
)
))}
</InstrumentSection>
);
};
@@ -1,16 +1,20 @@
import { Button, Group, SegmentedControl, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { Button, Group, SegmentedControl, Stack, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { LedgerEntryRow } from "@/entities/broker-operation";
import type { InstrumentEventsVm } from "../model/types";
import classes from "./InstrumentDetails.module.css";
import { InstrumentSection } from "./InstrumentSection.view";
type InstrumentEventsProps = {
vm: InstrumentEventsVm;
incomeLabel?: string;
incomeFilter?: string;
historyNote?: string;
incomeFilter?: string;
incomeLabel?: string;
vm: InstrumentEventsVm;
};
const InstrumentEvents: FC<InstrumentEventsProps> = (props) => {
@@ -18,73 +22,75 @@ const InstrumentEvents: FC<InstrumentEventsProps> = (props) => {
const { t } = useTranslation();
return (
<InstrumentSection
title={t("stock.history")}
state={vm.operationsState}
controls={
controls={(
<div className={classes.controls}>
<SegmentedControl
aria-label={t("stock.eventFilter")}
value={vm.filter}
onChange={vm.setFilter}
data={[
"all",
"trades",
props.incomeFilter ?? "dividends",
"other",
].map((value) => ({
value,
].map(value => ({
label:
value === (props.incomeFilter ?? "dividends") &&
props.incomeLabel
value === (props.incomeFilter ?? "dividends")
&& props.incomeLabel
? props.incomeLabel
: t(`stock.filters.${value}`),
value,
}))}
onChange={vm.setFilter}
value={vm.filter}
/>
</div>
}
)}
state={vm.operationsState}
title={t("stock.history")}
>
{vm.operations ? (
{!!(vm.operations) && ((
<>
<Text size="xs" c="dimmed">
<Text c="dimmed" size="xs">
{props.historyNote ?? t("stock.historyNote")}
</Text>
{vm.eventRows.length ? (
<Stack gap="sm" mt="md">
{vm.eventRows.map((event) => (
<LedgerEntryRow
key={`${event.account?.id}:${event.id}`}
operation={event}
withDetails
/>
))}
</Stack>
) : (
<Text c="dimmed" py="lg">
{t(
vm.operationsState.partial
? "investment.partial"
: "stock.noOperations",
{vm.eventRows.length > 0
? (
<Stack gap="sm" mt="md">
{vm.eventRows.map(event => (
<LedgerEntryRow
key={`${event.account?.id}:${event.id}`}
operation={event}
withDetails
/>
))}
</Stack>
)
: (
<Text c="dimmed" py="lg">
{t(
vm.operationsState.partial
? "investment.partial"
: "stock.noOperations",
)}
</Text>
)}
</Text>
)}
<Group justify="space-between" mt="md">
<Button
variant="default"
disabled={!vm.hasPrevious || vm.operationsState.refreshing}
onClick={vm.onPrevious}
variant="default"
>
{t("stock.previous")}
</Button>
<Button
variant="default"
disabled={!vm.operations.hasNext || vm.operationsState.refreshing}
onClick={vm.onNext}
variant="default"
>
{t("stock.next")}
</Button>
</Group>
</>
) : null}
))}
</InstrumentSection>
);
};
@@ -1,31 +1,35 @@
import { Alert, Anchor, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { Alert, Anchor, Stack, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { formatDecimal, formatMoney, formatSnapshotTime } from "@/shared/lib";
import type { InstrumentPositionVm } from "../model/types";
import classes from "./InstrumentDetails.module.css";
import { InstrumentSection } from "./InstrumentSection.view";
type InstrumentPositionProps = {
vm: InstrumentPositionVm;
returnNote?: string;
quantityLabel?: string;
returnNote?: string;
vm: InstrumentPositionVm;
};
const InstrumentPosition: FC<InstrumentPositionProps> = (props) => {
const { vm } = props;
const { t } = useTranslation();
if (vm.position && !vm.position.accounts.length) return null;
if (vm.position && vm.position.accounts.length === 0) return;
return (
<InstrumentSection title={t("stock.position")} state={vm.positionState}>
{vm.position ? (
<InstrumentSection state={vm.positionState} title={t("stock.position")}>
{!!(vm.position) && ((
<Stack gap="md">
{vm.position.isStale ? (
{!!(vm.position.isStale) && ((
<Alert color="orange">{t("portfolio.staleWarning")}</Alert>
) : null}
))}
<div className={`${classes.metrics} ${classes.holding}`}>
<div>
<Text size="sm" c="dimmed">
<Text c="dimmed" size="sm">
{props.quantityLabel ?? t("stock.quantity")}
</Text>
<Text className={classes.metricValue}>
@@ -33,7 +37,7 @@ const InstrumentPosition: FC<InstrumentPositionProps> = (props) => {
</Text>
</div>
<div>
<Text size="sm" c="dimmed">
<Text c="dimmed" size="sm">
{t("stock.value")}
</Text>
<Text className={classes.metricValue}>
@@ -41,7 +45,7 @@ const InstrumentPosition: FC<InstrumentPositionProps> = (props) => {
</Text>
</div>
<div>
<Text size="sm" c="dimmed">
<Text c="dimmed" size="sm">
{t("stock.average")}
</Text>
<Text className={classes.metricValue}>
@@ -49,89 +53,93 @@ const InstrumentPosition: FC<InstrumentPositionProps> = (props) => {
</Text>
</div>
<div>
<Text size="sm" c="dimmed">
<Text c="dimmed" size="sm">
{t("stock.openReturn")}
</Text>
<Text
className={classes.metricValue}
c={
vm.position.absoluteReturn?.value.startsWith("-")
? "red.8"
: "green.8"
}
className={classes.metricValue}
>
{formatMoney(vm.position.absoluteReturn)}
</Text>
{vm.position.returnPercent !== null ? (
{vm.position.returnPercent !== null && ((
<Text size="sm">
{formatDecimal(vm.position.returnPercent)} %
{formatDecimal(vm.position.returnPercent)}
{" "}
%
</Text>
) : null}
))}
</div>
</div>
<Text size="xs" c="dimmed">
<Text c="dimmed" size="xs">
{props.returnNote ?? t("stock.openReturnNote")}
</Text>
<div>
{vm.position.accounts.map((account) => (
{vm.position.accounts.map(account => (
<div className={classes.accountRow} key={account.account?.id}>
{account.account ? (
<Anchor
component={Link}
to={`/accounts/${encodeURIComponent(account.account.id)}`}
>
{account.account.name}
</Anchor>
) : (
<Text>{t("stock.portfolio")}</Text>
)}
{account.account
? (
<Anchor
component={Link}
to={`/accounts/${encodeURIComponent(account.account.id)}`}
>
{account.account.name}
</Anchor>
)
: (
<Text>{t("stock.portfolio")}</Text>
)}
<div>
<Text size="xs" c="dimmed">
<Text c="dimmed" size="xs">
{props.quantityLabel ?? t("stock.quantity")}
</Text>
<Text>{formatDecimal(account.quantity)}</Text>
</div>
<div>
<Text size="xs" c="dimmed">
<Text c="dimmed" size="xs">
{t("stock.average")}
</Text>
<Text>{formatMoney(account.averagePurchasePrice)}</Text>
</div>
<div>
<Text size="xs" c="dimmed">
<Text c="dimmed" size="xs">
{t("stock.value")}
</Text>
<Text>{formatMoney(account.currentValue)}</Text>
</div>
<div>
<Text size="xs" c="dimmed">
<Text c="dimmed" size="xs">
{t("stock.openReturn")}
</Text>
<Text
c={
account.absoluteReturn?.value.startsWith("-")
? "red.8"
: undefined
(account.absoluteReturn?.value.startsWith("-")) ? ("red.8") : undefined
}
>
{formatMoney(account.absoluteReturn)}
</Text>
{account.returnPercent !== null ? (
{account.returnPercent !== null && ((
<Text size="xs">
{formatDecimal(account.returnPercent)} %
{formatDecimal(account.returnPercent)}
{" "}
%
</Text>
) : null}
))}
</div>
</div>
))}
</div>
<Text size="xs" c="dimmed">
<Text c="dimmed" size="xs">
{t("stock.snapshotAt", {
date: formatSnapshotTime(vm.position.observedAt),
})}
</Text>
</Stack>
) : null}
))}
</InstrumentSection>
);
};
@@ -1,3 +1,5 @@
import type { FC, PropsWithChildren, ReactNode } from "react";
import {
Alert,
Button,
@@ -9,28 +11,31 @@ import {
Title,
} from "@mantine/core";
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";
const CHART_SKELETON_HEIGHT_PX = 280;
const SECTION_SKELETON_HEIGHT_PX = 65;
type InstrumentSectionProps = PropsWithChildren<{
title: string;
state: SectionState;
controls?: ReactNode;
large?: boolean;
embedded?: boolean;
large?: boolean;
state: SectionState;
title: string;
}>;
const InstrumentSection: FC<InstrumentSectionProps> = (props) => {
const { t } = useTranslation();
const readError = t(props.state.hasData ? "accounts.refreshError" : "stock.sectionError");
return (
<Paper
component="section"
className={props.embedded ? classes.embeddedSection : classes.section}
component="section"
withBorder={!props.embedded}
>
<Group justify="space-between" mb="md">
@@ -39,63 +44,63 @@ const InstrumentSection: FC<InstrumentSectionProps> = (props) => {
</Title>
{props.controls}
</Group>
{props.state.stale ? (
{!!(props.state.stale) && ((
<Text size="xs">{t("investment.stale")}</Text>
) : null}
{props.state.partial ? (
))}
{!!(props.state.partial) && ((
<Text role="status">{t("investment.partial")}</Text>
) : null}
{props.state.lastSuccessfulAt ? (
<Text size="xs" c="dimmed">
))}
{!!(props.state.lastSuccessfulAt) && ((
<Text c="dimmed" size="xs">
{t("investment.sourceTime", {
date: formatSnapshotTime(props.state.lastSuccessfulAt),
})}
</Text>
) : null}
{props.state.refreshing ? (
<Text role="status" size="xs" c="dimmed">
))}
{!!(props.state.refreshing) && ((
<Text c="dimmed" role="status" size="xs">
{t("accounts.refreshing")}
</Text>
) : null}
{props.state.error ? (
<Alert color="orange" mb="sm" role="status" aria-live="polite">
))}
{!!(props.state.error) && ((
<Alert aria-live="polite" color="orange" mb="sm" role="status">
<Group justify="space-between">
<Text size="sm">
{props.state.sourceError
? t("investment.syncFailed")
: props.state.hasData
? t("accounts.refreshError")
: t("stock.sectionError")}
: readError}
</Text>
<Button
disabled={props.state.refreshing}
onClick={props.state.retry}
size="xs"
variant="default"
onClick={props.state.retry}
disabled={props.state.refreshing}
>
{t("accounts.retry")}
</Button>
</Group>
</Alert>
) : null}
{props.state.loading ? (
<LoadingSkeleton
label={t("stock.loadingSection", { section: props.title })}
>
<Stack>
<Skeleton
h={
props.large
? CHART_SKELETON_HEIGHT_PX
: SECTION_SKELETON_HEIGHT_PX
}
/>
<Skeleton h={14} w="60%" />
</Stack>
</LoadingSkeleton>
) : (
props.children
)}
))}
{props.state.loading
? (
<LoadingSkeleton
label={t("stock.loadingSection", { section: props.title })}
>
<Stack>
<Skeleton
h={
props.large
? CHART_SKELETON_HEIGHT_PX
: SECTION_SKELETON_HEIGHT_PX
}
/>
<Skeleton h={14} w="60%" />
</Stack>
</LoadingSkeleton>
)
: (
props.children
)}
</Paper>
);
};
@@ -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 ?? "" } },
@@ -7,11 +7,13 @@ import {
waitFor,
within,
} 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 { createTestQueryClient } from "@/test/query";
import { server } from "@/test/server";
import { tbankConnectionQueryOptions } from "../../model/connection-boundary";
import { TbankConnectionSection } from "./TbankConnectionSection";
@@ -54,8 +56,8 @@ const unrelatedQueryKey = apiQueryClient.queryOptions(
function renderSection(client: QueryClient) {
configureAuthClient({
accessToken: () => "test-token",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
return render(
<MantineProvider>
@@ -69,12 +71,14 @@ function renderSection(client: QueryClient) {
function seededClient() {
const client = createTestQueryClient();
client.setQueryData(brokerageAccountsQueryKey, [
{
id: "account-1",
name: "Основной счет",
type: "BROKERAGE",
openedOn: null,
},
(/* 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 */),
]);
client.setQueryData(portfolioQueryKey, { source: "previous-connection" });
client.setQueryData(stockQueryKey, { source: "previous-connection" });
@@ -87,10 +91,8 @@ function seededClient() {
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" };
let finishRefetch: (() => void) | undefined;
const response = new Promise<void>((resolve) => {
finishRefetch = resolve;
});
const { promise: response, resolve: finishRefetch } = Promise.withResolvers<void>();
let reads = 0;
server.use(
http.get("*/api/v1/tbank-connection", async () => {
@@ -141,7 +143,9 @@ describe("TbankConnectionSection", () => {
reads += 1;
return reads === 1
? HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 })
: HttpResponse.json({ connected: false, connectedAt: null });
: 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 */));
}),
);
renderSection(createTestQueryClient());
@@ -238,22 +242,21 @@ describe("TbankConnectionSection", () => {
it("cancels an in-flight previous-boundary query and ignores its late response", async () => {
const client = seededClient();
let finishPrevious: ((value: { source: string }) => void) | undefined;
let aborted = false;
const previousResponse = new Promise<{ source: string }>((resolve) => {
finishPrevious = resolve;
});
let isAborted = false;
const { promise: previousResponse, resolve: finishPrevious } = Promise.withResolvers<{ source: string }>();
const previousRequest = client
.fetchQuery({
queryKey: operationsQueryKey,
.query({
queryFn: ({ signal }) => {
signal.addEventListener("abort", () => {
aborted = true;
isAborted = true;
});
return previousResponse;
},
queryKey: operationsQueryKey,
})
.catch(() => undefined);
// 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("Не подключено");
@@ -262,7 +265,7 @@ describe("TbankConnectionSection", () => {
});
fireEvent.click(screen.getByRole("button", { name: "Подключить" }));
await waitFor(() => expect(aborted).toBe(true));
await waitFor(() => expect(isAborted).toBe(true));
await previousRequest;
finishPrevious?.({ source: "previous-connection" });
await Promise.resolve();
@@ -298,10 +301,8 @@ describe("TbankConnectionSection", () => {
it("keeps DELETE recovery inside the dialog and preserves cache until successful retry", async () => {
let deletes = 0;
let finishDelete: (() => void) | undefined;
const response = new Promise<void>((resolve) => {
finishDelete = resolve;
});
const { promise: response, resolve: finishDelete } = Promise.withResolvers<void>();
server.use(
http.get("*/api/v1/tbank-connection", () =>
HttpResponse.json({
@@ -327,6 +328,7 @@ describe("TbankConnectionSection", () => {
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),
);
const confirm = within(dialog).getByRole("button", { name: /^Удалить$/ });
@@ -340,7 +342,7 @@ describe("TbankConnectionSection", () => {
document.body.tabIndex = -1;
document.body.focus();
document.body.removeAttribute("tabindex");
expect(document.activeElement).toBe(document.body);
expect(document.body).toHaveFocus();
finishDelete?.();
expect(await within(dialog).findByRole("alert")).toHaveTextContent(
@@ -1,4 +1,5 @@
import type { FC } from "react";
import {
TbankConnectionError,
TbankConnectionLoading,
@@ -9,9 +10,7 @@ import { TbankConnectionSectionLoaded } from "./TbankConnectionSectionLoaded";
const TbankConnectionSection: FC = () => {
const viewModel = useTbankConnectionViewModel();
if (viewModel.state === "loading") return <TbankConnectionLoading />;
if (viewModel.state === "error")
return <TbankConnectionError retry={viewModel.retry} />;
return <TbankConnectionSectionLoaded {...viewModel} />;
return viewModel.state === "error" ? <TbankConnectionError retry={viewModel.retry} /> : <TbankConnectionSectionLoaded {...viewModel} />;
};
export { TbankConnectionSection };
@@ -1,6 +1,7 @@
import { MantineProvider } from "@mantine/core";
import { render, screen } from "@testing-library/react";
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import {
TbankConnectionError,
TbankConnectionLoading,
@@ -23,7 +24,7 @@ describe("TbankConnectionSection state views", () => {
<TbankConnectionError retry={retry} />
</MantineProvider>,
);
screen.getByRole("button", { name: "Повторить" }).click();
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
expect(retry).toHaveBeenCalledOnce();
});
});
@@ -1,6 +1,7 @@
import type { FC } from "react";
import { Alert, Button, Skeleton } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
type TbankConnectionErrorProps = {
@@ -13,7 +14,7 @@ const TbankConnectionLoading: FC = () => {
return (
<LoadingSkeleton label={t("states.loadingTitle")}>
<Skeleton height={20} width="45%" />
<Skeleton height={36} width={140} radius="sm" />
<Skeleton height={36} radius="sm" width={140} />
</LoadingSkeleton>
);
};
@@ -24,7 +25,7 @@ const TbankConnectionError: FC<TbankConnectionErrorProps> = (props) => {
return (
<Alert color="red" title={t("tbank.statusError")}>
<Button variant="subtle" onClick={retry}>
<Button onClick={retry} variant="subtle">
{t("tbank.retry")}
</Button>
</Alert>
@@ -1,4 +1,5 @@
import { useAuthenticatedQuery } from "@/shared/api";
import { tbankConnectionQueryOptions } from "../../model/connection-boundary";
function useTbankConnectionViewModel() {
@@ -6,15 +7,14 @@ function useTbankConnectionViewModel() {
...tbankConnectionQueryOptions(),
});
if (!status.data) {
if (status.isPending) return { state: "loading" as const };
return { state: "error" as const, retry: () => status.refetch() };
return status.isPending ? { state: "loading" as const } : { retry: () => status.refetch(), state: "error" as const };
}
return {
refreshError: status.isError,
refreshing: status.isFetching,
retry: () => status.refetch(),
state: "loaded" as const,
status: status.data,
refreshing: status.isFetching,
refreshError: status.isError,
retry: () => status.refetch(),
};
}
@@ -1,3 +1,5 @@
import type { FC } from "react";
import {
Alert,
Button,
@@ -7,21 +9,22 @@ import {
Text,
} from "@mantine/core";
import { useQueryClient } from "@tanstack/react-query";
import type { FC } from "react";
import { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { apiErrorCode, apiQueryClient } from "@/shared/api";
import {
commitTbankConnectionBoundary,
type TbankConnectionStatus,
} from "../../model/connection-boundary";
type TbankConnectionSectionLoadedProps = {
status: TbankConnectionStatus;
refreshing: boolean;
refreshError: boolean;
refreshing: boolean;
retry: () => void;
status: TbankConnectionStatus;
};
const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
@@ -30,21 +33,21 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
const { status } = props;
const { t } = useTranslation();
const queryClient = useQueryClient();
const [deleteOpened, setDeleteOpened] = useState(false);
const deleteButton = useRef<HTMLButtonElement>(null);
const [requestError, setRequestError] = useState<string | null>(null);
const [isDeleteOpened, setIsDeleteOpened] = useState(false);
const removalButtonRef = useRef<HTMLButtonElement>(null);
const [requestError, setRequestError] = useState<null | string>(null);
const {
register,
handleSubmit,
reset,
formState: { errors },
handleSubmit,
register,
reset,
} = useForm<{ token: string }>();
const update = apiQueryClient.useMutation("put", "/api/v1/tbank-connection", {
onError: error => setRequestError(apiErrorCode(error) ?? "REQUEST_ERROR"),
onSuccess: (data) => {
commitTbankConnectionBoundary(queryClient, data);
reset();
},
onError: (error) => setRequestError(apiErrorCode(error) ?? "REQUEST_ERROR"),
});
const remove = apiQueryClient.useMutation(
"delete",
@@ -53,23 +56,24 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
onSuccess: () => {
commitTbankConnectionBoundary(queryClient, {
connected: false,
connectedAt: null,
connectedAt: /* eslint-disable-line unicorn/no-null -- The disconnected API snapshot requires a null connection timestamp. */ null,
});
setDeleteOpened(false);
setIsDeleteOpened(false);
},
},
);
const pending = update.isPending || remove.isPending;
const connected = status.connected;
const unavailableMessage = requestError === "TBANK_UNAVAILABLE" ? "tbank.unavailable" : "tbank.requestError";
const isPending = update.isPending || remove.isPending;
const isConnected = status.connected;
useEffect(() => {
if (deleteOpened && remove.isError) deleteButton.current?.focus();
}, [deleteOpened, remove.isError]);
if (isDeleteOpened && remove.isError) removalButtonRef.current?.focus();
}, [isDeleteOpened, remove.isError]);
return (
<Stack mt="xl">
<Text fw={600}>{t("tbank.title")}</Text>
<Text size="sm">
{connected
{isConnected
? t("tbank.connected", {
date: new Date(status.connectedAt ?? "").toLocaleDateString(
"ru-RU",
@@ -77,22 +81,22 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
})
: t("tbank.disconnected")}
</Text>
<Text size="sm" c="dimmed">
<Text c="dimmed" size="sm">
{t("tbank.hint")}
</Text>
{props.refreshing && (
<Text role="status" size="sm" c="dimmed">
<Text c="dimmed" role="status" size="sm">
{t("tbank.refreshing")}
</Text>
)}
{props.refreshError && (
<Alert color="orange" role="status" aria-live="polite">
<Alert aria-live="polite" color="orange" role="status">
<Stack gap="sm">
<Text>{t("tbank.refreshError")}</Text>
<Button
variant="default"
disabled={props.refreshing || isPending}
onClick={props.retry}
disabled={props.refreshing || pending}
variant="default"
>
{t("tbank.retry")}
</Button>
@@ -105,7 +109,7 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
update.mutate({ body: { token } });
})}
>
<fieldset disabled={pending}>
<fieldset disabled={isPending}>
<Stack>
<PasswordInput
label={t("tbank.token")}
@@ -117,23 +121,21 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
{t(
requestError === "INVALID_TBANK_TOKEN"
? "tbank.invalidToken"
: requestError === "TBANK_UNAVAILABLE"
? "tbank.unavailable"
: "tbank.requestError",
: unavailableMessage,
)}
</Alert>
)}
<Button type="submit" loading={update.isPending}>
{t(connected ? "tbank.replace" : "tbank.connect")}
<Button loading={update.isPending} type="submit">
{t(isConnected ? "tbank.replace" : "tbank.connect")}
</Button>
{connected && (
{isConnected && (
<Button
variant="outline"
color="red"
onClick={() => {
remove.reset();
setDeleteOpened(true);
setIsDeleteOpened(true);
}}
variant="outline"
>
{t("tbank.delete")}
</Button>
@@ -142,12 +144,12 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
</fieldset>
</form>
<Modal
opened={deleteOpened}
onClose={() => !pending && setDeleteOpened(false)}
closeButtonProps={{ "aria-label": t("tbank.close"), "disabled": isPending }}
closeOnClickOutside={!isPending}
closeOnEscape={!isPending}
onClose={() => !isPending && setIsDeleteOpened(false)}
opened={isDeleteOpened}
title={t("tbank.deleteTitle")}
closeOnClickOutside={!pending}
closeOnEscape={!pending}
closeButtonProps={{ "aria-label": t("tbank.close"), disabled: pending }}
>
<Stack>
<Text>{t("tbank.deleteText")}</Text>
@@ -155,11 +157,11 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
<Alert color="red">{t("tbank.requestError")}</Alert>
)}
<Button
ref={deleteButton}
color="red"
disabled={isPending}
loading={remove.isPending}
disabled={pending}
onClick={() => remove.mutate({})}
ref={removalButtonRef}
>
{t("tbank.deleteConfirm")}
</Button>