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
@@ -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>
);
};