refactor: enforce frontend view model boundaries
This commit is contained in:
+40
-14
@@ -21,26 +21,31 @@ const brokerageAccountsQueryKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/brokerage-accounts",
|
||||
).queryKey;
|
||||
|
||||
const portfolioQueryKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/brokerage-accounts/{accountId}/portfolio",
|
||||
{ params: { path: { accountId: "account-1" } } },
|
||||
).queryKey;
|
||||
|
||||
const operationsQueryKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/brokerage-accounts/{accountId}/operations",
|
||||
{ params: { path: { accountId: "account-1" } } },
|
||||
).queryKey;
|
||||
|
||||
const stockQueryKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/stocks/{uid}/position",
|
||||
{ params: { path: { uid: "e6123145-9665-43e0-8413-cd61b8aa9b13" } } },
|
||||
).queryKey;
|
||||
|
||||
const bondQueryKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/bonds/{uid}/position",
|
||||
{ params: { path: { uid: "e6123145-9665-43e0-8413-cd61b8aa9b13" } } },
|
||||
).queryKey;
|
||||
|
||||
const bankCardsQueryKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/bank-cards",
|
||||
@@ -48,6 +53,7 @@ const bankCardsQueryKey = apiQueryClient.queryOptions(
|
||||
params: { query: { includeArchived: "false" } },
|
||||
},
|
||||
).queryKey;
|
||||
|
||||
const unrelatedQueryKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/auth/me",
|
||||
@@ -59,6 +65,7 @@ function renderSection(client: QueryClient) {
|
||||
clear: vi.fn(),
|
||||
refresh: () => Promise.resolve(true),
|
||||
});
|
||||
|
||||
return render(
|
||||
<MantineProvider>
|
||||
<QueryClientProvider client={client}>
|
||||
@@ -70,21 +77,22 @@ function renderSection(client: QueryClient) {
|
||||
|
||||
function seededClient() {
|
||||
const client = createTestQueryClient();
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
client.setQueryData(brokerageAccountsQueryKey, [
|
||||
(/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
id: "account-1",
|
||||
name: "Основной счет",
|
||||
openedOn: null,
|
||||
type: "BROKERAGE",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */),
|
||||
{
|
||||
id: "account-1",
|
||||
name: "Основной счет",
|
||||
openedOn: null,
|
||||
type: "BROKERAGE",
|
||||
},
|
||||
/* eslint-enable unicorn/no-null */
|
||||
]);
|
||||
client.setQueryData(portfolioQueryKey, { source: "previous-connection" });
|
||||
client.setQueryData(stockQueryKey, { source: "previous-connection" });
|
||||
client.setQueryData(bondQueryKey, { source: "previous-connection" });
|
||||
client.setQueryData(unrelatedQueryKey, { id: "user-1" });
|
||||
client.setQueryData(bankCardsQueryKey, [{ id: "bank-card-1" }]);
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
@@ -92,18 +100,23 @@ describe("TbankConnectionSection", () => {
|
||||
it("preserves cached status and a draft entered during a delayed failed refetch", async () => {
|
||||
const status = { connected: true, connectedAt: "2026-08-14T00:00:00Z" };
|
||||
|
||||
const { promise: response, resolve: finishRefetch } = Promise.withResolvers<void>();
|
||||
const { promise: response, resolve: finishRefetch }
|
||||
= Promise.withResolvers<void>();
|
||||
|
||||
let reads = 0;
|
||||
server.use(
|
||||
http.get("*/api/v1/tbank-connection", async () => {
|
||||
reads += 1;
|
||||
|
||||
if (reads === 1) {
|
||||
await response;
|
||||
|
||||
return HttpResponse.json(
|
||||
{ code: "TBANK_UNAVAILABLE" },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
return HttpResponse.json(status);
|
||||
}),
|
||||
);
|
||||
@@ -141,11 +154,14 @@ describe("TbankConnectionSection", () => {
|
||||
server.use(
|
||||
http.get("*/api/v1/tbank-connection", () => {
|
||||
reads += 1;
|
||||
|
||||
return reads === 1
|
||||
? HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 })
|
||||
: HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{ connected: false, connectedAt: null }
|
||||
/* eslint-enable unicorn/no-null */));
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
: HttpResponse.json(
|
||||
{ connected: false, connectedAt: null },
|
||||
/* eslint-enable unicorn/no-null */
|
||||
);
|
||||
}),
|
||||
);
|
||||
renderSection(createTestQueryClient());
|
||||
@@ -244,19 +260,24 @@ describe("TbankConnectionSection", () => {
|
||||
const client = seededClient();
|
||||
|
||||
let isAborted = false;
|
||||
const { promise: previousResponse, resolve: finishPrevious } = Promise.withResolvers<{ source: string }>();
|
||||
|
||||
const { promise: previousResponse, resolve: finishPrevious }
|
||||
= Promise.withResolvers<{ source: string }>();
|
||||
|
||||
const previousRequest = client
|
||||
.query({
|
||||
queryFn: ({ signal }) => {
|
||||
signal.addEventListener("abort", () => {
|
||||
isAborted = true;
|
||||
});
|
||||
|
||||
return previousResponse;
|
||||
},
|
||||
queryKey: operationsQueryKey,
|
||||
})
|
||||
// eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering.
|
||||
.catch(() => {});
|
||||
|
||||
renderSection(client);
|
||||
|
||||
await screen.findByText("Не подключено");
|
||||
@@ -302,7 +323,9 @@ describe("TbankConnectionSection", () => {
|
||||
it("keeps DELETE recovery inside the dialog and preserves cache until successful retry", async () => {
|
||||
let deletes = 0;
|
||||
|
||||
const { promise: response, resolve: finishDelete } = Promise.withResolvers<void>();
|
||||
const { promise: response, resolve: finishDelete }
|
||||
= Promise.withResolvers<void>();
|
||||
|
||||
server.use(
|
||||
http.get("*/api/v1/tbank-connection", () =>
|
||||
HttpResponse.json({
|
||||
@@ -313,6 +336,7 @@ describe("TbankConnectionSection", () => {
|
||||
http.delete("*/api/v1/tbank-connection", async () => {
|
||||
deletes += 1;
|
||||
if (deletes === 1) await response;
|
||||
|
||||
return deletes === 1
|
||||
? HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 })
|
||||
: new HttpResponse(null, { status: 204 });
|
||||
@@ -324,9 +348,11 @@ describe("TbankConnectionSection", () => {
|
||||
fireEvent.click(
|
||||
await screen.findByRole("button", { name: "Удалить подключение" }),
|
||||
);
|
||||
|
||||
const dialog = await screen.findByRole("dialog", {
|
||||
name: "Удалить подключение?",
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
// eslint-disable-next-line testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
|
||||
expect(dialog.contains(document.activeElement)).toBe(true),
|
||||
|
||||
@@ -10,7 +10,14 @@ import { TbankConnectionSectionLoaded } from "./TbankConnectionSectionLoaded";
|
||||
const TbankConnectionSection: FC = () => {
|
||||
const viewModel = useTbankConnectionViewModel();
|
||||
if (viewModel.state === "loading") return <TbankConnectionLoading />;
|
||||
return viewModel.state === "error" ? <TbankConnectionError retry={viewModel.retry} /> : <TbankConnectionSectionLoaded {...viewModel} />;
|
||||
|
||||
return viewModel.state === "error"
|
||||
? (
|
||||
<TbankConnectionError retry={viewModel.retry} />
|
||||
)
|
||||
: (
|
||||
<TbankConnectionSectionLoaded {...viewModel} />
|
||||
);
|
||||
};
|
||||
|
||||
export { TbankConnectionSection };
|
||||
|
||||
+2
@@ -10,11 +10,13 @@ import {
|
||||
describe("TbankConnectionSection state views", () => {
|
||||
it("renders loading and retries a status error", () => {
|
||||
const retry = vi.fn();
|
||||
|
||||
const { rerender } = render(
|
||||
<MantineProvider>
|
||||
<TbankConnectionLoading />
|
||||
</MantineProvider>,
|
||||
);
|
||||
|
||||
expect(screen.getByRole("status", { name: "Загрузка" })).toHaveAttribute(
|
||||
"aria-busy",
|
||||
"true",
|
||||
|
||||
+1
@@ -14,6 +14,7 @@ const TbankConnectionLoading: FC = () => {
|
||||
return (
|
||||
<LoadingSkeleton label={t("states.loadingTitle")}>
|
||||
<Skeleton height={20} width="45%" />
|
||||
|
||||
<Skeleton height={36} radius="sm" width={140} />
|
||||
</LoadingSkeleton>
|
||||
);
|
||||
|
||||
+5
-1
@@ -6,9 +6,13 @@ function useTbankConnectionViewModel() {
|
||||
const status = useAuthenticatedQuery({
|
||||
...tbankConnectionQueryOptions(),
|
||||
});
|
||||
|
||||
if (!status.data) {
|
||||
return status.isPending ? { state: "loading" as const } : { retry: () => status.refetch(), state: "error" as const };
|
||||
return status.isPending
|
||||
? { state: "loading" as const }
|
||||
: { retry: () => status.refetch(), state: "error" as const };
|
||||
}
|
||||
|
||||
return {
|
||||
refreshError: status.isError,
|
||||
refreshing: status.isFetching,
|
||||
|
||||
+39
-64
@@ -8,19 +8,11 @@ import {
|
||||
Stack,
|
||||
Text,
|
||||
} from "@mantine/core";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { ApiErrorCode, apiErrorCode, apiQueryClient, isApiErrorCode } from "@/shared/api";
|
||||
import { ApiErrorCode, isApiErrorCode } from "@/shared/api";
|
||||
|
||||
import {
|
||||
commitTbankConnectionBoundary,
|
||||
type TbankConnectionStatus,
|
||||
} from "../../model/connection-boundary";
|
||||
|
||||
enum ConnectionErrorCode { RequestFailed = "REQUEST_ERROR" }
|
||||
import { type TbankConnectionStatus } from "../../model/connection-boundary";
|
||||
import { useTbankConnectionSectionLoadedVm } from "./TbankConnectionSectionLoaded.vm";
|
||||
|
||||
type TbankConnectionSectionLoadedProps = {
|
||||
refreshError: boolean;
|
||||
@@ -32,48 +24,29 @@ type TbankConnectionSectionLoadedProps = {
|
||||
const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
|
||||
props,
|
||||
) => {
|
||||
const { status } = props;
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const [isDeleteOpened, setIsDeleteOpened] = useState(false);
|
||||
const removalButtonRef = useRef<HTMLButtonElement>(null);
|
||||
const [requestError, setRequestError] = useState<null | string>(null);
|
||||
const {
|
||||
formState: { errors },
|
||||
handleSubmit,
|
||||
errors,
|
||||
isConnected,
|
||||
isDeleteOpened,
|
||||
isPending,
|
||||
onCloseDisconnect,
|
||||
onConfirmDisconnect,
|
||||
onOpenDisconnect,
|
||||
onSubmit,
|
||||
register,
|
||||
reset,
|
||||
} = useForm<{ token: string }>();
|
||||
const update = apiQueryClient.useMutation("put", "/api/v1/tbank-connection", {
|
||||
onError: error => setRequestError(apiErrorCode(error) ?? ConnectionErrorCode.RequestFailed),
|
||||
onSuccess: (data) => {
|
||||
commitTbankConnectionBoundary(queryClient, data);
|
||||
reset();
|
||||
},
|
||||
});
|
||||
const remove = apiQueryClient.useMutation(
|
||||
"delete",
|
||||
"/api/v1/tbank-connection",
|
||||
{
|
||||
onSuccess: () => {
|
||||
commitTbankConnectionBoundary(queryClient, {
|
||||
connected: false,
|
||||
connectedAt: /* eslint-disable-line unicorn/no-null -- The disconnected API snapshot requires a null connection timestamp. */ null,
|
||||
});
|
||||
setIsDeleteOpened(false);
|
||||
},
|
||||
},
|
||||
);
|
||||
const unavailableMessage = isApiErrorCode(requestError, ApiErrorCode.TbankUnavailable) ? "tbank.unavailable" : "tbank.requestError";
|
||||
const isPending = update.isPending || remove.isPending;
|
||||
const isConnected = status.connected;
|
||||
useEffect(() => {
|
||||
if (isDeleteOpened && remove.isError) removalButtonRef.current?.focus();
|
||||
}, [isDeleteOpened, remove.isError]);
|
||||
removalButtonRef,
|
||||
remove,
|
||||
requestError,
|
||||
status,
|
||||
t,
|
||||
unavailableMessage,
|
||||
update,
|
||||
} = useTbankConnectionSectionLoadedVm(props);
|
||||
|
||||
return (
|
||||
<Stack mt="xl">
|
||||
<Text fw={600}>{t("tbank.title")}</Text>
|
||||
|
||||
<Text size="sm">
|
||||
{isConnected
|
||||
? t("tbank.connected", {
|
||||
@@ -83,18 +56,22 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
|
||||
})
|
||||
: t("tbank.disconnected")}
|
||||
</Text>
|
||||
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("tbank.hint")}
|
||||
</Text>
|
||||
|
||||
{props.refreshing && (
|
||||
<Text c="dimmed" role="status" size="sm">
|
||||
{t("tbank.refreshing")}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
{props.refreshError && (
|
||||
<Alert aria-live="polite" color="orange" role="status">
|
||||
<Stack gap="sm">
|
||||
<Text>{t("tbank.refreshError")}</Text>
|
||||
|
||||
<Button
|
||||
disabled={props.refreshing || isPending}
|
||||
onClick={props.retry}
|
||||
@@ -105,12 +82,8 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
|
||||
</Stack>
|
||||
</Alert>
|
||||
)}
|
||||
<form
|
||||
onSubmit={handleSubmit(({ token }) => {
|
||||
setRequestError(null);
|
||||
update.mutate({ body: { token } });
|
||||
})}
|
||||
>
|
||||
|
||||
<form onSubmit={onSubmit}>
|
||||
<fieldset disabled={isPending}>
|
||||
<Stack>
|
||||
<PasswordInput
|
||||
@@ -118,6 +91,7 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
|
||||
{...register("token", { required: t("tbank.tokenRequired") })}
|
||||
error={errors.token?.message}
|
||||
/>
|
||||
|
||||
{requestError && (
|
||||
<Alert color="red">
|
||||
{t(
|
||||
@@ -127,42 +101,43 @@ const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
|
||||
)}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Button loading={update.isPending} type="submit">
|
||||
{t(isConnected ? "tbank.replace" : "tbank.connect")}
|
||||
</Button>
|
||||
|
||||
{isConnected && (
|
||||
<Button
|
||||
color="red"
|
||||
onClick={() => {
|
||||
remove.reset();
|
||||
setIsDeleteOpened(true);
|
||||
}}
|
||||
variant="outline"
|
||||
>
|
||||
<Button color="red" onClick={onOpenDisconnect} variant="outline">
|
||||
{t("tbank.delete")}
|
||||
</Button>
|
||||
)}
|
||||
</Stack>
|
||||
</fieldset>
|
||||
</form>
|
||||
|
||||
<Modal
|
||||
closeButtonProps={{ "aria-label": t("tbank.close"), "disabled": isPending }}
|
||||
closeButtonProps={{
|
||||
"aria-label": t("tbank.close"),
|
||||
"disabled": isPending,
|
||||
}}
|
||||
closeOnClickOutside={!isPending}
|
||||
closeOnEscape={!isPending}
|
||||
onClose={() => !isPending && setIsDeleteOpened(false)}
|
||||
onClose={onCloseDisconnect}
|
||||
opened={isDeleteOpened}
|
||||
title={t("tbank.deleteTitle")}
|
||||
>
|
||||
<Stack>
|
||||
<Text>{t("tbank.deleteText")}</Text>
|
||||
|
||||
{remove.isError && (
|
||||
<Alert color="red">{t("tbank.requestError")}</Alert>
|
||||
)}
|
||||
|
||||
<Button
|
||||
color="red"
|
||||
disabled={isPending}
|
||||
loading={remove.isPending}
|
||||
onClick={() => remove.mutate({})}
|
||||
onClick={onConfirmDisconnect}
|
||||
ref={removalButtonRef}
|
||||
>
|
||||
{t("tbank.deleteConfirm")}
|
||||
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import {
|
||||
ApiErrorCode,
|
||||
apiErrorCode,
|
||||
apiQueryClient,
|
||||
isApiErrorCode,
|
||||
} from "@/shared/api";
|
||||
|
||||
import {
|
||||
commitTbankConnectionBoundary,
|
||||
type TbankConnectionStatus,
|
||||
} from "../../model/connection-boundary";
|
||||
enum ConnectionErrorCode {
|
||||
RequestFailed = "REQUEST_ERROR",
|
||||
}
|
||||
|
||||
type TbankConnectionSectionLoadedProps = {
|
||||
refreshError: boolean;
|
||||
refreshing: boolean;
|
||||
retry: () => void;
|
||||
status: TbankConnectionStatus;
|
||||
};
|
||||
|
||||
function useTbankConnectionSectionLoadedVm(
|
||||
props: TbankConnectionSectionLoadedProps,
|
||||
) {
|
||||
const { status } = props;
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const [isDeleteOpened, setIsDeleteOpened] = useState(false);
|
||||
const removalButtonRef = useRef<HTMLButtonElement>(null);
|
||||
const [requestError, setRequestError] = useState<null | string>(null);
|
||||
|
||||
const {
|
||||
formState: { errors },
|
||||
handleSubmit,
|
||||
register,
|
||||
reset,
|
||||
} = useForm<{ token: string }>();
|
||||
|
||||
const update = apiQueryClient.useMutation("put", "/api/v1/tbank-connection", {
|
||||
onError: error =>
|
||||
setRequestError(apiErrorCode(error) ?? ConnectionErrorCode.RequestFailed),
|
||||
onSuccess: (data) => {
|
||||
commitTbankConnectionBoundary(queryClient, data);
|
||||
reset();
|
||||
},
|
||||
});
|
||||
|
||||
const remove = apiQueryClient.useMutation(
|
||||
"delete",
|
||||
"/api/v1/tbank-connection",
|
||||
{
|
||||
onSuccess: () => {
|
||||
commitTbankConnectionBoundary(queryClient, {
|
||||
connected: false,
|
||||
connectedAt:
|
||||
// eslint-disable-next-line unicorn/no-null -- The disconnected API snapshot requires a null connection timestamp.
|
||||
null,
|
||||
});
|
||||
setIsDeleteOpened(false);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const unavailableMessage = isApiErrorCode(
|
||||
requestError,
|
||||
ApiErrorCode.TbankUnavailable,
|
||||
)
|
||||
? "tbank.unavailable"
|
||||
: "tbank.requestError";
|
||||
|
||||
const isPending = update.isPending || remove.isPending;
|
||||
const isConnected = status.connected;
|
||||
useEffect(() => {
|
||||
if (isDeleteOpened && remove.isError) removalButtonRef.current?.focus();
|
||||
}, [isDeleteOpened, remove.isError]);
|
||||
|
||||
const onSubmit = handleSubmit(({ token }) => {
|
||||
setRequestError(null);
|
||||
update.mutate({ body: { token } });
|
||||
});
|
||||
|
||||
const onOpenDisconnect = () => {
|
||||
remove.reset();
|
||||
setIsDeleteOpened(true);
|
||||
};
|
||||
|
||||
const onCloseDisconnect = () => !isPending && setIsDeleteOpened(false);
|
||||
const onConfirmDisconnect = () => remove.mutate({});
|
||||
|
||||
return {
|
||||
errors,
|
||||
isConnected,
|
||||
isDeleteOpened,
|
||||
isPending,
|
||||
onCloseDisconnect,
|
||||
onConfirmDisconnect,
|
||||
onOpenDisconnect,
|
||||
onSubmit,
|
||||
register,
|
||||
removalButtonRef,
|
||||
remove,
|
||||
requestError,
|
||||
status,
|
||||
t,
|
||||
unavailableMessage,
|
||||
update,
|
||||
};
|
||||
}
|
||||
|
||||
export { useTbankConnectionSectionLoadedVm };
|
||||
Reference in New Issue
Block a user