refactor: enforce frontend view model boundaries
Frontend verify / commits (pull_request) Successful in 28s
Frontend verify / security (pull_request) Successful in 10s
Frontend verify / verify (pull_request) Successful in 8m19s

This commit is contained in:
2026-09-28 18:48:23 +03:00
parent 5b69003516
commit ca0ad4f824
287 changed files with 8558 additions and 4538 deletions
+2 -2
View File
@@ -1,5 +1,5 @@
export { AuthProvider } from "./model/auth";
export { useAuth } from "./model/auth-context";
export { AuthPageLayout } from "./ui/AuthPageLayout/AuthPageLayout";
export { LoginForm } from "./ui/LoginForm";
export { RegisterForm } from "./ui/RegisterForm";
export { LoginForm } from "./ui/LoginForm/LoginForm";
export { RegisterForm } from "./ui/RegisterForm/RegisterForm";
+3
View File
@@ -11,13 +11,16 @@ type AuthContextValue = {
register: (email: string, password: string) => Promise<void>;
user: undefined | User;
};
type User
= paths["/api/v1/auth/me"]["get"]["responses"][200]["content"]["application/json"];
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
function useAuth() {
const context = use(AuthContext);
if (!context) throw new Error("AuthProvider is required");
return context;
}
@@ -12,6 +12,7 @@ const MAX_PASSWORD_BYTES = 72;
function isEmailCharacterInvalid(character: string): boolean {
const codePoint = character.codePointAt(0);
return (
/\s/.test(character)
|| (codePoint !== undefined && codePoint < ASCII_SPACE)
@@ -31,6 +32,7 @@ const email = z
&& value.split("").every(element => !isEmailCharacterInvalid(element)),
{ error: validationMessage("auth.validation.invalidEmail") },
);
const password = z
.string()
.refine(
@@ -45,6 +47,7 @@ const loginSchema = z.object({
password,
passwordConfirmation: z.string().optional(),
});
const registerSchema = loginSchema.refine(
value => value.password === value.passwordConfirmation,
{
+34 -5
View File
@@ -17,7 +17,9 @@ const bankCardsKey = apiQueryClient.queryOptions("get", "/api/v1/bank-cards", {
params: { query: { includeArchived: "false" } },
}).queryKey;
function createAuthWrapper(queryClient: ReturnType<typeof createTestQueryClient>): FC<PropsWithChildren> {
function createAuthWrapper(
queryClient: ReturnType<typeof createTestQueryClient>,
): FC<PropsWithChildren> {
return props => (
<QueryClientProvider client={queryClient}>
<AuthProvider>{props.children}</AuthProvider>
@@ -27,7 +29,10 @@ function createAuthWrapper(queryClient: ReturnType<typeof createTestQueryClient>
describe("AuthProvider", () => {
it("authorizes requests after restoring the initial session", async () => {
let authorization: null | string = /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null;
let authorization: null | string
// eslint-disable-next-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({
@@ -37,11 +42,13 @@ describe("AuthProvider", () => {
),
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
authorization = request.headers.get("Authorization");
return HttpResponse.json(resource([]));
}),
);
const queryClient = createTestQueryClient();
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
const { rerender, result } = renderHook(
() => ({ ...useAuth(), queryClient: useQueryClient() }),
{ wrapper },
@@ -80,6 +87,7 @@ describe("AuthProvider", () => {
server.use(
http.post("*/api/v1/auth/refresh", () => {
refreshCalls += 1;
return refreshCalls === 1
? HttpResponse.json({
accessToken: "restored-token",
@@ -119,15 +127,18 @@ describe("AuthProvider", () => {
),
);
const queryClient = createTestQueryClient();
const statusKey = apiQueryClient.queryOptions(
"get",
"/api/v1/tbank-connection",
).queryKey;
const portfolioKey = apiQueryClient.queryOptions(
"get",
"/api/v1/brokerage-accounts/{accountId}/portfolio",
{ params: { path: { accountId: "account-1" } } },
).queryKey;
queryClient.setQueryData(statusKey, {
connected: true,
connectedAt: "2026-08-14T00:00:00Z",
@@ -157,7 +168,9 @@ describe("AuthProvider", () => {
])(
"serializes late refresh (failure=%s, login=%s)",
async (failure, loginAfterLogout) => {
const { promise: pending, resolve: release } = Promise.withResolvers<void>();
const { promise: pending, resolve: release }
= Promise.withResolvers<void>();
let calls = 0;
const order: string[] = [];
server.use(
@@ -167,6 +180,7 @@ describe("AuthProvider", () => {
await pending;
order.push("refresh-cookie");
}
return failure && calls > 1
? HttpResponse.error()
: HttpResponse.json({
@@ -176,10 +190,12 @@ describe("AuthProvider", () => {
}),
http.post("*/api/v1/auth/logout", () => {
order.push("logout-cookie");
return new HttpResponse(null, { status: 204 });
}),
http.post("*/api/v1/auth/login", () => {
order.push("login-cookie");
return HttpResponse.json({
accessToken: "b",
user: { email: "b@example.com", id: "b" },
@@ -193,11 +209,13 @@ describe("AuthProvider", () => {
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")
// 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(() => {
@@ -214,8 +232,14 @@ describe("AuthProvider", () => {
release();
await Promise.all([oldRequest, logout, login]);
});
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(
result.current.user?.id
// eslint-disable-next-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
?? null,
).toBe(
loginAfterLogout
? "b"
: null, // eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
);
expect(order).toEqual([
"refresh-start",
@@ -244,17 +268,20 @@ describe("AuthProvider", () => {
await act(() => result.current.refresh());
expect(queryClient.getQueryData(bankCardsKey)).toEqual([{ id: "a-card" }]);
let release!: (value: string) => void;
const pending = queryClient
.query({
queryFn: () => {
const deferred = Promise.withResolvers<string>();
release = deferred.resolve;
return deferred.promise;
},
queryKey: ["pending-finance"],
})
// 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");
@@ -278,6 +305,7 @@ describe("AuthProvider", () => {
);
const queryClient = createTestQueryClient();
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
const { result } = renderHook(
() => ({
auth: useAuth(),
@@ -289,6 +317,7 @@ describe("AuthProvider", () => {
}),
{ wrapper },
);
await waitFor(() =>
expect(result.current.cards.data?.[0].id).toBe("a-card"),
);
+4 -149
View File
@@ -1,157 +1,12 @@
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"];
async function request(
path: "/api/v1/auth/login" | "/api/v1/auth/register",
email: string,
password: string,
): Promise<Authentication> {
const { data, error } = await apiClient.POST(path, {
body: { email, password },
} satisfies { body: Credentials });
// eslint-disable-next-line @typescript-eslint/only-throw-error -- Preserve generated ProblemDetails for apiErrorCode and field-error consumers.
if (error) throw error;
return data;
}
import { AuthContext } from "./auth-context";
import { useAuthProviderVm } from "./auth.vm";
const AuthProvider: FC<PropsWithChildren> = (props) => {
const { children } = props;
const queryClient = useQueryClient();
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 value = useAuthProviderVm();
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> => {
// 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(),
);
// 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;
accessTokenRef.current = authentication.accessToken;
if (changedIdentity) {
generationRef.current += 1;
queryClient.removeQueries({ type: "inactive" });
queryClient.getMutationCache().clear();
void queryClient.resetQueries();
}
userRef.current = authentication.user;
setUser(authentication.user);
setAccessToken(authentication.accessToken);
},
[queryClient],
);
const clearSession = useCallback(() => {
generationRef.current += 1;
userRef.current = undefined;
setUser(undefined);
setAccessToken(undefined);
accessTokenRef.current = undefined;
queryClient.clear();
}, [queryClient]);
const refresh = useCallback((): Promise<boolean> => {
if (refreshPromiseRef.current) return refreshPromiseRef.current;
const started = generationRef.current;
const pending = serialize(async () => {
if (started !== generationRef.current) return false;
try {
const { data } = await apiClient.POST("/api/v1/auth/refresh");
if (started !== generationRef.current) return false;
if (!data) {
clearSession();
return false;
}
applyAuthentication(data);
return true;
}
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 (refreshPromiseRef.current === pending) refreshPromiseRef.current = undefined;
});
refreshPromiseRef.current = pending;
return pending;
}, [applyAuthentication, clearSession, serialize]);
useEffect(() => {
void refresh().finally(() => setReady(true));
}, [refresh]);
async function authenticate(
path: "/api/v1/auth/login" | "/api/v1/auth/register",
email: string,
password: string,
) {
clearSession();
const started = generationRef.current;
await serialize(async () => {
const authentication = await request(path, email, password);
if (started === generationRef.current) applyAuthentication(authentication);
});
}
async function logout() {
clearSession();
await serialize(async () => {
await apiClient.POST("/api/v1/auth/logout");
});
}
useEffect(() => {
configureAuthClient({
accessToken: () => accessTokenRef.current,
clear: clearSession,
generation: () => generationRef.current,
refresh,
});
});
useEffect(() => () => configureAuthClient(), []);
return (
<AuthContext
value={{
accessToken,
login: (email, password) =>
authenticate("/api/v1/auth/login", email, password),
logout,
ready,
refresh,
register: (email, password) =>
authenticate("/api/v1/auth/register", email, password),
user,
}}
>
{children}
</AuthContext>
);
return <AuthContext value={value}>{props.children}</AuthContext>;
};
export { AuthProvider };
+173
View File
@@ -0,0 +1,173 @@
import { useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useRef, useState } from "react";
import { apiClient, configureAuthClient, type paths } from "@/shared/api";
import { 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"];
async function request(
path: "/api/v1/auth/login" | "/api/v1/auth/register",
email: string,
password: string,
): Promise<Authentication> {
const { data, error } = await apiClient.POST(path, {
body: { email, password },
} satisfies { body: Credentials });
// eslint-disable-next-line @typescript-eslint/only-throw-error -- Preserve generated ProblemDetails for apiErrorCode and field-error consumers.
if (error) throw error;
return data;
}
function useAuthProviderVm() {
const queryClient = useQueryClient();
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 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> => {
// 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(),
);
// 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;
accessTokenRef.current = authentication.accessToken;
if (changedIdentity) {
generationRef.current += 1;
queryClient.removeQueries({ type: "inactive" });
queryClient.getMutationCache().clear();
void queryClient.resetQueries();
}
userRef.current = authentication.user;
setUser(authentication.user);
setAccessToken(authentication.accessToken);
},
[queryClient],
);
const clearSession = useCallback(() => {
generationRef.current += 1;
userRef.current = undefined;
setUser(undefined);
setAccessToken(undefined);
accessTokenRef.current = undefined;
queryClient.clear();
}, [queryClient]);
const refresh = useCallback((): Promise<boolean> => {
if (refreshPromiseRef.current) return refreshPromiseRef.current;
const started = generationRef.current;
const pending = serialize(async () => {
if (started !== generationRef.current) return false;
try {
const { data } = await apiClient.POST("/api/v1/auth/refresh");
if (started !== generationRef.current) return false;
if (!data) {
clearSession();
return false;
}
applyAuthentication(data);
return true;
}
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 (refreshPromiseRef.current === pending)
refreshPromiseRef.current = undefined;
});
refreshPromiseRef.current = pending;
return pending;
}, [applyAuthentication, clearSession, serialize]);
useEffect(() => {
void refresh().finally(() => setReady(true));
}, [refresh]);
async function authenticate(
path: "/api/v1/auth/login" | "/api/v1/auth/register",
email: string,
password: string,
) {
clearSession();
const started = generationRef.current;
await serialize(async () => {
const authentication = await request(path, email, password);
if (started === generationRef.current)
applyAuthentication(authentication);
});
}
async function logout() {
clearSession();
await serialize(async () => {
await apiClient.POST("/api/v1/auth/logout");
});
}
useEffect(() => {
configureAuthClient({
accessToken: () => accessTokenRef.current,
clear: clearSession,
generation: () => generationRef.current,
refresh,
});
});
useEffect(() => () => configureAuthClient(), []);
const authContextValue = {
accessToken,
login: (email: string, password: string) =>
authenticate("/api/v1/auth/login", email, password),
logout,
ready,
refresh,
register: (email: string, password: string) =>
authenticate("/api/v1/auth/register", email, password),
user,
};
return authContextValue;
}
export { useAuthProviderVm };
+25 -17
View File
@@ -11,7 +11,7 @@ import {
type AuthFormValues,
loginSchema,
registerSchema,
} from "../../model/validation";
} from "../../model/auth.schema";
import classes from "./AuthForm.module.css";
type AuthFormProps = {
@@ -23,26 +23,33 @@ const AuthForm: FC<AuthFormProps> = (props) => {
const { onSubmit, register } = props;
const { t } = useTranslation();
const schema = register ? registerSchema : loginSchema;
const methods = useForm<AuthFormValues>({
resolver: zodResolver(schema) as Resolver<AuthFormValues>,
});
const {
formState: { errors, isSubmitting },
} = methods;
const [submitError, setSubmitError] = useState<null | string>(null);
const onSubmit2 = methods.handleSubmit(async (values) => {
setSubmitError(null);
try {
await onSubmit(values.email, values.password);
}
catch {
setSubmitError(t("auth.requestError"));
}
});
const to = register ? "/login" : "/register";
return (
<FormProvider {...methods}>
<form
onSubmit={methods.handleSubmit(async (values) => {
setSubmitError(null);
try {
await onSubmit(values.email, values.password);
}
catch {
setSubmitError(t("auth.requestError"));
}
})}
>
<form onSubmit={onSubmit2}>
<fieldset className={classes.fieldset} disabled={isSubmitting}>
<Stack>
<TextInput
@@ -50,11 +57,13 @@ const AuthForm: FC<AuthFormProps> = (props) => {
{...methods.register("email")}
error={errors.email?.message as string}
/>
<PasswordInput
label={t("auth.password")}
{...methods.register("password")}
error={errors.password?.message as string}
/>
{register && (
<PasswordInput
label={t("auth.passwordConfirmation")}
@@ -62,15 +71,14 @@ const AuthForm: FC<AuthFormProps> = (props) => {
error={errors.passwordConfirmation?.message as string}
/>
)}
{submitError && <Alert color="red">{submitError}</Alert>}
<Button loading={isSubmitting} type="submit">
{t(register ? "auth.register" : "auth.login")}
</Button>
<Button
component={Link}
to={register ? "/login" : "/register"}
variant="subtle"
>
<Button component={Link} to={to} variant="subtle">
{t(register ? "auth.haveAccount" : "auth.noAccount")}
</Button>
</Stack>
@@ -8,11 +8,13 @@ type AuthPageLayoutProps = PropsWithChildren<{ title: string }>;
const AuthPageLayout: FC<AuthPageLayoutProps> = (props) => {
const { children, title } = props;
return (
<main className={classes.page}>
<Paper className={classes.card} p="xl" radius="lg" withBorder>
<Stack gap="lg">
<Title order={1}>{title}</Title>
{children}
</Stack>
</Paper>
-25
View File
@@ -1,25 +0,0 @@
import type { FC } from "react";
import { useLocation, useNavigate } from "react-router";
import { useAuth } from "../model/auth-context";
import { AuthForm } from "./AuthForm/AuthForm";
const LoginForm: FC = () => {
const { login } = useAuth();
const navigate = useNavigate();
const location = useLocation();
const returnTo
= (location.state as null | { returnTo?: string })?.returnTo ?? "/accounts";
return (
<AuthForm
onSubmit={async (email, password) => {
await login(email, password);
await navigate(returnTo, { replace: true });
}}
/>
);
};
export { LoginForm };
@@ -0,0 +1,12 @@
import type { FC } from "react";
import { AuthForm } from "../AuthForm/AuthForm";
import { useLoginFormVm } from "./LoginForm.vm";
const LoginForm: FC = () => {
const { onSubmit } = useLoginFormVm();
return <AuthForm onSubmit={onSubmit} />;
};
export { LoginForm };
@@ -0,0 +1,28 @@
import type { ComponentProps } from "react";
import { useLocation, useNavigate } from "react-router";
import { useAuth } from "../../model/auth-context";
import { AuthForm } from "../AuthForm/AuthForm";
function useLoginFormVm() {
const { login } = useAuth();
const navigate = useNavigate();
const location = useLocation();
const returnTo
= (location.state as null
| { returnTo?: string })?.returnTo ?? "/accounts";
const onSubmit: ComponentProps<typeof AuthForm>["onSubmit"] = async (
email,
password,
) => {
await login(email, password);
await navigate(returnTo, { replace: true });
};
return { onSubmit };
}
export { useLoginFormVm };
-26
View File
@@ -1,26 +0,0 @@
import type { FC } from "react";
import { useLocation, useNavigate } from "react-router";
import { useAuth } from "../model/auth-context";
import { AuthForm } from "./AuthForm/AuthForm";
const RegisterForm: FC = () => {
const { register } = useAuth();
const navigate = useNavigate();
const location = useLocation();
const returnTo
= (location.state as null | { returnTo?: string })?.returnTo ?? "/accounts";
return (
<AuthForm
onSubmit={async (email, password) => {
await register(email, password);
await navigate(returnTo, { replace: true });
}}
register
/>
);
};
export { RegisterForm };
@@ -0,0 +1,12 @@
import type { FC } from "react";
import { AuthForm } from "../AuthForm/AuthForm";
import { useRegisterFormVm } from "./RegisterForm.vm";
const RegisterForm: FC = () => {
const { onSubmit } = useRegisterFormVm();
return <AuthForm onSubmit={onSubmit} register />;
};
export { RegisterForm };
@@ -0,0 +1,28 @@
import type { ComponentProps } from "react";
import { useLocation, useNavigate } from "react-router";
import { useAuth } from "../../model/auth-context";
import { AuthForm } from "../AuthForm/AuthForm";
function useRegisterFormVm() {
const { register } = useAuth();
const navigate = useNavigate();
const location = useLocation();
const returnTo
= (location.state as null
| { returnTo?: string })?.returnTo ?? "/accounts";
const onSubmit: ComponentProps<typeof AuthForm>["onSubmit"] = async (
email,
password,
) => {
await register(email, password);
await navigate(returnTo, { replace: true });
};
return { onSubmit, register };
}
export { useRegisterFormVm };
+1 -1
View File
@@ -1,6 +1,6 @@
export { section } from "./model/section";
export { useInstrumentOperations } from "./model/useInstrumentOperations";
export { InstrumentChart } from "./ui/InstrumentChart.view";
export { InstrumentChart } from "./ui/InstrumentChart/InstrumentChart.view";
export { InstrumentEvents } from "./ui/InstrumentEvents.view";
export { InstrumentPosition } from "./ui/InstrumentPosition.view";
export { InstrumentSection } from "./ui/InstrumentSection.view";
@@ -9,6 +9,7 @@ describe("instrument source and transport presentation", () => {
"keeps %s separate from successful transport",
(availability) => {
const data = availability === "missing" ? undefined : { rows: [] };
const state = section({
data,
isError: false,
@@ -16,6 +17,7 @@ describe("instrument source and transport presentation", () => {
meta: resource(data, { availability }).meta,
refetch: vi.fn(),
});
expect(state.loading).toBe(availability === "missing");
expect(state.partial).toBe(availability === "partial");
expect(state.hasData).toBe(availability !== "missing");
@@ -24,13 +26,16 @@ describe("instrument source and transport presentation", () => {
it("preserves a full fresh source and timestamp when force fails, while offering scoped retry", () => {
const retry = vi.fn();
const refetch = vi.fn();
const meta = resource([], {
sync: { errorCode: "TBANK_UNAVAILABLE", id: "work", state: "failed" },
}).meta;
const state = section(
{ data: [], isError: false, isFetching: false, meta, refetch },
retry,
);
expect(state).toMatchObject({
error: true,
hasData: true,
@@ -43,17 +48,16 @@ describe("instrument source and transport presentation", () => {
expect(refetch).not.toHaveBeenCalled();
});
it("shows source failure without a false loading or empty result", () => {
const state = section((
{
data: undefined,
isError: false,
isFetching: false,
meta: resource(null, {
sync: { errorCode: "TBANK_UNAVAILABLE", id: "work", state: "failed" },
}).meta,
refetch: vi.fn(),
}
));
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,
@@ -2,6 +2,7 @@ import type { paths } from "@/shared/api";
type Meta
= paths["/api/v1/tbank-sync/{id}"]["get"]["responses"][200]["content"]["application/json"]["resources"][number];
type SectionState = {
error: boolean;
hasData: boolean;
@@ -13,6 +14,7 @@ type SectionState = {
sourceError?: boolean;
stale?: boolean;
};
function section(
query: {
data: unknown;
@@ -24,6 +26,7 @@ function section(
retry?: () => unknown,
): SectionState {
const isError = query.isError || query.meta?.sync.state === "failed";
return {
error: isError,
hasData: Boolean(query.data),
@@ -6,7 +6,9 @@ import type { SectionState } from "./section";
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;
@@ -18,6 +20,7 @@ type InstrumentChartVm = {
priceRows: ChartRow[];
setPeriod: (value: string) => void;
};
type InstrumentEventsVm = {
eventRows: BrokerageOperation[];
filter: string;
@@ -28,10 +31,12 @@ type InstrumentEventsVm = {
operationsState: SectionState;
setFilter: (value: string) => void;
};
type InstrumentPositionVm = {
position?: Position;
positionState: SectionState;
};
type Position = NonNullable<
paths["/api/v1/stocks/{uid}/position"]["get"]["responses"][200]["content"]["application/json"]["data"]
>;
@@ -14,19 +14,28 @@ function useInstrumentOperations(
categories: OperationCategory[],
) {
const scope = `${uid}:${filter}`;
const [pagination, setPagination] = useState<{
cursors: string[];
scope: string;
}>({ cursors: [], scope });
const cursors = pagination.scope === scope ? pagination.cursors : [];
const client = useQueryClient();
const firstPage = { categories, instrumentUid: uid, limit: 20 };
const operations = useBrokerageOperations(uid ? "all" : undefined, {
...firstPage,
cursor: cursors.at(-1),
});
const retry = (retryScreen: () => unknown) => {
if (isApiErrorCode(apiErrorCode(operations.error), ApiErrorCode.InvalidOperationsCursor)) {
if (
isApiErrorCode(
apiErrorCode(operations.error),
ApiErrorCode.InvalidOperationsCursor,
)
) {
setPagination({ cursors: [], scope });
void client.invalidateQueries({
exact: true,
@@ -35,6 +44,7 @@ function useInstrumentOperations(
}
else void retryScreen();
};
return {
hasPrevious: cursors.length > 0,
onNext: () => {
@@ -1,197 +0,0 @@
import type { FC } from "react";
import { AreaChart } from "@mantine/charts";
import {
Accordion,
Badge,
ScrollArea,
SegmentedControl,
Table,
Text,
} from "@mantine/core";
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 = { 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
controls={(
<div className={classes.controls}>
<SegmentedControl
aria-label={t("stock.period")}
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 > 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 ?? ""),
},
)}
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>
))}
{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>
);
};
export { InstrumentChart };
@@ -0,0 +1,195 @@
import type { FC } from "react";
import { AreaChart } from "@mantine/charts";
import {
Accordion,
Badge,
ScrollArea,
SegmentedControl,
Table,
Text,
} from "@mantine/core";
import { formatMoney } from "@/shared/lib";
import type { InstrumentChartVm } from "../../model/types";
import classes from "../InstrumentDetails.module.css";
import { InstrumentSection } from "../InstrumentSection.view";
import { useInstrumentChartVm } from "./InstrumentChart.vm";
type InstrumentChartProps = { priceUnit?: "percent"; vm: InstrumentChartVm };
const InstrumentChart: FC<InstrumentChartProps> = (props) => {
const {
chartLabel,
formatChartValue,
periodOptions,
priceRows,
referenceLines,
t,
vm,
} = useInstrumentChartVm(props);
let chartContent;
if (vm.candles) {
if (vm.chartData.length > 0) {
chartContent = (
<>
<AreaChart
areaProps={{ isAnimationActive: false }}
aria-label={chartLabel}
curveType="linear"
data={vm.chartData}
dataKey="date"
gridAxis="y"
h={310}
referenceLines={referenceLines}
series={[
{ color: "blue.6", label: t("stock.price"), name: "price" },
]}
tickLine="none"
tooltipAnimationDuration={0}
valueFormatter={formatChartValue}
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>
)}
{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>
{priceRows.map((candle) => {
const displayColor = candle.isComplete
? "gray"
: "blue";
return (
<Table.Tr key={candle.time}>
<Table.Td>{candle.date}</Table.Td>
<Table.Td>
{candle.price}
</Table.Td>
<Table.Td>
<Badge
color={displayColor}
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>
</>
);
}
else {
chartContent = (
<Text c="dimmed">
{t(
vm.candlesState.partial
? "investment.partial"
: "stock.noCandles",
)}
</Text>
);
}
}
return (
<InstrumentSection
controls={(
<div className={classes.controls}>
<SegmentedControl
aria-label={t("stock.period")}
data={periodOptions}
onChange={vm.setPeriod}
value={vm.period}
/>
</div>
)}
large
state={vm.candlesState}
title={t("stock.chart")}
>
{chartContent}
</InstrumentSection>
);
};
export { InstrumentChart };
@@ -0,0 +1,64 @@
import { useTranslation } from "react-i18next";
import { formatChartValue, formatDecimal, formatMoney } from "@/shared/lib";
import type { InstrumentChartVm } from "../../model/types";
type InstrumentChartProps = { priceUnit?: "percent"; vm: InstrumentChartVm };
function useInstrumentChartVm(props: InstrumentChartProps) {
const { vm } = props;
const { t } = useTranslation();
const priceRows = vm.priceRows.map((candle) => {
const currency = vm.candles?.currency;
const value = candle.close;
const amount = currency ? { currency, value } : undefined;
const price = props.priceUnit === "percent"
? `${formatDecimal(value)} %`
: formatMoney(amount);
return { ...candle, price };
});
const periodOptions = ["month", "halfYear", "year", "all"].map(value => ({
label: t(`stock.periods.${value}`),
value,
}));
const chartLabel = t(
props.priceUnit === "percent" ? "bond.chartLabel" : "stock.chartLabel",
{
currency:
props.priceUnit === "percent"
? t("bond.percentOfNominal")
: (vm.candles?.currency ?? ""),
},
);
const referenceLines
= vm.averageLine === null
? []
: [
{
color: "orange.7",
ifOverflow: "extendDomain" as const,
label: t("stock.averageLine"),
y: vm.averageLine,
},
];
return {
chartLabel,
formatChartValue,
periodOptions,
priceRows,
referenceLines,
t,
vm,
};
}
export { useInstrumentChartVm };
@@ -20,25 +20,54 @@ type InstrumentEventsProps = {
const InstrumentEvents: FC<InstrumentEventsProps> = (props) => {
const { vm } = props;
const { t } = useTranslation();
const options = [
"all",
"trades",
props.incomeFilter ?? "dividends",
"other",
].map(value => ({
label:
value === (props.incomeFilter ?? "dividends") && props.incomeLabel
? props.incomeLabel
: t(`stock.filters.${value}`),
value,
}));
let eventsContent;
if (vm.eventRows.length > 0) {
eventsContent = (
<Stack gap="sm" mt="md">
{vm.eventRows.map(event => (
<LedgerEntryRow
key={`${event.account?.id}:${event.id}`}
operation={event}
withDetails
/>
))}
</Stack>
);
}
else {
eventsContent = (
<Text c="dimmed" py="lg">
{t(
vm.operationsState.partial
? "investment.partial"
: "stock.noOperations",
)}
</Text>
);
}
return (
<InstrumentSection
controls={(
<div className={classes.controls}>
<SegmentedControl
aria-label={t("stock.eventFilter")}
data={[
"all",
"trades",
props.incomeFilter ?? "dividends",
"other",
].map(value => ({
label:
value === (props.incomeFilter ?? "dividends")
&& props.incomeLabel
? props.incomeLabel
: t(`stock.filters.${value}`),
value,
}))}
data={options}
onChange={vm.setFilter}
value={vm.filter}
/>
@@ -47,32 +76,14 @@ const InstrumentEvents: FC<InstrumentEventsProps> = (props) => {
state={vm.operationsState}
title={t("stock.history")}
>
{!!(vm.operations) && ((
{!!vm.operations && (
<>
<Text c="dimmed" size="xs">
{props.historyNote ?? t("stock.historyNote")}
</Text>
{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>
)}
{eventsContent}
<Group justify="space-between" mt="md">
<Button
disabled={!vm.hasPrevious || vm.operationsState.refreshing}
@@ -81,6 +92,7 @@ const InstrumentEvents: FC<InstrumentEventsProps> = (props) => {
>
{t("stock.previous")}
</Button>
<Button
disabled={!vm.operations.hasNext || vm.operationsState.refreshing}
onClick={vm.onNext}
@@ -90,7 +102,7 @@ const InstrumentEvents: FC<InstrumentEventsProps> = (props) => {
</Button>
</Group>
</>
))}
)}
</InstrumentSection>
);
};
@@ -16,130 +16,148 @@ type InstrumentPositionProps = {
returnNote?: string;
vm: InstrumentPositionVm;
};
const InstrumentPosition: FC<InstrumentPositionProps> = (props) => {
const { vm } = props;
const { t } = useTranslation();
if (vm.position && vm.position.accounts.length === 0) return;
const positionReturnColor = vm.position?.absoluteReturn?.value.startsWith("-")
? "red.8"
: "green.8";
return (
<InstrumentSection state={vm.positionState} title={t("stock.position")}>
{!!(vm.position) && ((
{!!vm.position && (
<Stack gap="md">
{!!(vm.position.isStale) && ((
{!!vm.position.isStale && (
<Alert color="orange">{t("portfolio.staleWarning")}</Alert>
))}
)}
<div className={`${classes.metrics} ${classes.holding}`}>
<div>
<Text c="dimmed" size="sm">
{props.quantityLabel ?? t("stock.quantity")}
</Text>
<Text className={classes.metricValue}>
{formatDecimal(vm.position.quantity)}
</Text>
</div>
<div>
<Text c="dimmed" size="sm">
{t("stock.value")}
</Text>
<Text className={classes.metricValue}>
{formatMoney(vm.position.currentValue)}
</Text>
</div>
<div>
<Text c="dimmed" size="sm">
{t("stock.average")}
</Text>
<Text className={classes.metricValue}>
{formatMoney(vm.position.averagePurchasePrice)}
</Text>
</div>
<div>
<Text c="dimmed" size="sm">
{t("stock.openReturn")}
</Text>
<Text
c={
vm.position.absoluteReturn?.value.startsWith("-")
? "red.8"
: "green.8"
}
className={classes.metricValue}
>
<Text c={positionReturnColor} 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>
))}
)}
</div>
</div>
<Text c="dimmed" size="xs">
{props.returnNote ?? t("stock.openReturnNote")}
</Text>
<div>
{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>
)}
<div>
<Text c="dimmed" size="xs">
{props.quantityLabel ?? t("stock.quantity")}
</Text>
<Text>{formatDecimal(account.quantity)}</Text>
</div>
<div>
<Text c="dimmed" size="xs">
{t("stock.average")}
</Text>
<Text>{formatMoney(account.averagePurchasePrice)}</Text>
</div>
<div>
<Text c="dimmed" size="xs">
{t("stock.value")}
</Text>
<Text>{formatMoney(account.currentValue)}</Text>
</div>
<div>
<Text c="dimmed" size="xs">
{t("stock.openReturn")}
</Text>
<Text
c={
(account.absoluteReturn?.value.startsWith("-")) ? ("red.8") : undefined
}
>
{formatMoney(account.absoluteReturn)}
</Text>
{account.returnPercent !== null && ((
<Text size="xs">
{formatDecimal(account.returnPercent)}
{" "}
%
{vm.position.accounts.map((account) => {
const accountReturnColor = account.absoluteReturn?.value.startsWith("-")
? "red.8"
: undefined;
return (
<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>
)}
<div>
<Text c="dimmed" size="xs">
{props.quantityLabel ?? t("stock.quantity")}
</Text>
))}
<Text>{formatDecimal(account.quantity)}</Text>
</div>
<div>
<Text c="dimmed" size="xs">
{t("stock.average")}
</Text>
<Text>{formatMoney(account.averagePurchasePrice)}</Text>
</div>
<div>
<Text c="dimmed" size="xs">
{t("stock.value")}
</Text>
<Text>{formatMoney(account.currentValue)}</Text>
</div>
<div>
<Text c="dimmed" size="xs">
{t("stock.openReturn")}
</Text>
<Text c={accountReturnColor}>
{formatMoney(account.absoluteReturn)}
</Text>
{account.returnPercent !== null && (
<Text size="xs">
{formatDecimal(account.returnPercent)} %
</Text>
)}
</div>
</div>
</div>
))}
);
})}
</div>
<Text c="dimmed" size="xs">
{t("stock.snapshotAt", {
date: formatSnapshotTime(vm.position.observedAt),
})}
</Text>
</Stack>
))}
)}
</InstrumentSection>
);
};
@@ -29,12 +29,46 @@ type InstrumentSectionProps = PropsWithChildren<{
state: SectionState;
title: string;
}>;
const InstrumentSection: FC<InstrumentSectionProps> = (props) => {
const { t } = useTranslation();
const readError = t(props.state.hasData ? "accounts.refreshError" : "stock.sectionError");
const readError = t(
props.state.hasData ? "accounts.refreshError" : "stock.sectionError",
);
const sectionClassName = props.embedded
? classes.embeddedSection
: classes.section;
const skeletonHeight = props.large
? CHART_SKELETON_HEIGHT_PX
: SECTION_SKELETON_HEIGHT_PX;
let sectionContent;
if (props.state.loading) {
sectionContent = (
<LoadingSkeleton
label={t("stock.loadingSection", { section: props.title })}
>
<Stack>
<Skeleton h={skeletonHeight} />
<Skeleton h={14} w="60%" />
</Stack>
</LoadingSkeleton>
);
}
else {
sectionContent = (
props.children
);
}
return (
<Paper
className={props.embedded ? classes.embeddedSection : classes.section}
className={sectionClassName}
component="section"
withBorder={!props.embedded}
>
@@ -42,34 +76,37 @@ const InstrumentSection: FC<InstrumentSectionProps> = (props) => {
<Title order={2} size="h3">
{props.title}
</Title>
{props.controls}
</Group>
{!!(props.state.stale) && ((
<Text size="xs">{t("investment.stale")}</Text>
))}
{!!(props.state.partial) && ((
{!!props.state.stale && <Text size="xs">{t("investment.stale")}</Text>}
{!!props.state.partial && (
<Text role="status">{t("investment.partial")}</Text>
))}
{!!(props.state.lastSuccessfulAt) && ((
)}
{!!props.state.lastSuccessfulAt && (
<Text c="dimmed" size="xs">
{t("investment.sourceTime", {
date: formatSnapshotTime(props.state.lastSuccessfulAt),
})}
</Text>
))}
{!!(props.state.refreshing) && ((
)}
{!!props.state.refreshing && (
<Text c="dimmed" role="status" size="xs">
{t("accounts.refreshing")}
</Text>
))}
{!!(props.state.error) && ((
)}
{!!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")
: readError}
{props.state.sourceError ? t("investment.syncFailed") : readError}
</Text>
<Button
disabled={props.state.refreshing}
onClick={props.state.retry}
@@ -80,27 +117,9 @@ const InstrumentSection: FC<InstrumentSectionProps> = (props) => {
</Button>
</Group>
</Alert>
))}
{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
)}
)}
{sectionContent}
</Paper>
);
};
@@ -31,6 +31,7 @@ function commitTbankConnectionBoundary(
void queryClient.resetQueries({
predicate: ({ queryKey }) => {
const [method, path] = queryKey;
return (
method === "get"
&& typeof path === "string"
@@ -19,11 +19,14 @@ function auth() {
refresh: () => Promise.resolve(true),
});
}
describe("page-owned screen synchronization", () => {
it("ignores a late sync acceptance after the account scope changes", async () => {
auth();
const { promise: blocked, resolve: release } = Promise.withResolvers<void>();
const { promise: blocked, resolve: release }
= Promise.withResolvers<void>();
const posted: string[] = [];
const polled: string[] = [];
server.use(
@@ -32,8 +35,10 @@ describe("page-owned screen synchronization", () => {
accountId: string;
screen: "account";
};
posted.push(scope.accountId);
await blocked;
return HttpResponse.json(
{ id: scope.accountId, now: "2026-09-25T00:00:00Z", scope },
{ status: 202 },
@@ -41,6 +46,7 @@ describe("page-owned screen synchronization", () => {
}),
http.get("*/api/v1/tbank-sync/:id", ({ params }) => {
polled.push(String(params.id));
return HttpResponse.json({
id: params.id,
resources: [],
@@ -48,6 +54,7 @@ describe("page-owned screen synchronization", () => {
});
}),
);
const { rerender, result } = renderHook(
({ accountId }) => useScreenSync({ accountId, screen: "account" }, []),
{
@@ -55,6 +62,7 @@ describe("page-owned screen synchronization", () => {
wrapper: createQueryWrapper().wrapper,
},
);
let pending!: Promise<void>;
act(() => {
pending = result.current.refresh();
@@ -79,6 +87,7 @@ describe("page-owned screen synchronization", () => {
server.use(
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
modes.push(new URL(request.url).searchParams.get("sync"));
return isUnavailable
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
: HttpResponse.json(
@@ -87,14 +96,17 @@ describe("page-owned screen synchronization", () => {
}),
http.post("*/api/v1/tbank-sync", () => {
posts += 1;
return new HttpResponse(null, { status: 500 });
}),
);
const { queryClient, wrapper } = createQueryWrapper();
const { result } = renderHook(
() => {
const accounts = useBrokerageAccounts();
const disabled = useStockQuote("");
return {
accounts,
disabled,
@@ -103,6 +115,7 @@ describe("page-owned screen synchronization", () => {
},
{ wrapper },
);
if (cached) {
await waitFor(() =>
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
@@ -111,6 +124,7 @@ describe("page-owned screen synchronization", () => {
isUnavailable = true;
await act(() => result.current.accounts.refetch());
}
await waitFor(() => expect(result.current.accounts.isError).toBe(true));
isUnavailable = false;
await act(() => result.current.sync.retry());
@@ -119,7 +133,14 @@ describe("page-owned screen synchronization", () => {
cached ? "3" : "2",
);
expect(modes).toEqual(
cached ? [null, /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null, "observe"] : [null, "observe"],
cached
? [
null, // eslint-disable-line unicorn/no-null -- Preserve explicit null in the API fixture.
// eslint-disable-next-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
null,
"observe",
]
: [null, "observe"], // eslint-disable-line unicorn/no-null -- Preserve explicit null in the API fixture.
);
expect(posts).toBe(0);
expect(result.current.disabled.data).toBeUndefined();
@@ -141,7 +162,9 @@ describe("page-owned screen synchronization", () => {
async (boundary, pending) => {
auth();
const { promise: blocked, resolve: release } = Promise.withResolvers<void>();
const { promise: blocked, resolve: release }
= Promise.withResolvers<void>();
let isRecovering = false;
let isChanged = false;
server.use(
@@ -154,18 +177,22 @@ describe("page-owned screen synchronization", () => {
: HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 });
isRecovering = true;
await blocked;
return HttpResponse.json(resource([], { stateVersion: "old" }));
}),
);
const { queryClient, wrapper } = createQueryWrapper();
const published: unknown[] = [];
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
if (event.type === "updated" && event.action.type === "success")
published.push(event.query.state.data);
});
const { result } = renderHook(
() => {
const accounts = useBrokerageAccounts();
return {
accounts,
sync: useScreenSync({ screen: "accounts" }, [accounts]),
@@ -173,6 +200,7 @@ describe("page-owned screen synchronization", () => {
},
{ wrapper },
);
await waitFor(() => expect(result.current.accounts.isError).toBe(true));
let recovery!: Promise<void>;
act(() => {
@@ -182,6 +210,7 @@ describe("page-owned screen synchronization", () => {
if (pending) await waitFor(() => expect(isRecovering).toBe(true));
await act(async () => {
isChanged = true;
switch (boundary) {
case "access": {
invalidateResourceAccess(queryClient, "brokerage", {
@@ -190,24 +219,29 @@ describe("page-owned screen synchronization", () => {
break;
}
case "logout": {
configureAuthClient();
queryClient.clear();
break;
}
case "session": {
auth();
queryClient.clear();
break;
}
case "connection": { commitTbankConnectionBoundary(queryClient, {
connected: true,
connectedAt: "2026-09-27T00:00:00Z",
});
case "connection": {
commitTbankConnectionBoundary(queryClient, {
connected: true,
connectedAt: "2026-09-27T00:00:00Z",
});
}
}
release();
await recovery;
});
@@ -233,6 +267,7 @@ describe("page-owned screen synchronization", () => {
server.use(
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
modes.push(new URL(request.url).searchParams.get("sync"));
return modes.length === 1
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
: HttpResponse.json(resource([]));
@@ -242,6 +277,7 @@ describe("page-owned screen synchronization", () => {
),
http.get("*/api/v1/tbank-sync/:id", () => {
polls += 1;
return retryStatus && polls === 1
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
: HttpResponse.json({
@@ -252,10 +288,12 @@ describe("page-owned screen synchronization", () => {
}),
);
const { queryClient, wrapper } = createQueryWrapper();
const { result } = renderHook(
() => {
const accounts = useBrokerageAccounts();
const disabled = useStockQuote("");
return {
accounts,
sync: useScreenSync({ screen: "accounts" }, [accounts, disabled]),
@@ -263,9 +301,11 @@ describe("page-owned screen synchronization", () => {
},
{ wrapper },
);
await waitFor(() => expect(result.current.accounts.isError).toBe(true));
expect(result.current.accounts.meta).toBeUndefined();
await act(() => result.current.sync.refresh());
if (retryStatus) {
await waitFor(() =>
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
@@ -273,6 +313,7 @@ describe("page-owned screen synchronization", () => {
);
await act(() => result.current.sync.retry());
}
await waitFor(() => expect(result.current.accounts.isSuccess).toBe(true));
expect(result.current.accounts.data).toEqual([]);
// eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response.
@@ -290,16 +331,20 @@ describe("page-owned screen synchronization", () => {
const bodies: unknown[] = [];
let isCompleted = false;
let polls = 0;
const meta = () =>
resource([], { stateVersion: isCompleted ? "2" : "1" }).meta;
server.use(
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
modes.push(new URL(request.url).searchParams.get("sync"));
return HttpResponse.json(resource([], meta()));
}),
http.post("*/api/v1/tbank-sync", async ({ request }) => {
bodies.push(await request.json());
isCompleted = true;
return HttpResponse.json(
{
id: "screen",
@@ -311,7 +356,10 @@ describe("page-owned screen synchronization", () => {
}),
http.get("*/api/v1/tbank-sync/:id", () => {
polls++;
return HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
return HttpResponse.json(
{
errorCode: null,
id: "screen",
@@ -320,13 +368,16 @@ describe("page-owned screen synchronization", () => {
resources: [meta()],
scope: { screen: "accounts" },
state: "succeeded",
}
/* eslint-enable unicorn/no-null */));
},
/* eslint-enable unicorn/no-null */
);
}),
);
const { result, unmount } = renderHook(
() => {
const accounts = useBrokerageAccounts();
return {
accounts,
sync: useScreenSync({ screen: "accounts" }, [accounts]),
@@ -334,6 +385,7 @@ describe("page-owned screen synchronization", () => {
},
{ wrapper: createQueryWrapper().wrapper },
);
await waitFor(() => expect(result.current.accounts.data).toEqual([]));
await act(async () => {
await Promise.all([
@@ -348,6 +400,7 @@ describe("page-owned screen synchronization", () => {
// eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response.
expect(modes).toEqual([null, "observe"]);
vi.useFakeTimers();
try {
await act(() => vi.advanceTimersByTimeAsync(120_000));
expect(polls).toBe(1);
@@ -365,26 +418,36 @@ describe("page-owned screen synchronization", () => {
"publishes completed empty coverage while history runs, then stops on %s",
async (boundary) => {
vi.useFakeTimers({ toFake: ["Date"] });
try {
auth();
let isCompleted = false;
let polls = 0;
const modes: (null | string)[] = [];
const snapshot = () =>
resource(isCompleted ? [] : /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null, (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
resource(
isCompleted
? []
: null, // eslint-disable-line unicorn/no-null -- Preserve the nullable API fixture.
{
stateVersion: isCompleted ? "covered" : "initial",
sync: { errorCode: null, id: "history", state: "running" },
}
/* eslint-enable unicorn/no-null */));
sync: { errorCode: null, id: "history", state: "running" }, // eslint-disable-line unicorn/no-null -- Preserve explicit null in the API fixture.
},
);
server.use(
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
modes.push(new URL(request.url).searchParams.get("sync"));
return HttpResponse.json(snapshot());
}),
http.get("*/api/v1/tbank-sync/:id", () => {
polls++;
return HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
return HttpResponse.json(
{
errorCode: null,
id: "history",
@@ -397,13 +460,16 @@ describe("page-owned screen synchronization", () => {
resources: [snapshot().meta],
scope: null,
state: "running",
}
/* eslint-enable unicorn/no-null */));
},
/* eslint-enable unicorn/no-null */
);
}),
);
const { result, unmount } = renderHook(
() => {
const accounts = useBrokerageAccounts();
return {
accounts,
sync: useScreenSync({ screen: "accounts" }, [accounts]),
@@ -411,6 +477,7 @@ describe("page-owned screen synchronization", () => {
},
{ wrapper: createQueryWrapper().wrapper },
);
await waitFor(() =>
expect(result.current.accounts.meta?.sync.id).toBe("history"),
);
@@ -447,20 +514,25 @@ describe("page-owned screen synchronization", () => {
server.use(
http.get("*/api/v1/brokerage-accounts", () =>
HttpResponse.json(
resource([], (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
resource(
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
[],
{
sync: { errorCode: null, id: "revoked", state: "running" },
}
/* eslint-enable unicorn/no-null */)),
},
/* eslint-enable unicorn/no-null */
),
),
),
http.get("*/api/v1/tbank-sync/:id", () =>
HttpResponse.json({ code: "INVALID_TBANK_TOKEN" }, { status: 400 }),
),
);
const { result } = renderHook(
() => {
const accounts = useBrokerageAccounts();
return {
accounts,
sync: useScreenSync({ screen: "accounts" }, [accounts]),
@@ -468,6 +540,7 @@ describe("page-owned screen synchronization", () => {
},
{ wrapper: createQueryWrapper().wrapper },
);
await waitFor(() => expect(result.current.accounts.isError).toBe(true));
expect(result.current.accounts.data).toBeUndefined();
});
@@ -475,7 +548,10 @@ describe("page-owned screen synchronization", () => {
auth();
let isObserved = false;
const modes: (null | string)[] = [];
const dependency = resource([], (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
const dependency = resource(
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
[],
{
resourceKey: "operations",
stateVersion: isObserved ? "covered" : "initial",
@@ -484,24 +560,36 @@ describe("page-owned screen synchronization", () => {
id: "dependency",
state: isObserved ? "idle" : "running",
},
}
/* eslint-enable unicorn/no-null */)).meta;
},
/* eslint-enable unicorn/no-null */
).meta;
server.use(
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
const mode = new URL(request.url).searchParams.get("sync");
modes.push(mode);
if (mode) isObserved = true;
return HttpResponse.json(
resource(isObserved ? [] : /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null, {
dependencies: [
{ ...dependency, stateVersion: isObserved ? "covered" : "initial" },
],
resourceKey: "projection",
}),
resource(
isObserved
? []
: null, // eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
{
dependencies: [
{
...dependency,
stateVersion: isObserved ? "covered" : "initial",
},
],
resourceKey: "projection",
},
),
);
}),
http.get("*/api/v1/tbank-sync/:id", () =>
HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
HttpResponse.json(
{
errorCode: null,
id: "dependency",
@@ -510,18 +598,22 @@ describe("page-owned screen synchronization", () => {
resources: [{ ...dependency, stateVersion: "covered" }],
scope: null,
state: "succeeded",
}
/* eslint-enable unicorn/no-null */)),
},
/* eslint-enable unicorn/no-null */
),
),
);
const { result } = renderHook(
() => {
const accounts = useBrokerageAccounts();
useScreenSync({ screen: "accounts" }, [accounts]);
return accounts;
},
{ wrapper: createQueryWrapper().wrapper },
);
await waitFor(() => expect(result.current.data).toEqual([]));
// eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response.
expect(modes).toEqual([null, "observe"]);
@@ -536,9 +628,11 @@ describe("page-owned screen synchronization", () => {
HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }),
),
);
const { result } = renderHook(
() => {
const accounts = useBrokerageAccounts();
return {
accounts,
sync: useScreenSync({ screen: "accounts" }, [accounts]),
@@ -546,6 +640,7 @@ describe("page-owned screen synchronization", () => {
},
{ wrapper: createQueryWrapper().wrapper },
);
await waitFor(() => expect(result.current.accounts.data).toEqual([]));
await act(() => result.current.sync.refresh());
await waitFor(() => expect(result.current.sync.transportError).toBe(true));
@@ -15,15 +15,21 @@ import { type InvestmentScreen, useTbankSync } from "./sync";
type ResourceMeta
= paths["/api/v1/tbank-sync/{id}"]["get"]["responses"][200]["content"]["application/json"]["resources"][number];
type ScreenResource = {
meta?: ResourceMeta;
observe: (version?: string) => Promise<unknown>;
queryKey: QueryKey;
transport: {
fetchStatus: "fetching" | "idle" | "paused";
status: "error" | "pending" | "success";
fetchStatus: "fetching"
| "idle"
| "paused";
status: "error"
| "pending"
| "success";
};
};
const STATUS_INTERVAL_MS = 1000;
function observeResource(
@@ -38,27 +44,34 @@ function observeResource(
if (observed.get(key) === completedId) return;
observed.set(key, completedId);
void resource.observe().catch(() => {});
return;
}
const changed = [
resource.meta,
...(resource.meta.dependencies ?? []),
].flatMap((current) => {
const notified = latest.get(current.resourceKey);
return notified && notified.stateVersion !== current.stateVersion
? [notified]
: [];
});
if (changed.length === 0) return;
const notification = JSON.stringify(
changed.map(meta => [meta.resourceKey, meta.stateVersion]),
);
if (observed.get(resource.meta.resourceKey) === notification)
return;
if (observed.get(resource.meta.resourceKey) === notification) return;
observed.set(resource.meta.resourceKey, notification);
const own = changed.find(
meta => meta.resourceKey === resource.meta?.resourceKey,
);
void resource.observe(own?.stateVersion).catch(() => {});
}
@@ -67,17 +80,24 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
const client = useQueryClient();
const deniedRef = useRef(new Set<unknown>());
const scopeKey = JSON.stringify(scope);
const [requested, setRequested] = useState<null | {
id: string;
scope: string;
}>(null);
const [requested, setRequested] = useState<null
| {
id: string;
scope: string;
}>(null);
const requestInFlightRef = useRef<null | string>(null);
const currentScopeRef = useRef(scopeKey);
useLayoutEffect(() => {
currentScopeRef.current = scopeKey;
}, [scopeKey]);
const isCurrentMutation = JSON.stringify(mutation.variables?.body) === scopeKey;
const isCurrentMutation
= JSON.stringify(mutation.variables?.body) === scopeKey;
const observedRef = useRef(new Map<string, string>());
const ids = [
...new Set([
...(requested?.scope === scopeKey ? [requested.id] : []),
@@ -93,6 +113,7 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
),
]),
];
const statuses = useAuthenticatedQueries(
ids.map(id => ({
...apiQueryClient.queryOptions("get", "/api/v1/tbank-sync/{id}", {
@@ -101,12 +122,16 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
refetchInterval: (query: {
state: { data?: { state: string }; error: unknown };
}) =>
!(query.state.error || (query.state.data && query.state.data.state !== "running")) && STATUS_INTERVAL_MS,
!(
query.state.error
|| (query.state.data && query.state.data.state !== "running")
) && STATUS_INTERVAL_MS,
refetchOnMount: false,
refetchOnWindowFocus: false,
retry: false,
})),
);
useEffect(() => {
for (const status of statuses) {
if (!status.error || deniedRef.current.has(status.error)) {
@@ -117,10 +142,16 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
if (!isApiErrorCode(apiErrorCode(status.error), ApiErrorCode.NotFound))
invalidateResourceAccess(client, "brokerage", status.error);
}
const latest = new Map<string, ResourceMeta>();
const orderedStatuses = statuses.toSorted((a, b) => a.dataUpdatedAt - b.dataUpdatedAt);
const orderedStatuses = statuses.toSorted(
(a, b) => a.dataUpdatedAt - b.dataUpdatedAt,
);
for (const status of orderedStatuses) {
const statusResources = status.data?.resources ?? [];
for (const meta of statusResources) {
latest.set(meta.resourceKey, meta);
const dependencies = meta.dependencies ?? [];
@@ -128,10 +159,18 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
latest.set(dependency.resourceKey, dependency);
}
}
const completed = statuses.find(status => requested?.scope === scopeKey
&& status.data?.id === requested.id && status.data.state !== "running")?.data;
for (const resource of resources) observeResource(resource, latest, completed?.id, observedRef.current);
const completed = statuses.find(
status =>
requested?.scope === scopeKey
&& status.data?.id === requested.id
&& status.data.state !== "running",
)?.data;
for (const resource of resources)
observeResource(resource, latest, completed?.id, observedRef.current);
}, [client, statuses, resources, requested, scopeKey]);
const isRefreshing
= (isCurrentMutation && mutation.isPending)
|| statuses.some(
@@ -139,15 +178,18 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
)
|| resources.some(({ meta }) => {
const status = statuses[ids.indexOf(meta?.sync.id ?? "")];
return (
!status?.isError
&& (!status?.data || status.data.state === "running")
&& (meta?.sync.state === "running" || meta?.sync.state === "queued")
);
});
const refresh = async () => {
if (isRefreshing || requestInFlightRef.current === scopeKey) return;
requestInFlightRef.current = scopeKey;
try {
const accepted = await mutation.mutateAsync({ body: scope });
if (
@@ -162,15 +204,20 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
*/
}
finally {
if (requestInFlightRef.current === scopeKey) requestInFlightRef.current = /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null;
if (requestInFlightRef.current === scopeKey)
requestInFlightRef.current
// eslint-disable-next-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model.
= null;
}
};
// Retry failed HTTP reads without asking the source to import again.
// A source failure (or explicit refresh with no read error) still needs a sync.
const retry = async () => {
const failed = resources.filter(
resource => resource.transport.status === "error",
);
const failedStatuses = statuses.filter(status => status.isError);
if (failed.length > 0 || failedStatuses.length > 0) {
await Promise.allSettled([
@@ -180,6 +227,7 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
}
else await refresh();
};
return {
refresh,
refreshing: isRefreshing,
@@ -25,25 +25,32 @@ describe("sync connection and session boundaries", () => {
refresh: () => Promise.resolve(true),
});
const { promise: blocked, resolve: release } = Promise.withResolvers<void>();
const { promise: blocked, resolve: release }
= Promise.withResolvers<void>();
const accepted = {
id: "work",
now: "2026-09-25T12:00:00Z",
scope: { screen: "accounts" },
};
let started = 0;
let isChanged = false;
server.use(
http.post("*/api/v1/tbank-sync", async () => {
started += 1;
await blocked;
return HttpResponse.json(accepted, { status: 202 });
}),
http.get("*/api/v1/tbank-sync/:id", async () => {
const now = isChanged ? "2026-09-25T12:01:00Z" : accepted.now;
started += 1;
await blocked;
return HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
return HttpResponse.json(
{
...accepted,
errorCode: null,
@@ -51,21 +58,26 @@ describe("sync connection and session boundaries", () => {
progress: { completed: 1, discovering: false, total: 1 },
resources: [],
state: "succeeded",
}
/* eslint-enable unicorn/no-null */));
},
/* eslint-enable unicorn/no-null */
);
}),
);
const { queryClient, wrapper } = createQueryWrapper();
const published: string[] = [];
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
if ((event.query.queryKey as readonly unknown[])[1]
!== "/api/v1/tbank-sync/{id}") {
if (
(event.query.queryKey as readonly unknown[])[1]
!== "/api/v1/tbank-sync/{id}"
) {
return;
}
const data = event.query.state.data as undefined | { now?: string };
if (data?.now) published.push(data.now);
});
const { result } = renderHook(
() => ({
mutation: useTbankSync(),
@@ -73,39 +85,49 @@ describe("sync connection and session boundaries", () => {
}),
{ wrapper },
);
const screen: InvestmentScreen = { screen: "accounts" };
let mutation!: Promise<unknown>;
act(() => {
mutation = result.current.mutation.mutateAsync({ body: screen });
});
// eslint-disable-next-line vitest/valid-expect -- Attach rejection handling before releasing the request; the assertion is awaited below.
const discarded = expect(mutation).rejects.toMatchObject({
name: "AbortError",
});
await waitFor(() => expect(started).toBe(2));
await act(async () => {
isChanged = true;
if (boundary === "connection")
commitTbankConnectionBoundary(queryClient, (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
commitTbankConnectionBoundary(
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
queryClient,
{
connected: false,
connectedAt: null,
}
/* eslint-enable unicorn/no-null */));
},
/* eslint-enable unicorn/no-null */
);
else {
generation += 1;
queryClient.clear();
}
release();
await blocked;
});
await discarded;
expect(result.current.mutation.data).toBeUndefined();
const key = apiQueryClient.queryOptions(
"get",
"/api/v1/tbank-sync/{id}",
{ params: { path: { id: "work" } } },
).queryKey;
// A new request may start after a successful connection boundary; an old result cannot win it.
if (boundary === "session")
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
@@ -6,11 +6,13 @@ import {
type InvestmentScreen
= paths["/api/v1/tbank-sync"]["post"]["requestBody"]["content"]["application/json"];
function useTbankSync() {
return apiQueryClient.useMutation("post", "/api/v1/tbank-sync", {
retry: false,
});
}
function useTbankSyncStatus(id: null | string) {
return useAuthenticatedQuery({
...apiQueryClient.queryOptions("get", "/api/v1/tbank-sync/{id}", {
@@ -21,26 +21,31 @@ const brokerageAccountsQueryKey = apiQueryClient.queryOptions(
"get",
"/api/v1/brokerage-accounts",
).queryKey;
const portfolioQueryKey = apiQueryClient.queryOptions(
"get",
"/api/v1/brokerage-accounts/{accountId}/portfolio",
{ params: { path: { accountId: "account-1" } } },
).queryKey;
const operationsQueryKey = apiQueryClient.queryOptions(
"get",
"/api/v1/brokerage-accounts/{accountId}/operations",
{ params: { path: { accountId: "account-1" } } },
).queryKey;
const stockQueryKey = apiQueryClient.queryOptions(
"get",
"/api/v1/stocks/{uid}/position",
{ params: { path: { uid: "e6123145-9665-43e0-8413-cd61b8aa9b13" } } },
).queryKey;
const bondQueryKey = apiQueryClient.queryOptions(
"get",
"/api/v1/bonds/{uid}/position",
{ params: { path: { uid: "e6123145-9665-43e0-8413-cd61b8aa9b13" } } },
).queryKey;
const bankCardsQueryKey = apiQueryClient.queryOptions(
"get",
"/api/v1/bank-cards",
@@ -48,6 +53,7 @@ const bankCardsQueryKey = apiQueryClient.queryOptions(
params: { query: { includeArchived: "false" } },
},
).queryKey;
const unrelatedQueryKey = apiQueryClient.queryOptions(
"get",
"/api/v1/auth/me",
@@ -59,6 +65,7 @@ function renderSection(client: QueryClient) {
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
return render(
<MantineProvider>
<QueryClientProvider client={client}>
@@ -70,21 +77,22 @@ function renderSection(client: QueryClient) {
function seededClient() {
const client = createTestQueryClient();
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
client.setQueryData(brokerageAccountsQueryKey, [
(/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
id: "account-1",
name: "Основной счет",
openedOn: null,
type: "BROKERAGE",
}
/* eslint-enable unicorn/no-null */),
{
id: "account-1",
name: "Основной счет",
openedOn: null,
type: "BROKERAGE",
},
/* eslint-enable unicorn/no-null */
]);
client.setQueryData(portfolioQueryKey, { source: "previous-connection" });
client.setQueryData(stockQueryKey, { source: "previous-connection" });
client.setQueryData(bondQueryKey, { source: "previous-connection" });
client.setQueryData(unrelatedQueryKey, { id: "user-1" });
client.setQueryData(bankCardsQueryKey, [{ id: "bank-card-1" }]);
return client;
}
@@ -92,18 +100,23 @@ describe("TbankConnectionSection", () => {
it("preserves cached status and a draft entered during a delayed failed refetch", async () => {
const status = { connected: true, connectedAt: "2026-08-14T00:00:00Z" };
const { promise: response, resolve: finishRefetch } = Promise.withResolvers<void>();
const { promise: response, resolve: finishRefetch }
= Promise.withResolvers<void>();
let reads = 0;
server.use(
http.get("*/api/v1/tbank-connection", async () => {
reads += 1;
if (reads === 1) {
await response;
return HttpResponse.json(
{ code: "TBANK_UNAVAILABLE" },
{ status: 503 },
);
}
return HttpResponse.json(status);
}),
);
@@ -141,11 +154,14 @@ describe("TbankConnectionSection", () => {
server.use(
http.get("*/api/v1/tbank-connection", () => {
reads += 1;
return reads === 1
? HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 })
: HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{ connected: false, connectedAt: null }
/* eslint-enable unicorn/no-null */));
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
: HttpResponse.json(
{ connected: false, connectedAt: null },
/* eslint-enable unicorn/no-null */
);
}),
);
renderSection(createTestQueryClient());
@@ -244,19 +260,24 @@ describe("TbankConnectionSection", () => {
const client = seededClient();
let isAborted = false;
const { promise: previousResponse, resolve: finishPrevious } = Promise.withResolvers<{ source: string }>();
const { promise: previousResponse, resolve: finishPrevious }
= Promise.withResolvers<{ source: string }>();
const previousRequest = client
.query({
queryFn: ({ signal }) => {
signal.addEventListener("abort", () => {
isAborted = true;
});
return previousResponse;
},
queryKey: operationsQueryKey,
})
// eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering.
.catch(() => {});
renderSection(client);
await screen.findByText("Не подключено");
@@ -302,7 +323,9 @@ describe("TbankConnectionSection", () => {
it("keeps DELETE recovery inside the dialog and preserves cache until successful retry", async () => {
let deletes = 0;
const { promise: response, resolve: finishDelete } = Promise.withResolvers<void>();
const { promise: response, resolve: finishDelete }
= Promise.withResolvers<void>();
server.use(
http.get("*/api/v1/tbank-connection", () =>
HttpResponse.json({
@@ -313,6 +336,7 @@ describe("TbankConnectionSection", () => {
http.delete("*/api/v1/tbank-connection", async () => {
deletes += 1;
if (deletes === 1) await response;
return deletes === 1
? HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 })
: new HttpResponse(null, { status: 204 });
@@ -324,9 +348,11 @@ describe("TbankConnectionSection", () => {
fireEvent.click(
await screen.findByRole("button", { name: "Удалить подключение" }),
);
const dialog = await screen.findByRole("dialog", {
name: "Удалить подключение?",
});
await waitFor(() =>
// eslint-disable-next-line testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
expect(dialog.contains(document.activeElement)).toBe(true),
@@ -10,7 +10,14 @@ import { TbankConnectionSectionLoaded } from "./TbankConnectionSectionLoaded";
const TbankConnectionSection: FC = () => {
const viewModel = useTbankConnectionViewModel();
if (viewModel.state === "loading") return <TbankConnectionLoading />;
return viewModel.state === "error" ? <TbankConnectionError retry={viewModel.retry} /> : <TbankConnectionSectionLoaded {...viewModel} />;
return viewModel.state === "error"
? (
<TbankConnectionError retry={viewModel.retry} />
)
: (
<TbankConnectionSectionLoaded {...viewModel} />
);
};
export { TbankConnectionSection };
@@ -10,11 +10,13 @@ import {
describe("TbankConnectionSection state views", () => {
it("renders loading and retries a status error", () => {
const retry = vi.fn();
const { rerender } = render(
<MantineProvider>
<TbankConnectionLoading />
</MantineProvider>,
);
expect(screen.getByRole("status", { name: "Загрузка" })).toHaveAttribute(
"aria-busy",
"true",
@@ -14,6 +14,7 @@ const TbankConnectionLoading: FC = () => {
return (
<LoadingSkeleton label={t("states.loadingTitle")}>
<Skeleton height={20} width="45%" />
<Skeleton height={36} radius="sm" width={140} />
</LoadingSkeleton>
);
@@ -6,9 +6,13 @@ function useTbankConnectionViewModel() {
const status = useAuthenticatedQuery({
...tbankConnectionQueryOptions(),
});
if (!status.data) {
return status.isPending ? { state: "loading" as const } : { retry: () => status.refetch(), state: "error" as const };
return status.isPending
? { state: "loading" as const }
: { retry: () => status.refetch(), state: "error" as const };
}
return {
refreshError: status.isError,
refreshing: status.isFetching,
@@ -8,19 +8,11 @@ import {
Stack,
Text,
} from "@mantine/core";
import { useQueryClient } from "@tanstack/react-query";
import { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { ApiErrorCode, apiErrorCode, apiQueryClient, isApiErrorCode } from "@/shared/api";
import { ApiErrorCode, isApiErrorCode } from "@/shared/api";
import {
commitTbankConnectionBoundary,
type TbankConnectionStatus,
} from "../../model/connection-boundary";
enum ConnectionErrorCode { RequestFailed = "REQUEST_ERROR" }
import { type TbankConnectionStatus } from "../../model/connection-boundary";
import { useTbankConnectionSectionLoadedVm } from "./TbankConnectionSectionLoaded.vm";
type TbankConnectionSectionLoadedProps = {
refreshError: boolean;
@@ -32,48 +24,29 @@ type TbankConnectionSectionLoadedProps = {
const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
props,
) => {
const { status } = props;
const { t } = useTranslation();
const queryClient = useQueryClient();
const [isDeleteOpened, setIsDeleteOpened] = useState(false);
const removalButtonRef = useRef<HTMLButtonElement>(null);
const [requestError, setRequestError] = useState<null | string>(null);
const {
formState: { errors },
handleSubmit,
errors,
isConnected,
isDeleteOpened,
isPending,
onCloseDisconnect,
onConfirmDisconnect,
onOpenDisconnect,
onSubmit,
register,
reset,
} = useForm<{ token: string }>();
const update = apiQueryClient.useMutation("put", "/api/v1/tbank-connection", {
onError: error => setRequestError(apiErrorCode(error) ?? ConnectionErrorCode.RequestFailed),
onSuccess: (data) => {
commitTbankConnectionBoundary(queryClient, data);
reset();
},
});
const remove = apiQueryClient.useMutation(
"delete",
"/api/v1/tbank-connection",
{
onSuccess: () => {
commitTbankConnectionBoundary(queryClient, {
connected: false,
connectedAt: /* eslint-disable-line unicorn/no-null -- The disconnected API snapshot requires a null connection timestamp. */ null,
});
setIsDeleteOpened(false);
},
},
);
const unavailableMessage = isApiErrorCode(requestError, ApiErrorCode.TbankUnavailable) ? "tbank.unavailable" : "tbank.requestError";
const isPending = update.isPending || remove.isPending;
const isConnected = status.connected;
useEffect(() => {
if (isDeleteOpened && remove.isError) removalButtonRef.current?.focus();
}, [isDeleteOpened, remove.isError]);
removalButtonRef,
remove,
requestError,
status,
t,
unavailableMessage,
update,
} = useTbankConnectionSectionLoadedVm(props);
return (
<Stack mt="xl">
<Text fw={600}>{t("tbank.title")}</Text>
<Text size="sm">
{isConnected
? t("tbank.connected", {
@@ -83,18 +56,22 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
})
: t("tbank.disconnected")}
</Text>
<Text c="dimmed" size="sm">
{t("tbank.hint")}
</Text>
{props.refreshing && (
<Text c="dimmed" role="status" size="sm">
{t("tbank.refreshing")}
</Text>
)}
{props.refreshError && (
<Alert aria-live="polite" color="orange" role="status">
<Stack gap="sm">
<Text>{t("tbank.refreshError")}</Text>
<Button
disabled={props.refreshing || isPending}
onClick={props.retry}
@@ -105,12 +82,8 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
</Stack>
</Alert>
)}
<form
onSubmit={handleSubmit(({ token }) => {
setRequestError(null);
update.mutate({ body: { token } });
})}
>
<form onSubmit={onSubmit}>
<fieldset disabled={isPending}>
<Stack>
<PasswordInput
@@ -118,6 +91,7 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
{...register("token", { required: t("tbank.tokenRequired") })}
error={errors.token?.message}
/>
{requestError && (
<Alert color="red">
{t(
@@ -127,42 +101,43 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
)}
</Alert>
)}
<Button loading={update.isPending} type="submit">
{t(isConnected ? "tbank.replace" : "tbank.connect")}
</Button>
{isConnected && (
<Button
color="red"
onClick={() => {
remove.reset();
setIsDeleteOpened(true);
}}
variant="outline"
>
<Button color="red" onClick={onOpenDisconnect} variant="outline">
{t("tbank.delete")}
</Button>
)}
</Stack>
</fieldset>
</form>
<Modal
closeButtonProps={{ "aria-label": t("tbank.close"), "disabled": isPending }}
closeButtonProps={{
"aria-label": t("tbank.close"),
"disabled": isPending,
}}
closeOnClickOutside={!isPending}
closeOnEscape={!isPending}
onClose={() => !isPending && setIsDeleteOpened(false)}
onClose={onCloseDisconnect}
opened={isDeleteOpened}
title={t("tbank.deleteTitle")}
>
<Stack>
<Text>{t("tbank.deleteText")}</Text>
{remove.isError && (
<Alert color="red">{t("tbank.requestError")}</Alert>
)}
<Button
color="red"
disabled={isPending}
loading={remove.isPending}
onClick={() => remove.mutate({})}
onClick={onConfirmDisconnect}
ref={removalButtonRef}
>
{t("tbank.deleteConfirm")}
@@ -0,0 +1,116 @@
import { useQueryClient } from "@tanstack/react-query";
import { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import {
ApiErrorCode,
apiErrorCode,
apiQueryClient,
isApiErrorCode,
} from "@/shared/api";
import {
commitTbankConnectionBoundary,
type TbankConnectionStatus,
} from "../../model/connection-boundary";
enum ConnectionErrorCode {
RequestFailed = "REQUEST_ERROR",
}
type TbankConnectionSectionLoadedProps = {
refreshError: boolean;
refreshing: boolean;
retry: () => void;
status: TbankConnectionStatus;
};
function useTbankConnectionSectionLoadedVm(
props: TbankConnectionSectionLoadedProps,
) {
const { status } = props;
const { t } = useTranslation();
const queryClient = useQueryClient();
const [isDeleteOpened, setIsDeleteOpened] = useState(false);
const removalButtonRef = useRef<HTMLButtonElement>(null);
const [requestError, setRequestError] = useState<null | string>(null);
const {
formState: { errors },
handleSubmit,
register,
reset,
} = useForm<{ token: string }>();
const update = apiQueryClient.useMutation("put", "/api/v1/tbank-connection", {
onError: error =>
setRequestError(apiErrorCode(error) ?? ConnectionErrorCode.RequestFailed),
onSuccess: (data) => {
commitTbankConnectionBoundary(queryClient, data);
reset();
},
});
const remove = apiQueryClient.useMutation(
"delete",
"/api/v1/tbank-connection",
{
onSuccess: () => {
commitTbankConnectionBoundary(queryClient, {
connected: false,
connectedAt:
// eslint-disable-next-line unicorn/no-null -- The disconnected API snapshot requires a null connection timestamp.
null,
});
setIsDeleteOpened(false);
},
},
);
const unavailableMessage = isApiErrorCode(
requestError,
ApiErrorCode.TbankUnavailable,
)
? "tbank.unavailable"
: "tbank.requestError";
const isPending = update.isPending || remove.isPending;
const isConnected = status.connected;
useEffect(() => {
if (isDeleteOpened && remove.isError) removalButtonRef.current?.focus();
}, [isDeleteOpened, remove.isError]);
const onSubmit = handleSubmit(({ token }) => {
setRequestError(null);
update.mutate({ body: { token } });
});
const onOpenDisconnect = () => {
remove.reset();
setIsDeleteOpened(true);
};
const onCloseDisconnect = () => !isPending && setIsDeleteOpened(false);
const onConfirmDisconnect = () => remove.mutate({});
return {
errors,
isConnected,
isDeleteOpened,
isPending,
onCloseDisconnect,
onConfirmDisconnect,
onOpenDisconnect,
onSubmit,
register,
removalButtonRef,
remove,
requestError,
status,
t,
unavailableMessage,
update,
};
}
export { useTbankConnectionSectionLoadedVm };