feat: add quiet reading with rare confirmations

Part of the quiet-user-feedback change; docs and specs land in their own repositories.
This commit is contained in:
2026-10-06 07:01:58 +03:00
parent c096fc70ef
commit 5b30bb802a
77 changed files with 1352 additions and 1259 deletions
@@ -3,7 +3,6 @@ import type { FC } from "react";
import { MantineProvider } from "@mantine/core";
import { QueryClientProvider } from "@tanstack/react-query";
import {
act,
fireEvent,
render,
renderHook,
@@ -115,7 +114,6 @@ describe("Upcoming event date filters", () => {
"keeps event calendar dates in GET and source sync requests: %s",
async (search) => {
const requested: string[] = [];
const syncRequests: unknown[] = [];
server.use(
http.get("*/api/v1/brokerage-accounts/all/events", ({ request }) => {
requested.push(new URL(request.url).search);
@@ -133,16 +131,7 @@ describe("Upcoming event date filters", () => {
),
);
}),
http.post("*/api/v1/tbank-sync", async ({ request }) => {
syncRequests.push(await request.json());
return HttpResponse.json(
{ code: "TBANK_UNAVAILABLE" },
{ status: 503 },
);
}),
);
const period = Object.fromEntries(new URLSearchParams(search));
const queryClient = createTestQueryClient();
const { result } = renderHook(
@@ -162,15 +151,6 @@ describe("Upcoming event date filters", () => {
await waitFor(() => expect(result.current.state).toBe("error"));
expect(requested).toEqual([`?${search}`]);
expect(syncRequests).toEqual([]);
act(() => {
if (result.current.state === "error") result.current.retry();
});
await waitFor(() =>
expect(syncRequests).toEqual([
{ accountId: "all", screen: "events", ...period },
]),
);
},
);
@@ -232,7 +212,7 @@ describe("Upcoming event date filters", () => {
),
);
renderEvents(accountId, ["?from=2099-02-01"]);
await screen.findByRole("button", { name: "Повторить" });
await screen.findByRole("button", { name: "Сбросить" });
fireEvent.click(screen.getByRole("button", { name: "Сбросить" }));
await screen.findByLabelText("Период");
expect(screen.getByLabelText("URL")).toBeEmptyDOMElement();
@@ -300,7 +280,7 @@ describe("Upcoming event date filters", () => {
);
});
it("retains the previous complete forecast and timestamp when its source refresh fails", async () => {
it("retains the previous complete forecast when its source refresh fails", async () => {
configureAuthClient({
accessToken: () => "synthetic",
clear: vi.fn(),
@@ -343,9 +323,6 @@ it("retains the previous complete forecast and timestamp when its source refresh
await waitFor(() =>
expect(result.current).toMatchObject({
events,
lastSuccessfulAt: snapshot.meta.lastSuccessfulAt,
refreshError: true,
sourceError: true,
state: "loaded",
}),
);
@@ -159,8 +159,7 @@ describe("AccountEventsPage", () => {
expect(screen.getAllByText("O")).toHaveLength(2);
});
it("renders empty and retryable error states", () => {
const refetch = vi.fn();
it("renders empty and quiet error states", async () => {
const { rerender } = renderPage();
expect(
screen.getByText("За выбранный период событий не найдено"),
@@ -169,7 +168,6 @@ describe("AccountEventsPage", () => {
data: undefined,
isError: true,
isLoading: false,
refetch,
} as never);
rerender(
<MantineProvider>
@@ -178,8 +176,8 @@ describe("AccountEventsPage", () => {
</MemoryRouter>
</MantineProvider>,
);
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
expect(refresh).toHaveBeenCalledOnce();
expect(await screen.findByRole("button", { name: "Сбросить" })).toBeVisible();
expect(screen.queryByRole("button", { name: "Повторить" })).not.toBeInTheDocument();
});
it("shows a structural busy state before events are available", () => {
@@ -6,25 +6,20 @@ import {
useBrokerageEvents,
} from "@/entities/brokerage-event";
import { useScreenSync } from "@/features/tbank-connection";
import { isValidPeriod, useUrlPeriod } from "@/shared/lib";
import { isValidPeriod, useInitialAvailability, useUrlPeriod } from "@/shared/lib";
type AccountEventsPageViewModel
= | {
canApply: boolean;
draftPeriod: [null | string, null | string];
events: BrokerageEvent[];
lastSuccessfulAt?: null | string;
onApply: () => void;
onPeriodChange: (value: [null | string, null | string]) => void;
onReset: () => void;
partial?: boolean;
refreshError: boolean;
refreshing: boolean;
retry: () => void;
sourceError?: boolean;
state: "loaded";
}
| { onReset: () => void; retry: () => void; state: "error" }
| { onReset: () => void; state: "error" }
| { state: "loading" };
function useAccountEventsPageViewModel(): AccountEventsPageViewModel {
@@ -56,7 +51,7 @@ function useAccountEventsPageViewModel(): AccountEventsPageViewModel {
...(appliedTo && { to: appliedTo }),
});
const sync = useScreenSync(
useScreenSync(
{
accountId,
screen: "events",
@@ -66,7 +61,15 @@ function useAccountEventsPageViewModel(): AccountEventsPageViewModel {
[events],
);
if (events.isLoading) return { state: "loading" };
const availability = useInitialAvailability({
hasContent: !!events.data,
identity: scope,
isError: events.isError || events.meta?.sync.state === "failed",
isFetching: events.isFetching,
});
if (availability === "loading" && events.isLoading)
return { state: "loading" };
const onReset = () => {
setDraftPeriod([null, null]);
@@ -76,12 +79,12 @@ function useAccountEventsPageViewModel(): AccountEventsPageViewModel {
if ((events.isError || events.meta?.sync.state === "failed") && !events.data)
return {
onReset,
retry: () => {
void sync.retry();
},
state: "error",
};
if (!events.data) return { state: "loading" };
if (!events.data)
return availability === "unavailable"
? { onReset, state: "error" }
: { state: "loading" };
return {
canApply:
@@ -89,7 +92,6 @@ function useAccountEventsPageViewModel(): AccountEventsPageViewModel {
&& isValidPeriod(draftFrom, draftTo),
draftPeriod,
events: events.data.events,
lastSuccessfulAt: events.meta?.lastSuccessfulAt,
onApply: () => {
if (!isValidPeriod(draftFrom, draftTo)) return;
setSearchParameters({
@@ -100,12 +102,6 @@ function useAccountEventsPageViewModel(): AccountEventsPageViewModel {
onPeriodChange: setDraftPeriod,
onReset,
partial: events.meta?.availability !== "complete",
refreshError: events.isError || sync.sourceError || sync.transportError,
refreshing: events.isFetching || sync.refreshing,
retry: () => {
void sync.retry();
},
sourceError: sync.sourceError,
state: "loaded",
};
}
@@ -4,7 +4,7 @@ import { Button, Group } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import { useTranslation } from "react-i18next";
type AccountEventsPageErrorProps = { onReset: () => void; retry: () => void };
type AccountEventsPageErrorProps = { onReset: () => void };
const AccountEventsPageError: FC<AccountEventsPageErrorProps> = (props) => {
const { t } = useTranslation();
@@ -13,8 +13,6 @@ const AccountEventsPageError: FC<AccountEventsPageErrorProps> = (props) => {
<StateView
action={(
<Group>
<Button onClick={props.retry}>{t("events.retry")}</Button>
<Button onClick={props.onReset} variant="default">
{t("ledger.reset")}
</Button>
@@ -4,7 +4,6 @@ import {
Alert,
Button,
Group,
Progress,
Stack,
Text,
Title,
@@ -16,7 +15,6 @@ import {
BrokerageEventCard,
brokerageEventKey,
} from "@/entities/brokerage-event";
import { SourceSyncStatus } from "@/shared/ui";
import type { AccountEventsPageViewModel } from "../AccountEventsPage.vm";
@@ -55,32 +53,10 @@ const AccountEventsPageLoaded: FC<AccountEventsPageLoadedProps> = (props) => {
return (
<Stack gap="lg">
<SourceSyncStatus lastSuccessfulAt={props.lastSuccessfulAt} />
<Title order={1}>{t("events.title")}</Title>
<Button disabled={props.refreshing} onClick={props.retry} w="fit-content">
{t("investment.refresh")}
</Button>
{!!props.partial && <Alert role="status">{t("investment.partial")}</Alert>}
{!!props.refreshing && <Progress animated aria-label={t("accounts.refreshing")} value={100} />}
{!!props.refreshError && (
<Alert aria-live="polite" color="yellow" role="status">
{t(
props.sourceError
? "investment.syncFailed"
: "accounts.refreshError",
)}
<Button onClick={props.retry} variant="subtle">
{t("accounts.retry")}
</Button>
</Alert>
)}
<Text c="dimmed">{t("events.hint")}</Text>
<Group align="end">
@@ -195,7 +195,6 @@ describe("AccountIncomePage", () => {
it("keeps income calendar dates in GET and source sync requests", async () => {
const requested: string[] = [];
const syncRequests: unknown[] = [];
server.use(
http.get(
"*/api/v1/brokerage-accounts/:accountId/income-analytics",
@@ -216,30 +215,11 @@ describe("AccountIncomePage", () => {
);
},
),
http.post("*/api/v1/tbank-sync", async ({ request }) => {
syncRequests.push(await request.json());
return HttpResponse.json(
{ code: "TBANK_UNAVAILABLE" },
{ status: 503 },
);
}),
);
renderPage("from=2024-02-29&to=2024-03-01");
const retry = await screen.findByRole("button", { name: "Повторить" });
await screen.findByText("Не удалось рассчитать пассивный доход");
expect(requested).toEqual(["?from=2024-02-29&to=2024-03-01"]);
expect(syncRequests).toEqual([]);
fireEvent.click(retry);
await waitFor(() =>
expect(syncRequests).toEqual([
{
accountId: "account-1",
from: "2024-02-29",
screen: "income",
to: "2024-03-01",
},
]),
);
expect(screen.queryByRole("button", { name: "Повторить" })).not.toBeInTheDocument();
});
it("requests a multi-year period from the URL without resetting it", async () => {
@@ -486,7 +466,7 @@ describe("AccountIncomePage", () => {
).toBeVisible();
});
it("shows a recoverable realized error", async () => {
it("shows a quiet realized error", async () => {
server.use(
http.get(
"*/api/v1/brokerage-accounts/account-1/income-analytics",
@@ -495,8 +475,11 @@ describe("AccountIncomePage", () => {
);
renderPage();
expect(
await screen.findByRole("button", { name: "Повторить" }),
await screen.findByText("Не удалось рассчитать пассивный доход", undefined, {
timeout: 4000,
}),
).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Повторить" })).not.toBeInTheDocument();
});
});
@@ -631,7 +614,7 @@ describe("income period and snapshot boundary", () => {
expect(requests).toEqual(["?from=2026-09-01&to=2026-09-01"]);
});
it("keeps valid data and draft during refetch, warns on failure and retries", async () => {
it("keeps valid data and draft during refetch failure", async () => {
respondWithRequestedPeriod([]);
const { queryClient } = renderPage();
await screen.findByLabelText("Период");
@@ -653,51 +636,13 @@ describe("income period and snapshot boundary", () => {
act(() => {
void queryClient.invalidateQueries();
});
expect(
await screen.findByRole("status", { name: "Обновляем пассивный доход" }),
).toBeInTheDocument();
expect(screen.getByRole("region", { name: "Выплаты" })).toBeVisible();
expect(screen.getByLabelText("Период")).toHaveTextContent(
"02.08.2026 – 27.08.2026",
);
release();
expect(
await screen.findByText(/Показан последний загруженный результат/),
).toBeInTheDocument();
expect(screen.getByRole("region", { name: "Выплаты" })).toBeVisible();
server.use(
http.post("*/api/v1/tbank-sync", () =>
HttpResponse.json(
{
id: "income",
now: "2026-09-25T00:00:00Z",
scope: { accountId: "account-1", screen: "income" },
},
{ status: 202 },
),
),
http.get("*/api/v1/tbank-sync/:id", () =>
HttpResponse.json(
{
errorCode: null,
id: "income",
now: "2026-09-25T00:00:00Z",
scope: null,
state: "succeeded",
},
),
),
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
HttpResponse.json(resource(analytics, { dataRevision: "2" })),
),
);
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
await waitFor(() =>
expect(
screen.queryByText(/Показан последний загруженный результат/),
).not.toBeInTheDocument(),
);
expect(screen.queryByText(/Показан последний загруженный результат/)).not.toBeInTheDocument();
expect(screen.getByLabelText("Период")).toHaveTextContent(
"02.08.2026 – 27.08.2026",
);
@@ -5,7 +5,7 @@ import { useParams, useSearchParams } from "react-router";
import { type IncomeAnalytics, useIncomeAnalytics } from "@/entities/income";
import { useScreenSync } from "@/features/tbank-connection";
import { isValidPeriod, moscowDate } from "@/shared/lib";
import { isValidPeriod, moscowDate, useInitialAvailability } from "@/shared/lib";
import {
type IncomeDisplayModel,
@@ -27,19 +27,13 @@ type AccountIncomePageViewModel
display: IncomeDisplayModel;
form: ReturnType<typeof useForm<IncomeForm>>;
formRevision: string;
lastSuccessfulAt?: null | string;
onReset: () => void;
onSubmit: (values: IncomeForm) => void;
partial?: boolean;
refreshError: boolean;
refreshing: boolean;
retry: () => Promise<unknown> | undefined;
sourceError?: boolean;
state: "loaded";
}
| {
period: IncomePeriod;
retry: () => Promise<unknown> | undefined;
state: "error";
}
| { state: "loading" };
@@ -69,7 +63,7 @@ const useAccountIncomePageViewModel = (): AccountIncomePageViewModel => {
const [resetRevision, setResetRevision] = useState(0);
const analytics = useIncomeAnalytics(accountId, period);
const sync = useScreenSync(
useScreenSync(
{ accountId, from: period.from, screen: "income", to: period.to },
[analytics],
);
@@ -82,11 +76,20 @@ const useAccountIncomePageViewModel = (): AccountIncomePageViewModel => {
form.reset(draftPeriod(period));
}, [accountId, form, period]);
if (analytics.isLoading || !analytics.data) {
return analytics.isError || analytics.meta?.sync.state === "failed"
? { period, retry: sync.retry, state: "error" }
const availability = useInitialAvailability({
hasContent: !!analytics.data,
identity: `${accountId}:${period.from}:${period.to}`,
isError: analytics.isError || analytics.meta?.sync.state === "failed",
isFetching: analytics.isFetching,
});
if (availability === "loading" && analytics.isLoading)
return { state: "loading" };
if (!analytics.data)
return availability === "unavailable"
? { period, state: "error" }
: { state: "loading" };
}
const display = toIncomeDisplayModel(analytics.data, analytics.meta);
@@ -109,14 +112,9 @@ const useAccountIncomePageViewModel = (): AccountIncomePageViewModel => {
display,
form,
formRevision: `${accountId}:${period.from}:${period.to}:${resetRevision}`,
lastSuccessfulAt: analytics.meta?.lastSuccessfulAt,
onReset,
onSubmit,
partial: analytics.meta?.availability !== "complete",
refreshError: analytics.isError || sync.sourceError || sync.transportError,
refreshing: analytics.isFetching || sync.refreshing,
retry: sync.retry,
sourceError: sync.sourceError,
state: "loaded",
};
};
@@ -1,6 +1,5 @@
import type { FC } from "react";
import { Button } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import { useTranslation } from "react-i18next";
@@ -8,12 +7,11 @@ import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
type ErrorProps = Extract<AccountIncomePageViewModel, { state: "error" }>;
const AccountIncomePageError: FC<ErrorProps> = (props) => {
const AccountIncomePageError: FC<ErrorProps> = () => {
const { t } = useTranslation();
return (
<StateView
action={<Button onClick={props.retry}>{t("income.retry")}</Button>}
error
text={t("income.errorText")}
title={t("income.errorTitle")}
@@ -2,19 +2,13 @@ import type { FC } from "react";
import {
Alert,
Button,
Group,
Loader,
Stack,
Text,
Title,
} from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import { FormProvider } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { SourceSyncStatus } from "@/shared/ui";
import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
import classes from "../AccountIncomePage.module.css";
@@ -40,21 +34,14 @@ const AccountIncomePageLoadedSummary: FC<LoadedProps> = (props) => {
};
const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
const { display, form, onReset, onSubmit, refreshError, refreshing, retry }
= props;
const { display, form, onReset, onSubmit } = props;
const { t } = useTranslation();
return (
<Stack className={classes.page} gap="lg">
<SourceSyncStatus lastSuccessfulAt={props.lastSuccessfulAt} />
<Title order={1}>{t("income.title")}</Title>
<Button disabled={refreshing} onClick={retry} w="fit-content">
{t("investment.refresh")}
</Button>
<FormProvider {...form}>
<IncomePeriodForm
key={props.formRevision}
@@ -63,32 +50,6 @@ const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
/>
</FormProvider>
{!!refreshing && (
<Group aria-label={t("income.refreshing")} gap="xs" role="status">
<Loader size="sm" />
<Text>{t("income.refreshing")}</Text>
</Group>
)}
{!!refreshError && (
<Alert aria-live="polite" color="orange" role="status">
<Stack gap="sm">
<Text>
{t(
props.sourceError
? "investment.syncFailed"
: "income.refreshError",
)}
</Text>
<Button onClick={retry} variant="default">
{t("income.retry")}
</Button>
</Stack>
</Alert>
)}
<AccountIncomePageLoadedSummary {...props} />
<Alert color="blue">{t("income.taxBoundary")}</Alert>
@@ -346,7 +346,7 @@ describe("AccountOperationsPage", () => {
</MantineProvider>
</QueryClientProvider>,
);
await screen.findByRole("button", { name: "Повторить" });
await screen.findByRole("button", { name: "Сбросить" });
fireEvent.click(screen.getByRole("button", { name: "Сбросить" }));
await screen.findByLabelText("Период");
expect(screen.getByLabelText("URL")).toBeEmptyDOMElement();
@@ -484,7 +484,9 @@ describe("AccountOperationsPage", () => {
);
renderPage();
expect(
await screen.findByText("Не удалось загрузить журнал"),
await screen.findByText("Не удалось загрузить журнал", undefined, {
timeout: 4000,
}),
).toBeInTheDocument();
});
});
@@ -520,7 +522,7 @@ it("keeps UTC operation boundaries in GET and source sync requests", async () =>
}),
);
renderPage("?from=2024-02-29&to=2024-03-01&categories=trade");
const retry = await screen.findByRole("button", { name: "Повторить" });
await screen.findByRole("button", { name: "Сбросить" });
expect(requested).toEqual([
{
categories: "trade",
@@ -530,19 +532,6 @@ it("keeps UTC operation boundaries in GET and source sync requests", async () =>
},
]);
expect(syncRequests).toEqual([]);
fireEvent.click(retry);
await waitFor(() =>
expect(syncRequests).toEqual([
{
accountId: "account-1",
categories: ["trade"],
from: "2024-02-29T00:00:00.000Z",
limit: 100,
screen: "operations",
to: "2024-03-01T23:59:59.999Z",
},
]),
);
});
it("does not label incomplete empty operations as a confirmed empty period", async () => {
@@ -595,7 +584,6 @@ it("recovers an invalid cursor at the first page without clearing applied filter
);
renderPage("?from=2026-08-01&to=2026-08-14&categories=trade");
fireEvent.click(await screen.findByRole("button", { name: "Далее" }));
fireEvent.click(await screen.findByRole("button", { name: "Повторить" }));
await waitFor(() => expect(searches).toHaveLength(3));
assert.isDefined(searches[0]);
assert.isDefined(searches[2]);
@@ -11,7 +11,7 @@ import {
} from "@/entities/broker-operation";
import { useScreenSync } from "@/features/tbank-connection";
import { ApiErrorCode, apiErrorCode, isApiErrorCode } from "@/shared/api";
import { isValidPeriod, useUrlPeriod } from "@/shared/lib";
import { isValidPeriod, useInitialAvailability, useUrlPeriod } from "@/shared/lib";
const operationCategorySet = new Set<string>(operationCategories);
@@ -24,7 +24,6 @@ type AccountOperationsPageViewModel
hasPrevious: boolean;
historyLoading?: boolean;
items: BrokerageOperation[];
lastSuccessfulAt?: null | string;
onApply: () => void;
onCategoriesChange: (value: string[]) => void;
onNext: () => void;
@@ -32,13 +31,9 @@ type AccountOperationsPageViewModel
onPrevious: () => void;
onReset: () => void;
partial?: boolean;
refreshError?: boolean;
refreshing?: boolean;
retry?: () => void;
sourceError?: boolean;
state: "loaded";
}
| { onReset: () => void; retry: () => void; state: "error" }
| { onReset: () => void; state: "error" }
| { state: "loading" };
const useAccountOperationsPageVm = (): AccountOperationsPageViewModel => {
@@ -85,19 +80,28 @@ const useAccountOperationsPageVm = (): AccountOperationsPageViewModel => {
history.reset();
}
const sync = useScreenSync(
useScreenSync(
{ accountId, screen: "operations", ...firstPageQuery },
[operations],
);
if (operations.isLoading) return { state: "loading" };
const availability = useInitialAvailability({
hasContent: !!operations.data,
identity: scope,
isError: operations.isError || operations.meta?.sync.state === "failed",
isFetching: operations.isFetching,
});
if (availability === "loading" && operations.isLoading)
return { state: "loading" };
if (history.isRecoveringInvalidCursor)
return { state: "loading" };
const resetQueryKey = brokerageOperationsQueryOptions(accountId, {
limit: 100,
}).queryKey;
const retry = () => history.retry(sync.retry);
const onReset = () => {
setDraftPeriod([null, null]);
setDraftCategories([]);
@@ -106,16 +110,22 @@ const useAccountOperationsPageVm = (): AccountOperationsPageViewModel => {
void queryClient.invalidateQueries({ queryKey: resetQueryKey });
};
const isInvalidCursor = isApiErrorCode(
apiErrorCode(operations.error),
ApiErrorCode.InvalidOperationsCursor,
);
if (
(operations.isError || operations.meta?.sync.state === "failed")
&& (!operations.data
|| isApiErrorCode(
apiErrorCode(operations.error),
ApiErrorCode.InvalidOperationsCursor,
))
(isInvalidCursor || !operations.data)
&& (operations.isError || operations.meta?.sync.state === "failed")
)
return { onReset, retry, state: "error" };
if (!operations.data) return { state: "loading" };
return { onReset, state: "error" };
if (!operations.data)
return availability === "unavailable"
? { onReset, state: "error" }
: { state: "loading" };
const nextCursor = operations.data.nextCursor;
const isDirty
@@ -133,7 +143,6 @@ const useAccountOperationsPageVm = (): AccountOperationsPageViewModel => {
operations.meta?.coverage?.historyState === "loading"
|| operations.meta?.coverage?.historyState === "partial",
items: operations.data.items,
lastSuccessfulAt: operations.meta?.lastSuccessfulAt,
onApply: () => {
if (!isValidPeriod(draftFrom, draftTo)) return;
setSearchParameters({
@@ -155,10 +164,6 @@ const useAccountOperationsPageVm = (): AccountOperationsPageViewModel => {
onPrevious: history.onPrevious,
onReset,
partial: operations.meta?.availability !== "complete",
refreshError: operations.isError || sync.sourceError || sync.transportError,
refreshing: operations.isFetching || sync.refreshing,
retry,
sourceError: sync.sourceError,
state: "loaded",
};
};
@@ -1,6 +1,6 @@
import type { FC } from "react";
import { Button, Group } from "@mantine/core";
import { Button } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import { useTranslation } from "react-i18next";
@@ -14,21 +14,15 @@ type AccountOperationsPageErrorProps = Extract<
const AccountOperationsPageError: FC<AccountOperationsPageErrorProps> = (
props,
) => {
const { retry } = props;
const { t } = useTranslation();
return (
<StateView
action={(
<Group>
<Button onClick={retry}>{t("ledger.retry")}</Button>
<Button onClick={props.onReset} variant="default">
{t("ledger.reset")}
</Button>
</Group>
<Button onClick={props.onReset} variant="default">
{t("ledger.reset")}
</Button>
)}
error
text={t("ledger.errorText")}
title={t("ledger.errorTitle")}
/>
@@ -5,7 +5,6 @@ import {
Button,
Group,
MultiSelect,
Progress,
Stack,
Title,
} from "@mantine/core";
@@ -14,7 +13,6 @@ import { StateView } from "@wealthledger/ui";
import { useTranslation } from "react-i18next";
import { LedgerEntryRow, operationCategories } from "@/entities/broker-operation";
import { SourceSyncStatus } from "@/shared/ui";
import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm";
@@ -62,34 +60,12 @@ const AccountOperationsPageLoaded: FC<AccountOperationsPageLoadedProps> = (
return (
<Stack gap="lg">
<SourceSyncStatus lastSuccessfulAt={props.lastSuccessfulAt} />
<Title order={1}>{t("ledger.title")}</Title>
<Button disabled={props.refreshing} onClick={props.retry} w="fit-content">
{t("investment.refresh")}
</Button>
{!!props.partial && <Alert role="status">{t("investment.partial")}</Alert>}
{!!props.historyLoading && <Alert>{t("investment.history")}</Alert>}
{!!props.refreshing && <Progress animated aria-label={t("accounts.refreshing")} value={100} />}
{!!props.refreshError && (
<Alert aria-live="polite" color="yellow" role="status">
{t(
props.sourceError
? "investment.syncFailed"
: "accounts.refreshError",
)}
<Button onClick={props.retry} variant="subtle">
{t("accounts.retry")}
</Button>
</Alert>
)}
<Group align="end">
<DatePickerInput
allowSingleDateInRange
+9 -18
View File
@@ -10,20 +10,18 @@ const RECENT_EVENTS_LIMIT = 5;
type AccountPageIncomeSummary
= | {
lastSuccessfulAt?: null | string;
refreshError?: boolean;
stale?: boolean;
state: "loaded";
summary: IncomeSummary;
to: string;
}
| { retry: () => Promise<unknown> | undefined; state: "error"; to: string }
| {
state: "empty"
| "loading"
| "partial";
to: string;
};
}
| { state: "error"; to: string }
| {
state: "loaded";
summary: IncomeSummary;
to: string;
}
;
type AccountPageRecentEvents = BrokerageEventsPreviewState;
@@ -57,20 +55,16 @@ type PreviewResource<T> = {
function toIncomeSummary(
accountId: string | undefined,
income: PreviewResource<IncomeSummary>,
retry: () => Promise<unknown>,
): AccountPageIncomeSummary {
const to = `/accounts/${accountId}/income`;
if (!income.data && !income.isError && income.meta?.sync.state !== "failed")
return { state: "loading", to };
if (income.meta?.availability === "partial") return { state: "partial", to };
if (!income.data && (income.isError || income.meta?.sync.state === "failed"))
return { retry, state: "error", to };
return { state: "error", to };
if (!income.data?.totalsByCurrency.length) return { state: "empty", to };
return {
lastSuccessfulAt: income.meta?.lastSuccessfulAt,
refreshError: income.isError || income.meta?.sync.state === "failed",
stale: income.meta?.freshness === "stale",
state: "loaded",
summary: income.data,
to,
@@ -97,9 +91,6 @@ function toRecentEvents(
return {
items,
lastSuccessfulAt: events.meta?.lastSuccessfulAt,
refreshError: events.isError || events.meta?.sync.state === "failed",
stale: events.meta?.freshness === "stale",
state: "loaded",
to,
};
@@ -1,7 +1,6 @@
import { MantineProvider } from "@mantine/core";
import { type QueryClient, QueryClientProvider } from "@tanstack/react-query";
import {
fireEvent,
render,
screen,
waitFor,
@@ -261,7 +260,7 @@ describe("AccountPage states", () => {
it.each(["NOT_FOUND", "TBANK_NOT_CONNECTED", "INVALID_TBANK_TOKEN"])(
"does not offer retry without cached data for %s",
(code) => {
renderPage(<AccountPageError code={code} retry={vi.fn()} />);
renderPage(<AccountPageError code={code} />);
expect(
screen.queryByRole("button", { name: "Повторить" }),
).not.toBeInTheDocument();
@@ -274,12 +273,16 @@ describe("AccountPage states", () => {
},
);
it.each(["TBANK_UNAVAILABLE", "UNKNOWN"])("allows retry for %s", (code) => {
const retry = vi.fn();
renderPage(<AccountPageError code={code} retry={retry} />);
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
expect(retry).toHaveBeenCalledOnce();
});
it.each(["TBANK_UNAVAILABLE", "UNKNOWN"])(
"shows neutral unavailable without retry for %s",
(code) => {
renderPage(<AccountPageError code={code} />);
expect(screen.getByRole("heading", { name: "Пока недоступно" }))
.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Повторить" }))
.not.toBeInTheDocument();
},
);
it("shows supplied cash separately without adding currency instruments or recalculating totals", () => {
renderPage(
@@ -405,11 +408,9 @@ describe("AccountPage states", () => {
expect(
screen.getByRole("heading", { level: 1, name: "Портфель" }),
).toBeInTheDocument();
expect(
screen.getByText(
"T-Bank временно недоступен. Показан последний успешный снимок.",
),
).toBeInTheDocument();
expect(screen.queryByText(/T-Bank временно недоступен/))
.not.toBeInTheDocument();
expect(screen.queryByText(/Данные получены/)).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Акции" })).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Облигации" }),
@@ -573,7 +574,7 @@ describe("AccountPage states", () => {
);
expect(
screen.getByText("Не удалось загрузить последние события."),
screen.getByText("Пока недоступно"),
).toBeInTheDocument();
expect(screen.getByText("Вторая")).toBeInTheDocument();
});
@@ -742,13 +743,13 @@ describe("AccountPage states", () => {
);
expect(
screen.getByText("Не удалось загрузить будущие события."),
screen.getByText("Данные появятся здесь, когда чтение восстановится."),
).toBeInTheDocument();
expect(screen.getByText("Вторая")).toBeInTheDocument();
});
it.each([503])(
"preserves totals and UTC snapshot through refresh error %i, retry and success",
"preserves totals quietly through refresh error %i and success",
async (status) => {
const initialPortfolio: Portfolio
= {
@@ -821,40 +822,30 @@ describe("AccountPage states", () => {
});
expect(structure).toHaveTextContent("10 ₽");
const snapshotText = screen.getByText(/Данные получены/).textContent;
expect(snapshotText).toContain("10:00");
expect(screen.queryByText(/Данные получены/)).not.toBeInTheDocument();
void queryClient.invalidateQueries({
queryKey: portfolioQueryOptions("account-1").queryKey,
});
expect(
await screen.findByText(
"Не удалось обновить портфель. Показан последний полученный снимок.",
),
).toBeInTheDocument();
expect(
screen.getByText(
"T-Bank временно недоступен. Показан последний успешный снимок.",
),
).toBeInTheDocument();
await waitFor(() => expect(requestCount).toBe(2));
expect(screen.queryByText(/Не удалось обновить портфель/))
.not.toBeInTheDocument();
expect(screen.queryByText(/T-Bank временно недоступен/))
.not.toBeInTheDocument();
expect(screen.getByText("Вторая")).toBeInTheDocument();
expect(
screen.getAllByRole("definition").map(node => node.textContent),
).toEqual(["1 234,5 ₽", "0,5 $"]);
// eslint-disable-next-line jest-dom/prefer-to-have-text-content -- The cached timestamp must remain exactly unchanged.
expect(screen.getByText(/Данные получены/).textContent).toBe(
snapshotText,
);
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
expect(screen.queryByRole("button", { name: "Повторить" }))
.not.toBeInTheDocument();
void queryClient.invalidateQueries({
queryKey: portfolioQueryOptions("account-1").queryKey,
});
await waitFor(() => expect(requestCount).toBe(3));
expect(structure).toHaveTextContent("10 ₽");
expect(
screen.getAllByRole("definition").map(node => node.textContent),
).toEqual(["1 234,5 ₽", "0,5 $"]);
// eslint-disable-next-line jest-dom/prefer-to-have-text-content -- The cached timestamp must remain exactly unchanged.
expect(screen.getByText(/Данные получены/).textContent).toBe(
snapshotText,
);
resolveRetry?.(
HttpResponse.json(
resource(
@@ -875,7 +866,7 @@ describe("AccountPage states", () => {
screen.getAllByRole("definition").map(node => node.textContent),
).toEqual(["-0,5 $", "2,50 €"]),
);
expect(screen.getByText(/Данные получены/)).toHaveTextContent("11:30");
expect(screen.queryByText(/Данные получены/)).not.toBeInTheDocument();
expect(structure).not.toHaveTextContent("10 ₽");
expect(structure).toHaveTextContent("Нет положительной стоимости");
expect(
@@ -916,13 +907,12 @@ describe("AccountPage states", () => {
expect(
screen.getAllByRole("definition").map(node => node.textContent),
).toEqual(["1 234,5 ₽", "0,5 $"]);
expect(screen.getByText(/Данные получены/)).toHaveTextContent("10:00");
expect(screen.queryByText(/Данные получены/)).not.toBeInTheDocument();
expect(
screen.queryByRole("status", { name: "Загрузка" }),
).not.toBeInTheDocument();
expect(
screen.getByRole("status", { name: "Обновляем портфель" }),
).toBeInTheDocument();
expect(screen.queryByRole("status", { name: "Обновляем портфель" }))
.not.toBeInTheDocument();
resolveRefresh?.(HttpResponse.json(resource(portfolio)));
});
@@ -18,10 +18,6 @@ const AccountPage: FC = () => {
incomeSummary={viewModel.incomeSummary}
recentEvents={viewModel.recentEvents}
recentOperations={viewModel.recentOperations}
refreshError={viewModel.refreshError}
refreshing={viewModel.refreshing}
retry={viewModel.retry}
sourceError={viewModel.sourceError}
/>
);
@@ -35,10 +31,6 @@ const AccountPage: FC = () => {
positionSections={viewModel.positionSections}
recentEvents={viewModel.recentEvents}
recentOperations={viewModel.recentOperations}
refreshError={viewModel.refreshError}
refreshing={viewModel.refreshing}
retry={viewModel.retry}
sourceError={viewModel.sourceError}
/>
);
};
@@ -1,7 +1,7 @@
import type { FC, PropsWithChildren } from "react";
import { MantineProvider } from "@mantine/core";
import { act, renderHook, waitFor } from "@testing-library/react";
import { renderHook, waitFor } from "@testing-library/react";
import { http, HttpResponse } from "msw";
import { MemoryRouter, Route, Routes } from "react-router";
import { describe, expect, it, vi } from "vitest";
@@ -147,10 +147,10 @@ describe("useAccountPageViewModel", () => {
HttpResponse.json(resource(portfolio)),
),
http.get("*/api/v1/brokerage-accounts/:accountId/operations", () =>
HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }),
HttpResponse.json({ code: "DEMO_FAILURE" }, { status: 400 }),
),
http.get("*/api/v1/brokerage-accounts/:accountId/events", () =>
HttpResponse.json({ code: "MOEX_UNAVAILABLE" }, { status: 503 }),
HttpResponse.json({ code: "DEMO_FAILURE" }, { status: 400 }),
),
);
@@ -208,7 +208,7 @@ it("keeps overview sections independent when their source data is incomplete", a
);
});
it("refreshes every overview section through one account descriptor and observational reads", async () => {
it("keeps overview sections loaded without exposing technical retry", async () => {
configureTestAuth();
const sections: Record<string, unknown>
@@ -219,48 +219,17 @@ it("refreshes every overview section through one account descriptor and observat
portfolio,
};
const observed: string[] = [];
const scopes: unknown[] = [];
let version = "1";
server.use(
...Object.entries(sections).map(([path, data]) =>
http.get(
`*/api/v1/brokerage-accounts/:accountId/${path}`,
({ request }) => {
if (new URL(request.url).searchParams.get("sync") === "observe")
observed.push(path);
() => {
return HttpResponse.json(
resource(data, { dataRevision: version, resourceKey: path }),
resource(data, { dataRevision: "1", resourceKey: path }),
);
},
),
),
http.post("*/api/v1/tbank-sync", async ({ request }) => {
scopes.push(await request.json());
version = "2";
return HttpResponse.json(
{
id: "overview",
now: "2026-09-25T00:00:00Z",
scope: { accountId: "account-1", screen: "account" },
},
{ status: 202 },
);
}),
http.get("*/api/v1/tbank-sync/:id", () =>
HttpResponse.json(
{
errorCode: null,
id: "overview",
now: "2026-09-25T00:00:00Z",
scope: null,
state: "succeeded",
},
),
),
);
const { result } = renderHook(() => useAccountPageViewModel(), {
@@ -275,11 +244,5 @@ it("refreshes every overview section through one account descriptor and observat
state: "loaded",
}),
);
await act(async () => {
if (result.current.state === "loaded") await result.current.retry();
});
await waitFor(() =>
expect(new Set(observed)).toEqual(new Set(Object.keys(sections))),
);
expect(scopes).toEqual([{ accountId: "account-1", screen: "account" }]);
expect(result.current).not.toHaveProperty("retry");
});
@@ -13,7 +13,8 @@ import {
import { useIncomeSummary } from "@/entities/income";
import { usePortfolio } from "@/entities/portfolio";
import { useScreenSync } from "@/features/tbank-connection";
import { apiErrorCode } from "@/shared/api";
import { ApiErrorCode, apiErrorCode, isApiErrorCode } from "@/shared/api";
import { useInitialAvailability } from "@/shared/lib";
import {
type AccountPagePositionSection,
@@ -35,10 +36,6 @@ type AccountPageContent = {
partial?: boolean;
recentEvents: AccountPageRecentEvents;
recentOperations: AccountPageRecentOperations;
refreshError: boolean;
refreshing: boolean;
retry: () => Promise<unknown> | undefined;
sourceError?: boolean;
};
type AccountPageEmptyViewModel = AccountPageContent & {
@@ -54,9 +51,16 @@ type AccountPageLoadedViewModel = AccountPageContent & {
type AccountPageViewModel
= | AccountPageEmptyViewModel
| AccountPageLoadedViewModel
| { code?: string; retry: () => Promise<unknown> | undefined; state: "error" }
| { code?: string; state: "error" }
| { state: "loading" };
function isPortfolioAccessFailure(code?: string) {
return isApiErrorCode(code, ApiErrorCode.Forbidden)
|| isApiErrorCode(code, ApiErrorCode.InvalidTbankToken)
|| isApiErrorCode(code, ApiErrorCode.NotFound)
|| isApiErrorCode(code, ApiErrorCode.TbankNotConnected);
}
function useAccountPageViewModel(): AccountPageViewModel {
const { accountId } = useParams();
const portfolio = usePortfolio(accountId);
@@ -69,7 +73,7 @@ function useAccountPageViewModel(): AccountPageViewModel {
const income = useIncomeSummary(accountId);
const accounts = useBrokerageAccounts();
const sync = useScreenSync({ accountId, screen: "account" }, [
useScreenSync({ accountId, screen: "account" }, [
accounts,
portfolio,
operations,
@@ -77,32 +81,28 @@ function useAccountPageViewModel(): AccountPageViewModel {
income,
]);
if (!portfolio.data) {
if (portfolio.isError || portfolio.meta?.sync.state === "failed")
return {
code: apiErrorCode(portfolio.error),
retry: sync.retry,
state: "error" as const,
};
const code = apiErrorCode(portfolio.error);
const isAccessFailure = isPortfolioAccessFailure(code);
return { state: "loading" as const };
}
const availability = useInitialAvailability({
hasContent: !!portfolio.data,
identity: accountId ?? "account",
isError: portfolio.isError || portfolio.meta?.sync.state === "failed",
isFetching: portfolio.isFetching,
});
if (isAccessFailure) return { code, state: "error" as const };
if (!portfolio.data)
return {
state: availability === "unavailable" ? "error" : "loading",
} as const;
const account = accounts.data?.find(item => item.id === accountId);
const recentOperations = toRecentOperations(accountId, operations);
const recentEvents = toRecentEvents(accountId, events);
const incomeSummary = toIncomeSummary(
accountId, income, () => income.refetch(),
);
const refresh = {
partial: portfolio.meta?.availability === "partial",
refreshError: portfolio.isError || sync.transportError || sync.sourceError,
refreshing: portfolio.isFetching || sync.refreshing,
retry: sync.retry,
sourceError: sync.sourceError,
};
const incomeSummary = toIncomeSummary(accountId, income);
if (
portfolio.meta?.availability === "complete"
@@ -116,19 +116,20 @@ function useAccountPageViewModel(): AccountPageViewModel {
recentEvents,
recentOperations,
state: "empty" as const,
...refresh,
};
const isPartial = portfolio.meta?.availability === "partial";
return {
account,
accountId,
incomeSummary,
partial: isPartial,
portfolio: portfolio.data,
positionSections: toAccountPagePositionSections(portfolio.data),
recentEvents,
recentOperations,
state: "loaded" as const,
...refresh,
};
}
@@ -7,7 +7,6 @@ import { useTranslation } from "react-i18next";
import type { BrokerageAccount } from "@/entities/brokerage-account";
import { BrokerageEventsPreview } from "@/entities/brokerage-event";
import { InvestmentRefreshState } from "@/features/tbank-connection";
import type {
AccountPageIncomeSummary,
@@ -26,10 +25,6 @@ type AccountPageEmptyProps = {
incomeSummary?: AccountPageIncomeSummary;
recentEvents: AccountPageRecentEvents;
recentOperations: AccountPageRecentOperations;
refreshError?: boolean;
refreshing?: boolean;
retry?: () => void;
sourceError?: boolean;
};
const AccountPageEmpty: FC<AccountPageEmptyProps> = (props) => {
@@ -45,14 +40,6 @@ const AccountPageEmpty: FC<AccountPageEmptyProps> = (props) => {
<Stack>
<AccountHeading account={props.account} accountId={props.accountId} />
<InvestmentRefreshState
labelScope="portfolio"
refreshError={props.refreshError ?? false}
refreshing={props.refreshing ?? false}
retry={props.retry}
sourceError={props.sourceError}
/>
<StateView text={text} title={t("portfolio.emptyTitle")} />
<PortfolioStructure
@@ -7,10 +7,10 @@ import { Link } from "react-router";
import { ApiErrorCode, isApiErrorCode } from "@/shared/api";
type AccountPageErrorProps = { code?: string; retry: () => void };
type AccountPageErrorProps = { code?: string };
const AccountPageError: FC<AccountPageErrorProps> = (props) => {
const { code, retry } = props;
const { code } = props;
const { t } = useTranslation();
if (isApiErrorCode(code, ApiErrorCode.NotFound))
return (
@@ -25,6 +25,7 @@ const AccountPageError: FC<AccountPageErrorProps> = (props) => {
title={t("portfolio.accountUnavailableTitle")}
/>
);
if (
isApiErrorCode(code, ApiErrorCode.TbankNotConnected)
|| isApiErrorCode(code, ApiErrorCode.InvalidTbankToken)
@@ -41,22 +42,11 @@ const AccountPageError: FC<AccountPageErrorProps> = (props) => {
title={t("portfolio.connectionErrorTitle")}
/>
);
if (isApiErrorCode(code, ApiErrorCode.TbankUnavailable))
return (
<StateView
action={<Button onClick={retry}>{t("accounts.retry")}</Button>}
error
text={t("accounts.unavailableText")}
title={t("accounts.unavailableTitle")}
/>
);
return (
<StateView
action={<Button onClick={retry}>{t("accounts.retry")}</Button>}
error
text={t("states.errorText")}
title={t("states.errorTitle")}
text={t("states.unavailableText")}
title={t("states.unavailableTitle")}
/>
);
};
@@ -1,14 +1,12 @@
import type { FC } from "react";
import { Accordion, Alert, Stack, Text } from "@mantine/core";
import { Accordion, Alert, Stack } from "@mantine/core";
import { useTranslation } from "react-i18next";
import type { BrokerageAccount } from "@/entities/brokerage-account";
import type { Portfolio } from "@/entities/portfolio";
import { BrokerageEventsPreview } from "@/entities/brokerage-event";
import { InvestmentRefreshState } from "@/features/tbank-connection";
import { formatSnapshotTime } from "@/shared/lib";
import type { AccountPagePositionSection } from "../../../model/positions";
import type {
@@ -34,10 +32,6 @@ type AccountPageLoadedProps = {
positionSections: AccountPagePositionSection[];
recentEvents: AccountPageRecentEvents;
recentOperations: AccountPageRecentOperations;
refreshError?: boolean;
refreshing?: boolean;
retry?: () => void;
sourceError?: boolean;
};
const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
@@ -55,27 +49,6 @@ const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
<Stack gap="lg">
<AccountHeading account={props.account} accountId={props.accountId} />
<InvestmentRefreshState
labelScope="portfolio"
refreshError={props.refreshError ?? false}
refreshing={props.refreshing ?? false}
retry={props.retry}
sourceError={props.sourceError}
/>
{!!props.portfolio.isStale && <Alert color="blue">{t("portfolio.staleWarning")}</Alert>}
<Text c="dimmed" size="sm">
{t(
props.accountId === "all"
? "portfolio.allUpdatedAt"
: "portfolio.updatedAt",
{
date: formatSnapshotTime(props.portfolio.lastSuccessfulAt),
},
)}
</Text>
{props.partial
? <Alert role="status">{t("investment.partial")}</Alert>
: <CurrencyCards amounts={props.portfolio.totalsByCurrency} />}
@@ -8,30 +8,30 @@ import { Link } from "react-router";
import type { IncomeSummary as IncomeSummaryData } from "@/entities/income";
import { formatMoney } from "@/shared/lib";
import { SourceSyncStatus } from "@/shared/ui";
type IncomeSummaryProps
= | {
lastSuccessfulAt?: null | string;
refreshError?: boolean;
stale?: boolean;
state: "empty";
to: string;
}
| { state: "error"; to: string }
| {
state: "loaded";
summary: IncomeSummaryData;
to: string;
}
| { retry: () => void; state: "error"; to: string }
| { state: "empty"; to: string }
| { state: "loading"; to: string }
| { state: "partial"; to: string };
| {
state: "loading";
to: string;
}
| {
state: "partial";
to: string;
};
const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
const { t } = useTranslation();
const errorText
= props.state === "loaded" && props.refreshError
? t("income.refreshError")
: null;
if (props.state === "loading" || props.state === "partial")
return (
<Text c="dimmed" role="status">
@@ -45,9 +45,6 @@ const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
if (props.state === "error")
return (
<StateView
action={
<Button onClick={props.retry}>{t("income.summaryRetry")}</Button>
}
error
text={t("income.errorText")}
title={t("income.summaryError")}
@@ -66,12 +63,6 @@ const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
return (
<Stack gap="xs">
<SourceSyncStatus
errorText={errorText}
lastSuccessfulAt={props.lastSuccessfulAt}
stale={props.stale}
/>
{props.summary.totalsByCurrency.map(total => (
<Paper key={total.currency} p="sm" withBorder>
<Text fw={700}>{formatMoney(total.total)}</Text>
@@ -1,12 +1,11 @@
import type { FC } from "react";
import { Alert, Button, Skeleton, Stack, Text } from "@mantine/core";
import { Button, Skeleton, Stack, Text } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { LedgerEntryRow } from "@/entities/broker-operation";
import { SourceSyncStatus } from "@/shared/ui";
import type { AccountPageRecentOperations } from "../../../model/previews";
@@ -18,28 +17,15 @@ const RecentOperations: FC<RecentOperationsProps> = (props) => {
const { t } = useTranslation();
const { operations } = props;
const errorText
= operations.state === "loaded" && operations.refreshError
? t("accounts.refreshError")
: null;
return (
<Stack gap="sm">
{operations.state === "loaded" && (
<SourceSyncStatus
errorText={errorText}
lastSuccessfulAt={operations.lastSuccessfulAt}
stale={operations.stale}
/>
)}
{operations.state === "loading" && (
<LoadingSkeleton label={t("ledger.recentLoading")}>
{["first", "second", "third"].map(placeholder => <Skeleton height={48} key={placeholder} radius="sm" />)}
</LoadingSkeleton>
)}
{operations.state === "error" && <Alert color="red">{t("ledger.recentError")}</Alert>}
{operations.state === "error" && <Text c="dimmed">{t("states.unavailableTitle")}</Text>}
{operations.state === "empty" && <Text c="dimmed">{t("ledger.recentEmpty")}</Text>}
@@ -1,6 +1,6 @@
import { MantineProvider } from "@mantine/core";
import { type QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { render, screen, waitFor } from "@testing-library/react";
import { http, HttpResponse } from "msw";
import { MemoryRouter } from "react-router";
import { describe, expect, it, vi } from "vitest";
@@ -58,10 +58,11 @@ describe("AccountsPage", () => {
}),
);
renderPage(createTestQueryClient());
fireEvent.click(await screen.findByRole("button", { name: "Повторить" }));
expect(await screen.findByText(account.name)).toBeVisible();
expect(await screen.findByText(account.name, undefined, {
timeout: 4000,
})).toBeVisible();
expect(modes).toEqual([null, "observe"]);
expect(modes).toEqual([null, null]);
});
it.each([
["loading", AccountsPageLoading, "status"],
@@ -81,17 +82,16 @@ describe("AccountsPage", () => {
).toBeInTheDocument();
});
it("routes connection errors to settings and keeps retry available", () => {
const retry = vi.fn();
it("routes connection errors to settings without technical retry", () => {
render(
<MantineProvider>
<MemoryRouter>
<AccountsPageError code="TBANK_UNAVAILABLE" retry={retry} />
<AccountsPageError code="TBANK_NOT_CONNECTED" />
</MemoryRouter>
</MantineProvider>,
);
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
expect(retry).toHaveBeenCalledOnce();
expect(screen.queryByRole("button", { name: "Повторить" }))
.not.toBeInTheDocument();
expect(
screen.getByRole("link", { name: "Открыть настройки T-Bank" }),
).toHaveAttribute("href", "/settings");
@@ -123,14 +123,13 @@ describe("AccountsPage", () => {
await waitFor(() => expect(requestCount).toBe(2));
expect(screen.getByText(account.name)).toBeInTheDocument();
expect(
screen.getByRole("status", { name: "Обновляем данные" }),
).toBeInTheDocument();
expect(screen.queryByRole("status", { name: "Обновляем данные" }))
.not.toBeInTheDocument();
resolveRefresh?.(HttpResponse.json(resource([account])));
});
it("keeps the cached account list and offers retry after a refresh error", async () => {
it("keeps the cached account list quietly after a refresh error", async () => {
const requests: unknown[] = [];
server.use(
http.post("*/api/v1/tbank-sync", async ({ request }) => {
@@ -161,17 +160,15 @@ describe("AccountsPage", () => {
queryKey: brokerageAccountsQueryKey,
});
const warning = await screen.findByText(
"Не удалось обновить данные. Показаны последние полученные.",
);
expect(warning).toBeInTheDocument();
await waitFor(() => expect(requestCount).toBe(2));
expect(
screen.queryByText(
"Не удалось обновить данные. Показаны последние полученные.",
),
).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Повторить" }))
.not.toBeInTheDocument();
expect(screen.getByText(account.name)).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
await waitFor(() => expect(requestCount).toBe(3));
await waitFor(() => expect(warning).not.toBeInTheDocument());
expect(screen.getByText(account.name)).toBeVisible();
expect(requests).toEqual([]);
});
@@ -194,11 +191,12 @@ describe("AccountsPage", () => {
queryKey: brokerageAccountsQueryKey,
});
await waitFor(() => expect(requestCount).toBe(2));
expect(
await screen.findByText(
screen.queryByText(
"Не удалось обновить данные. Показаны последние полученные.",
),
).toBeInTheDocument();
).not.toBeInTheDocument();
expect(screen.getByText("Нет инвестиционных счетов")).toBeInTheDocument();
});
});
@@ -226,7 +224,7 @@ it.each(["idle", "failed"] as const)(
.not.toBeInTheDocument();
if (state === "failed")
// eslint-disable-next-line vitest/no-conditional-expect -- Each fixed state has a different observable recovery contract.
expect(await screen.findByRole("button", { name: "Повторить" }))
expect(await screen.findByRole("heading", { name: "Пока недоступно" }))
.toBeVisible();
else
// eslint-disable-next-line vitest/no-conditional-expect -- Each fixed state has a different observable recovery contract.
@@ -10,25 +10,11 @@ const AccountsPage: FC = () => {
const viewModel = useAccountsPageViewModel();
if (viewModel.state === "loading") return <AccountsPageLoading />;
if (viewModel.state === "error") return <AccountsPageError {...viewModel} />;
if (viewModel.state === "empty")
return (
<AccountsPageEmpty
lastSuccessfulAt={viewModel.lastSuccessfulAt}
refreshError={viewModel.refreshError}
refreshing={viewModel.refreshing}
retry={viewModel.retry}
sourceError={viewModel.sourceError}
/>
);
if (viewModel.state === "empty") return <AccountsPageEmpty />;
return (
<AccountsPageLoaded
accounts={viewModel.accounts}
lastSuccessfulAt={viewModel.lastSuccessfulAt}
refreshError={viewModel.refreshError}
refreshing={viewModel.refreshing}
retry={viewModel.retry}
sourceError={viewModel.sourceError}
/>
);
};
@@ -1,45 +1,54 @@
import {
type BrokerageAccountCard,
brokerageAccountCards,
useBrokerageAccounts,
} from "@/entities/brokerage-account";
import { useScreenSync } from "@/features/tbank-connection";
import { apiErrorCode } from "@/shared/api";
import { ApiErrorCode, apiErrorCode, isApiErrorCode } from "@/shared/api";
import { useInitialAvailability } from "@/shared/lib";
function useAccountsPageViewModel() {
type AccountsPageViewModel
= | { accounts: BrokerageAccountCard[]; state: "loaded" }
| { code?: string; state: "error" }
| { state: "empty" }
| { state: "loading" };
function isAccountsAccessFailure(code?: string) {
return isApiErrorCode(code, ApiErrorCode.InvalidTbankToken)
|| isApiErrorCode(code, ApiErrorCode.TbankNotConnected);
}
function useAccountsPageViewModel(): AccountsPageViewModel {
const accounts = useBrokerageAccounts();
const sync = useScreenSync({ screen: "accounts" }, [accounts]);
useScreenSync({ screen: "accounts" }, [accounts]);
if (
!accounts.data
|| (accounts.meta?.availability === "partial" && accounts.data.length === 0)
) {
if (!accounts.isError && accounts.meta?.sync.state !== "failed")
return { state: "loading" as const };
const code = apiErrorCode(accounts.error);
const isAccessFailure = isAccountsAccessFailure(code);
const hasResult = !!accounts.data
&& !(accounts.meta?.availability === "partial" && accounts.data.length === 0);
const availability = useInitialAvailability({
hasContent: hasResult,
identity: "accounts",
isError: accounts.isError || accounts.meta?.sync.state === "failed",
isFetching: accounts.isFetching,
});
if (isAccessFailure) return { code, state: "error" as const };
if (!hasResult || !accounts.data)
return {
code: apiErrorCode(accounts.error),
retry: sync.retry,
state: "error" as const,
};
}
const refresh = {
lastSuccessfulAt: accounts.meta?.lastSuccessfulAt,
refreshError: accounts.isError || sync.transportError || sync.sourceError,
refreshing: accounts.isFetching || sync.refreshing,
retry: sync.retry,
sourceError: sync.sourceError,
};
state: availability === "unavailable" ? "error" : "loading",
} as const;
if (accounts.data.length === 0)
return {
...refresh,
state: "empty" as const,
};
return {
accounts: brokerageAccountCards(accounts.data, accounts.meta?.dependencies),
...refresh,
state: "loaded" as const,
};
}
@@ -1,26 +1,16 @@
import type { FC } from "react";
import { Stack } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import { useTranslation } from "react-i18next";
import {
InvestmentRefreshState,
type InvestmentRefreshStateProps,
} from "@/features/tbank-connection";
const AccountsPageEmpty: FC<InvestmentRefreshStateProps> = (props) => {
const AccountsPageEmpty: FC = () => {
const { t } = useTranslation();
return (
<Stack>
<InvestmentRefreshState {...props} />
<StateView
text={t("accounts.emptyText")}
title={t("accounts.emptyTitle")}
/>
</Stack>
<StateView
text={t("accounts.emptyText")}
title={t("accounts.emptyTitle")}
/>
);
};
@@ -1,16 +1,16 @@
import type { FC } from "react";
import { Button, Stack } from "@mantine/core";
import { Button } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { ApiErrorCode, isApiErrorCode } from "@/shared/api";
type AccountsPageErrorProps = { code?: string; retry?: () => void };
type AccountsPageErrorProps = { code?: string };
const AccountsPageError: FC<AccountsPageErrorProps> = (props) => {
const { code, retry } = props;
const { code } = props;
const { t } = useTranslation();
const settingsAction = (
@@ -37,28 +37,11 @@ const AccountsPageError: FC<AccountsPageErrorProps> = (props) => {
title={t("accounts.invalidTokenTitle")}
/>
);
if (isApiErrorCode(code, ApiErrorCode.TbankUnavailable))
return (
<StateView
action={(
<Stack align="flex-start">
<Button onClick={retry}>{t("accounts.retry")}</Button>
{settingsAction}
</Stack>
)}
error
text={t("accounts.unavailableText")}
title={t("accounts.unavailableTitle")}
/>
);
return (
<StateView
action={<Button onClick={retry}>{t("accounts.retry")}</Button>}
error
text={t("states.errorText")}
title={t("states.errorTitle")}
text={t("states.unavailableText")}
title={t("states.unavailableTitle")}
/>
);
};
@@ -8,17 +8,12 @@ import {
type BrokerageAccountCard,
BrokerageAccountList,
} from "@/entities/brokerage-account";
import {
InvestmentRefreshState,
type InvestmentRefreshStateProps,
} from "@/features/tbank-connection";
type AccountsPageLoadedProps = InvestmentRefreshStateProps & {
type AccountsPageLoadedProps = {
accounts: BrokerageAccountCard[];
};
const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
const { accounts, ...refresh } = props;
const { t } = useTranslation();
return (
@@ -31,8 +26,6 @@ const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
</Text>
</Stack>
<InvestmentRefreshState {...refresh} />
<Button
component={Link}
to="/accounts/all"
@@ -42,7 +35,7 @@ const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
{t("accounts.openAll")}
</Button>
<BrokerageAccountList accounts={accounts} />
<BrokerageAccountList accounts={props.accounts} />
</Stack>
);
};
+3 -33
View File
@@ -352,11 +352,7 @@ describe("bond page", () => {
it("keeps market content and sold-position history when coupons fail", async () => {
setup({ failCoupons: true, noPosition: true });
await screen.findByText("98,125 %");
const message = await screen.findByText(/Не удалось загрузить этот раздел/);
expect(
// eslint-disable-next-line testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
message.closest("[role=\"status\"]"),
).toHaveAttribute("aria-live", "polite");
expect(screen.queryByRole("button", { name: "Повторить" })).not.toBeInTheDocument();
expect(
screen.queryByRole("heading", { name: "Моя позиция" }),
).not.toBeInTheDocument();
@@ -364,38 +360,12 @@ describe("bond page", () => {
screen.getByRole("heading", { name: "Моя история событий" }),
).toBeVisible();
});
it("preserves cached quote on refresh failure", async () => {
const scopes: unknown[] = [];
server.use(
http.post("*/api/v1/tbank-sync", async ({ request }) => {
scopes.push(await request.json());
return HttpResponse.json(
{ code: "TBANK_UNAVAILABLE" },
{ status: 503 },
);
}),
);
it("preserves cached quote without manual refresh", async () => {
const controls = setup({ path: `/bonds/${uid}?period=year&events=trades` });
await screen.findByText("98,125 %");
controls.failQuote();
fireEvent.click(screen.getByRole("button", { name: "Обновить" }));
const message = await screen.findByText(/последние полученные/);
expect(
// eslint-disable-next-line testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
message.closest("[role=\"status\"]"),
).toHaveAttribute("aria-live", "polite");
expect(screen.getByText("98,125 %")).toBeVisible();
expect(scopes).toEqual([
{
accountId: "all",
candlePeriod: "year",
categories: ["trade"],
instrumentUid: uid,
limit: 20,
screen: "bond",
},
]);
expect(screen.queryByRole("button", { name: "Обновить" })).not.toBeInTheDocument();
});
it("offers search for an ambiguous or missing instrument without loading personal data", async () => {
const { requests } = setup({ ambiguousTicker: true, path: "/bonds/SAME" });
-1
View File
@@ -15,7 +15,6 @@ const BondPage: FC = () => {
code={vm.code}
kind="bond"
loading={vm.bondState.loading}
retry={vm.bondState.retry}
/>
);
@@ -1,7 +1,6 @@
import type { FC } from "react";
import {
Alert,
Badge,
Group,
Skeleton,
@@ -137,8 +136,6 @@ const BondPageView: FC<BondPageViewProps> = (props) => {
<InstrumentHeader
logoSrc={vm.logoSrc}
name={bond.name}
onRefresh={vm.refresh}
refreshing={vm.refreshing}
subtitle={subtitle}
>
@@ -156,20 +153,8 @@ const BondPageView: FC<BondPageViewProps> = (props) => {
)}
</Group>
{!!(vm.refreshError || vm.bondState.error || vm.quoteState.error) && (
<Alert aria-live="polite" color="orange" mt="md" role="status">
{t(vm.quote ? "accounts.refreshError" : "stock.sectionError")}
</Alert>
)}
{quoteContent}
{!!(vm.quoteState.refreshing || vm.bondState.refreshing) && (
<Text c="dimmed" role="status" size="xs">
{t("accounts.refreshing")}
</Text>
)}
<InstrumentTerms title={t("bond.terms")}>
<InstrumentMetrics>
+8 -14
View File
@@ -42,7 +42,7 @@ function useBondPageVm() {
const { operations } = history;
const sync = useScreenSync(
useScreenSync(
{
accountId: "all",
candlePeriod: period,
@@ -56,29 +56,26 @@ function useBondPageVm() {
return {
bond: bond.data,
bondState: section(bond, uid ? sync.retry : () => bond.refetch()),
bondState: section(bond),
candles: candles.data,
candlesState: section(candles, sync.retry),
candlesState: section(candles),
canonicalTo:
bond.data?.slug && bond.data.slug !== bondId
? `/bonds/${encodeURIComponent(bond.data.slug)}${search}`
: null,
code: apiErrorCode(bond.error),
coupons: coupons.data,
couponsState: section(coupons, sync.retry),
couponsState: section(coupons),
eventRows: toInstrumentEventRows(operations.data?.items, bond.data),
filter,
hasPrevious: history.hasPrevious,
logoSrc: instrumentLogoUrl(bond.data?.logoName),
metrics: metrics.data,
metricsState: section(metrics, sync.retry),
metricsState: section(metrics),
onNext: history.onNext,
onPrevious: history.onPrevious,
operations: operations.data,
operationsState: {
...section(operations, sync.retry),
retry: () => history.retry(sync.retry),
},
operationsState: section(operations),
pastCoupons:
coupons.data?.coupons
.filter(event => event.timing !== "upcoming")
@@ -87,12 +84,9 @@ function useBondPageVm() {
) ?? [],
period,
position: position.data,
positionState: section(position, sync.retry),
positionState: section(position),
quote: quote.data,
quoteState: section(quote, sync.retry),
refresh: sync.refresh,
refreshError: sync.transportError || sync.sourceError,
refreshing: sync.refreshing,
quoteState: section(quote),
setFilter,
setPeriod,
upcoming:
+4 -6
View File
@@ -10,12 +10,14 @@ function useBondsPageVm() {
const search = useInstrumentSearch(MIN_BOND_SEARCH_LENGTH);
const { canSearch, debounced, isWaiting, query } = search;
const result = useBondSearch(debounced);
const sync = useScreenSync({ query: debounced, screen: "bonds" }, [result]);
useScreenSync({ query: debounced, screen: "bonds" }, [result]);
return {
canSearch,
code: apiErrorCode(result.error),
error: result.isError || sync.sourceError || sync.transportError,
error:
!result.data
&& (result.isError || result.meta?.sync.state === "failed"),
items:
result.data?.map(bond => ({
...bond,
@@ -35,10 +37,6 @@ function useBondsPageVm() {
debounced.length >= MIN_BOND_SEARCH_LENGTH
&& !isWaiting
&& Boolean(result.data),
refreshing: sync.refreshing,
retry: () => {
void sync.retry();
},
};
}
+16 -19
View File
@@ -256,21 +256,19 @@ describe("CardPage", () => {
}),
);
fireEvent.click(screen.getByRole("button", { name: "Далее" }));
await waitFor(() =>
expect(screen.getByRole("button", { name: "Далее" })).toBeDisabled(),
);
await waitFor(() => {
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
expect(screen.getByText("Перевод на «Запасная»")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Изменить" })).toBeDisabled();
expect(
screen.queryByLabelText("Загрузка операций"),
).not.toBeInTheDocument();
expect(screen.queryByLabelText("Загрузка операций")).not.toBeInTheDocument();
expect(scroll).not.toHaveBeenCalled();
measure.mockReturnValue({ top: 200 } as DOMRect);
release();
await screen.findByText(/Новая страница/);
// eslint-disable-next-line testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
const list = screen.getByText(/Новая страница/).closest("[aria-busy]");
expect(list?.parentElement?.style.minHeight).toBe("");
const newPageText = screen.getByText(/Новая страница/);
expect(newPageText).toBeInTheDocument();
expect(scroll).toHaveBeenCalledExactlyOnceWith({
behavior: "instant",
top: -400,
@@ -317,7 +315,9 @@ describe("CardPage", () => {
it("keeps card and journal when summary fails", async () => {
setup({ summaryError: true });
await screen.findByRole("heading", { name: "Повседневная" });
await screen.findByRole("alert");
expect(
screen.queryByRole("alert"),
).not.toBeInTheDocument();
expect(
await screen.findByText("Перевод на «Запасная»"),
).toBeInTheDocument();
@@ -331,7 +331,9 @@ describe("CardPage", () => {
http.get("*/api/v1/bank-cards/a/operations", () => HttpResponse.error()),
);
await client.invalidateQueries();
await screen.findAllByRole("alert");
await waitFor(() => {
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
expect(
screen.getByRole("heading", { name: "Повседневная" }),
).toBeInTheDocument();
@@ -401,9 +403,9 @@ describe("CardPage", () => {
it("recovers the prerequisite card list while preserving the visible balance and journal", async () => {
setup({ cardsError: true });
await screen.findByText("Перевод на «Запасная»");
expect(await screen.findByRole("alert")).toHaveTextContent(
"Не удалось загрузить данные карт.",
);
expect(
screen.queryByRole("alert"),
).not.toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Добавить операцию" }),
).toBeDisabled();
@@ -412,11 +414,6 @@ describe("CardPage", () => {
HttpResponse.json([card, { ...card, id: "b", name: "Запасная" }]),
),
);
fireEvent.click(
within(screen.getByRole("alert")).getByRole("button", {
name: "Повторить",
}),
);
await waitFor(() =>
expect(
screen.getByRole("button", { name: "Добавить операцию" }),
+2 -22
View File
@@ -75,7 +75,6 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
{t("bank.back")}
</Button>
{!vm.notFound && <Button onClick={vm.retryCard}>{t("bank.retry")}</Button>}
</Group>
)}
error
@@ -125,27 +124,16 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
</div>
{!!vm.archiveError && (
<BankFeedback error={vm.archiveError} retry={vm.retryCard} />
<BankFeedback error={vm.archiveError} />
)}
{card.archivedAt && <Text>{t("bank.archiveHint")}</Text>}
</Stack>
{vm.cardRefreshError && (
<Group role="alert">
<Text>{t("bank.refreshError")}</Text>
<Button onClick={vm.retryCard}>{t("bank.retry")}</Button>
</Group>
)}
{vm.cardRefreshing && <Text role="status">{t("bank.refreshing")}</Text>}
{vm.cardsFeedback && (
<BankFeedback
{...vm.cardsFeedback}
loadingError
retry={vm.retryCards}
/>
)}
@@ -187,7 +175,6 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
</Group>
<Stack
aria-busy={vm.history.refreshing}
className={classes.operations}
data-pending={vm.history.changingPage || undefined}
gap="lg"
@@ -196,13 +183,7 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
<CardHistory history={vm.history} period={vm.period} rows={vm.rows} />
</Stack>
{vm.history.error && (
<Group role="alert">
<Text>{t(vm.rows ? "bank.refreshError" : "bank.error")}</Text>
<Button onClick={vm.history.retry}>{t("bank.retry")}</Button>
</Group>
)}
{vm.history.error && !vm.rows && <Text role="alert">{t("bank.error")}</Text>}
{vm.history.page !== undefined && vm.pageSize !== "all" && (
<Group
@@ -213,7 +194,6 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
ref={paginationRef}
>
<Pagination
disabled={vm.history.refreshing}
getControlProps={getControlProps}
getItemProps={getItemProps}
onChange={onPageChange}
@@ -115,8 +115,6 @@ function useCardPageVm() {
error: history.isError,
loading: history.isLoading,
page: history.data?.page,
refreshing: history.isFetching,
retry: () => void history.refetch(),
},
notFound: isApiErrorCode(
apiErrorCode(card.error),
@@ -128,8 +126,6 @@ function useCardPageVm() {
page,
pageSize,
period,
retryCard: () => void card.refetch(),
retryCards: () => void cards.refetch(),
rows,
setPage: (value: number) =>
setParameters({ ...period, limit: pageSize, page: String(value) }),
@@ -146,7 +142,6 @@ function useCardPageVm() {
error: summary.isError,
fetching: summary.isFetching,
loading: summary.isLoading,
retry: () => void summary.refetch(),
},
toggleArchive: () => {
if (!card.data) return;
@@ -1,3 +1,4 @@
import { notifications } from "@mantine/notifications";
import { useState } from "react";
import { useTranslation } from "react-i18next";
@@ -44,10 +45,16 @@ function useDeleteOperationVm(props: DeleteOperationProps) {
setError(undefined);
try {
const actionId = crypto.randomUUID();
await operationDeletion.mutateAsync({
id: record.id,
version: record.version,
});
notifications.show({
id: "bank-operation-deleted-" + actionId,
message: t("bank.operationDeleted"),
});
setOpened(false);
}
catch (error_) {
@@ -1,4 +1,5 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { notifications } from "@mantine/notifications";
import { useState } from "react";
import { useForm, useWatch } from "react-hook-form";
import { useTranslation } from "react-i18next";
@@ -112,6 +113,8 @@ const useOperationFormVm = (props: OperationFormProps) => {
description: values.description,
};
const actionId = crypto.randomUUID();
if (props.operation)
await updateOperation.mutateAsync({
body: { ...body, version },
@@ -122,6 +125,11 @@ const useOperationFormVm = (props: OperationFormProps) => {
id: intent,
...body,
});
notifications.show({
id: "bank-operation-saved-" + actionId,
message: t("bank.operationSaved"),
});
setOpened(false);
}
catch (error_) {
+17 -18
View File
@@ -198,26 +198,26 @@ describe("CardsPage", () => {
it("shows retry after failure instead of presenting an empty list", async () => {
renderCards(true);
// Mount starts asynchronously; this handler owns the request.
expect(await screen.findByRole("alert")).toHaveTextContent(
"Не удалось загрузить данные карт.",
);
expect(
screen.queryByRole("alert"),
).not.toBeInTheDocument();
expect(
screen.queryByRole("heading", { name: "Добавьте первую карту" }),
).not.toBeInTheDocument();
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
server.use(http.get("*/api/v1/bank-cards", () => HttpResponse.json([])));
fireEvent.click(
within(screen.getByRole("alert")).getByRole("button", {
name: "Повторить",
}),
);
await screen.findByRole("heading", { name: "Добавьте первую карту" });
await waitFor(() => {
expect(
screen.queryByRole("alert"),
).not.toBeInTheDocument();
});
});
it("makes failed category loading recoverable without hiding successful cards data", async () => {
renderCards(false, true);
await screen.findByRole("heading", { name: "Добавьте первую карту" });
expect(await screen.findByRole("alert")).toHaveTextContent(
"Не удалось загрузить данные карт.",
);
expect(
screen.queryByRole("alert"),
).not.toBeInTheDocument();
server.use(
http.get("*/api/v1/bank-cards/categories", () =>
HttpResponse.json([
@@ -225,12 +225,11 @@ describe("CardsPage", () => {
]),
),
);
fireEvent.click(
within(screen.getByRole("alert")).getByRole("button", {
name: "Повторить",
}),
);
await screen.findByRole("button", { name: "Категории" });
await waitFor(() => {
expect(
screen.getByRole("button", { name: "Категории" }),
).toBeInTheDocument();
});
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
});
@@ -9,7 +9,6 @@ import {
Skeleton,
Stack,
Switch,
Text,
Title,
} from "@mantine/core";
import { AddIcon, CategoriesIcon } from "@wealthledger/icons";
@@ -19,7 +18,6 @@ import { Link } from "react-router";
import {
BankCardFace,
BankFeedback,
BankPeriodPicker,
BankSummaryView,
} from "@/entities/bank-card";
@@ -107,18 +105,6 @@ const CardsPageView: FC<CardsPageViewProps> = (props) => {
<CardsPageViewCards {...props} />
{vm.cards.isError && (
<Group role="alert">
<Text>{t(vm.items ? "bank.refreshError" : "bank.error")}</Text>
<Button onClick={vm.retryCards} variant="default">
{t("bank.retry")}
</Button>
</Group>
)}
{vm.cards.data && vm.cards.isFetching && <Text role="status">{t("bank.refreshing")}</Text>}
<Group align="flex-end" justify="space-between">
<BankPeriodPicker onChange={vm.setPeriod} period={vm.period} />
@@ -140,17 +126,7 @@ const CardsPageView: FC<CardsPageViewProps> = (props) => {
error={vm.summary.isError}
fetching={vm.summary.isFetching}
loading={vm.summary.isLoading}
retry={vm.retrySummary}
/>
{vm.categories.isError && (
<BankFeedback
cached={Boolean(vm.categories.data)}
error={vm.categories.error}
loadingError
retry={vm.retryCategories}
/>
)}
</Stack>
);
};
@@ -39,9 +39,6 @@ function useCardsPageVm() {
setArchive(event.currentTarget.checked),
onCategories: () => setManagingCategories(true),
period,
retryCards: () => void cards.refetch(),
retryCategories: () => void categories.refetch(),
retrySummary: () => void summary.refetch(),
setPeriod: (value: [null | string, null | string]) => {
if (value[0] && value[1]) setParameters({ from: value[0], to: value[1] });
},
+11 -80
View File
@@ -396,37 +396,15 @@ describe("stock page", () => {
screen.queryByRole("heading", { name: "Моя позиция" }),
).not.toBeInTheDocument();
expect(screen.getByRole("heading", { name: "График цены" })).toBeVisible();
const message = await screen.findByText(/Не удалось загрузить этот раздел/);
expect(
// eslint-disable-next-line testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
message.closest("[role=\"status\"]"),
).toHaveAttribute("aria-live", "polite");
expect(screen.queryByRole("button", { name: "Повторить" })).not.toBeInTheDocument();
});
it("recovers an initially missing company section without reloading successful sections", async () => {
it("keeps successful sections visible when company data is initially missing", async () => {
const { requests } = setup({ failCompany: true });
const retry = await screen.findByRole("button", { name: "Повторить" });
await screen.findByText("Зачисление дивидендов");
const modes: (null | string)[] = [];
server.use(
http.get("*/api/v1/stocks/:uid/company", ({ request }) => {
modes.push(new URL(request.url).searchParams.get("sync"));
return HttpResponse.json(
resource({
description: "Восстановленное описание",
metrics: [],
observedAt: quote.observedAt,
unavailable: [],
}),
);
}),
);
const previousRequests = requests.length;
fireEvent.click(retry);
expect(await screen.findByText("Восстановленное описание")).toBeVisible();
expect(screen.getByText("Зачисление дивидендов")).toBeVisible();
expect(requests).toHaveLength(previousRequests);
expect(modes).toEqual(["observe"]);
expect(screen.queryByRole("button", { name: "Повторить" })).not.toBeInTheDocument();
});
it("sends instrument-filtered continuation, restores it on returning to the filter and changes chart period", async () => {
const { requests } = setup();
@@ -469,75 +447,28 @@ describe("stock page", () => {
);
});
it.each([
[
"INVALID_OPERATIONS_CURSOR",
null,
null,
],
["TBANK_UNAVAILABLE", "next", "observe"],
"INVALID_OPERATIONS_CURSOR",
"TBANK_UNAVAILABLE",
])(
"recovers history after %s with fresh data and the correct cursor",
async (code, cursor, sync) => {
"keeps history quiet after %s without technical retry",
async (code) => {
const controls = setup({ cursorError: code });
await screen.findByText("Зачисление дивидендов");
fireEvent.click(screen.getByRole("button", { name: "Далее" }));
const retry = await screen.findByRole("button", { name: "Повторить" });
controls.recoverOperations();
const previousRequests = controls.requests.length;
fireEvent.click(retry);
expect(await screen.findByText("+201 ₽")).toBeVisible();
const recovered = controls.requests.slice(previousRequests);
expect(recovered).toHaveLength(1);
expect(recovered[0]?.pathname).toBe(
"/api/v1/brokerage-accounts/all/operations",
);
expect(recovered[0]?.searchParams.get("instrumentUid")).toBe(uid);
expect(recovered[0]?.searchParams.get("limit")).toBe("20");
expect(recovered[0]?.searchParams.get("cursor")).toBe(cursor);
expect(recovered[0]?.searchParams.get("sync")).toBe(sync);
if (cursor)
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
expect(screen.getByRole("button", { name: "Назад" })).toBeEnabled();
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
else expect(screen.getByRole("button", { name: "Назад" })).toBeDisabled();
expect(screen.queryByRole("button", { name: "Повторить" })).not.toBeInTheDocument();
expect(screen.getByRole("heading", { name: "Моя история событий" })).toBeVisible();
},
);
it("keeps the last quote on a refresh failure", async () => {
const scopes: unknown[] = [];
server.use(
http.post("*/api/v1/tbank-sync", async ({ request }) => {
scopes.push(await request.json());
return HttpResponse.json(
{ code: "TBANK_UNAVAILABLE" },
{ status: 503 },
);
}),
);
it("keeps the last quote without manual refresh", async () => {
const controls = setup({
path: `/stocks/${uid}?period=year&events=trades`,
});
await screen.findByText("300 ₽");
controls.failQuote();
fireEvent.click(screen.getByRole("button", { name: "Обновить" }));
const message = await screen.findByText(/последние полученные/);
expect(
// eslint-disable-next-line testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
message.closest("[role=\"status\"]"),
).toHaveAttribute("aria-live", "polite");
expect(screen.getByText("300 ₽")).toBeVisible();
expect(scopes).toEqual([
{
accountId: "all",
candlePeriod: "year",
categories: ["trade"],
instrumentUid: uid,
limit: 20,
screen: "stock",
},
]);
expect(screen.queryByRole("button", { name: "Обновить" })).not.toBeInTheDocument();
});
it("offers recovery for an unavailable direct link", async () => {
setup({ failStock: true });
@@ -15,7 +15,6 @@ const StockPage: FC = () => {
code={vm.code}
kind="stock"
loading={vm.stockState.loading}
retry={vm.stockState.retry}
/>
);
@@ -1,9 +1,6 @@
import type { FC } from "react";
import {
Alert,
Text,
} from "@mantine/core";
import { Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import {
@@ -42,8 +39,6 @@ const StockPageView: FC<StockPageViewProps> = (props) => {
<InstrumentHeader
logoSrc={vm.logoSrc}
name={stock.name}
onRefresh={vm.refresh}
refreshing={vm.refreshing}
subtitle={subtitle}
>
@@ -53,12 +48,6 @@ const StockPageView: FC<StockPageViewProps> = (props) => {
</Text>
)}
{!!(vm.refreshError || vm.stockState.error || vm.quoteState.error) && (
<Alert aria-live="polite" color="orange" mt="md" role="status">
{t(vm.quote ? "accounts.refreshError" : "stock.sectionError")}
</Alert>
)}
<StockQuote quote={vm.quote} quoteState={vm.quoteState} />
<StockCompany
+8 -14
View File
@@ -42,7 +42,7 @@ function useStockPageVm() {
const { operations } = history;
const sync = useScreenSync(
useScreenSync(
{
accountId: "all",
candlePeriod: period,
@@ -56,16 +56,16 @@ function useStockPageVm() {
return {
candles: candles.data,
candlesState: section(candles, sync.retry),
candlesState: section(candles),
canonicalTo:
stock.data?.slug && stock.data.slug !== stockId
? `/stocks/${encodeURIComponent(stock.data.slug)}${search}`
: null,
code: apiErrorCode(stock.error),
company: company.data,
companyState: section(company, sync.retry),
companyState: section(company),
dividends: dividends.data,
dividendsState: section(dividends, sync.retry),
dividendsState: section(dividends),
eventRows: toInstrumentEventRows(operations.data?.items, stock.data),
filter,
hasPrevious: history.hasPrevious,
@@ -73,10 +73,7 @@ function useStockPageVm() {
onNext: history.onNext,
onPrevious: history.onPrevious,
operations: operations.data,
operationsState: {
...section(operations, sync.retry),
retry: () => history.retry(sync.retry),
},
operationsState: section(operations),
pastDividends:
dividends.data?.dividends
.filter(event => event.timing !== "upcoming")
@@ -85,16 +82,13 @@ function useStockPageVm() {
) ?? [],
period,
position: position.data,
positionState: section(position, sync.retry),
positionState: section(position),
quote: quote.data,
quoteState: section(quote, sync.retry),
refresh: sync.refresh,
refreshError: sync.transportError || sync.sourceError,
refreshing: sync.refreshing,
quoteState: section(quote),
setFilter,
setPeriod,
stock: stock.data,
stockState: section(stock, uid ? sync.retry : () => stock.refetch()),
stockState: section(stock),
upcoming:
dividends.data?.dividends
.filter(event => event.timing === "upcoming")
@@ -1,12 +1,6 @@
import type { FC } from "react";
import {
Alert,
Button,
Group,
Stack,
Text,
} from "@mantine/core";
import { Alert, Group, Stack, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import {
@@ -80,17 +74,7 @@ const StockCompany: FC<StockCompanyProps> = (props) => {
<Stack gap="lg">
{props.company.unavailable.length > 0 && (
<Alert aria-live="polite" color="orange" role="status">
<Group justify="space-between">
<Text size="sm">{t("stock.partialCompany")}</Text>
<Button
onClick={props.companyState.retry}
size="xs"
variant="default"
>
{t("accounts.retry")}
</Button>
</Group>
<Text size="sm">{t("stock.partialCompany")}</Text>
</Alert>
)}
@@ -82,12 +82,6 @@ const StockQuote: FC<StockQuoteProps> = (props) => {
{t("stock.partialQuote")}
</Text>
)}
{!!props.quoteState.refreshing && (
<Text c="dimmed" role="status" size="xs">
{t("accounts.refreshing")}
</Text>
)}
</div>
);
}
@@ -10,12 +10,14 @@ function useStocksPageVm() {
const search = useInstrumentSearch(MIN_STOCK_SEARCH_LENGTH);
const { canSearch, debounced, isWaiting, query } = search;
const result = useStockSearch(debounced);
const sync = useScreenSync({ query: debounced, screen: "stocks" }, [result]);
useScreenSync({ query: debounced, screen: "stocks" }, [result]);
return {
canSearch,
code: apiErrorCode(result.error),
error: result.isError || sync.sourceError || sync.transportError,
error:
!result.data
&& (result.isError || result.meta?.sync.state === "failed"),
items:
result.data?.map(stock => ({
...stock,
@@ -35,10 +37,6 @@ function useStocksPageVm() {
debounced.length >= MIN_STOCK_SEARCH_LENGTH
&& !isWaiting
&& Boolean(result.data),
refreshing: sync.refreshing,
retry: () => {
void sync.retry();
},
};
}