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:
Generated
+90
-2
@@ -16,6 +16,7 @@
|
|||||||
"@mantine/core": "9.6.1",
|
"@mantine/core": "9.6.1",
|
||||||
"@mantine/dates": "9.6.1",
|
"@mantine/dates": "9.6.1",
|
||||||
"@mantine/hooks": "9.6.1",
|
"@mantine/hooks": "9.6.1",
|
||||||
|
"@mantine/notifications": "9.6.1",
|
||||||
"@tanstack/react-query": "5.102.8",
|
"@tanstack/react-query": "5.102.8",
|
||||||
"@wealthledger/icons": "file:packages/icons",
|
"@wealthledger/icons": "file:packages/icons",
|
||||||
"@wealthledger/tokens": "file:packages/tokens",
|
"@wealthledger/tokens": "file:packages/tokens",
|
||||||
@@ -2841,6 +2842,31 @@
|
|||||||
"react": "^19.2.0"
|
"react": "^19.2.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@mantine/notifications": {
|
||||||
|
"version": "9.6.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@mantine/notifications/-/notifications-9.6.1.tgz",
|
||||||
|
"integrity": "sha512-6bikkVCAf6wd1KO/oVhBuXGDZ+HcWeNGCEvdgkL0pQ6jmjzd24ShW6UnbGu6aLABhYxQdfLnrE1cbOjC93Tj6A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@mantine/store": "9.6.1",
|
||||||
|
"react-transition-group": "4.4.5"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@mantine/core": "9.6.1",
|
||||||
|
"@mantine/hooks": "9.6.1",
|
||||||
|
"react": "^19.2.0",
|
||||||
|
"react-dom": "^19.2.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@mantine/store": {
|
||||||
|
"version": "9.6.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@mantine/store/-/store-9.6.1.tgz",
|
||||||
|
"integrity": "sha512-KePeOIAg2n7wkHlxFxF7s6qYeD9EE/GrFIK3cc329nTSDIEIJQ+oFQv1S/t4sZJTIz7YnBlRuvA9Wc8pRg8TRA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "^19.2.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@mdx-js/react": {
|
"node_modules/@mdx-js/react": {
|
||||||
"version": "3.1.1",
|
"version": "3.1.1",
|
||||||
"integrity": "sha512-f++rKLQgUVYDAtECQ6fn/is15GkEH9+nZPM3MS0RcxVqoTfawHvDlSCH7JbMhAM6uJ32v3eXLvLmLvjGu7PTQw==",
|
"integrity": "sha512-f++rKLQgUVYDAtECQ6fn/is15GkEH9+nZPM3MS0RcxVqoTfawHvDlSCH7JbMhAM6uJ32v3eXLvLmLvjGu7PTQw==",
|
||||||
@@ -7275,7 +7301,6 @@
|
|||||||
"node_modules/csstype": {
|
"node_modules/csstype": {
|
||||||
"version": "3.2.3",
|
"version": "3.2.3",
|
||||||
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
|
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
|
||||||
"devOptional": true,
|
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/d3-array": {
|
"node_modules/d3-array": {
|
||||||
@@ -7749,6 +7774,16 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/dom-helpers": {
|
||||||
|
"version": "5.2.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz",
|
||||||
|
"integrity": "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@babel/runtime": "^7.8.7",
|
||||||
|
"csstype": "^3.0.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/dotenv": {
|
"node_modules/dotenv": {
|
||||||
"version": "17.4.2",
|
"version": "17.4.2",
|
||||||
"integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==",
|
"integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==",
|
||||||
@@ -10715,7 +10750,6 @@
|
|||||||
"node_modules/js-tokens": {
|
"node_modules/js-tokens": {
|
||||||
"version": "4.0.0",
|
"version": "4.0.0",
|
||||||
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
|
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/js-yaml": {
|
"node_modules/js-yaml": {
|
||||||
@@ -11363,6 +11397,18 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/loose-envify": {
|
||||||
|
"version": "1.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
|
||||||
|
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"js-tokens": "^3.0.0 || ^4.0.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"loose-envify": "cli.js"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/loupe": {
|
"node_modules/loupe": {
|
||||||
"version": "3.2.1",
|
"version": "3.2.1",
|
||||||
"integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",
|
"integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",
|
||||||
@@ -11819,6 +11865,15 @@
|
|||||||
"node": ">=18"
|
"node": ">=18"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/object-assign": {
|
||||||
|
"version": "4.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
|
||||||
|
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/object-inspect": {
|
"node_modules/object-inspect": {
|
||||||
"version": "1.13.4",
|
"version": "1.13.4",
|
||||||
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
|
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
|
||||||
@@ -12536,6 +12591,23 @@
|
|||||||
"node": ">= 6"
|
"node": ">= 6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/prop-types": {
|
||||||
|
"version": "15.8.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
|
||||||
|
"integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"loose-envify": "^1.4.0",
|
||||||
|
"object-assign": "^4.1.1",
|
||||||
|
"react-is": "^16.13.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/prop-types/node_modules/react-is": {
|
||||||
|
"version": "16.13.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
|
||||||
|
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/protocols": {
|
"node_modules/protocols": {
|
||||||
"version": "2.0.2",
|
"version": "2.0.2",
|
||||||
"integrity": "sha512-hHVTzba3wboROl0/aWRRG9dMytgH6ow//STBZh43l/wQgmMhYhOFi0EHWAPtoCz9IAUymsyP0TSBHkhgMEGNnQ==",
|
"integrity": "sha512-hHVTzba3wboROl0/aWRRG9dMytgH6ow//STBZh43l/wQgmMhYhOFi0EHWAPtoCz9IAUymsyP0TSBHkhgMEGNnQ==",
|
||||||
@@ -13001,6 +13073,22 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/react-transition-group": {
|
||||||
|
"version": "4.4.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz",
|
||||||
|
"integrity": "sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==",
|
||||||
|
"license": "BSD-3-Clause",
|
||||||
|
"dependencies": {
|
||||||
|
"@babel/runtime": "^7.5.5",
|
||||||
|
"dom-helpers": "^5.0.1",
|
||||||
|
"loose-envify": "^1.4.0",
|
||||||
|
"prop-types": "^15.6.2"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": ">=16.6.0",
|
||||||
|
"react-dom": ">=16.6.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/readable-stream": {
|
"node_modules/readable-stream": {
|
||||||
"version": "3.6.2",
|
"version": "3.6.2",
|
||||||
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
|
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
|
||||||
|
|||||||
@@ -42,6 +42,7 @@
|
|||||||
"@mantine/core": "9.6.1",
|
"@mantine/core": "9.6.1",
|
||||||
"@mantine/dates": "9.6.1",
|
"@mantine/dates": "9.6.1",
|
||||||
"@mantine/hooks": "9.6.1",
|
"@mantine/hooks": "9.6.1",
|
||||||
|
"@mantine/notifications": "9.6.1",
|
||||||
"@tanstack/react-query": "5.102.8",
|
"@tanstack/react-query": "5.102.8",
|
||||||
"@wealthledger/icons": "file:packages/icons",
|
"@wealthledger/icons": "file:packages/icons",
|
||||||
"@wealthledger/tokens": "file:packages/tokens",
|
"@wealthledger/tokens": "file:packages/tokens",
|
||||||
|
|||||||
@@ -369,7 +369,9 @@ describe("All accounts routes", () => {
|
|||||||
renderPage("/accounts/all/operations?from=2026-08-01&to=2026-08-31");
|
renderPage("/accounts/all/operations?from=2026-08-01&to=2026-08-31");
|
||||||
await screen.findAllByText("Выплата купона");
|
await screen.findAllByText("Выплата купона");
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Далее" }));
|
fireEvent.click(screen.getByRole("button", { name: "Далее" }));
|
||||||
fireEvent.click(await screen.findByRole("button", { name: "Повторить" }));
|
await waitFor(() => {
|
||||||
|
expect(screen.queryByRole("button", { name: "Повторить" })).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
expect(await screen.findAllByText("Выплата купона")).toHaveLength(2);
|
expect(await screen.findAllByText("Выплата купона")).toHaveLength(2);
|
||||||
expect(screen.getByLabelText("Текущий путь")).toHaveTextContent(
|
expect(screen.getByLabelText("Текущий путь")).toHaveTextContent(
|
||||||
"from=2026-08-01&to=2026-08-31",
|
"from=2026-08-01&to=2026-08-31",
|
||||||
@@ -390,10 +392,12 @@ describe("All accounts routes", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
expect(screen.getAllByText("Сбербанк")).toHaveLength(1);
|
expect(screen.getAllByText("Сбербанк")).toHaveLength(1);
|
||||||
expect(
|
await waitFor(() => {
|
||||||
await screen.findByRole("button", {
|
expect(
|
||||||
name: "Повторить",
|
screen.queryByRole("button", {
|
||||||
}),
|
name: "Повторить",
|
||||||
).toBeInTheDocument();
|
}),
|
||||||
|
).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+8
-1
@@ -2,6 +2,7 @@ import type { FC } from "react";
|
|||||||
|
|
||||||
import { MantineProvider } from "@mantine/core";
|
import { MantineProvider } from "@mantine/core";
|
||||||
import { DatesProvider } from "@mantine/dates";
|
import { DatesProvider } from "@mantine/dates";
|
||||||
|
import { Notifications } from "@mantine/notifications";
|
||||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
import { cssVariablesResolver, theme } from "@wealthledger/ui/theme";
|
import { cssVariablesResolver, theme } from "@wealthledger/ui/theme";
|
||||||
import { BrowserRouter } from "react-router";
|
import { BrowserRouter } from "react-router";
|
||||||
@@ -11,7 +12,11 @@ import { AuthProvider } from "@/features/auth";
|
|||||||
|
|
||||||
const queryClient = new QueryClient({
|
const queryClient = new QueryClient({
|
||||||
defaultOptions: {
|
defaultOptions: {
|
||||||
queries: { refetchOnWindowFocus: false, retry: false },
|
queries: {
|
||||||
|
refetchOnReconnect: true,
|
||||||
|
refetchOnWindowFocus: true,
|
||||||
|
retry: false,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -31,6 +36,8 @@ const App: FC = () => {
|
|||||||
</RouteErrorBoundary>
|
</RouteErrorBoundary>
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
|
|
||||||
|
<Notifications autoClose={4000} limit={2} position="top-right" zIndex={1000} />
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
</DatesProvider>
|
</DatesProvider>
|
||||||
</MantineProvider>
|
</MantineProvider>
|
||||||
|
|||||||
@@ -147,7 +147,7 @@ describe("banking API", () => {
|
|||||||
expect(url.searchParams.get("from")).toBe("2026-09-01");
|
expect(url.searchParams.get("from")).toBe("2026-09-01");
|
||||||
expect(url.searchParams.get("to")).toBe("2026-09-30");
|
expect(url.searchParams.get("to")).toBe("2026-09-30");
|
||||||
if (isFail && page === 2)
|
if (isFail && page === 2)
|
||||||
return HttpResponse.json({ code: "FAILED" }, { status: 500 });
|
return HttpResponse.json({ code: "NOT_FOUND" }, { status: 404 });
|
||||||
|
|
||||||
return HttpResponse.json({
|
return HttpResponse.json({
|
||||||
hasNext: page === 1,
|
hasNext: page === 1,
|
||||||
@@ -299,7 +299,7 @@ describe("banking API", () => {
|
|||||||
expect(result.current.query.data?.balance.value).toBe("100");
|
expect(result.current.query.data?.balance.value).toBe("100");
|
||||||
server.use(
|
server.use(
|
||||||
http.get("*/api/v1/bank-cards/a", () =>
|
http.get("*/api/v1/bank-cards/a", () =>
|
||||||
HttpResponse.json({ code: "INTERNAL_ERROR" }, { status: 500 }),
|
HttpResponse.json({ code: "NOT_FOUND" }, { status: 404 }),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
await act(() => result.current.query.refetch());
|
await act(() => result.current.query.refetch());
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { notifications } from "@mantine/notifications";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
@@ -71,7 +72,7 @@ function useBankCardFormVm(props: BankCardFormProps) {
|
|||||||
openingDate: values.openingDate,
|
openingDate: values.openingDate,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (props.card)
|
if (props.card) {
|
||||||
await updateCard.mutateAsync({
|
await updateCard.mutateAsync({
|
||||||
body: {
|
body: {
|
||||||
...metadata,
|
...metadata,
|
||||||
@@ -80,12 +81,19 @@ function useBankCardFormVm(props: BankCardFormProps) {
|
|||||||
},
|
},
|
||||||
id: props.card.id,
|
id: props.card.id,
|
||||||
});
|
});
|
||||||
else
|
}
|
||||||
|
else {
|
||||||
await cardCreation.mutateAsync({
|
await cardCreation.mutateAsync({
|
||||||
id: intent,
|
id: intent,
|
||||||
...metadata,
|
...metadata,
|
||||||
...financial,
|
...financial,
|
||||||
});
|
});
|
||||||
|
notifications.show({
|
||||||
|
id: "bank-card-created-" + intent,
|
||||||
|
message: t("bank.cardSaved"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
setOpened(false);
|
setOpened(false);
|
||||||
}
|
}
|
||||||
catch (error_) {
|
catch (error_) {
|
||||||
|
|||||||
@@ -47,7 +47,6 @@ const meta
|
|||||||
error: false,
|
error: false,
|
||||||
fetching: false,
|
fetching: false,
|
||||||
loading: false,
|
loading: false,
|
||||||
retry: () => {},
|
|
||||||
},
|
},
|
||||||
component: BankSummaryView,
|
component: BankSummaryView,
|
||||||
parameters: {
|
parameters: {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { CSSProperties, FC } from "react";
|
import type { CSSProperties, FC } from "react";
|
||||||
|
|
||||||
import { Button, Group, Skeleton, Stack, Text, Title } from "@mantine/core";
|
import { Skeleton, Stack, Text, Title } from "@mantine/core";
|
||||||
import { OperationIcon } from "@wealthledger/icons";
|
import { OperationIcon } from "@wealthledger/icons";
|
||||||
import { LoadingSkeleton } from "@wealthledger/ui";
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
@@ -20,7 +20,6 @@ type BankSummaryViewProps = {
|
|||||||
error: boolean;
|
error: boolean;
|
||||||
fetching: boolean;
|
fetching: boolean;
|
||||||
loading: boolean;
|
loading: boolean;
|
||||||
retry: () => void;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const BankSummaryViewCategories: FC<BankSummaryViewProps> = (props) => {
|
const BankSummaryViewCategories: FC<BankSummaryViewProps> = (props) => {
|
||||||
@@ -101,17 +100,7 @@ const BankSummaryView: FC<BankSummaryViewProps> = (props) => {
|
|||||||
|
|
||||||
<BankSummaryViewCategories {...props} />
|
<BankSummaryViewCategories {...props} />
|
||||||
|
|
||||||
{props.error && (
|
{props.error && !props.data && <Text role="alert">{t("bank.error")}</Text>}
|
||||||
<Group role="alert">
|
|
||||||
<Text>{t(props.data ? "bank.refreshError" : "bank.error")}</Text>
|
|
||||||
|
|
||||||
<Button onClick={props.retry} variant="default">
|
|
||||||
{t("bank.retry")}
|
|
||||||
</Button>
|
|
||||||
</Group>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{props.data && props.fetching && <Text role="status">{t("bank.refreshing")}</Text>}
|
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { hashKey, useQueryClient } from "@tanstack/react-query";
|
import { hashKey, useQueryClient } from "@tanstack/react-query";
|
||||||
import { useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
import { ApiErrorCode, apiErrorCode, isApiErrorCode } from "@/shared/api";
|
import { ApiErrorCode, apiErrorCode, isApiErrorCode } from "@/shared/api";
|
||||||
|
|
||||||
@@ -29,15 +29,28 @@ function useBrokerageOperationHistory(
|
|||||||
cursor: cursors.at(-1),
|
cursor: cursors.at(-1),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const isInvalidCursor = isApiErrorCode(
|
||||||
|
apiErrorCode(operations.error),
|
||||||
|
ApiErrorCode.InvalidOperationsCursor,
|
||||||
|
);
|
||||||
|
|
||||||
|
const isRecoveringInvalidCursor = cursors.length > 0 && isInvalidCursor;
|
||||||
|
|
||||||
const reset = () => setPagination({ cursors: [], scope });
|
const reset = () => setPagination({ cursors: [], scope });
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isRecoveringInvalidCursor) return;
|
||||||
|
|
||||||
|
const timeout = setTimeout(() => {
|
||||||
|
setPagination({ cursors: [], scope });
|
||||||
|
void client.invalidateQueries({ exact: true, queryKey });
|
||||||
|
}, 0);
|
||||||
|
|
||||||
|
return () => clearTimeout(timeout);
|
||||||
|
}, [client, isRecoveringInvalidCursor, queryKey, scope]);
|
||||||
|
|
||||||
const retry = (retryScreen: () => unknown) => {
|
const retry = (retryScreen: () => unknown) => {
|
||||||
if (
|
if (isInvalidCursor) {
|
||||||
isApiErrorCode(
|
|
||||||
apiErrorCode(operations.error),
|
|
||||||
ApiErrorCode.InvalidOperationsCursor,
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
reset();
|
reset();
|
||||||
void client.invalidateQueries({
|
void client.invalidateQueries({
|
||||||
exact: true,
|
exact: true,
|
||||||
@@ -49,6 +62,7 @@ function useBrokerageOperationHistory(
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
hasPrevious: cursors.length > 0,
|
hasPrevious: cursors.length > 0,
|
||||||
|
isRecoveringInvalidCursor,
|
||||||
onNext: () => {
|
onNext: () => {
|
||||||
if (operations.data?.nextCursor)
|
if (operations.data?.nextCursor)
|
||||||
setPagination({
|
setPagination({
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
import type { FC } from "react";
|
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 { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
|
|
||||||
import { SourceSyncStatus } from "@/shared/ui";
|
|
||||||
|
|
||||||
import type { BrokerageEvent } from "../../api/useBrokerageEvents";
|
import type { BrokerageEvent } from "../../api/useBrokerageEvents";
|
||||||
|
|
||||||
import { brokerageEventKey } from "../../model/event-key";
|
import { brokerageEventKey } from "../../model/event-key";
|
||||||
@@ -19,9 +17,6 @@ type BrokerageEventsPreviewProps = {
|
|||||||
type BrokerageEventsPreviewState
|
type BrokerageEventsPreviewState
|
||||||
= | {
|
= | {
|
||||||
items: BrokerageEvent[];
|
items: BrokerageEvent[];
|
||||||
lastSuccessfulAt?: null | string;
|
|
||||||
refreshError?: boolean;
|
|
||||||
stale?: boolean;
|
|
||||||
state: "loaded" | "partial";
|
state: "loaded" | "partial";
|
||||||
to: string;
|
to: string;
|
||||||
}
|
}
|
||||||
@@ -33,28 +28,15 @@ const BrokerageEventsPreview: FC<BrokerageEventsPreviewProps> = (props) => {
|
|||||||
const { events } = props;
|
const { events } = props;
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
const errorText
|
|
||||||
= events.state === "loaded" && events.refreshError
|
|
||||||
? t("accounts.refreshError")
|
|
||||||
: null;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap="sm">
|
<Stack gap="sm">
|
||||||
{events.state === "loaded" && (
|
|
||||||
<SourceSyncStatus
|
|
||||||
errorText={errorText}
|
|
||||||
lastSuccessfulAt={events.lastSuccessfulAt}
|
|
||||||
stale={events.stale}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{events.state === "loading" && (
|
{events.state === "loading" && (
|
||||||
<LoadingSkeleton label={t("events.recentLoading")}>
|
<LoadingSkeleton label={t("events.recentLoading")}>
|
||||||
{["first", "second", "third"].map(placeholder => <Skeleton height={48} key={placeholder} radius="sm" />)}
|
{["first", "second", "third"].map(placeholder => <Skeleton height={48} key={placeholder} radius="sm" />)}
|
||||||
</LoadingSkeleton>
|
</LoadingSkeleton>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{events.state === "error" && <Alert color="red">{t("events.recentError")}</Alert>}
|
{events.state === "error" && <Text c="dimmed">{t("states.unavailableText")}</Text>}
|
||||||
|
|
||||||
{events.state === "empty" && <Text c="dimmed">{t("events.recentEmpty")}</Text>}
|
{events.state === "empty" && <Text c="dimmed">{t("events.recentEmpty")}</Text>}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import { resource } from "@/test/resource";
|
import { resource } from "@/test/resource";
|
||||||
|
|
||||||
@@ -13,9 +13,7 @@ describe("instrument source and transport presentation", () => {
|
|||||||
const state = section({
|
const state = section({
|
||||||
data,
|
data,
|
||||||
isError: false,
|
isError: false,
|
||||||
isFetching: false,
|
|
||||||
meta: resource(data, { availability }).meta,
|
meta: resource(data, { availability }).meta,
|
||||||
refetch: vi.fn(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(state.loading).toBe(availability === "missing");
|
expect(state.loading).toBe(availability === "missing");
|
||||||
@@ -23,39 +21,40 @@ describe("instrument source and transport presentation", () => {
|
|||||||
expect(state.hasData).toBe(availability !== "missing");
|
expect(state.hasData).toBe(availability !== "missing");
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
it("preserves a full fresh source and timestamp when force fails, while offering scoped retry", () => {
|
it("preserves empty successful data instead of treating it as missing", () => {
|
||||||
const retry = vi.fn();
|
const state = section({
|
||||||
const refetch = vi.fn();
|
data: [],
|
||||||
|
isError: false,
|
||||||
|
meta: resource([]).meta,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(state).toMatchObject({
|
||||||
|
error: false,
|
||||||
|
hasData: true,
|
||||||
|
loading: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves a full source when force fails", () => {
|
||||||
const meta = resource([], {
|
const meta = resource([], {
|
||||||
sync: { errorCode: "TBANK_UNAVAILABLE", id: "work", state: "failed" },
|
sync: { errorCode: "TBANK_UNAVAILABLE", id: "work", state: "failed" },
|
||||||
}).meta;
|
}).meta;
|
||||||
|
|
||||||
const state = section(
|
const state = section({ data: [], isError: false, meta });
|
||||||
{ data: [], isError: false, isFetching: false, meta, refetch },
|
|
||||||
retry,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(state).toMatchObject({
|
expect(state).toMatchObject({
|
||||||
error: true,
|
error: true,
|
||||||
hasData: true,
|
hasData: true,
|
||||||
lastSuccessfulAt: meta.lastSuccessfulAt,
|
|
||||||
loading: false,
|
loading: false,
|
||||||
refreshing: false,
|
|
||||||
});
|
});
|
||||||
state.retry();
|
|
||||||
expect(retry).toHaveBeenCalledOnce();
|
|
||||||
expect(refetch).not.toHaveBeenCalled();
|
|
||||||
});
|
});
|
||||||
it("shows source failure without a false loading or empty result", () => {
|
it("shows source failure without a false loading or empty result", () => {
|
||||||
const state = section({
|
const state = section({
|
||||||
data: undefined,
|
data: undefined,
|
||||||
isError: false,
|
isError: false,
|
||||||
isFetching: false,
|
|
||||||
meta: resource(null, {
|
meta: resource(null, {
|
||||||
sync: { errorCode: "TBANK_UNAVAILABLE", id: "work", state: "failed" },
|
sync: { errorCode: "TBANK_UNAVAILABLE", id: "work", state: "failed" },
|
||||||
}).meta,
|
}).meta,
|
||||||
refetch: vi.fn(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(state).toMatchObject({
|
expect(state).toMatchObject({
|
||||||
|
|||||||
@@ -3,43 +3,27 @@ import type { InvestmentResourceMeta } from "@/shared/api";
|
|||||||
type SectionState = {
|
type SectionState = {
|
||||||
error: boolean;
|
error: boolean;
|
||||||
hasData: boolean;
|
hasData: boolean;
|
||||||
lastSuccessfulAt?: null | string;
|
|
||||||
loading: boolean;
|
loading: boolean;
|
||||||
partial?: boolean;
|
partial?: boolean;
|
||||||
refreshing: boolean;
|
|
||||||
retry: () => void;
|
|
||||||
sourceError?: boolean;
|
|
||||||
stale?: boolean;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
function section(
|
function hasSectionData(data: unknown) {
|
||||||
query: {
|
return data !== undefined;
|
||||||
data: unknown;
|
}
|
||||||
isError: boolean;
|
|
||||||
isFetching: boolean;
|
function section(query: {
|
||||||
meta?: InvestmentResourceMeta;
|
data: unknown;
|
||||||
refetch: () => unknown;
|
isError: boolean;
|
||||||
},
|
meta?: InvestmentResourceMeta;
|
||||||
retry?: () => unknown,
|
}): SectionState {
|
||||||
): SectionState {
|
|
||||||
const isError = query.isError || query.meta?.sync.state === "failed";
|
const isError = query.isError || query.meta?.sync.state === "failed";
|
||||||
|
const hasData = hasSectionData(query.data);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
error: isError,
|
error: isError,
|
||||||
hasData: Boolean(query.data),
|
hasData,
|
||||||
lastSuccessfulAt: query.meta?.lastSuccessfulAt,
|
loading: !hasData && !isError,
|
||||||
loading: !query.data && !isError,
|
|
||||||
partial: query.meta?.availability === "partial",
|
partial: query.meta?.availability === "partial",
|
||||||
refreshing:
|
|
||||||
Boolean(query.data)
|
|
||||||
&& (query.isFetching
|
|
||||||
|| query.meta?.sync.state === "running"
|
|
||||||
),
|
|
||||||
retry: () => {
|
|
||||||
void (retry ?? query.refetch)();
|
|
||||||
},
|
|
||||||
sourceError: query.meta?.sync.state === "failed",
|
|
||||||
stale: query.meta?.freshness === "stale",
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -86,7 +86,7 @@ const InstrumentEvents: FC<InstrumentEventsProps> = (props) => {
|
|||||||
|
|
||||||
<Group justify="space-between" mt="md">
|
<Group justify="space-between" mt="md">
|
||||||
<Button
|
<Button
|
||||||
disabled={!vm.hasPrevious || vm.operationsState.refreshing}
|
disabled={!vm.hasPrevious}
|
||||||
onClick={vm.onPrevious}
|
onClick={vm.onPrevious}
|
||||||
variant="default"
|
variant="default"
|
||||||
>
|
>
|
||||||
@@ -94,7 +94,7 @@ const InstrumentEvents: FC<InstrumentEventsProps> = (props) => {
|
|||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
disabled={!vm.operations.hasNext || vm.operationsState.refreshing}
|
disabled={!vm.operations.hasNext}
|
||||||
onClick={vm.onNext}
|
onClick={vm.onNext}
|
||||||
variant="default"
|
variant="default"
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -1,21 +1,17 @@
|
|||||||
import type { FC, PropsWithChildren, ReactNode } from "react";
|
import type { FC, PropsWithChildren, ReactNode } from "react";
|
||||||
|
|
||||||
import { Avatar, Button, Group, Paper, Text, Title } from "@mantine/core";
|
import { Avatar, Group, Paper, Text, Title } from "@mantine/core";
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
|
|
||||||
import classes from "./InstrumentHeader.module.css";
|
import classes from "./InstrumentHeader.module.css";
|
||||||
|
|
||||||
type InstrumentHeaderProps = PropsWithChildren<{
|
type InstrumentHeaderProps = PropsWithChildren<{
|
||||||
logoSrc: null | string;
|
logoSrc: null | string;
|
||||||
name: string;
|
name: string;
|
||||||
onRefresh: () => void;
|
|
||||||
refreshing: boolean;
|
|
||||||
subtitle: ReactNode;
|
subtitle: ReactNode;
|
||||||
}>;
|
}>;
|
||||||
|
|
||||||
const InstrumentHeader: FC<InstrumentHeaderProps> = (props) => {
|
const InstrumentHeader: FC<InstrumentHeaderProps> = (props) => {
|
||||||
const { children, logoSrc, name, onRefresh, refreshing, subtitle } = props;
|
const { children, logoSrc, name, subtitle } = props;
|
||||||
const { t } = useTranslation();
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Paper className={classes.header} component="header" withBorder>
|
<Paper className={classes.header} component="header" withBorder>
|
||||||
@@ -31,10 +27,6 @@ const InstrumentHeader: FC<InstrumentHeaderProps> = (props) => {
|
|||||||
<Text c="dimmed" size="sm">{subtitle}</Text>
|
<Text c="dimmed" size="sm">{subtitle}</Text>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Button disabled={refreshing} onClick={onRefresh} variant="subtle">
|
|
||||||
{t("investment.refresh")}
|
|
||||||
</Button>
|
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
{children}
|
{children}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
|
|
||||||
import { Anchor, Button, Skeleton, Stack, Text, Title } from "@mantine/core";
|
import { Anchor, Skeleton, Stack, Text, Title } from "@mantine/core";
|
||||||
import { LoadingSkeleton } from "@wealthledger/ui";
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
@@ -11,11 +11,10 @@ type InstrumentPageStateProps = {
|
|||||||
code?: string;
|
code?: string;
|
||||||
kind: "bond" | "stock";
|
kind: "bond" | "stock";
|
||||||
loading: boolean;
|
loading: boolean;
|
||||||
retry: () => void;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const InstrumentPageState: FC<InstrumentPageStateProps> = (props) => {
|
const InstrumentPageState: FC<InstrumentPageStateProps> = (props) => {
|
||||||
const { code, kind, loading, retry } = props;
|
const { code, kind, loading } = props;
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
if (loading) return (
|
if (loading) return (
|
||||||
<LoadingSkeleton label={t(`${kind}.loading`)}>
|
<LoadingSkeleton label={t(`${kind}.loading`)}>
|
||||||
@@ -55,10 +54,6 @@ const InstrumentPageState: FC<InstrumentPageStateProps> = (props) => {
|
|||||||
<Anchor component={Link} to="/settings">
|
<Anchor component={Link} to="/settings">
|
||||||
{t("accounts.openSettings")}
|
{t("accounts.openSettings")}
|
||||||
</Anchor>
|
</Anchor>
|
||||||
|
|
||||||
<Button onClick={retry} variant="default">
|
|
||||||
{t("accounts.retry")}
|
|
||||||
</Button>
|
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import type { FC, PropsWithChildren, ReactNode } from "react";
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
Alert,
|
Alert,
|
||||||
Button,
|
|
||||||
Group,
|
Group,
|
||||||
Paper,
|
Paper,
|
||||||
Skeleton,
|
Skeleton,
|
||||||
@@ -13,8 +12,6 @@ import {
|
|||||||
import { LoadingSkeleton } from "@wealthledger/ui";
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import { SourceSyncStatus } from "@/shared/ui";
|
|
||||||
|
|
||||||
import type { SectionState } from "../model/section";
|
import type { SectionState } from "../model/section";
|
||||||
|
|
||||||
import classes from "./InstrumentDetails.module.css";
|
import classes from "./InstrumentDetails.module.css";
|
||||||
@@ -33,10 +30,6 @@ type InstrumentSectionProps = PropsWithChildren<{
|
|||||||
const InstrumentSection: FC<InstrumentSectionProps> = (props) => {
|
const InstrumentSection: FC<InstrumentSectionProps> = (props) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
const readError = t(
|
|
||||||
props.state.hasData ? "accounts.refreshError" : "stock.sectionError",
|
|
||||||
);
|
|
||||||
|
|
||||||
const sectionClassName = props.embedded
|
const sectionClassName = props.embedded
|
||||||
? classes.embeddedSection
|
? classes.embeddedSection
|
||||||
: classes.section;
|
: classes.section;
|
||||||
@@ -80,35 +73,11 @@ const InstrumentSection: FC<InstrumentSectionProps> = (props) => {
|
|||||||
{props.controls}
|
{props.controls}
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
<SourceSyncStatus
|
|
||||||
lastSuccessfulAt={props.state.lastSuccessfulAt}
|
|
||||||
stale={props.state.stale}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{!!props.state.partial && <Text role="status">{t("investment.partial")}</Text>}
|
{!!props.state.partial && <Text role="status">{t("investment.partial")}</Text>}
|
||||||
|
|
||||||
{!!props.state.refreshing && (
|
{!!(props.state.error && !props.state.hasData) && (
|
||||||
<Text c="dimmed" role="status" size="xs">
|
|
||||||
{t("accounts.refreshing")}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!!props.state.error && (
|
|
||||||
<Alert aria-live="polite" color="orange" mb="sm" role="status">
|
<Alert aria-live="polite" color="orange" mb="sm" role="status">
|
||||||
<Group justify="space-between">
|
<Text size="sm">{t("stock.sectionError")}</Text>
|
||||||
<Text size="sm">
|
|
||||||
{props.state.sourceError ? t("investment.syncFailed") : readError}
|
|
||||||
</Text>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
disabled={props.state.refreshing}
|
|
||||||
onClick={props.state.retry}
|
|
||||||
size="xs"
|
|
||||||
variant="default"
|
|
||||||
>
|
|
||||||
{t("accounts.retry")}
|
|
||||||
</Button>
|
|
||||||
</Group>
|
|
||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { ComponentProps } from "react";
|
import type { ComponentProps } from "react";
|
||||||
|
|
||||||
import { MantineProvider } from "@mantine/core";
|
import { MantineProvider } from "@mantine/core";
|
||||||
import { fireEvent, render, screen } from "@testing-library/react";
|
import { render, screen } from "@testing-library/react";
|
||||||
import { MemoryRouter } from "react-router";
|
import { MemoryRouter } from "react-router";
|
||||||
import { expect, it, vi } from "vitest";
|
import { expect, it, vi } from "vitest";
|
||||||
|
|
||||||
@@ -16,8 +16,6 @@ it("keeps cached results on failure, hides them during a new search and distingu
|
|||||||
partial: false,
|
partial: false,
|
||||||
query: "SBER",
|
query: "SBER",
|
||||||
ready: true,
|
ready: true,
|
||||||
refreshing: false,
|
|
||||||
retry: vi.fn(),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const cached = [<a href="/stocks/SBER" key="SBER">Сбербанк</a>];
|
const cached = [<a href="/stocks/SBER" key="SBER">Сбербанк</a>];
|
||||||
@@ -44,8 +42,7 @@ it("keeps cached results on failure, hides them during a new search and distingu
|
|||||||
expect(
|
expect(
|
||||||
screen.getByRole("link", { name: "Открыть настройки T-Bank" }),
|
screen.getByRole("link", { name: "Открыть настройки T-Bank" }),
|
||||||
).toHaveAttribute("href", "/settings");
|
).toHaveAttribute("href", "/settings");
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
|
expect(screen.queryByRole("button", { name: "Повторить" })).not.toBeInTheDocument();
|
||||||
expect(vm.retry).toHaveBeenCalledOnce();
|
|
||||||
|
|
||||||
rerender(view({ loading: true, ready: false }));
|
rerender(view({ loading: true, ready: false }));
|
||||||
expect(screen.queryByRole("link", { name: "Сбербанк" })).not.toBeInTheDocument();
|
expect(screen.queryByRole("link", { name: "Сбербанк" })).not.toBeInTheDocument();
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import type { ChangeEvent, FC, ReactNode } from "react";
|
|||||||
import {
|
import {
|
||||||
Alert,
|
Alert,
|
||||||
Anchor,
|
Anchor,
|
||||||
Button,
|
|
||||||
Skeleton,
|
Skeleton,
|
||||||
Stack,
|
Stack,
|
||||||
Text,
|
Text,
|
||||||
@@ -28,8 +27,6 @@ type InstrumentSearchProps = {
|
|||||||
partial: boolean;
|
partial: boolean;
|
||||||
query: string;
|
query: string;
|
||||||
ready: boolean;
|
ready: boolean;
|
||||||
refreshing: boolean;
|
|
||||||
retry: () => void;
|
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -77,14 +74,6 @@ const InstrumentSearch: FC<InstrumentSearchProps> = (props) => {
|
|||||||
</Text>
|
</Text>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Button
|
|
||||||
disabled={vm.refreshing || !vm.canSearch}
|
|
||||||
onClick={vm.retry}
|
|
||||||
w="fit-content"
|
|
||||||
>
|
|
||||||
{t("investment.refresh")}
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
{!!vm.partial && <Alert role="status">{t("investment.partial")}</Alert>}
|
{!!vm.partial && <Alert role="status">{t("investment.partial")}</Alert>}
|
||||||
|
|
||||||
<TextInput
|
<TextInput
|
||||||
@@ -114,9 +103,6 @@ const InstrumentSearch: FC<InstrumentSearchProps> = (props) => {
|
|||||||
{t("accounts.openSettings")}
|
{t("accounts.openSettings")}
|
||||||
</Anchor>
|
</Anchor>
|
||||||
|
|
||||||
<Button onClick={vm.retry} variant="default">
|
|
||||||
{t("accounts.retry")}
|
|
||||||
</Button>
|
|
||||||
</Stack>
|
</Stack>
|
||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ describe("page-owned screen synchronization", () => {
|
|||||||
expect(posted).toEqual(["old", "new"]);
|
expect(posted).toEqual(["old", "new"]);
|
||||||
});
|
});
|
||||||
it.each([false, true])(
|
it.each([false, true])(
|
||||||
"retries a failed GET without forcing the source (cached=%s)",
|
"recovers a failed GET without forcing the source (cached=%s)",
|
||||||
async (cached) => {
|
async (cached) => {
|
||||||
auth();
|
auth();
|
||||||
const modes: (null | string)[] = [];
|
const modes: (null | string)[] = [];
|
||||||
@@ -122,26 +122,13 @@ describe("page-owned screen synchronization", () => {
|
|||||||
expect(result.current.accounts.isSuccess).toBe(true),
|
expect(result.current.accounts.isSuccess).toBe(true),
|
||||||
);
|
);
|
||||||
isUnavailable = true;
|
isUnavailable = true;
|
||||||
await act(() => result.current.accounts.refetch());
|
void result.current.accounts.refetch();
|
||||||
}
|
}
|
||||||
|
|
||||||
await waitFor(() => expect(result.current.accounts.isError).toBe(true));
|
|
||||||
isUnavailable = false;
|
isUnavailable = false;
|
||||||
await act(() => result.current.sync.retry());
|
|
||||||
await waitFor(() => expect(result.current.accounts.isSuccess).toBe(true));
|
await waitFor(() => expect(result.current.accounts.isSuccess).toBe(true));
|
||||||
expect(result.current.accounts.meta?.dataRevision).toBe(
|
|
||||||
cached ? "3" : "2",
|
|
||||||
);
|
|
||||||
expect(modes).toEqual(
|
|
||||||
cached
|
|
||||||
? [
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
"observe",
|
|
||||||
]
|
|
||||||
: [null, "observe"],
|
|
||||||
);
|
|
||||||
expect(posts).toBe(0);
|
expect(posts).toBe(0);
|
||||||
|
expect(modes.every(mode => mode === null)).toBe(true);
|
||||||
expect(result.current.disabled.data).toBeUndefined();
|
expect(result.current.disabled.data).toBeUndefined();
|
||||||
expect(
|
expect(
|
||||||
queryClient
|
queryClient
|
||||||
@@ -157,171 +144,193 @@ describe("page-owned screen synchronization", () => {
|
|||||||
["connection", false],
|
["connection", false],
|
||||||
["access", false],
|
["access", false],
|
||||||
] as const)(
|
] as const)(
|
||||||
"discards recovery after %s changes (HTTP already pending=%s)",
|
"discards source recovery after %s changes (HTTP already pending=%s)",
|
||||||
async (boundary, pending) => {
|
async (boundary, pending) => {
|
||||||
auth();
|
auth();
|
||||||
|
|
||||||
const { promise: blocked, resolve: release }
|
const { promise: blocked, resolve: release }
|
||||||
= Promise.withResolvers<void>();
|
= Promise.withResolvers<void>();
|
||||||
|
|
||||||
let isRecovering = false;
|
let recoveryRequests = 0;
|
||||||
let isChanged = false;
|
let isChanged = false;
|
||||||
server.use(
|
|
||||||
http.get("*/api/v1/brokerage-accounts", async ({ request }) => {
|
|
||||||
if (boundary === "connection" && isChanged && !request.signal.aborted)
|
|
||||||
return HttpResponse.json(resource([], { dataRevision: "current" }));
|
|
||||||
if (!new URL(request.url).searchParams.has("sync"))
|
|
||||||
return isChanged
|
|
||||||
? HttpResponse.json(resource([], { dataRevision: "current" }))
|
|
||||||
: HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 });
|
|
||||||
isRecovering = true;
|
|
||||||
await blocked;
|
|
||||||
|
|
||||||
return HttpResponse.json(resource([], { dataRevision: "old" }));
|
try {
|
||||||
}),
|
server.use(
|
||||||
);
|
http.get("*/api/v1/brokerage-accounts", async () => {
|
||||||
const { queryClient, wrapper } = createQueryWrapper();
|
if (isChanged)
|
||||||
const published: unknown[] = [];
|
return HttpResponse.json(
|
||||||
|
resource([], { dataRevision: "current" }),
|
||||||
|
);
|
||||||
|
|
||||||
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
|
if (recoveryRequests > 0) {
|
||||||
if (event.type === "updated" && event.action.type === "success")
|
recoveryRequests += 1;
|
||||||
published.push(event.query.state.data);
|
await blocked;
|
||||||
});
|
|
||||||
|
|
||||||
const { result } = renderHook(
|
return HttpResponse.json(resource([], { dataRevision: "old" }));
|
||||||
() => {
|
}
|
||||||
const accounts = useBrokerageAccounts();
|
|
||||||
|
|
||||||
return {
|
recoveryRequests += 1;
|
||||||
accounts,
|
|
||||||
sync: useScreenSync({ screen: "accounts" }, [accounts]),
|
|
||||||
};
|
|
||||||
},
|
|
||||||
{ wrapper },
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => expect(result.current.accounts.isError).toBe(true));
|
return HttpResponse.json(
|
||||||
let recovery!: Promise<void>;
|
resource(null, {
|
||||||
act(() => {
|
sync: {
|
||||||
recovery = result.current.sync.retry();
|
errorCode: "TBANK_UNAVAILABLE",
|
||||||
});
|
id: "failed",
|
||||||
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
|
state: "failed",
|
||||||
if (pending) await waitFor(() => expect(isRecovering).toBe(true));
|
},
|
||||||
await act(async () => {
|
}),
|
||||||
isChanged = true;
|
);
|
||||||
|
}),
|
||||||
switch (boundary) {
|
|
||||||
case "access": {
|
|
||||||
invalidateResourceAccess(queryClient, "brokerage", {
|
|
||||||
code: "FORBIDDEN",
|
|
||||||
});
|
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
case "logout": {
|
|
||||||
configureAuthClient();
|
|
||||||
queryClient.clear();
|
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
case "session": {
|
|
||||||
auth();
|
|
||||||
queryClient.clear();
|
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
case "connection": {
|
|
||||||
commitTbankConnectionBoundary(queryClient, {
|
|
||||||
connected: true,
|
|
||||||
connectedAt: "2026-09-27T00:00:00Z",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
release();
|
|
||||||
await recovery;
|
|
||||||
});
|
|
||||||
if (boundary === "connection")
|
|
||||||
await waitFor(() =>
|
|
||||||
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
|
|
||||||
expect(result.current.accounts.meta?.dataRevision).toBe("current"),
|
|
||||||
);
|
);
|
||||||
expect(published).not.toContainEqual(
|
const { queryClient, wrapper } = createQueryWrapper();
|
||||||
expect.objectContaining({
|
const published: unknown[] = [];
|
||||||
meta: expect.objectContaining({ dataRevision: "old" }) as unknown,
|
|
||||||
}),
|
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
|
||||||
);
|
if (event.type === "updated" && event.action.type === "success")
|
||||||
unsubscribe();
|
published.push(event.query.state.data);
|
||||||
|
});
|
||||||
|
|
||||||
|
const { result } = renderHook(
|
||||||
|
() => {
|
||||||
|
const accounts = useBrokerageAccounts();
|
||||||
|
|
||||||
|
return {
|
||||||
|
accounts,
|
||||||
|
sync: useScreenSync({ screen: "accounts" }, [accounts]),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
{ wrapper },
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(result.current.accounts.meta?.sync.state).toBe("failed"),
|
||||||
|
);
|
||||||
|
vi.useFakeTimers();
|
||||||
|
if (pending)
|
||||||
|
await act(() => vi.advanceTimersByTimeAsync(5000));
|
||||||
|
expect(recoveryRequests).toBeGreaterThanOrEqual(1);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
isChanged = true;
|
||||||
|
|
||||||
|
switch (boundary) {
|
||||||
|
case "access": {
|
||||||
|
invalidateResourceAccess(queryClient, "brokerage", {
|
||||||
|
code: "FORBIDDEN",
|
||||||
|
});
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "logout": {
|
||||||
|
configureAuthClient();
|
||||||
|
queryClient.clear();
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "session": {
|
||||||
|
auth();
|
||||||
|
queryClient.clear();
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "connection": {
|
||||||
|
commitTbankConnectionBoundary(queryClient, {
|
||||||
|
connected: true,
|
||||||
|
connectedAt: "2026-09-27T00:00:00Z",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
release();
|
||||||
|
if (!pending) await vi.advanceTimersByTimeAsync(5000);
|
||||||
|
});
|
||||||
|
vi.useRealTimers();
|
||||||
|
if (boundary === "connection" && !pending)
|
||||||
|
await waitFor(() =>
|
||||||
|
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
|
||||||
|
expect(result.current.accounts.meta?.dataRevision).toBe("current"),
|
||||||
|
);
|
||||||
|
expect(published).not.toContainEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
meta: expect.objectContaining({ dataRevision: "old" }) as unknown,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
unsubscribe();
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
it.each([false, true])(
|
it.each([false, true])(
|
||||||
"recovers an initial GET failure after forced sync without metadata (status retry=%s)",
|
"recovers an initial GET failure without forced sync (status retry=%s)",
|
||||||
async (retryStatus) => {
|
async (retryStatus) => {
|
||||||
auth();
|
auth();
|
||||||
const modes: (null | string)[] = [];
|
const modes: (null | string)[] = [];
|
||||||
|
let posts = 0;
|
||||||
let polls = 0;
|
let polls = 0;
|
||||||
server.use(
|
|
||||||
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
|
||||||
modes.push(new URL(request.url).searchParams.get("sync"));
|
|
||||||
|
|
||||||
return modes.length === 1
|
try {
|
||||||
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
|
server.use(
|
||||||
: HttpResponse.json(resource([]));
|
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
||||||
}),
|
modes.push(new URL(request.url).searchParams.get("sync"));
|
||||||
http.post("*/api/v1/tbank-sync", () =>
|
|
||||||
HttpResponse.json({ id: "recover" }, { status: 202 }),
|
|
||||||
),
|
|
||||||
http.get("*/api/v1/tbank-sync/:id", () => {
|
|
||||||
polls += 1;
|
|
||||||
|
|
||||||
return retryStatus && polls === 1
|
return modes.length === 1
|
||||||
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
|
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
|
||||||
: HttpResponse.json({
|
: HttpResponse.json(resource([]));
|
||||||
id: "recover",
|
}),
|
||||||
state: "succeeded",
|
http.post("*/api/v1/tbank-sync", () => {
|
||||||
});
|
posts += 1;
|
||||||
}),
|
|
||||||
);
|
|
||||||
const { queryClient, wrapper } = createQueryWrapper();
|
|
||||||
|
|
||||||
const { result } = renderHook(
|
return HttpResponse.json({ id: "recover" }, { status: 202 });
|
||||||
() => {
|
}),
|
||||||
const accounts = useBrokerageAccounts();
|
http.get("*/api/v1/tbank-sync/:id", () => {
|
||||||
const disabled = useStockQuote("");
|
polls += 1;
|
||||||
|
|
||||||
return {
|
return retryStatus && polls === 1
|
||||||
accounts,
|
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
|
||||||
sync: useScreenSync({ screen: "accounts" }, [accounts, disabled]),
|
: HttpResponse.json({
|
||||||
};
|
id: "recover",
|
||||||
},
|
state: "succeeded",
|
||||||
{ wrapper },
|
});
|
||||||
);
|
}),
|
||||||
|
|
||||||
await waitFor(() => expect(result.current.accounts.isError).toBe(true));
|
|
||||||
expect(result.current.accounts.meta).toBeUndefined();
|
|
||||||
await act(() => result.current.sync.refresh());
|
|
||||||
|
|
||||||
if (retryStatus) {
|
|
||||||
await waitFor(() =>
|
|
||||||
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
|
|
||||||
expect(result.current.sync.transportError).toBe(true),
|
|
||||||
);
|
);
|
||||||
await act(() => result.current.sync.retry());
|
const { queryClient, wrapper } = createQueryWrapper();
|
||||||
|
|
||||||
|
const { result } = renderHook(
|
||||||
|
() => {
|
||||||
|
const accounts = useBrokerageAccounts();
|
||||||
|
const disabled = useStockQuote("");
|
||||||
|
|
||||||
|
return {
|
||||||
|
accounts,
|
||||||
|
sync: useScreenSync({ screen: "accounts" }, [accounts, disabled]),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
{ wrapper },
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(
|
||||||
|
() => expect(result.current.accounts.isSuccess).toBe(true),
|
||||||
|
{ timeout: 3000 },
|
||||||
|
);
|
||||||
|
expect(result.current.accounts.data).toEqual([]);
|
||||||
|
|
||||||
|
expect(modes).toEqual([null, null]);
|
||||||
|
expect(posts).toBe(0);
|
||||||
|
expect(polls).toBe(0);
|
||||||
|
expect(
|
||||||
|
queryClient
|
||||||
|
.getQueryCache()
|
||||||
|
.findAll({ queryKey: ["get", "/api/v1/brokerage-accounts"] }),
|
||||||
|
).toHaveLength(1);
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
vi.useRealTimers();
|
||||||
}
|
}
|
||||||
|
|
||||||
await waitFor(() => expect(result.current.accounts.isSuccess).toBe(true));
|
|
||||||
expect(result.current.accounts.data).toEqual([]);
|
|
||||||
|
|
||||||
expect(modes[0]).toBeNull();
|
|
||||||
expect(modes.slice(1).every(mode => mode === "observe")).toBe(true);
|
|
||||||
expect(
|
|
||||||
queryClient
|
|
||||||
.getQueryCache()
|
|
||||||
.findAll({ queryKey: ["get", "/api/v1/brokerage-accounts"] }),
|
|
||||||
).toHaveLength(1);
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
it("posts only its scope once and observes completion without importing again", async () => {
|
it("posts only its scope once and observes completion without importing again", async () => {
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
import { type QueryKey, useQueryClient } from "@tanstack/react-query";
|
import {
|
||||||
|
focusManager,
|
||||||
|
onlineManager,
|
||||||
|
type QueryKey,
|
||||||
|
useQueryClient,
|
||||||
|
} from "@tanstack/react-query";
|
||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -21,9 +26,39 @@ type ScreenResource = {
|
|||||||
meta?: InvestmentResourceMeta;
|
meta?: InvestmentResourceMeta;
|
||||||
observe: () => Promise<unknown>;
|
observe: () => Promise<unknown>;
|
||||||
queryKey: QueryKey;
|
queryKey: QueryKey;
|
||||||
|
refetch: () => Promise<unknown>;
|
||||||
};
|
};
|
||||||
|
|
||||||
const STATUS_INTERVAL_MS = 1000;
|
const STATUS_INTERVAL_MS = 1000;
|
||||||
|
const FIRST_SOURCE_RECOVERY_DELAY_MS = 5000;
|
||||||
|
const SECOND_SOURCE_RECOVERY_DELAY_MS = 15_000;
|
||||||
|
|
||||||
|
function requiresSourceRecovery(meta?: InvestmentResourceMeta): boolean {
|
||||||
|
if (!meta || meta.unavailableReason) return false;
|
||||||
|
|
||||||
|
return ["cancelled", "failed"].includes(meta.sync.state)
|
||||||
|
|| meta.availability === "missing"
|
||||||
|
|| meta.freshness === "stale"
|
||||||
|
|| (meta.dependencies ?? []).some(dependency =>
|
||||||
|
requiresSourceRecovery(dependency),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sourceRecoveryDelay(attempt: number): number | undefined {
|
||||||
|
switch (attempt) {
|
||||||
|
case 0: {
|
||||||
|
return FIRST_SOURCE_RECOVERY_DELAY_MS;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 1: {
|
||||||
|
return SECOND_SOURCE_RECOVERY_DELAY_MS;
|
||||||
|
}
|
||||||
|
|
||||||
|
default: {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
|
function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
|
||||||
const mutation = apiQueryClient.useMutation("post", "/api/v1/tbank-sync", {
|
const mutation = apiQueryClient.useMutation("post", "/api/v1/tbank-sync", {
|
||||||
@@ -35,6 +70,9 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
|
|||||||
const scopeKey = JSON.stringify(scope);
|
const scopeKey = JSON.stringify(scope);
|
||||||
|
|
||||||
const requestInFlightRef = useRef<null | string>(null);
|
const requestInFlightRef = useRef<null | string>(null);
|
||||||
|
const lifecycleRecoveryRef = useRef(new Set<string>());
|
||||||
|
const sourceRecoveryRef = useRef(new Map<string, number>());
|
||||||
|
const sourceTimersRef = useRef(new Set<ReturnType<typeof setTimeout>>());
|
||||||
|
|
||||||
const isCurrentMutation
|
const isCurrentMutation
|
||||||
= JSON.stringify(mutation.variables?.body) === scopeKey;
|
= JSON.stringify(mutation.variables?.body) === scopeKey;
|
||||||
@@ -110,6 +148,73 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
|
|||||||
void resource.observe().catch(() => {});
|
void resource.observe().catch(() => {});
|
||||||
}, [client, statuses, resources, scopeKey]);
|
}, [client, statuses, resources, scopeKey]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timers = sourceTimersRef.current;
|
||||||
|
const attempts = sourceRecoveryRef.current;
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
for (const timer of timers) clearTimeout(timer);
|
||||||
|
timers.clear();
|
||||||
|
attempts.clear();
|
||||||
|
};
|
||||||
|
}, [scopeKey]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
for (const resource of resources) {
|
||||||
|
if (
|
||||||
|
!requiresSourceRecovery(resource.meta)
|
||||||
|
|| resource.isFetching
|
||||||
|
) continue;
|
||||||
|
|
||||||
|
const key = JSON.stringify([scopeKey, resource.queryKey]);
|
||||||
|
const attempt = sourceRecoveryRef.current.get(key) ?? 0;
|
||||||
|
const delay = sourceRecoveryDelay(attempt);
|
||||||
|
if (delay === undefined) continue;
|
||||||
|
|
||||||
|
sourceRecoveryRef.current.set(key, attempt + 1);
|
||||||
|
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
sourceTimersRef.current.delete(timer);
|
||||||
|
void resource.refetch().catch(() => {});
|
||||||
|
}, delay);
|
||||||
|
|
||||||
|
sourceTimersRef.current.add(timer);
|
||||||
|
}
|
||||||
|
}, [resources, scopeKey]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const recover = () => {
|
||||||
|
for (const resource of resources) {
|
||||||
|
if (
|
||||||
|
!requiresSourceRecovery(resource.meta)
|
||||||
|
|| resource.isFetching
|
||||||
|
) continue;
|
||||||
|
|
||||||
|
const key = JSON.stringify([scopeKey, resource.queryKey]);
|
||||||
|
if (lifecycleRecoveryRef.current.has(key)) continue;
|
||||||
|
|
||||||
|
sourceRecoveryRef.current.delete(key);
|
||||||
|
lifecycleRecoveryRef.current.add(key);
|
||||||
|
void resource.refetch()
|
||||||
|
.catch(() => {})
|
||||||
|
.finally(() => lifecycleRecoveryRef.current.delete(key));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const unsubscribeFocus = focusManager.subscribe((focused) => {
|
||||||
|
if (focused) recover();
|
||||||
|
});
|
||||||
|
|
||||||
|
const unsubscribeOnline = onlineManager.subscribe((online) => {
|
||||||
|
if (online) recover();
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
unsubscribeFocus();
|
||||||
|
unsubscribeOnline();
|
||||||
|
};
|
||||||
|
}, [resources, scopeKey]);
|
||||||
|
|
||||||
const isRefreshing
|
const isRefreshing
|
||||||
= (isCurrentMutation && mutation.isPending)
|
= (isCurrentMutation && mutation.isPending)
|
||||||
|| statuses.some(
|
|| statuses.some(
|
||||||
|
|||||||
+11
-11
@@ -127,9 +127,11 @@ describe("TbankConnectionSection", () => {
|
|||||||
const token = screen.getByLabelText("Token T-Bank");
|
const token = screen.getByLabelText("Token T-Bank");
|
||||||
fireEvent.change(token, { target: { value: "replacement-draft" } });
|
fireEvent.change(token, { target: { value: "replacement-draft" } });
|
||||||
finishRefetch?.();
|
finishRefetch?.();
|
||||||
expect(
|
await waitFor(() => {
|
||||||
await screen.findByText(/Не удалось обновить статус подключения/),
|
expect(
|
||||||
).toBeVisible();
|
screen.queryByText(/Не удалось обновить статус подключения/),
|
||||||
|
).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
expect(screen.getByLabelText("Token T-Bank")).toBe(token);
|
expect(screen.getByLabelText("Token T-Bank")).toBe(token);
|
||||||
expect(token).toHaveValue("replacement-draft");
|
expect(token).toHaveValue("replacement-draft");
|
||||||
expect(screen.getByText("Подключено с 14.08.2026")).toBeVisible();
|
expect(screen.getByText("Подключено с 14.08.2026")).toBeVisible();
|
||||||
@@ -139,7 +141,6 @@ describe("TbankConnectionSection", () => {
|
|||||||
expect(client.getQueryData(portfolioQueryKey)).toEqual({
|
expect(client.getQueryData(portfolioQueryKey)).toEqual({
|
||||||
source: "previous-connection",
|
source: "previous-connection",
|
||||||
});
|
});
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
|
|
||||||
await waitFor(() => expect(reads).toBe(2));
|
await waitFor(() => expect(reads).toBe(2));
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(
|
expect(
|
||||||
@@ -164,13 +165,12 @@ describe("TbankConnectionSection", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
renderSection(createTestQueryClient());
|
renderSection(createTestQueryClient());
|
||||||
expect(
|
await waitFor(() => {
|
||||||
await screen.findByText(/Не удалось загрузить статус подключения/),
|
expect(
|
||||||
).toBeVisible();
|
screen.queryByText(/Не удалось загрузить статус подключения/),
|
||||||
expect(screen.queryByLabelText("Token T-Bank")).not.toBeInTheDocument();
|
).not.toBeInTheDocument();
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
|
});
|
||||||
expect(await screen.findByLabelText("Token T-Bank")).toBeVisible();
|
expect(reads).toBe(1);
|
||||||
expect(reads).toBe(2);
|
|
||||||
});
|
});
|
||||||
it("commits connection status and resets the complete brokerage query subtree after connecting", async () => {
|
it("commits connection status and resets the complete brokerage query subtree after connecting", async () => {
|
||||||
const client = seededClient();
|
const client = seededClient();
|
||||||
|
|||||||
+7
@@ -1,3 +1,4 @@
|
|||||||
|
import { notifications } from "@mantine/notifications";
|
||||||
import { useQueryClient } from "@tanstack/react-query";
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
@@ -32,6 +33,12 @@ function useTbankConnectionSectionLoadedVm(status: TbankConnectionStatus) {
|
|||||||
onSuccess: (data) => {
|
onSuccess: (data) => {
|
||||||
commitTbankConnectionBoundary(queryClient, data);
|
commitTbankConnectionBoundary(queryClient, data);
|
||||||
reset();
|
reset();
|
||||||
|
|
||||||
|
if (status.connected && data.connected)
|
||||||
|
notifications.show({
|
||||||
|
id: "tbank-token-replaced-" + crypto.randomUUID(),
|
||||||
|
message: t("tbank.tokenReplaced"),
|
||||||
|
});
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import type { FC } from "react";
|
|||||||
import { MantineProvider } from "@mantine/core";
|
import { MantineProvider } from "@mantine/core";
|
||||||
import { QueryClientProvider } from "@tanstack/react-query";
|
import { QueryClientProvider } from "@tanstack/react-query";
|
||||||
import {
|
import {
|
||||||
act,
|
|
||||||
fireEvent,
|
fireEvent,
|
||||||
render,
|
render,
|
||||||
renderHook,
|
renderHook,
|
||||||
@@ -115,7 +114,6 @@ describe("Upcoming event date filters", () => {
|
|||||||
"keeps event calendar dates in GET and source sync requests: %s",
|
"keeps event calendar dates in GET and source sync requests: %s",
|
||||||
async (search) => {
|
async (search) => {
|
||||||
const requested: string[] = [];
|
const requested: string[] = [];
|
||||||
const syncRequests: unknown[] = [];
|
|
||||||
server.use(
|
server.use(
|
||||||
http.get("*/api/v1/brokerage-accounts/all/events", ({ request }) => {
|
http.get("*/api/v1/brokerage-accounts/all/events", ({ request }) => {
|
||||||
requested.push(new URL(request.url).search);
|
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 queryClient = createTestQueryClient();
|
||||||
|
|
||||||
const { result } = renderHook(
|
const { result } = renderHook(
|
||||||
@@ -162,15 +151,6 @@ describe("Upcoming event date filters", () => {
|
|||||||
|
|
||||||
await waitFor(() => expect(result.current.state).toBe("error"));
|
await waitFor(() => expect(result.current.state).toBe("error"));
|
||||||
expect(requested).toEqual([`?${search}`]);
|
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"]);
|
renderEvents(accountId, ["?from=2099-02-01"]);
|
||||||
await screen.findByRole("button", { name: "Повторить" });
|
await screen.findByRole("button", { name: "Сбросить" });
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Сбросить" }));
|
fireEvent.click(screen.getByRole("button", { name: "Сбросить" }));
|
||||||
await screen.findByLabelText("Период");
|
await screen.findByLabelText("Период");
|
||||||
expect(screen.getByLabelText("URL")).toBeEmptyDOMElement();
|
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({
|
configureAuthClient({
|
||||||
accessToken: () => "synthetic",
|
accessToken: () => "synthetic",
|
||||||
clear: vi.fn(),
|
clear: vi.fn(),
|
||||||
@@ -343,9 +323,6 @@ it("retains the previous complete forecast and timestamp when its source refresh
|
|||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(result.current).toMatchObject({
|
expect(result.current).toMatchObject({
|
||||||
events,
|
events,
|
||||||
lastSuccessfulAt: snapshot.meta.lastSuccessfulAt,
|
|
||||||
refreshError: true,
|
|
||||||
sourceError: true,
|
|
||||||
state: "loaded",
|
state: "loaded",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -159,8 +159,7 @@ describe("AccountEventsPage", () => {
|
|||||||
expect(screen.getAllByText("O")).toHaveLength(2);
|
expect(screen.getAllByText("O")).toHaveLength(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("renders empty and retryable error states", () => {
|
it("renders empty and quiet error states", async () => {
|
||||||
const refetch = vi.fn();
|
|
||||||
const { rerender } = renderPage();
|
const { rerender } = renderPage();
|
||||||
expect(
|
expect(
|
||||||
screen.getByText("За выбранный период событий не найдено"),
|
screen.getByText("За выбранный период событий не найдено"),
|
||||||
@@ -169,7 +168,6 @@ describe("AccountEventsPage", () => {
|
|||||||
data: undefined,
|
data: undefined,
|
||||||
isError: true,
|
isError: true,
|
||||||
isLoading: false,
|
isLoading: false,
|
||||||
refetch,
|
|
||||||
} as never);
|
} as never);
|
||||||
rerender(
|
rerender(
|
||||||
<MantineProvider>
|
<MantineProvider>
|
||||||
@@ -178,8 +176,8 @@ describe("AccountEventsPage", () => {
|
|||||||
</MemoryRouter>
|
</MemoryRouter>
|
||||||
</MantineProvider>,
|
</MantineProvider>,
|
||||||
);
|
);
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
|
expect(await screen.findByRole("button", { name: "Сбросить" })).toBeVisible();
|
||||||
expect(refresh).toHaveBeenCalledOnce();
|
expect(screen.queryByRole("button", { name: "Повторить" })).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("shows a structural busy state before events are available", () => {
|
it("shows a structural busy state before events are available", () => {
|
||||||
|
|||||||
@@ -6,25 +6,20 @@ import {
|
|||||||
useBrokerageEvents,
|
useBrokerageEvents,
|
||||||
} from "@/entities/brokerage-event";
|
} from "@/entities/brokerage-event";
|
||||||
import { useScreenSync } from "@/features/tbank-connection";
|
import { useScreenSync } from "@/features/tbank-connection";
|
||||||
import { isValidPeriod, useUrlPeriod } from "@/shared/lib";
|
import { isValidPeriod, useInitialAvailability, useUrlPeriod } from "@/shared/lib";
|
||||||
|
|
||||||
type AccountEventsPageViewModel
|
type AccountEventsPageViewModel
|
||||||
= | {
|
= | {
|
||||||
canApply: boolean;
|
canApply: boolean;
|
||||||
draftPeriod: [null | string, null | string];
|
draftPeriod: [null | string, null | string];
|
||||||
events: BrokerageEvent[];
|
events: BrokerageEvent[];
|
||||||
lastSuccessfulAt?: null | string;
|
|
||||||
onApply: () => void;
|
onApply: () => void;
|
||||||
onPeriodChange: (value: [null | string, null | string]) => void;
|
onPeriodChange: (value: [null | string, null | string]) => void;
|
||||||
onReset: () => void;
|
onReset: () => void;
|
||||||
partial?: boolean;
|
partial?: boolean;
|
||||||
refreshError: boolean;
|
|
||||||
refreshing: boolean;
|
|
||||||
retry: () => void;
|
|
||||||
sourceError?: boolean;
|
|
||||||
state: "loaded";
|
state: "loaded";
|
||||||
}
|
}
|
||||||
| { onReset: () => void; retry: () => void; state: "error" }
|
| { onReset: () => void; state: "error" }
|
||||||
| { state: "loading" };
|
| { state: "loading" };
|
||||||
|
|
||||||
function useAccountEventsPageViewModel(): AccountEventsPageViewModel {
|
function useAccountEventsPageViewModel(): AccountEventsPageViewModel {
|
||||||
@@ -56,7 +51,7 @@ function useAccountEventsPageViewModel(): AccountEventsPageViewModel {
|
|||||||
...(appliedTo && { to: appliedTo }),
|
...(appliedTo && { to: appliedTo }),
|
||||||
});
|
});
|
||||||
|
|
||||||
const sync = useScreenSync(
|
useScreenSync(
|
||||||
{
|
{
|
||||||
accountId,
|
accountId,
|
||||||
screen: "events",
|
screen: "events",
|
||||||
@@ -66,7 +61,15 @@ function useAccountEventsPageViewModel(): AccountEventsPageViewModel {
|
|||||||
[events],
|
[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 = () => {
|
const onReset = () => {
|
||||||
setDraftPeriod([null, null]);
|
setDraftPeriod([null, null]);
|
||||||
@@ -76,12 +79,12 @@ function useAccountEventsPageViewModel(): AccountEventsPageViewModel {
|
|||||||
if ((events.isError || events.meta?.sync.state === "failed") && !events.data)
|
if ((events.isError || events.meta?.sync.state === "failed") && !events.data)
|
||||||
return {
|
return {
|
||||||
onReset,
|
onReset,
|
||||||
retry: () => {
|
|
||||||
void sync.retry();
|
|
||||||
},
|
|
||||||
state: "error",
|
state: "error",
|
||||||
};
|
};
|
||||||
if (!events.data) return { state: "loading" };
|
if (!events.data)
|
||||||
|
return availability === "unavailable"
|
||||||
|
? { onReset, state: "error" }
|
||||||
|
: { state: "loading" };
|
||||||
|
|
||||||
return {
|
return {
|
||||||
canApply:
|
canApply:
|
||||||
@@ -89,7 +92,6 @@ function useAccountEventsPageViewModel(): AccountEventsPageViewModel {
|
|||||||
&& isValidPeriod(draftFrom, draftTo),
|
&& isValidPeriod(draftFrom, draftTo),
|
||||||
draftPeriod,
|
draftPeriod,
|
||||||
events: events.data.events,
|
events: events.data.events,
|
||||||
lastSuccessfulAt: events.meta?.lastSuccessfulAt,
|
|
||||||
onApply: () => {
|
onApply: () => {
|
||||||
if (!isValidPeriod(draftFrom, draftTo)) return;
|
if (!isValidPeriod(draftFrom, draftTo)) return;
|
||||||
setSearchParameters({
|
setSearchParameters({
|
||||||
@@ -100,12 +102,6 @@ function useAccountEventsPageViewModel(): AccountEventsPageViewModel {
|
|||||||
onPeriodChange: setDraftPeriod,
|
onPeriodChange: setDraftPeriod,
|
||||||
onReset,
|
onReset,
|
||||||
partial: events.meta?.availability !== "complete",
|
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",
|
state: "loaded",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-3
@@ -4,7 +4,7 @@ import { Button, Group } from "@mantine/core";
|
|||||||
import { StateView } from "@wealthledger/ui";
|
import { StateView } from "@wealthledger/ui";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
type AccountEventsPageErrorProps = { onReset: () => void; retry: () => void };
|
type AccountEventsPageErrorProps = { onReset: () => void };
|
||||||
|
|
||||||
const AccountEventsPageError: FC<AccountEventsPageErrorProps> = (props) => {
|
const AccountEventsPageError: FC<AccountEventsPageErrorProps> = (props) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -13,8 +13,6 @@ const AccountEventsPageError: FC<AccountEventsPageErrorProps> = (props) => {
|
|||||||
<StateView
|
<StateView
|
||||||
action={(
|
action={(
|
||||||
<Group>
|
<Group>
|
||||||
<Button onClick={props.retry}>{t("events.retry")}</Button>
|
|
||||||
|
|
||||||
<Button onClick={props.onReset} variant="default">
|
<Button onClick={props.onReset} variant="default">
|
||||||
{t("ledger.reset")}
|
{t("ledger.reset")}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
-24
@@ -4,7 +4,6 @@ import {
|
|||||||
Alert,
|
Alert,
|
||||||
Button,
|
Button,
|
||||||
Group,
|
Group,
|
||||||
Progress,
|
|
||||||
Stack,
|
Stack,
|
||||||
Text,
|
Text,
|
||||||
Title,
|
Title,
|
||||||
@@ -16,7 +15,6 @@ import {
|
|||||||
BrokerageEventCard,
|
BrokerageEventCard,
|
||||||
brokerageEventKey,
|
brokerageEventKey,
|
||||||
} from "@/entities/brokerage-event";
|
} from "@/entities/brokerage-event";
|
||||||
import { SourceSyncStatus } from "@/shared/ui";
|
|
||||||
|
|
||||||
import type { AccountEventsPageViewModel } from "../AccountEventsPage.vm";
|
import type { AccountEventsPageViewModel } from "../AccountEventsPage.vm";
|
||||||
|
|
||||||
@@ -55,32 +53,10 @@ const AccountEventsPageLoaded: FC<AccountEventsPageLoadedProps> = (props) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap="lg">
|
<Stack gap="lg">
|
||||||
<SourceSyncStatus lastSuccessfulAt={props.lastSuccessfulAt} />
|
|
||||||
|
|
||||||
<Title order={1}>{t("events.title")}</Title>
|
<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.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>
|
<Text c="dimmed">{t("events.hint")}</Text>
|
||||||
|
|
||||||
<Group align="end">
|
<Group align="end">
|
||||||
|
|||||||
@@ -195,7 +195,6 @@ describe("AccountIncomePage", () => {
|
|||||||
|
|
||||||
it("keeps income calendar dates in GET and source sync requests", async () => {
|
it("keeps income calendar dates in GET and source sync requests", async () => {
|
||||||
const requested: string[] = [];
|
const requested: string[] = [];
|
||||||
const syncRequests: unknown[] = [];
|
|
||||||
server.use(
|
server.use(
|
||||||
http.get(
|
http.get(
|
||||||
"*/api/v1/brokerage-accounts/:accountId/income-analytics",
|
"*/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");
|
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(requested).toEqual(["?from=2024-02-29&to=2024-03-01"]);
|
||||||
expect(syncRequests).toEqual([]);
|
expect(screen.queryByRole("button", { name: "Повторить" })).not.toBeInTheDocument();
|
||||||
fireEvent.click(retry);
|
|
||||||
await waitFor(() =>
|
|
||||||
expect(syncRequests).toEqual([
|
|
||||||
{
|
|
||||||
accountId: "account-1",
|
|
||||||
from: "2024-02-29",
|
|
||||||
screen: "income",
|
|
||||||
to: "2024-03-01",
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("requests a multi-year period from the URL without resetting it", async () => {
|
it("requests a multi-year period from the URL without resetting it", async () => {
|
||||||
@@ -486,7 +466,7 @@ describe("AccountIncomePage", () => {
|
|||||||
).toBeVisible();
|
).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("shows a recoverable realized error", async () => {
|
it("shows a quiet realized error", async () => {
|
||||||
server.use(
|
server.use(
|
||||||
http.get(
|
http.get(
|
||||||
"*/api/v1/brokerage-accounts/account-1/income-analytics",
|
"*/api/v1/brokerage-accounts/account-1/income-analytics",
|
||||||
@@ -495,8 +475,11 @@ describe("AccountIncomePage", () => {
|
|||||||
);
|
);
|
||||||
renderPage();
|
renderPage();
|
||||||
expect(
|
expect(
|
||||||
await screen.findByRole("button", { name: "Повторить" }),
|
await screen.findByText("Не удалось рассчитать пассивный доход", undefined, {
|
||||||
|
timeout: 4000,
|
||||||
|
}),
|
||||||
).toBeInTheDocument();
|
).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"]);
|
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([]);
|
respondWithRequestedPeriod([]);
|
||||||
const { queryClient } = renderPage();
|
const { queryClient } = renderPage();
|
||||||
await screen.findByLabelText("Период");
|
await screen.findByLabelText("Период");
|
||||||
@@ -653,51 +636,13 @@ describe("income period and snapshot boundary", () => {
|
|||||||
act(() => {
|
act(() => {
|
||||||
void queryClient.invalidateQueries();
|
void queryClient.invalidateQueries();
|
||||||
});
|
});
|
||||||
expect(
|
|
||||||
await screen.findByRole("status", { name: "Обновляем пассивный доход" }),
|
|
||||||
).toBeInTheDocument();
|
|
||||||
expect(screen.getByRole("region", { name: "Выплаты" })).toBeVisible();
|
expect(screen.getByRole("region", { name: "Выплаты" })).toBeVisible();
|
||||||
expect(screen.getByLabelText("Период")).toHaveTextContent(
|
expect(screen.getByLabelText("Период")).toHaveTextContent(
|
||||||
"02.08.2026 – 27.08.2026",
|
"02.08.2026 – 27.08.2026",
|
||||||
);
|
);
|
||||||
release();
|
release();
|
||||||
expect(
|
|
||||||
await screen.findByText(/Показан последний загруженный результат/),
|
|
||||||
).toBeInTheDocument();
|
|
||||||
expect(screen.getByRole("region", { name: "Выплаты" })).toBeVisible();
|
expect(screen.getByRole("region", { name: "Выплаты" })).toBeVisible();
|
||||||
server.use(
|
expect(screen.queryByText(/Показан последний загруженный результат/)).not.toBeInTheDocument();
|
||||||
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.getByLabelText("Период")).toHaveTextContent(
|
expect(screen.getByLabelText("Период")).toHaveTextContent(
|
||||||
"02.08.2026 – 27.08.2026",
|
"02.08.2026 – 27.08.2026",
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { useParams, useSearchParams } from "react-router";
|
|||||||
|
|
||||||
import { type IncomeAnalytics, useIncomeAnalytics } from "@/entities/income";
|
import { type IncomeAnalytics, useIncomeAnalytics } from "@/entities/income";
|
||||||
import { useScreenSync } from "@/features/tbank-connection";
|
import { useScreenSync } from "@/features/tbank-connection";
|
||||||
import { isValidPeriod, moscowDate } from "@/shared/lib";
|
import { isValidPeriod, moscowDate, useInitialAvailability } from "@/shared/lib";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
type IncomeDisplayModel,
|
type IncomeDisplayModel,
|
||||||
@@ -27,19 +27,13 @@ type AccountIncomePageViewModel
|
|||||||
display: IncomeDisplayModel;
|
display: IncomeDisplayModel;
|
||||||
form: ReturnType<typeof useForm<IncomeForm>>;
|
form: ReturnType<typeof useForm<IncomeForm>>;
|
||||||
formRevision: string;
|
formRevision: string;
|
||||||
lastSuccessfulAt?: null | string;
|
|
||||||
onReset: () => void;
|
onReset: () => void;
|
||||||
onSubmit: (values: IncomeForm) => void;
|
onSubmit: (values: IncomeForm) => void;
|
||||||
partial?: boolean;
|
partial?: boolean;
|
||||||
refreshError: boolean;
|
|
||||||
refreshing: boolean;
|
|
||||||
retry: () => Promise<unknown> | undefined;
|
|
||||||
sourceError?: boolean;
|
|
||||||
state: "loaded";
|
state: "loaded";
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
period: IncomePeriod;
|
period: IncomePeriod;
|
||||||
retry: () => Promise<unknown> | undefined;
|
|
||||||
state: "error";
|
state: "error";
|
||||||
}
|
}
|
||||||
| { state: "loading" };
|
| { state: "loading" };
|
||||||
@@ -69,7 +63,7 @@ const useAccountIncomePageViewModel = (): AccountIncomePageViewModel => {
|
|||||||
const [resetRevision, setResetRevision] = useState(0);
|
const [resetRevision, setResetRevision] = useState(0);
|
||||||
const analytics = useIncomeAnalytics(accountId, period);
|
const analytics = useIncomeAnalytics(accountId, period);
|
||||||
|
|
||||||
const sync = useScreenSync(
|
useScreenSync(
|
||||||
{ accountId, from: period.from, screen: "income", to: period.to },
|
{ accountId, from: period.from, screen: "income", to: period.to },
|
||||||
[analytics],
|
[analytics],
|
||||||
);
|
);
|
||||||
@@ -82,11 +76,20 @@ const useAccountIncomePageViewModel = (): AccountIncomePageViewModel => {
|
|||||||
form.reset(draftPeriod(period));
|
form.reset(draftPeriod(period));
|
||||||
}, [accountId, form, period]);
|
}, [accountId, form, period]);
|
||||||
|
|
||||||
if (analytics.isLoading || !analytics.data) {
|
const availability = useInitialAvailability({
|
||||||
return analytics.isError || analytics.meta?.sync.state === "failed"
|
hasContent: !!analytics.data,
|
||||||
? { period, retry: sync.retry, state: "error" }
|
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" };
|
: { state: "loading" };
|
||||||
}
|
|
||||||
|
|
||||||
const display = toIncomeDisplayModel(analytics.data, analytics.meta);
|
const display = toIncomeDisplayModel(analytics.data, analytics.meta);
|
||||||
|
|
||||||
@@ -109,14 +112,9 @@ const useAccountIncomePageViewModel = (): AccountIncomePageViewModel => {
|
|||||||
display,
|
display,
|
||||||
form,
|
form,
|
||||||
formRevision: `${accountId}:${period.from}:${period.to}:${resetRevision}`,
|
formRevision: `${accountId}:${period.from}:${period.to}:${resetRevision}`,
|
||||||
lastSuccessfulAt: analytics.meta?.lastSuccessfulAt,
|
|
||||||
onReset,
|
onReset,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
partial: analytics.meta?.availability !== "complete",
|
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",
|
state: "loaded",
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
+1
-3
@@ -1,6 +1,5 @@
|
|||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
|
|
||||||
import { Button } from "@mantine/core";
|
|
||||||
import { StateView } from "@wealthledger/ui";
|
import { StateView } from "@wealthledger/ui";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
@@ -8,12 +7,11 @@ import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
|
|||||||
|
|
||||||
type ErrorProps = Extract<AccountIncomePageViewModel, { state: "error" }>;
|
type ErrorProps = Extract<AccountIncomePageViewModel, { state: "error" }>;
|
||||||
|
|
||||||
const AccountIncomePageError: FC<ErrorProps> = (props) => {
|
const AccountIncomePageError: FC<ErrorProps> = () => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<StateView
|
<StateView
|
||||||
action={<Button onClick={props.retry}>{t("income.retry")}</Button>}
|
|
||||||
error
|
error
|
||||||
text={t("income.errorText")}
|
text={t("income.errorText")}
|
||||||
title={t("income.errorTitle")}
|
title={t("income.errorTitle")}
|
||||||
|
|||||||
+1
-40
@@ -2,19 +2,13 @@ import type { FC } from "react";
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
Alert,
|
Alert,
|
||||||
Button,
|
|
||||||
Group,
|
|
||||||
Loader,
|
|
||||||
Stack,
|
Stack,
|
||||||
Text,
|
|
||||||
Title,
|
Title,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
import { StateView } from "@wealthledger/ui";
|
import { StateView } from "@wealthledger/ui";
|
||||||
import { FormProvider } from "react-hook-form";
|
import { FormProvider } from "react-hook-form";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import { SourceSyncStatus } from "@/shared/ui";
|
|
||||||
|
|
||||||
import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
|
import type { AccountIncomePageViewModel } from "../AccountIncomePage.vm";
|
||||||
|
|
||||||
import classes from "../AccountIncomePage.module.css";
|
import classes from "../AccountIncomePage.module.css";
|
||||||
@@ -40,21 +34,14 @@ const AccountIncomePageLoadedSummary: FC<LoadedProps> = (props) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
|
const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
|
||||||
const { display, form, onReset, onSubmit, refreshError, refreshing, retry }
|
const { display, form, onReset, onSubmit } = props;
|
||||||
= props;
|
|
||||||
|
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack className={classes.page} gap="lg">
|
<Stack className={classes.page} gap="lg">
|
||||||
<SourceSyncStatus lastSuccessfulAt={props.lastSuccessfulAt} />
|
|
||||||
|
|
||||||
<Title order={1}>{t("income.title")}</Title>
|
<Title order={1}>{t("income.title")}</Title>
|
||||||
|
|
||||||
<Button disabled={refreshing} onClick={retry} w="fit-content">
|
|
||||||
{t("investment.refresh")}
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<FormProvider {...form}>
|
<FormProvider {...form}>
|
||||||
<IncomePeriodForm
|
<IncomePeriodForm
|
||||||
key={props.formRevision}
|
key={props.formRevision}
|
||||||
@@ -63,32 +50,6 @@ const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
|
|||||||
/>
|
/>
|
||||||
</FormProvider>
|
</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} />
|
<AccountIncomePageLoadedSummary {...props} />
|
||||||
|
|
||||||
<Alert color="blue">{t("income.taxBoundary")}</Alert>
|
<Alert color="blue">{t("income.taxBoundary")}</Alert>
|
||||||
|
|||||||
+5
-17
@@ -346,7 +346,7 @@ describe("AccountOperationsPage", () => {
|
|||||||
</MantineProvider>
|
</MantineProvider>
|
||||||
</QueryClientProvider>,
|
</QueryClientProvider>,
|
||||||
);
|
);
|
||||||
await screen.findByRole("button", { name: "Повторить" });
|
await screen.findByRole("button", { name: "Сбросить" });
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Сбросить" }));
|
fireEvent.click(screen.getByRole("button", { name: "Сбросить" }));
|
||||||
await screen.findByLabelText("Период");
|
await screen.findByLabelText("Период");
|
||||||
expect(screen.getByLabelText("URL")).toBeEmptyDOMElement();
|
expect(screen.getByLabelText("URL")).toBeEmptyDOMElement();
|
||||||
@@ -484,7 +484,9 @@ describe("AccountOperationsPage", () => {
|
|||||||
);
|
);
|
||||||
renderPage();
|
renderPage();
|
||||||
expect(
|
expect(
|
||||||
await screen.findByText("Не удалось загрузить журнал"),
|
await screen.findByText("Не удалось загрузить журнал", undefined, {
|
||||||
|
timeout: 4000,
|
||||||
|
}),
|
||||||
).toBeInTheDocument();
|
).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");
|
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([
|
expect(requested).toEqual([
|
||||||
{
|
{
|
||||||
categories: "trade",
|
categories: "trade",
|
||||||
@@ -530,19 +532,6 @@ it("keeps UTC operation boundaries in GET and source sync requests", async () =>
|
|||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
expect(syncRequests).toEqual([]);
|
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 () => {
|
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");
|
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: "Далее" }));
|
||||||
fireEvent.click(await screen.findByRole("button", { name: "Повторить" }));
|
|
||||||
await waitFor(() => expect(searches).toHaveLength(3));
|
await waitFor(() => expect(searches).toHaveLength(3));
|
||||||
assert.isDefined(searches[0]);
|
assert.isDefined(searches[0]);
|
||||||
assert.isDefined(searches[2]);
|
assert.isDefined(searches[2]);
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import {
|
|||||||
} from "@/entities/broker-operation";
|
} from "@/entities/broker-operation";
|
||||||
import { useScreenSync } from "@/features/tbank-connection";
|
import { useScreenSync } from "@/features/tbank-connection";
|
||||||
import { ApiErrorCode, apiErrorCode, isApiErrorCode } from "@/shared/api";
|
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);
|
const operationCategorySet = new Set<string>(operationCategories);
|
||||||
|
|
||||||
@@ -24,7 +24,6 @@ type AccountOperationsPageViewModel
|
|||||||
hasPrevious: boolean;
|
hasPrevious: boolean;
|
||||||
historyLoading?: boolean;
|
historyLoading?: boolean;
|
||||||
items: BrokerageOperation[];
|
items: BrokerageOperation[];
|
||||||
lastSuccessfulAt?: null | string;
|
|
||||||
onApply: () => void;
|
onApply: () => void;
|
||||||
onCategoriesChange: (value: string[]) => void;
|
onCategoriesChange: (value: string[]) => void;
|
||||||
onNext: () => void;
|
onNext: () => void;
|
||||||
@@ -32,13 +31,9 @@ type AccountOperationsPageViewModel
|
|||||||
onPrevious: () => void;
|
onPrevious: () => void;
|
||||||
onReset: () => void;
|
onReset: () => void;
|
||||||
partial?: boolean;
|
partial?: boolean;
|
||||||
refreshError?: boolean;
|
|
||||||
refreshing?: boolean;
|
|
||||||
retry?: () => void;
|
|
||||||
sourceError?: boolean;
|
|
||||||
state: "loaded";
|
state: "loaded";
|
||||||
}
|
}
|
||||||
| { onReset: () => void; retry: () => void; state: "error" }
|
| { onReset: () => void; state: "error" }
|
||||||
| { state: "loading" };
|
| { state: "loading" };
|
||||||
|
|
||||||
const useAccountOperationsPageVm = (): AccountOperationsPageViewModel => {
|
const useAccountOperationsPageVm = (): AccountOperationsPageViewModel => {
|
||||||
@@ -85,19 +80,28 @@ const useAccountOperationsPageVm = (): AccountOperationsPageViewModel => {
|
|||||||
history.reset();
|
history.reset();
|
||||||
}
|
}
|
||||||
|
|
||||||
const sync = useScreenSync(
|
useScreenSync(
|
||||||
{ accountId, screen: "operations", ...firstPageQuery },
|
{ accountId, screen: "operations", ...firstPageQuery },
|
||||||
[operations],
|
[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, {
|
const resetQueryKey = brokerageOperationsQueryOptions(accountId, {
|
||||||
limit: 100,
|
limit: 100,
|
||||||
}).queryKey;
|
}).queryKey;
|
||||||
|
|
||||||
const retry = () => history.retry(sync.retry);
|
|
||||||
|
|
||||||
const onReset = () => {
|
const onReset = () => {
|
||||||
setDraftPeriod([null, null]);
|
setDraftPeriod([null, null]);
|
||||||
setDraftCategories([]);
|
setDraftCategories([]);
|
||||||
@@ -106,16 +110,22 @@ const useAccountOperationsPageVm = (): AccountOperationsPageViewModel => {
|
|||||||
void queryClient.invalidateQueries({ queryKey: resetQueryKey });
|
void queryClient.invalidateQueries({ queryKey: resetQueryKey });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const isInvalidCursor = isApiErrorCode(
|
||||||
|
apiErrorCode(operations.error),
|
||||||
|
ApiErrorCode.InvalidOperationsCursor,
|
||||||
|
);
|
||||||
|
|
||||||
if (
|
if (
|
||||||
(operations.isError || operations.meta?.sync.state === "failed")
|
(isInvalidCursor || !operations.data)
|
||||||
&& (!operations.data
|
&& (operations.isError || operations.meta?.sync.state === "failed")
|
||||||
|| isApiErrorCode(
|
|
||||||
apiErrorCode(operations.error),
|
|
||||||
ApiErrorCode.InvalidOperationsCursor,
|
|
||||||
))
|
|
||||||
)
|
)
|
||||||
return { onReset, retry, state: "error" };
|
return { onReset, state: "error" };
|
||||||
if (!operations.data) return { state: "loading" };
|
|
||||||
|
if (!operations.data)
|
||||||
|
return availability === "unavailable"
|
||||||
|
? { onReset, state: "error" }
|
||||||
|
: { state: "loading" };
|
||||||
|
|
||||||
const nextCursor = operations.data.nextCursor;
|
const nextCursor = operations.data.nextCursor;
|
||||||
|
|
||||||
const isDirty
|
const isDirty
|
||||||
@@ -133,7 +143,6 @@ const useAccountOperationsPageVm = (): AccountOperationsPageViewModel => {
|
|||||||
operations.meta?.coverage?.historyState === "loading"
|
operations.meta?.coverage?.historyState === "loading"
|
||||||
|| operations.meta?.coverage?.historyState === "partial",
|
|| operations.meta?.coverage?.historyState === "partial",
|
||||||
items: operations.data.items,
|
items: operations.data.items,
|
||||||
lastSuccessfulAt: operations.meta?.lastSuccessfulAt,
|
|
||||||
onApply: () => {
|
onApply: () => {
|
||||||
if (!isValidPeriod(draftFrom, draftTo)) return;
|
if (!isValidPeriod(draftFrom, draftTo)) return;
|
||||||
setSearchParameters({
|
setSearchParameters({
|
||||||
@@ -155,10 +164,6 @@ const useAccountOperationsPageVm = (): AccountOperationsPageViewModel => {
|
|||||||
onPrevious: history.onPrevious,
|
onPrevious: history.onPrevious,
|
||||||
onReset,
|
onReset,
|
||||||
partial: operations.meta?.availability !== "complete",
|
partial: operations.meta?.availability !== "complete",
|
||||||
refreshError: operations.isError || sync.sourceError || sync.transportError,
|
|
||||||
refreshing: operations.isFetching || sync.refreshing,
|
|
||||||
retry,
|
|
||||||
sourceError: sync.sourceError,
|
|
||||||
state: "loaded",
|
state: "loaded",
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
+4
-10
@@ -1,6 +1,6 @@
|
|||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
|
|
||||||
import { Button, Group } from "@mantine/core";
|
import { Button } from "@mantine/core";
|
||||||
import { StateView } from "@wealthledger/ui";
|
import { StateView } from "@wealthledger/ui";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
@@ -14,21 +14,15 @@ type AccountOperationsPageErrorProps = Extract<
|
|||||||
const AccountOperationsPageError: FC<AccountOperationsPageErrorProps> = (
|
const AccountOperationsPageError: FC<AccountOperationsPageErrorProps> = (
|
||||||
props,
|
props,
|
||||||
) => {
|
) => {
|
||||||
const { retry } = props;
|
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<StateView
|
<StateView
|
||||||
action={(
|
action={(
|
||||||
<Group>
|
<Button onClick={props.onReset} variant="default">
|
||||||
<Button onClick={retry}>{t("ledger.retry")}</Button>
|
{t("ledger.reset")}
|
||||||
|
</Button>
|
||||||
<Button onClick={props.onReset} variant="default">
|
|
||||||
{t("ledger.reset")}
|
|
||||||
</Button>
|
|
||||||
</Group>
|
|
||||||
)}
|
)}
|
||||||
error
|
|
||||||
text={t("ledger.errorText")}
|
text={t("ledger.errorText")}
|
||||||
title={t("ledger.errorTitle")}
|
title={t("ledger.errorTitle")}
|
||||||
/>
|
/>
|
||||||
|
|||||||
-24
@@ -5,7 +5,6 @@ import {
|
|||||||
Button,
|
Button,
|
||||||
Group,
|
Group,
|
||||||
MultiSelect,
|
MultiSelect,
|
||||||
Progress,
|
|
||||||
Stack,
|
Stack,
|
||||||
Title,
|
Title,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
@@ -14,7 +13,6 @@ import { StateView } from "@wealthledger/ui";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import { LedgerEntryRow, operationCategories } from "@/entities/broker-operation";
|
import { LedgerEntryRow, operationCategories } from "@/entities/broker-operation";
|
||||||
import { SourceSyncStatus } from "@/shared/ui";
|
|
||||||
|
|
||||||
import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm";
|
import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm";
|
||||||
|
|
||||||
@@ -62,34 +60,12 @@ const AccountOperationsPageLoaded: FC<AccountOperationsPageLoadedProps> = (
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap="lg">
|
<Stack gap="lg">
|
||||||
<SourceSyncStatus lastSuccessfulAt={props.lastSuccessfulAt} />
|
|
||||||
|
|
||||||
<Title order={1}>{t("ledger.title")}</Title>
|
<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.partial && <Alert role="status">{t("investment.partial")}</Alert>}
|
||||||
|
|
||||||
{!!props.historyLoading && <Alert>{t("investment.history")}</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">
|
<Group align="end">
|
||||||
<DatePickerInput
|
<DatePickerInput
|
||||||
allowSingleDateInRange
|
allowSingleDateInRange
|
||||||
|
|||||||
@@ -10,20 +10,18 @@ const RECENT_EVENTS_LIMIT = 5;
|
|||||||
|
|
||||||
type AccountPageIncomeSummary
|
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"
|
state: "empty"
|
||||||
| "loading"
|
| "loading"
|
||||||
| "partial";
|
| "partial";
|
||||||
to: string;
|
to: string;
|
||||||
};
|
}
|
||||||
|
| { state: "error"; to: string }
|
||||||
|
| {
|
||||||
|
state: "loaded";
|
||||||
|
summary: IncomeSummary;
|
||||||
|
to: string;
|
||||||
|
}
|
||||||
|
;
|
||||||
|
|
||||||
type AccountPageRecentEvents = BrokerageEventsPreviewState;
|
type AccountPageRecentEvents = BrokerageEventsPreviewState;
|
||||||
|
|
||||||
@@ -57,20 +55,16 @@ type PreviewResource<T> = {
|
|||||||
function toIncomeSummary(
|
function toIncomeSummary(
|
||||||
accountId: string | undefined,
|
accountId: string | undefined,
|
||||||
income: PreviewResource<IncomeSummary>,
|
income: PreviewResource<IncomeSummary>,
|
||||||
retry: () => Promise<unknown>,
|
|
||||||
): AccountPageIncomeSummary {
|
): AccountPageIncomeSummary {
|
||||||
const to = `/accounts/${accountId}/income`;
|
const to = `/accounts/${accountId}/income`;
|
||||||
if (!income.data && !income.isError && income.meta?.sync.state !== "failed")
|
if (!income.data && !income.isError && income.meta?.sync.state !== "failed")
|
||||||
return { state: "loading", to };
|
return { state: "loading", to };
|
||||||
if (income.meta?.availability === "partial") return { state: "partial", to };
|
if (income.meta?.availability === "partial") return { state: "partial", to };
|
||||||
if (!income.data && (income.isError || income.meta?.sync.state === "failed"))
|
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 };
|
if (!income.data?.totalsByCurrency.length) return { state: "empty", to };
|
||||||
|
|
||||||
return {
|
return {
|
||||||
lastSuccessfulAt: income.meta?.lastSuccessfulAt,
|
|
||||||
refreshError: income.isError || income.meta?.sync.state === "failed",
|
|
||||||
stale: income.meta?.freshness === "stale",
|
|
||||||
state: "loaded",
|
state: "loaded",
|
||||||
summary: income.data,
|
summary: income.data,
|
||||||
to,
|
to,
|
||||||
@@ -97,9 +91,6 @@ function toRecentEvents(
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
items,
|
items,
|
||||||
lastSuccessfulAt: events.meta?.lastSuccessfulAt,
|
|
||||||
refreshError: events.isError || events.meta?.sync.state === "failed",
|
|
||||||
stale: events.meta?.freshness === "stale",
|
|
||||||
state: "loaded",
|
state: "loaded",
|
||||||
to,
|
to,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { MantineProvider } from "@mantine/core";
|
import { MantineProvider } from "@mantine/core";
|
||||||
import { type QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
import { type QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
import {
|
import {
|
||||||
fireEvent,
|
|
||||||
render,
|
render,
|
||||||
screen,
|
screen,
|
||||||
waitFor,
|
waitFor,
|
||||||
@@ -261,7 +260,7 @@ describe("AccountPage states", () => {
|
|||||||
it.each(["NOT_FOUND", "TBANK_NOT_CONNECTED", "INVALID_TBANK_TOKEN"])(
|
it.each(["NOT_FOUND", "TBANK_NOT_CONNECTED", "INVALID_TBANK_TOKEN"])(
|
||||||
"does not offer retry without cached data for %s",
|
"does not offer retry without cached data for %s",
|
||||||
(code) => {
|
(code) => {
|
||||||
renderPage(<AccountPageError code={code} retry={vi.fn()} />);
|
renderPage(<AccountPageError code={code} />);
|
||||||
expect(
|
expect(
|
||||||
screen.queryByRole("button", { name: "Повторить" }),
|
screen.queryByRole("button", { name: "Повторить" }),
|
||||||
).not.toBeInTheDocument();
|
).not.toBeInTheDocument();
|
||||||
@@ -274,12 +273,16 @@ describe("AccountPage states", () => {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
it.each(["TBANK_UNAVAILABLE", "UNKNOWN"])("allows retry for %s", (code) => {
|
it.each(["TBANK_UNAVAILABLE", "UNKNOWN"])(
|
||||||
const retry = vi.fn();
|
"shows neutral unavailable without retry for %s",
|
||||||
renderPage(<AccountPageError code={code} retry={retry} />);
|
(code) => {
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
|
renderPage(<AccountPageError code={code} />);
|
||||||
expect(retry).toHaveBeenCalledOnce();
|
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", () => {
|
it("shows supplied cash separately without adding currency instruments or recalculating totals", () => {
|
||||||
renderPage(
|
renderPage(
|
||||||
@@ -405,11 +408,9 @@ describe("AccountPage states", () => {
|
|||||||
expect(
|
expect(
|
||||||
screen.getByRole("heading", { level: 1, name: "Портфель" }),
|
screen.getByRole("heading", { level: 1, name: "Портфель" }),
|
||||||
).toBeInTheDocument();
|
).toBeInTheDocument();
|
||||||
expect(
|
expect(screen.queryByText(/T-Bank временно недоступен/))
|
||||||
screen.getByText(
|
.not.toBeInTheDocument();
|
||||||
"T-Bank временно недоступен. Показан последний успешный снимок.",
|
expect(screen.queryByText(/Данные получены/)).not.toBeInTheDocument();
|
||||||
),
|
|
||||||
).toBeInTheDocument();
|
|
||||||
expect(screen.getByRole("button", { name: "Акции" })).toBeInTheDocument();
|
expect(screen.getByRole("button", { name: "Акции" })).toBeInTheDocument();
|
||||||
expect(
|
expect(
|
||||||
screen.getByRole("button", { name: "Облигации" }),
|
screen.getByRole("button", { name: "Облигации" }),
|
||||||
@@ -573,7 +574,7 @@ describe("AccountPage states", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
screen.getByText("Не удалось загрузить последние события."),
|
screen.getByText("Пока недоступно"),
|
||||||
).toBeInTheDocument();
|
).toBeInTheDocument();
|
||||||
expect(screen.getByText("Вторая")).toBeInTheDocument();
|
expect(screen.getByText("Вторая")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
@@ -742,13 +743,13 @@ describe("AccountPage states", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
screen.getByText("Не удалось загрузить будущие события."),
|
screen.getByText("Данные появятся здесь, когда чтение восстановится."),
|
||||||
).toBeInTheDocument();
|
).toBeInTheDocument();
|
||||||
expect(screen.getByText("Вторая")).toBeInTheDocument();
|
expect(screen.getByText("Вторая")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
it.each([503])(
|
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) => {
|
async (status) => {
|
||||||
const initialPortfolio: Portfolio
|
const initialPortfolio: Portfolio
|
||||||
= {
|
= {
|
||||||
@@ -821,40 +822,30 @@ describe("AccountPage states", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
expect(structure).toHaveTextContent("10 ₽");
|
expect(structure).toHaveTextContent("10 ₽");
|
||||||
const snapshotText = screen.getByText(/Данные получены/).textContent;
|
expect(screen.queryByText(/Данные получены/)).not.toBeInTheDocument();
|
||||||
expect(snapshotText).toContain("10:00");
|
|
||||||
void queryClient.invalidateQueries({
|
void queryClient.invalidateQueries({
|
||||||
queryKey: portfolioQueryOptions("account-1").queryKey,
|
queryKey: portfolioQueryOptions("account-1").queryKey,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(
|
await waitFor(() => expect(requestCount).toBe(2));
|
||||||
await screen.findByText(
|
expect(screen.queryByText(/Не удалось обновить портфель/))
|
||||||
"Не удалось обновить портфель. Показан последний полученный снимок.",
|
.not.toBeInTheDocument();
|
||||||
),
|
expect(screen.queryByText(/T-Bank временно недоступен/))
|
||||||
).toBeInTheDocument();
|
.not.toBeInTheDocument();
|
||||||
expect(
|
|
||||||
screen.getByText(
|
|
||||||
"T-Bank временно недоступен. Показан последний успешный снимок.",
|
|
||||||
),
|
|
||||||
).toBeInTheDocument();
|
|
||||||
expect(screen.getByText("Вторая")).toBeInTheDocument();
|
expect(screen.getByText("Вторая")).toBeInTheDocument();
|
||||||
expect(
|
expect(
|
||||||
screen.getAllByRole("definition").map(node => node.textContent),
|
screen.getAllByRole("definition").map(node => node.textContent),
|
||||||
).toEqual(["1 234,5 ₽", "0,5 $"]);
|
).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.queryByRole("button", { name: "Повторить" }))
|
||||||
expect(screen.getByText(/Данные получены/).textContent).toBe(
|
.not.toBeInTheDocument();
|
||||||
snapshotText,
|
void queryClient.invalidateQueries({
|
||||||
);
|
queryKey: portfolioQueryOptions("account-1").queryKey,
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
|
});
|
||||||
await waitFor(() => expect(requestCount).toBe(3));
|
await waitFor(() => expect(requestCount).toBe(3));
|
||||||
expect(structure).toHaveTextContent("10 ₽");
|
expect(structure).toHaveTextContent("10 ₽");
|
||||||
expect(
|
expect(
|
||||||
screen.getAllByRole("definition").map(node => node.textContent),
|
screen.getAllByRole("definition").map(node => node.textContent),
|
||||||
).toEqual(["1 234,5 ₽", "0,5 $"]);
|
).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?.(
|
resolveRetry?.(
|
||||||
HttpResponse.json(
|
HttpResponse.json(
|
||||||
resource(
|
resource(
|
||||||
@@ -875,7 +866,7 @@ describe("AccountPage states", () => {
|
|||||||
screen.getAllByRole("definition").map(node => node.textContent),
|
screen.getAllByRole("definition").map(node => node.textContent),
|
||||||
).toEqual(["-0,5 $", "2,50 €"]),
|
).toEqual(["-0,5 $", "2,50 €"]),
|
||||||
);
|
);
|
||||||
expect(screen.getByText(/Данные получены/)).toHaveTextContent("11:30");
|
expect(screen.queryByText(/Данные получены/)).not.toBeInTheDocument();
|
||||||
expect(structure).not.toHaveTextContent("10 ₽");
|
expect(structure).not.toHaveTextContent("10 ₽");
|
||||||
expect(structure).toHaveTextContent("Нет положительной стоимости");
|
expect(structure).toHaveTextContent("Нет положительной стоимости");
|
||||||
expect(
|
expect(
|
||||||
@@ -916,13 +907,12 @@ describe("AccountPage states", () => {
|
|||||||
expect(
|
expect(
|
||||||
screen.getAllByRole("definition").map(node => node.textContent),
|
screen.getAllByRole("definition").map(node => node.textContent),
|
||||||
).toEqual(["1 234,5 ₽", "0,5 $"]);
|
).toEqual(["1 234,5 ₽", "0,5 $"]);
|
||||||
expect(screen.getByText(/Данные получены/)).toHaveTextContent("10:00");
|
expect(screen.queryByText(/Данные получены/)).not.toBeInTheDocument();
|
||||||
expect(
|
expect(
|
||||||
screen.queryByRole("status", { name: "Загрузка" }),
|
screen.queryByRole("status", { name: "Загрузка" }),
|
||||||
).not.toBeInTheDocument();
|
).not.toBeInTheDocument();
|
||||||
expect(
|
expect(screen.queryByRole("status", { name: "Обновляем портфель" }))
|
||||||
screen.getByRole("status", { name: "Обновляем портфель" }),
|
.not.toBeInTheDocument();
|
||||||
).toBeInTheDocument();
|
|
||||||
|
|
||||||
resolveRefresh?.(HttpResponse.json(resource(portfolio)));
|
resolveRefresh?.(HttpResponse.json(resource(portfolio)));
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -18,10 +18,6 @@ const AccountPage: FC = () => {
|
|||||||
incomeSummary={viewModel.incomeSummary}
|
incomeSummary={viewModel.incomeSummary}
|
||||||
recentEvents={viewModel.recentEvents}
|
recentEvents={viewModel.recentEvents}
|
||||||
recentOperations={viewModel.recentOperations}
|
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}
|
positionSections={viewModel.positionSections}
|
||||||
recentEvents={viewModel.recentEvents}
|
recentEvents={viewModel.recentEvents}
|
||||||
recentOperations={viewModel.recentOperations}
|
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 type { FC, PropsWithChildren } from "react";
|
||||||
|
|
||||||
import { MantineProvider } from "@mantine/core";
|
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 { http, HttpResponse } from "msw";
|
||||||
import { MemoryRouter, Route, Routes } from "react-router";
|
import { MemoryRouter, Route, Routes } from "react-router";
|
||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
@@ -147,10 +147,10 @@ describe("useAccountPageViewModel", () => {
|
|||||||
HttpResponse.json(resource(portfolio)),
|
HttpResponse.json(resource(portfolio)),
|
||||||
),
|
),
|
||||||
http.get("*/api/v1/brokerage-accounts/:accountId/operations", () =>
|
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", () =>
|
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();
|
configureTestAuth();
|
||||||
|
|
||||||
const sections: Record<string, unknown>
|
const sections: Record<string, unknown>
|
||||||
@@ -219,48 +219,17 @@ it("refreshes every overview section through one account descriptor and observat
|
|||||||
portfolio,
|
portfolio,
|
||||||
};
|
};
|
||||||
|
|
||||||
const observed: string[] = [];
|
|
||||||
const scopes: unknown[] = [];
|
|
||||||
let version = "1";
|
|
||||||
server.use(
|
server.use(
|
||||||
...Object.entries(sections).map(([path, data]) =>
|
...Object.entries(sections).map(([path, data]) =>
|
||||||
http.get(
|
http.get(
|
||||||
`*/api/v1/brokerage-accounts/:accountId/${path}`,
|
`*/api/v1/brokerage-accounts/:accountId/${path}`,
|
||||||
({ request }) => {
|
() => {
|
||||||
if (new URL(request.url).searchParams.get("sync") === "observe")
|
|
||||||
observed.push(path);
|
|
||||||
|
|
||||||
return HttpResponse.json(
|
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(), {
|
const { result } = renderHook(() => useAccountPageViewModel(), {
|
||||||
@@ -275,11 +244,5 @@ it("refreshes every overview section through one account descriptor and observat
|
|||||||
state: "loaded",
|
state: "loaded",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
await act(async () => {
|
expect(result.current).not.toHaveProperty("retry");
|
||||||
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" }]);
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ import {
|
|||||||
import { useIncomeSummary } from "@/entities/income";
|
import { useIncomeSummary } from "@/entities/income";
|
||||||
import { usePortfolio } from "@/entities/portfolio";
|
import { usePortfolio } from "@/entities/portfolio";
|
||||||
import { useScreenSync } from "@/features/tbank-connection";
|
import { useScreenSync } from "@/features/tbank-connection";
|
||||||
import { apiErrorCode } from "@/shared/api";
|
import { ApiErrorCode, apiErrorCode, isApiErrorCode } from "@/shared/api";
|
||||||
|
import { useInitialAvailability } from "@/shared/lib";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
type AccountPagePositionSection,
|
type AccountPagePositionSection,
|
||||||
@@ -35,10 +36,6 @@ type AccountPageContent = {
|
|||||||
partial?: boolean;
|
partial?: boolean;
|
||||||
recentEvents: AccountPageRecentEvents;
|
recentEvents: AccountPageRecentEvents;
|
||||||
recentOperations: AccountPageRecentOperations;
|
recentOperations: AccountPageRecentOperations;
|
||||||
refreshError: boolean;
|
|
||||||
refreshing: boolean;
|
|
||||||
retry: () => Promise<unknown> | undefined;
|
|
||||||
sourceError?: boolean;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
type AccountPageEmptyViewModel = AccountPageContent & {
|
type AccountPageEmptyViewModel = AccountPageContent & {
|
||||||
@@ -54,9 +51,16 @@ type AccountPageLoadedViewModel = AccountPageContent & {
|
|||||||
type AccountPageViewModel
|
type AccountPageViewModel
|
||||||
= | AccountPageEmptyViewModel
|
= | AccountPageEmptyViewModel
|
||||||
| AccountPageLoadedViewModel
|
| AccountPageLoadedViewModel
|
||||||
| { code?: string; retry: () => Promise<unknown> | undefined; state: "error" }
|
| { code?: string; state: "error" }
|
||||||
| { state: "loading" };
|
| { 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 {
|
function useAccountPageViewModel(): AccountPageViewModel {
|
||||||
const { accountId } = useParams();
|
const { accountId } = useParams();
|
||||||
const portfolio = usePortfolio(accountId);
|
const portfolio = usePortfolio(accountId);
|
||||||
@@ -69,7 +73,7 @@ function useAccountPageViewModel(): AccountPageViewModel {
|
|||||||
const income = useIncomeSummary(accountId);
|
const income = useIncomeSummary(accountId);
|
||||||
const accounts = useBrokerageAccounts();
|
const accounts = useBrokerageAccounts();
|
||||||
|
|
||||||
const sync = useScreenSync({ accountId, screen: "account" }, [
|
useScreenSync({ accountId, screen: "account" }, [
|
||||||
accounts,
|
accounts,
|
||||||
portfolio,
|
portfolio,
|
||||||
operations,
|
operations,
|
||||||
@@ -77,32 +81,28 @@ function useAccountPageViewModel(): AccountPageViewModel {
|
|||||||
income,
|
income,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (!portfolio.data) {
|
const code = apiErrorCode(portfolio.error);
|
||||||
if (portfolio.isError || portfolio.meta?.sync.state === "failed")
|
const isAccessFailure = isPortfolioAccessFailure(code);
|
||||||
return {
|
|
||||||
code: apiErrorCode(portfolio.error),
|
|
||||||
retry: sync.retry,
|
|
||||||
state: "error" as const,
|
|
||||||
};
|
|
||||||
|
|
||||||
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 account = accounts.data?.find(item => item.id === accountId);
|
||||||
const recentOperations = toRecentOperations(accountId, operations);
|
const recentOperations = toRecentOperations(accountId, operations);
|
||||||
const recentEvents = toRecentEvents(accountId, events);
|
const recentEvents = toRecentEvents(accountId, events);
|
||||||
|
|
||||||
const incomeSummary = toIncomeSummary(
|
const incomeSummary = toIncomeSummary(accountId, income);
|
||||||
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,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (
|
if (
|
||||||
portfolio.meta?.availability === "complete"
|
portfolio.meta?.availability === "complete"
|
||||||
@@ -116,19 +116,20 @@ function useAccountPageViewModel(): AccountPageViewModel {
|
|||||||
recentEvents,
|
recentEvents,
|
||||||
recentOperations,
|
recentOperations,
|
||||||
state: "empty" as const,
|
state: "empty" as const,
|
||||||
...refresh,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const isPartial = portfolio.meta?.availability === "partial";
|
||||||
|
|
||||||
return {
|
return {
|
||||||
account,
|
account,
|
||||||
accountId,
|
accountId,
|
||||||
incomeSummary,
|
incomeSummary,
|
||||||
|
partial: isPartial,
|
||||||
portfolio: portfolio.data,
|
portfolio: portfolio.data,
|
||||||
positionSections: toAccountPagePositionSections(portfolio.data),
|
positionSections: toAccountPagePositionSections(portfolio.data),
|
||||||
recentEvents,
|
recentEvents,
|
||||||
recentOperations,
|
recentOperations,
|
||||||
state: "loaded" as const,
|
state: "loaded" as const,
|
||||||
...refresh,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import { useTranslation } from "react-i18next";
|
|||||||
import type { BrokerageAccount } from "@/entities/brokerage-account";
|
import type { BrokerageAccount } from "@/entities/brokerage-account";
|
||||||
|
|
||||||
import { BrokerageEventsPreview } from "@/entities/brokerage-event";
|
import { BrokerageEventsPreview } from "@/entities/brokerage-event";
|
||||||
import { InvestmentRefreshState } from "@/features/tbank-connection";
|
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
AccountPageIncomeSummary,
|
AccountPageIncomeSummary,
|
||||||
@@ -26,10 +25,6 @@ type AccountPageEmptyProps = {
|
|||||||
incomeSummary?: AccountPageIncomeSummary;
|
incomeSummary?: AccountPageIncomeSummary;
|
||||||
recentEvents: AccountPageRecentEvents;
|
recentEvents: AccountPageRecentEvents;
|
||||||
recentOperations: AccountPageRecentOperations;
|
recentOperations: AccountPageRecentOperations;
|
||||||
refreshError?: boolean;
|
|
||||||
refreshing?: boolean;
|
|
||||||
retry?: () => void;
|
|
||||||
sourceError?: boolean;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const AccountPageEmpty: FC<AccountPageEmptyProps> = (props) => {
|
const AccountPageEmpty: FC<AccountPageEmptyProps> = (props) => {
|
||||||
@@ -45,14 +40,6 @@ const AccountPageEmpty: FC<AccountPageEmptyProps> = (props) => {
|
|||||||
<Stack>
|
<Stack>
|
||||||
<AccountHeading account={props.account} accountId={props.accountId} />
|
<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")} />
|
<StateView text={text} title={t("portfolio.emptyTitle")} />
|
||||||
|
|
||||||
<PortfolioStructure
|
<PortfolioStructure
|
||||||
|
|||||||
@@ -7,10 +7,10 @@ import { Link } from "react-router";
|
|||||||
|
|
||||||
import { ApiErrorCode, isApiErrorCode } from "@/shared/api";
|
import { ApiErrorCode, isApiErrorCode } from "@/shared/api";
|
||||||
|
|
||||||
type AccountPageErrorProps = { code?: string; retry: () => void };
|
type AccountPageErrorProps = { code?: string };
|
||||||
|
|
||||||
const AccountPageError: FC<AccountPageErrorProps> = (props) => {
|
const AccountPageError: FC<AccountPageErrorProps> = (props) => {
|
||||||
const { code, retry } = props;
|
const { code } = props;
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
if (isApiErrorCode(code, ApiErrorCode.NotFound))
|
if (isApiErrorCode(code, ApiErrorCode.NotFound))
|
||||||
return (
|
return (
|
||||||
@@ -25,6 +25,7 @@ const AccountPageError: FC<AccountPageErrorProps> = (props) => {
|
|||||||
title={t("portfolio.accountUnavailableTitle")}
|
title={t("portfolio.accountUnavailableTitle")}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
if (
|
if (
|
||||||
isApiErrorCode(code, ApiErrorCode.TbankNotConnected)
|
isApiErrorCode(code, ApiErrorCode.TbankNotConnected)
|
||||||
|| isApiErrorCode(code, ApiErrorCode.InvalidTbankToken)
|
|| isApiErrorCode(code, ApiErrorCode.InvalidTbankToken)
|
||||||
@@ -41,22 +42,11 @@ const AccountPageError: FC<AccountPageErrorProps> = (props) => {
|
|||||||
title={t("portfolio.connectionErrorTitle")}
|
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 (
|
return (
|
||||||
<StateView
|
<StateView
|
||||||
action={<Button onClick={retry}>{t("accounts.retry")}</Button>}
|
text={t("states.unavailableText")}
|
||||||
error
|
title={t("states.unavailableTitle")}
|
||||||
text={t("states.errorText")}
|
|
||||||
title={t("states.errorTitle")}
|
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,14 +1,12 @@
|
|||||||
import type { FC } from "react";
|
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 { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import type { BrokerageAccount } from "@/entities/brokerage-account";
|
import type { BrokerageAccount } from "@/entities/brokerage-account";
|
||||||
import type { Portfolio } from "@/entities/portfolio";
|
import type { Portfolio } from "@/entities/portfolio";
|
||||||
|
|
||||||
import { BrokerageEventsPreview } from "@/entities/brokerage-event";
|
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 { AccountPagePositionSection } from "../../../model/positions";
|
||||||
import type {
|
import type {
|
||||||
@@ -34,10 +32,6 @@ type AccountPageLoadedProps = {
|
|||||||
positionSections: AccountPagePositionSection[];
|
positionSections: AccountPagePositionSection[];
|
||||||
recentEvents: AccountPageRecentEvents;
|
recentEvents: AccountPageRecentEvents;
|
||||||
recentOperations: AccountPageRecentOperations;
|
recentOperations: AccountPageRecentOperations;
|
||||||
refreshError?: boolean;
|
|
||||||
refreshing?: boolean;
|
|
||||||
retry?: () => void;
|
|
||||||
sourceError?: boolean;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
|
const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
|
||||||
@@ -55,27 +49,6 @@ const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
|
|||||||
<Stack gap="lg">
|
<Stack gap="lg">
|
||||||
<AccountHeading account={props.account} accountId={props.accountId} />
|
<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
|
{props.partial
|
||||||
? <Alert role="status">{t("investment.partial")}</Alert>
|
? <Alert role="status">{t("investment.partial")}</Alert>
|
||||||
: <CurrencyCards amounts={props.portfolio.totalsByCurrency} />}
|
: <CurrencyCards amounts={props.portfolio.totalsByCurrency} />}
|
||||||
|
|||||||
@@ -8,30 +8,30 @@ import { Link } from "react-router";
|
|||||||
import type { IncomeSummary as IncomeSummaryData } from "@/entities/income";
|
import type { IncomeSummary as IncomeSummaryData } from "@/entities/income";
|
||||||
|
|
||||||
import { formatMoney } from "@/shared/lib";
|
import { formatMoney } from "@/shared/lib";
|
||||||
import { SourceSyncStatus } from "@/shared/ui";
|
|
||||||
|
|
||||||
type IncomeSummaryProps
|
type IncomeSummaryProps
|
||||||
= | {
|
= | {
|
||||||
lastSuccessfulAt?: null | string;
|
state: "empty";
|
||||||
refreshError?: boolean;
|
to: string;
|
||||||
stale?: boolean;
|
}
|
||||||
|
| { state: "error"; to: string }
|
||||||
|
| {
|
||||||
state: "loaded";
|
state: "loaded";
|
||||||
summary: IncomeSummaryData;
|
summary: IncomeSummaryData;
|
||||||
to: string;
|
to: string;
|
||||||
}
|
}
|
||||||
| { retry: () => void; state: "error"; to: string }
|
| {
|
||||||
| { state: "empty"; to: string }
|
state: "loading";
|
||||||
| { state: "loading"; to: string }
|
to: string;
|
||||||
| { state: "partial"; to: string };
|
}
|
||||||
|
| {
|
||||||
|
state: "partial";
|
||||||
|
to: string;
|
||||||
|
};
|
||||||
|
|
||||||
const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
|
const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
const errorText
|
|
||||||
= props.state === "loaded" && props.refreshError
|
|
||||||
? t("income.refreshError")
|
|
||||||
: null;
|
|
||||||
|
|
||||||
if (props.state === "loading" || props.state === "partial")
|
if (props.state === "loading" || props.state === "partial")
|
||||||
return (
|
return (
|
||||||
<Text c="dimmed" role="status">
|
<Text c="dimmed" role="status">
|
||||||
@@ -45,9 +45,6 @@ const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
|
|||||||
if (props.state === "error")
|
if (props.state === "error")
|
||||||
return (
|
return (
|
||||||
<StateView
|
<StateView
|
||||||
action={
|
|
||||||
<Button onClick={props.retry}>{t("income.summaryRetry")}</Button>
|
|
||||||
}
|
|
||||||
error
|
error
|
||||||
text={t("income.errorText")}
|
text={t("income.errorText")}
|
||||||
title={t("income.summaryError")}
|
title={t("income.summaryError")}
|
||||||
@@ -66,12 +63,6 @@ const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap="xs">
|
<Stack gap="xs">
|
||||||
<SourceSyncStatus
|
|
||||||
errorText={errorText}
|
|
||||||
lastSuccessfulAt={props.lastSuccessfulAt}
|
|
||||||
stale={props.stale}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{props.summary.totalsByCurrency.map(total => (
|
{props.summary.totalsByCurrency.map(total => (
|
||||||
<Paper key={total.currency} p="sm" withBorder>
|
<Paper key={total.currency} p="sm" withBorder>
|
||||||
<Text fw={700}>{formatMoney(total.total)}</Text>
|
<Text fw={700}>{formatMoney(total.total)}</Text>
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import type { FC } from "react";
|
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 { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
|
|
||||||
import { LedgerEntryRow } from "@/entities/broker-operation";
|
import { LedgerEntryRow } from "@/entities/broker-operation";
|
||||||
import { SourceSyncStatus } from "@/shared/ui";
|
|
||||||
|
|
||||||
import type { AccountPageRecentOperations } from "../../../model/previews";
|
import type { AccountPageRecentOperations } from "../../../model/previews";
|
||||||
|
|
||||||
@@ -18,28 +17,15 @@ const RecentOperations: FC<RecentOperationsProps> = (props) => {
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { operations } = props;
|
const { operations } = props;
|
||||||
|
|
||||||
const errorText
|
|
||||||
= operations.state === "loaded" && operations.refreshError
|
|
||||||
? t("accounts.refreshError")
|
|
||||||
: null;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap="sm">
|
<Stack gap="sm">
|
||||||
{operations.state === "loaded" && (
|
|
||||||
<SourceSyncStatus
|
|
||||||
errorText={errorText}
|
|
||||||
lastSuccessfulAt={operations.lastSuccessfulAt}
|
|
||||||
stale={operations.stale}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{operations.state === "loading" && (
|
{operations.state === "loading" && (
|
||||||
<LoadingSkeleton label={t("ledger.recentLoading")}>
|
<LoadingSkeleton label={t("ledger.recentLoading")}>
|
||||||
{["first", "second", "third"].map(placeholder => <Skeleton height={48} key={placeholder} radius="sm" />)}
|
{["first", "second", "third"].map(placeholder => <Skeleton height={48} key={placeholder} radius="sm" />)}
|
||||||
</LoadingSkeleton>
|
</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>}
|
{operations.state === "empty" && <Text c="dimmed">{t("ledger.recentEmpty")}</Text>}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { MantineProvider } from "@mantine/core";
|
import { MantineProvider } from "@mantine/core";
|
||||||
import { type QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
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 { http, HttpResponse } from "msw";
|
||||||
import { MemoryRouter } from "react-router";
|
import { MemoryRouter } from "react-router";
|
||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
@@ -58,10 +58,11 @@ describe("AccountsPage", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
renderPage(createTestQueryClient());
|
renderPage(createTestQueryClient());
|
||||||
fireEvent.click(await screen.findByRole("button", { name: "Повторить" }));
|
expect(await screen.findByText(account.name, undefined, {
|
||||||
expect(await screen.findByText(account.name)).toBeVisible();
|
timeout: 4000,
|
||||||
|
})).toBeVisible();
|
||||||
|
|
||||||
expect(modes).toEqual([null, "observe"]);
|
expect(modes).toEqual([null, null]);
|
||||||
});
|
});
|
||||||
it.each([
|
it.each([
|
||||||
["loading", AccountsPageLoading, "status"],
|
["loading", AccountsPageLoading, "status"],
|
||||||
@@ -81,17 +82,16 @@ describe("AccountsPage", () => {
|
|||||||
).toBeInTheDocument();
|
).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("routes connection errors to settings and keeps retry available", () => {
|
it("routes connection errors to settings without technical retry", () => {
|
||||||
const retry = vi.fn();
|
|
||||||
render(
|
render(
|
||||||
<MantineProvider>
|
<MantineProvider>
|
||||||
<MemoryRouter>
|
<MemoryRouter>
|
||||||
<AccountsPageError code="TBANK_UNAVAILABLE" retry={retry} />
|
<AccountsPageError code="TBANK_NOT_CONNECTED" />
|
||||||
</MemoryRouter>
|
</MemoryRouter>
|
||||||
</MantineProvider>,
|
</MantineProvider>,
|
||||||
);
|
);
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
|
expect(screen.queryByRole("button", { name: "Повторить" }))
|
||||||
expect(retry).toHaveBeenCalledOnce();
|
.not.toBeInTheDocument();
|
||||||
expect(
|
expect(
|
||||||
screen.getByRole("link", { name: "Открыть настройки T-Bank" }),
|
screen.getByRole("link", { name: "Открыть настройки T-Bank" }),
|
||||||
).toHaveAttribute("href", "/settings");
|
).toHaveAttribute("href", "/settings");
|
||||||
@@ -123,14 +123,13 @@ describe("AccountsPage", () => {
|
|||||||
|
|
||||||
await waitFor(() => expect(requestCount).toBe(2));
|
await waitFor(() => expect(requestCount).toBe(2));
|
||||||
expect(screen.getByText(account.name)).toBeInTheDocument();
|
expect(screen.getByText(account.name)).toBeInTheDocument();
|
||||||
expect(
|
expect(screen.queryByRole("status", { name: "Обновляем данные" }))
|
||||||
screen.getByRole("status", { name: "Обновляем данные" }),
|
.not.toBeInTheDocument();
|
||||||
).toBeInTheDocument();
|
|
||||||
|
|
||||||
resolveRefresh?.(HttpResponse.json(resource([account])));
|
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[] = [];
|
const requests: unknown[] = [];
|
||||||
server.use(
|
server.use(
|
||||||
http.post("*/api/v1/tbank-sync", async ({ request }) => {
|
http.post("*/api/v1/tbank-sync", async ({ request }) => {
|
||||||
@@ -161,17 +160,15 @@ describe("AccountsPage", () => {
|
|||||||
queryKey: brokerageAccountsQueryKey,
|
queryKey: brokerageAccountsQueryKey,
|
||||||
});
|
});
|
||||||
|
|
||||||
const warning = await screen.findByText(
|
await waitFor(() => expect(requestCount).toBe(2));
|
||||||
"Не удалось обновить данные. Показаны последние полученные.",
|
expect(
|
||||||
);
|
screen.queryByText(
|
||||||
|
"Не удалось обновить данные. Показаны последние полученные.",
|
||||||
expect(warning).toBeInTheDocument();
|
),
|
||||||
|
).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole("button", { name: "Повторить" }))
|
||||||
|
.not.toBeInTheDocument();
|
||||||
expect(screen.getByText(account.name)).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([]);
|
expect(requests).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -194,11 +191,12 @@ describe("AccountsPage", () => {
|
|||||||
queryKey: brokerageAccountsQueryKey,
|
queryKey: brokerageAccountsQueryKey,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
await waitFor(() => expect(requestCount).toBe(2));
|
||||||
expect(
|
expect(
|
||||||
await screen.findByText(
|
screen.queryByText(
|
||||||
"Не удалось обновить данные. Показаны последние полученные.",
|
"Не удалось обновить данные. Показаны последние полученные.",
|
||||||
),
|
),
|
||||||
).toBeInTheDocument();
|
).not.toBeInTheDocument();
|
||||||
expect(screen.getByText("Нет инвестиционных счетов")).toBeInTheDocument();
|
expect(screen.getByText("Нет инвестиционных счетов")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -226,7 +224,7 @@ it.each(["idle", "failed"] as const)(
|
|||||||
.not.toBeInTheDocument();
|
.not.toBeInTheDocument();
|
||||||
if (state === "failed")
|
if (state === "failed")
|
||||||
// eslint-disable-next-line vitest/no-conditional-expect -- Each fixed state has a different observable recovery contract.
|
// 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();
|
.toBeVisible();
|
||||||
else
|
else
|
||||||
// eslint-disable-next-line vitest/no-conditional-expect -- Each fixed state has a different observable recovery contract.
|
// 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();
|
const viewModel = useAccountsPageViewModel();
|
||||||
if (viewModel.state === "loading") return <AccountsPageLoading />;
|
if (viewModel.state === "loading") return <AccountsPageLoading />;
|
||||||
if (viewModel.state === "error") return <AccountsPageError {...viewModel} />;
|
if (viewModel.state === "error") return <AccountsPageError {...viewModel} />;
|
||||||
if (viewModel.state === "empty")
|
if (viewModel.state === "empty") return <AccountsPageEmpty />;
|
||||||
return (
|
|
||||||
<AccountsPageEmpty
|
|
||||||
lastSuccessfulAt={viewModel.lastSuccessfulAt}
|
|
||||||
refreshError={viewModel.refreshError}
|
|
||||||
refreshing={viewModel.refreshing}
|
|
||||||
retry={viewModel.retry}
|
|
||||||
sourceError={viewModel.sourceError}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AccountsPageLoaded
|
<AccountsPageLoaded
|
||||||
accounts={viewModel.accounts}
|
accounts={viewModel.accounts}
|
||||||
lastSuccessfulAt={viewModel.lastSuccessfulAt}
|
|
||||||
refreshError={viewModel.refreshError}
|
|
||||||
refreshing={viewModel.refreshing}
|
|
||||||
retry={viewModel.retry}
|
|
||||||
sourceError={viewModel.sourceError}
|
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,45 +1,54 @@
|
|||||||
import {
|
import {
|
||||||
|
type BrokerageAccountCard,
|
||||||
brokerageAccountCards,
|
brokerageAccountCards,
|
||||||
useBrokerageAccounts,
|
useBrokerageAccounts,
|
||||||
} from "@/entities/brokerage-account";
|
} from "@/entities/brokerage-account";
|
||||||
import { useScreenSync } from "@/features/tbank-connection";
|
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 accounts = useBrokerageAccounts();
|
||||||
const sync = useScreenSync({ screen: "accounts" }, [accounts]);
|
useScreenSync({ screen: "accounts" }, [accounts]);
|
||||||
|
|
||||||
if (
|
const code = apiErrorCode(accounts.error);
|
||||||
!accounts.data
|
const isAccessFailure = isAccountsAccessFailure(code);
|
||||||
|| (accounts.meta?.availability === "partial" && accounts.data.length === 0)
|
|
||||||
) {
|
|
||||||
if (!accounts.isError && accounts.meta?.sync.state !== "failed")
|
|
||||||
return { state: "loading" as const };
|
|
||||||
|
|
||||||
|
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 {
|
return {
|
||||||
code: apiErrorCode(accounts.error),
|
state: availability === "unavailable" ? "error" : "loading",
|
||||||
retry: sync.retry,
|
} as const;
|
||||||
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,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (accounts.data.length === 0)
|
if (accounts.data.length === 0)
|
||||||
return {
|
return {
|
||||||
...refresh,
|
|
||||||
state: "empty" as const,
|
state: "empty" as const,
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
accounts: brokerageAccountCards(accounts.data, accounts.meta?.dependencies),
|
accounts: brokerageAccountCards(accounts.data, accounts.meta?.dependencies),
|
||||||
...refresh,
|
|
||||||
state: "loaded" as const,
|
state: "loaded" as const,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,26 +1,16 @@
|
|||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
|
|
||||||
import { Stack } from "@mantine/core";
|
|
||||||
import { StateView } from "@wealthledger/ui";
|
import { StateView } from "@wealthledger/ui";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import {
|
const AccountsPageEmpty: FC = () => {
|
||||||
InvestmentRefreshState,
|
|
||||||
type InvestmentRefreshStateProps,
|
|
||||||
} from "@/features/tbank-connection";
|
|
||||||
|
|
||||||
const AccountsPageEmpty: FC<InvestmentRefreshStateProps> = (props) => {
|
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack>
|
<StateView
|
||||||
<InvestmentRefreshState {...props} />
|
text={t("accounts.emptyText")}
|
||||||
|
title={t("accounts.emptyTitle")}
|
||||||
<StateView
|
/>
|
||||||
text={t("accounts.emptyText")}
|
|
||||||
title={t("accounts.emptyTitle")}
|
|
||||||
/>
|
|
||||||
</Stack>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,16 @@
|
|||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
|
|
||||||
import { Button, Stack } from "@mantine/core";
|
import { Button } from "@mantine/core";
|
||||||
import { StateView } from "@wealthledger/ui";
|
import { StateView } from "@wealthledger/ui";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
|
|
||||||
import { ApiErrorCode, isApiErrorCode } from "@/shared/api";
|
import { ApiErrorCode, isApiErrorCode } from "@/shared/api";
|
||||||
|
|
||||||
type AccountsPageErrorProps = { code?: string; retry?: () => void };
|
type AccountsPageErrorProps = { code?: string };
|
||||||
|
|
||||||
const AccountsPageError: FC<AccountsPageErrorProps> = (props) => {
|
const AccountsPageError: FC<AccountsPageErrorProps> = (props) => {
|
||||||
const { code, retry } = props;
|
const { code } = props;
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
const settingsAction = (
|
const settingsAction = (
|
||||||
@@ -37,28 +37,11 @@ const AccountsPageError: FC<AccountsPageErrorProps> = (props) => {
|
|||||||
title={t("accounts.invalidTokenTitle")}
|
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 (
|
return (
|
||||||
<StateView
|
<StateView
|
||||||
action={<Button onClick={retry}>{t("accounts.retry")}</Button>}
|
text={t("states.unavailableText")}
|
||||||
error
|
title={t("states.unavailableTitle")}
|
||||||
text={t("states.errorText")}
|
|
||||||
title={t("states.errorTitle")}
|
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -8,17 +8,12 @@ import {
|
|||||||
type BrokerageAccountCard,
|
type BrokerageAccountCard,
|
||||||
BrokerageAccountList,
|
BrokerageAccountList,
|
||||||
} from "@/entities/brokerage-account";
|
} from "@/entities/brokerage-account";
|
||||||
import {
|
|
||||||
InvestmentRefreshState,
|
|
||||||
type InvestmentRefreshStateProps,
|
|
||||||
} from "@/features/tbank-connection";
|
|
||||||
|
|
||||||
type AccountsPageLoadedProps = InvestmentRefreshStateProps & {
|
type AccountsPageLoadedProps = {
|
||||||
accounts: BrokerageAccountCard[];
|
accounts: BrokerageAccountCard[];
|
||||||
};
|
};
|
||||||
|
|
||||||
const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
|
const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
|
||||||
const { accounts, ...refresh } = props;
|
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -31,8 +26,6 @@ const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
|
|||||||
</Text>
|
</Text>
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
<InvestmentRefreshState {...refresh} />
|
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
component={Link}
|
component={Link}
|
||||||
to="/accounts/all"
|
to="/accounts/all"
|
||||||
@@ -42,7 +35,7 @@ const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
|
|||||||
{t("accounts.openAll")}
|
{t("accounts.openAll")}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<BrokerageAccountList accounts={accounts} />
|
<BrokerageAccountList accounts={props.accounts} />
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -352,11 +352,7 @@ describe("bond page", () => {
|
|||||||
it("keeps market content and sold-position history when coupons fail", async () => {
|
it("keeps market content and sold-position history when coupons fail", async () => {
|
||||||
setup({ failCoupons: true, noPosition: true });
|
setup({ failCoupons: true, noPosition: true });
|
||||||
await screen.findByText("98,125 %");
|
await screen.findByText("98,125 %");
|
||||||
const message = await screen.findByText(/Не удалось загрузить этот раздел/);
|
expect(screen.queryByRole("button", { name: "Повторить" })).not.toBeInTheDocument();
|
||||||
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(
|
expect(
|
||||||
screen.queryByRole("heading", { name: "Моя позиция" }),
|
screen.queryByRole("heading", { name: "Моя позиция" }),
|
||||||
).not.toBeInTheDocument();
|
).not.toBeInTheDocument();
|
||||||
@@ -364,38 +360,12 @@ describe("bond page", () => {
|
|||||||
screen.getByRole("heading", { name: "Моя история событий" }),
|
screen.getByRole("heading", { name: "Моя история событий" }),
|
||||||
).toBeVisible();
|
).toBeVisible();
|
||||||
});
|
});
|
||||||
it("preserves cached quote on refresh failure", async () => {
|
it("preserves cached quote without manual refresh", 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 },
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const controls = setup({ path: `/bonds/${uid}?period=year&events=trades` });
|
const controls = setup({ path: `/bonds/${uid}?period=year&events=trades` });
|
||||||
await screen.findByText("98,125 %");
|
await screen.findByText("98,125 %");
|
||||||
controls.failQuote();
|
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(screen.getByText("98,125 %")).toBeVisible();
|
||||||
expect(scopes).toEqual([
|
expect(screen.queryByRole("button", { name: "Обновить" })).not.toBeInTheDocument();
|
||||||
{
|
|
||||||
accountId: "all",
|
|
||||||
candlePeriod: "year",
|
|
||||||
categories: ["trade"],
|
|
||||||
instrumentUid: uid,
|
|
||||||
limit: 20,
|
|
||||||
screen: "bond",
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
it("offers search for an ambiguous or missing instrument without loading personal data", async () => {
|
it("offers search for an ambiguous or missing instrument without loading personal data", async () => {
|
||||||
const { requests } = setup({ ambiguousTicker: true, path: "/bonds/SAME" });
|
const { requests } = setup({ ambiguousTicker: true, path: "/bonds/SAME" });
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ const BondPage: FC = () => {
|
|||||||
code={vm.code}
|
code={vm.code}
|
||||||
kind="bond"
|
kind="bond"
|
||||||
loading={vm.bondState.loading}
|
loading={vm.bondState.loading}
|
||||||
retry={vm.bondState.retry}
|
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Alert,
|
|
||||||
Badge,
|
Badge,
|
||||||
Group,
|
Group,
|
||||||
Skeleton,
|
Skeleton,
|
||||||
@@ -137,8 +136,6 @@ const BondPageView: FC<BondPageViewProps> = (props) => {
|
|||||||
<InstrumentHeader
|
<InstrumentHeader
|
||||||
logoSrc={vm.logoSrc}
|
logoSrc={vm.logoSrc}
|
||||||
name={bond.name}
|
name={bond.name}
|
||||||
onRefresh={vm.refresh}
|
|
||||||
refreshing={vm.refreshing}
|
|
||||||
subtitle={subtitle}
|
subtitle={subtitle}
|
||||||
>
|
>
|
||||||
|
|
||||||
@@ -156,20 +153,8 @@ const BondPageView: FC<BondPageViewProps> = (props) => {
|
|||||||
)}
|
)}
|
||||||
</Group>
|
</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}
|
{quoteContent}
|
||||||
|
|
||||||
{!!(vm.quoteState.refreshing || vm.bondState.refreshing) && (
|
|
||||||
<Text c="dimmed" role="status" size="xs">
|
|
||||||
{t("accounts.refreshing")}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<InstrumentTerms title={t("bond.terms")}>
|
<InstrumentTerms title={t("bond.terms")}>
|
||||||
|
|
||||||
<InstrumentMetrics>
|
<InstrumentMetrics>
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ function useBondPageVm() {
|
|||||||
|
|
||||||
const { operations } = history;
|
const { operations } = history;
|
||||||
|
|
||||||
const sync = useScreenSync(
|
useScreenSync(
|
||||||
{
|
{
|
||||||
accountId: "all",
|
accountId: "all",
|
||||||
candlePeriod: period,
|
candlePeriod: period,
|
||||||
@@ -56,29 +56,26 @@ function useBondPageVm() {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
bond: bond.data,
|
bond: bond.data,
|
||||||
bondState: section(bond, uid ? sync.retry : () => bond.refetch()),
|
bondState: section(bond),
|
||||||
candles: candles.data,
|
candles: candles.data,
|
||||||
candlesState: section(candles, sync.retry),
|
candlesState: section(candles),
|
||||||
canonicalTo:
|
canonicalTo:
|
||||||
bond.data?.slug && bond.data.slug !== bondId
|
bond.data?.slug && bond.data.slug !== bondId
|
||||||
? `/bonds/${encodeURIComponent(bond.data.slug)}${search}`
|
? `/bonds/${encodeURIComponent(bond.data.slug)}${search}`
|
||||||
: null,
|
: null,
|
||||||
code: apiErrorCode(bond.error),
|
code: apiErrorCode(bond.error),
|
||||||
coupons: coupons.data,
|
coupons: coupons.data,
|
||||||
couponsState: section(coupons, sync.retry),
|
couponsState: section(coupons),
|
||||||
eventRows: toInstrumentEventRows(operations.data?.items, bond.data),
|
eventRows: toInstrumentEventRows(operations.data?.items, bond.data),
|
||||||
filter,
|
filter,
|
||||||
hasPrevious: history.hasPrevious,
|
hasPrevious: history.hasPrevious,
|
||||||
logoSrc: instrumentLogoUrl(bond.data?.logoName),
|
logoSrc: instrumentLogoUrl(bond.data?.logoName),
|
||||||
metrics: metrics.data,
|
metrics: metrics.data,
|
||||||
metricsState: section(metrics, sync.retry),
|
metricsState: section(metrics),
|
||||||
onNext: history.onNext,
|
onNext: history.onNext,
|
||||||
onPrevious: history.onPrevious,
|
onPrevious: history.onPrevious,
|
||||||
operations: operations.data,
|
operations: operations.data,
|
||||||
operationsState: {
|
operationsState: section(operations),
|
||||||
...section(operations, sync.retry),
|
|
||||||
retry: () => history.retry(sync.retry),
|
|
||||||
},
|
|
||||||
pastCoupons:
|
pastCoupons:
|
||||||
coupons.data?.coupons
|
coupons.data?.coupons
|
||||||
.filter(event => event.timing !== "upcoming")
|
.filter(event => event.timing !== "upcoming")
|
||||||
@@ -87,12 +84,9 @@ function useBondPageVm() {
|
|||||||
) ?? [],
|
) ?? [],
|
||||||
period,
|
period,
|
||||||
position: position.data,
|
position: position.data,
|
||||||
positionState: section(position, sync.retry),
|
positionState: section(position),
|
||||||
quote: quote.data,
|
quote: quote.data,
|
||||||
quoteState: section(quote, sync.retry),
|
quoteState: section(quote),
|
||||||
refresh: sync.refresh,
|
|
||||||
refreshError: sync.transportError || sync.sourceError,
|
|
||||||
refreshing: sync.refreshing,
|
|
||||||
setFilter,
|
setFilter,
|
||||||
setPeriod,
|
setPeriod,
|
||||||
upcoming:
|
upcoming:
|
||||||
|
|||||||
@@ -10,12 +10,14 @@ function useBondsPageVm() {
|
|||||||
const search = useInstrumentSearch(MIN_BOND_SEARCH_LENGTH);
|
const search = useInstrumentSearch(MIN_BOND_SEARCH_LENGTH);
|
||||||
const { canSearch, debounced, isWaiting, query } = search;
|
const { canSearch, debounced, isWaiting, query } = search;
|
||||||
const result = useBondSearch(debounced);
|
const result = useBondSearch(debounced);
|
||||||
const sync = useScreenSync({ query: debounced, screen: "bonds" }, [result]);
|
useScreenSync({ query: debounced, screen: "bonds" }, [result]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
canSearch,
|
canSearch,
|
||||||
code: apiErrorCode(result.error),
|
code: apiErrorCode(result.error),
|
||||||
error: result.isError || sync.sourceError || sync.transportError,
|
error:
|
||||||
|
!result.data
|
||||||
|
&& (result.isError || result.meta?.sync.state === "failed"),
|
||||||
items:
|
items:
|
||||||
result.data?.map(bond => ({
|
result.data?.map(bond => ({
|
||||||
...bond,
|
...bond,
|
||||||
@@ -35,10 +37,6 @@ function useBondsPageVm() {
|
|||||||
debounced.length >= MIN_BOND_SEARCH_LENGTH
|
debounced.length >= MIN_BOND_SEARCH_LENGTH
|
||||||
&& !isWaiting
|
&& !isWaiting
|
||||||
&& Boolean(result.data),
|
&& Boolean(result.data),
|
||||||
refreshing: sync.refreshing,
|
|
||||||
retry: () => {
|
|
||||||
void sync.retry();
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -256,21 +256,19 @@ describe("CardPage", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Далее" }));
|
fireEvent.click(screen.getByRole("button", { name: "Далее" }));
|
||||||
await waitFor(() =>
|
await waitFor(() => {
|
||||||
expect(screen.getByRole("button", { name: "Далее" })).toBeDisabled(),
|
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||||
);
|
});
|
||||||
expect(screen.getByText("Перевод на «Запасная»")).toBeInTheDocument();
|
expect(screen.getByText("Перевод на «Запасная»")).toBeInTheDocument();
|
||||||
expect(screen.getByRole("button", { name: "Изменить" })).toBeDisabled();
|
expect(screen.getByRole("button", { name: "Изменить" })).toBeDisabled();
|
||||||
expect(
|
expect(screen.queryByLabelText("Загрузка операций")).not.toBeInTheDocument();
|
||||||
screen.queryByLabelText("Загрузка операций"),
|
|
||||||
).not.toBeInTheDocument();
|
|
||||||
expect(scroll).not.toHaveBeenCalled();
|
expect(scroll).not.toHaveBeenCalled();
|
||||||
measure.mockReturnValue({ top: 200 } as DOMRect);
|
measure.mockReturnValue({ top: 200 } as DOMRect);
|
||||||
release();
|
release();
|
||||||
await screen.findByText(/Новая страница/);
|
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 newPageText = screen.getByText(/Новая страница/);
|
||||||
const list = screen.getByText(/Новая страница/).closest("[aria-busy]");
|
expect(newPageText).toBeInTheDocument();
|
||||||
expect(list?.parentElement?.style.minHeight).toBe("");
|
|
||||||
expect(scroll).toHaveBeenCalledExactlyOnceWith({
|
expect(scroll).toHaveBeenCalledExactlyOnceWith({
|
||||||
behavior: "instant",
|
behavior: "instant",
|
||||||
top: -400,
|
top: -400,
|
||||||
@@ -317,7 +315,9 @@ describe("CardPage", () => {
|
|||||||
it("keeps card and journal when summary fails", async () => {
|
it("keeps card and journal when summary fails", async () => {
|
||||||
setup({ summaryError: true });
|
setup({ summaryError: true });
|
||||||
await screen.findByRole("heading", { name: "Повседневная" });
|
await screen.findByRole("heading", { name: "Повседневная" });
|
||||||
await screen.findByRole("alert");
|
expect(
|
||||||
|
screen.queryByRole("alert"),
|
||||||
|
).not.toBeInTheDocument();
|
||||||
expect(
|
expect(
|
||||||
await screen.findByText("Перевод на «Запасная»"),
|
await screen.findByText("Перевод на «Запасная»"),
|
||||||
).toBeInTheDocument();
|
).toBeInTheDocument();
|
||||||
@@ -331,7 +331,9 @@ describe("CardPage", () => {
|
|||||||
http.get("*/api/v1/bank-cards/a/operations", () => HttpResponse.error()),
|
http.get("*/api/v1/bank-cards/a/operations", () => HttpResponse.error()),
|
||||||
);
|
);
|
||||||
await client.invalidateQueries();
|
await client.invalidateQueries();
|
||||||
await screen.findAllByRole("alert");
|
await waitFor(() => {
|
||||||
|
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
expect(
|
expect(
|
||||||
screen.getByRole("heading", { name: "Повседневная" }),
|
screen.getByRole("heading", { name: "Повседневная" }),
|
||||||
).toBeInTheDocument();
|
).toBeInTheDocument();
|
||||||
@@ -401,9 +403,9 @@ describe("CardPage", () => {
|
|||||||
it("recovers the prerequisite card list while preserving the visible balance and journal", async () => {
|
it("recovers the prerequisite card list while preserving the visible balance and journal", async () => {
|
||||||
setup({ cardsError: true });
|
setup({ cardsError: true });
|
||||||
await screen.findByText("Перевод на «Запасная»");
|
await screen.findByText("Перевод на «Запасная»");
|
||||||
expect(await screen.findByRole("alert")).toHaveTextContent(
|
expect(
|
||||||
"Не удалось загрузить данные карт.",
|
screen.queryByRole("alert"),
|
||||||
);
|
).not.toBeInTheDocument();
|
||||||
expect(
|
expect(
|
||||||
screen.getByRole("button", { name: "Добавить операцию" }),
|
screen.getByRole("button", { name: "Добавить операцию" }),
|
||||||
).toBeDisabled();
|
).toBeDisabled();
|
||||||
@@ -412,11 +414,6 @@ describe("CardPage", () => {
|
|||||||
HttpResponse.json([card, { ...card, id: "b", name: "Запасная" }]),
|
HttpResponse.json([card, { ...card, id: "b", name: "Запасная" }]),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
fireEvent.click(
|
|
||||||
within(screen.getByRole("alert")).getByRole("button", {
|
|
||||||
name: "Повторить",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(
|
expect(
|
||||||
screen.getByRole("button", { name: "Добавить операцию" }),
|
screen.getByRole("button", { name: "Добавить операцию" }),
|
||||||
|
|||||||
@@ -75,7 +75,6 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
|
|||||||
{t("bank.back")}
|
{t("bank.back")}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
{!vm.notFound && <Button onClick={vm.retryCard}>{t("bank.retry")}</Button>}
|
|
||||||
</Group>
|
</Group>
|
||||||
)}
|
)}
|
||||||
error
|
error
|
||||||
@@ -125,27 +124,16 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{!!vm.archiveError && (
|
{!!vm.archiveError && (
|
||||||
<BankFeedback error={vm.archiveError} retry={vm.retryCard} />
|
<BankFeedback error={vm.archiveError} />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{card.archivedAt && <Text>{t("bank.archiveHint")}</Text>}
|
{card.archivedAt && <Text>{t("bank.archiveHint")}</Text>}
|
||||||
</Stack>
|
</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 && (
|
{vm.cardsFeedback && (
|
||||||
<BankFeedback
|
<BankFeedback
|
||||||
{...vm.cardsFeedback}
|
{...vm.cardsFeedback}
|
||||||
loadingError
|
loadingError
|
||||||
retry={vm.retryCards}
|
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -187,7 +175,6 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
|
|||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
<Stack
|
<Stack
|
||||||
aria-busy={vm.history.refreshing}
|
|
||||||
className={classes.operations}
|
className={classes.operations}
|
||||||
data-pending={vm.history.changingPage || undefined}
|
data-pending={vm.history.changingPage || undefined}
|
||||||
gap="lg"
|
gap="lg"
|
||||||
@@ -196,13 +183,7 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
|
|||||||
<CardHistory history={vm.history} period={vm.period} rows={vm.rows} />
|
<CardHistory history={vm.history} period={vm.period} rows={vm.rows} />
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
{vm.history.error && (
|
{vm.history.error && !vm.rows && <Text role="alert">{t("bank.error")}</Text>}
|
||||||
<Group role="alert">
|
|
||||||
<Text>{t(vm.rows ? "bank.refreshError" : "bank.error")}</Text>
|
|
||||||
|
|
||||||
<Button onClick={vm.history.retry}>{t("bank.retry")}</Button>
|
|
||||||
</Group>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{vm.history.page !== undefined && vm.pageSize !== "all" && (
|
{vm.history.page !== undefined && vm.pageSize !== "all" && (
|
||||||
<Group
|
<Group
|
||||||
@@ -213,7 +194,6 @@ const CardPageView: FC<CardPageViewProps> = (props) => {
|
|||||||
ref={paginationRef}
|
ref={paginationRef}
|
||||||
>
|
>
|
||||||
<Pagination
|
<Pagination
|
||||||
disabled={vm.history.refreshing}
|
|
||||||
getControlProps={getControlProps}
|
getControlProps={getControlProps}
|
||||||
getItemProps={getItemProps}
|
getItemProps={getItemProps}
|
||||||
onChange={onPageChange}
|
onChange={onPageChange}
|
||||||
|
|||||||
@@ -115,8 +115,6 @@ function useCardPageVm() {
|
|||||||
error: history.isError,
|
error: history.isError,
|
||||||
loading: history.isLoading,
|
loading: history.isLoading,
|
||||||
page: history.data?.page,
|
page: history.data?.page,
|
||||||
refreshing: history.isFetching,
|
|
||||||
retry: () => void history.refetch(),
|
|
||||||
},
|
},
|
||||||
notFound: isApiErrorCode(
|
notFound: isApiErrorCode(
|
||||||
apiErrorCode(card.error),
|
apiErrorCode(card.error),
|
||||||
@@ -128,8 +126,6 @@ function useCardPageVm() {
|
|||||||
page,
|
page,
|
||||||
pageSize,
|
pageSize,
|
||||||
period,
|
period,
|
||||||
retryCard: () => void card.refetch(),
|
|
||||||
retryCards: () => void cards.refetch(),
|
|
||||||
rows,
|
rows,
|
||||||
setPage: (value: number) =>
|
setPage: (value: number) =>
|
||||||
setParameters({ ...period, limit: pageSize, page: String(value) }),
|
setParameters({ ...period, limit: pageSize, page: String(value) }),
|
||||||
@@ -146,7 +142,6 @@ function useCardPageVm() {
|
|||||||
error: summary.isError,
|
error: summary.isError,
|
||||||
fetching: summary.isFetching,
|
fetching: summary.isFetching,
|
||||||
loading: summary.isLoading,
|
loading: summary.isLoading,
|
||||||
retry: () => void summary.refetch(),
|
|
||||||
},
|
},
|
||||||
toggleArchive: () => {
|
toggleArchive: () => {
|
||||||
if (!card.data) return;
|
if (!card.data) return;
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { notifications } from "@mantine/notifications";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
@@ -44,10 +45,16 @@ function useDeleteOperationVm(props: DeleteOperationProps) {
|
|||||||
setError(undefined);
|
setError(undefined);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
const actionId = crypto.randomUUID();
|
||||||
await operationDeletion.mutateAsync({
|
await operationDeletion.mutateAsync({
|
||||||
id: record.id,
|
id: record.id,
|
||||||
version: record.version,
|
version: record.version,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
notifications.show({
|
||||||
|
id: "bank-operation-deleted-" + actionId,
|
||||||
|
message: t("bank.operationDeleted"),
|
||||||
|
});
|
||||||
setOpened(false);
|
setOpened(false);
|
||||||
}
|
}
|
||||||
catch (error_) {
|
catch (error_) {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { notifications } from "@mantine/notifications";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useForm, useWatch } from "react-hook-form";
|
import { useForm, useWatch } from "react-hook-form";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
@@ -112,6 +113,8 @@ const useOperationFormVm = (props: OperationFormProps) => {
|
|||||||
description: values.description,
|
description: values.description,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const actionId = crypto.randomUUID();
|
||||||
|
|
||||||
if (props.operation)
|
if (props.operation)
|
||||||
await updateOperation.mutateAsync({
|
await updateOperation.mutateAsync({
|
||||||
body: { ...body, version },
|
body: { ...body, version },
|
||||||
@@ -122,6 +125,11 @@ const useOperationFormVm = (props: OperationFormProps) => {
|
|||||||
id: intent,
|
id: intent,
|
||||||
...body,
|
...body,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
notifications.show({
|
||||||
|
id: "bank-operation-saved-" + actionId,
|
||||||
|
message: t("bank.operationSaved"),
|
||||||
|
});
|
||||||
setOpened(false);
|
setOpened(false);
|
||||||
}
|
}
|
||||||
catch (error_) {
|
catch (error_) {
|
||||||
|
|||||||
@@ -198,26 +198,26 @@ describe("CardsPage", () => {
|
|||||||
it("shows retry after failure instead of presenting an empty list", async () => {
|
it("shows retry after failure instead of presenting an empty list", async () => {
|
||||||
renderCards(true);
|
renderCards(true);
|
||||||
// Mount starts asynchronously; this handler owns the request.
|
// Mount starts asynchronously; this handler owns the request.
|
||||||
expect(await screen.findByRole("alert")).toHaveTextContent(
|
expect(
|
||||||
"Не удалось загрузить данные карт.",
|
screen.queryByRole("alert"),
|
||||||
);
|
).not.toBeInTheDocument();
|
||||||
expect(
|
expect(
|
||||||
screen.queryByRole("heading", { name: "Добавьте первую карту" }),
|
screen.queryByRole("heading", { name: "Добавьте первую карту" }),
|
||||||
).not.toBeInTheDocument();
|
).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||||
server.use(http.get("*/api/v1/bank-cards", () => HttpResponse.json([])));
|
server.use(http.get("*/api/v1/bank-cards", () => HttpResponse.json([])));
|
||||||
fireEvent.click(
|
await waitFor(() => {
|
||||||
within(screen.getByRole("alert")).getByRole("button", {
|
expect(
|
||||||
name: "Повторить",
|
screen.queryByRole("alert"),
|
||||||
}),
|
).not.toBeInTheDocument();
|
||||||
);
|
});
|
||||||
await screen.findByRole("heading", { name: "Добавьте первую карту" });
|
|
||||||
});
|
});
|
||||||
it("makes failed category loading recoverable without hiding successful cards data", async () => {
|
it("makes failed category loading recoverable without hiding successful cards data", async () => {
|
||||||
renderCards(false, true);
|
renderCards(false, true);
|
||||||
await screen.findByRole("heading", { name: "Добавьте первую карту" });
|
await screen.findByRole("heading", { name: "Добавьте первую карту" });
|
||||||
expect(await screen.findByRole("alert")).toHaveTextContent(
|
expect(
|
||||||
"Не удалось загрузить данные карт.",
|
screen.queryByRole("alert"),
|
||||||
);
|
).not.toBeInTheDocument();
|
||||||
server.use(
|
server.use(
|
||||||
http.get("*/api/v1/bank-cards/categories", () =>
|
http.get("*/api/v1/bank-cards/categories", () =>
|
||||||
HttpResponse.json([
|
HttpResponse.json([
|
||||||
@@ -225,12 +225,11 @@ describe("CardsPage", () => {
|
|||||||
]),
|
]),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
fireEvent.click(
|
await waitFor(() => {
|
||||||
within(screen.getByRole("alert")).getByRole("button", {
|
expect(
|
||||||
name: "Повторить",
|
screen.getByRole("button", { name: "Категории" }),
|
||||||
}),
|
).toBeInTheDocument();
|
||||||
);
|
});
|
||||||
await screen.findByRole("button", { name: "Категории" });
|
|
||||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import {
|
|||||||
Skeleton,
|
Skeleton,
|
||||||
Stack,
|
Stack,
|
||||||
Switch,
|
Switch,
|
||||||
Text,
|
|
||||||
Title,
|
Title,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
import { AddIcon, CategoriesIcon } from "@wealthledger/icons";
|
import { AddIcon, CategoriesIcon } from "@wealthledger/icons";
|
||||||
@@ -19,7 +18,6 @@ import { Link } from "react-router";
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
BankCardFace,
|
BankCardFace,
|
||||||
BankFeedback,
|
|
||||||
BankPeriodPicker,
|
BankPeriodPicker,
|
||||||
BankSummaryView,
|
BankSummaryView,
|
||||||
} from "@/entities/bank-card";
|
} from "@/entities/bank-card";
|
||||||
@@ -107,18 +105,6 @@ const CardsPageView: FC<CardsPageViewProps> = (props) => {
|
|||||||
|
|
||||||
<CardsPageViewCards {...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">
|
<Group align="flex-end" justify="space-between">
|
||||||
<BankPeriodPicker onChange={vm.setPeriod} period={vm.period} />
|
<BankPeriodPicker onChange={vm.setPeriod} period={vm.period} />
|
||||||
|
|
||||||
@@ -140,17 +126,7 @@ const CardsPageView: FC<CardsPageViewProps> = (props) => {
|
|||||||
error={vm.summary.isError}
|
error={vm.summary.isError}
|
||||||
fetching={vm.summary.isFetching}
|
fetching={vm.summary.isFetching}
|
||||||
loading={vm.summary.isLoading}
|
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>
|
</Stack>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -39,9 +39,6 @@ function useCardsPageVm() {
|
|||||||
setArchive(event.currentTarget.checked),
|
setArchive(event.currentTarget.checked),
|
||||||
onCategories: () => setManagingCategories(true),
|
onCategories: () => setManagingCategories(true),
|
||||||
period,
|
period,
|
||||||
retryCards: () => void cards.refetch(),
|
|
||||||
retryCategories: () => void categories.refetch(),
|
|
||||||
retrySummary: () => void summary.refetch(),
|
|
||||||
setPeriod: (value: [null | string, null | string]) => {
|
setPeriod: (value: [null | string, null | string]) => {
|
||||||
if (value[0] && value[1]) setParameters({ from: value[0], to: value[1] });
|
if (value[0] && value[1]) setParameters({ from: value[0], to: value[1] });
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -396,37 +396,15 @@ describe("stock page", () => {
|
|||||||
screen.queryByRole("heading", { name: "Моя позиция" }),
|
screen.queryByRole("heading", { name: "Моя позиция" }),
|
||||||
).not.toBeInTheDocument();
|
).not.toBeInTheDocument();
|
||||||
expect(screen.getByRole("heading", { name: "График цены" })).toBeVisible();
|
expect(screen.getByRole("heading", { name: "График цены" })).toBeVisible();
|
||||||
const message = await screen.findByText(/Не удалось загрузить этот раздел/);
|
expect(screen.queryByRole("button", { name: "Повторить" })).not.toBeInTheDocument();
|
||||||
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");
|
|
||||||
});
|
});
|
||||||
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 { requests } = setup({ failCompany: true });
|
||||||
const retry = await screen.findByRole("button", { name: "Повторить" });
|
|
||||||
await screen.findByText("Зачисление дивидендов");
|
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;
|
const previousRequests = requests.length;
|
||||||
fireEvent.click(retry);
|
|
||||||
expect(await screen.findByText("Восстановленное описание")).toBeVisible();
|
|
||||||
expect(screen.getByText("Зачисление дивидендов")).toBeVisible();
|
expect(screen.getByText("Зачисление дивидендов")).toBeVisible();
|
||||||
expect(requests).toHaveLength(previousRequests);
|
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 () => {
|
it("sends instrument-filtered continuation, restores it on returning to the filter and changes chart period", async () => {
|
||||||
const { requests } = setup();
|
const { requests } = setup();
|
||||||
@@ -469,75 +447,28 @@ describe("stock page", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
it.each([
|
it.each([
|
||||||
[
|
"INVALID_OPERATIONS_CURSOR",
|
||||||
"INVALID_OPERATIONS_CURSOR",
|
"TBANK_UNAVAILABLE",
|
||||||
null,
|
|
||||||
null,
|
|
||||||
],
|
|
||||||
["TBANK_UNAVAILABLE", "next", "observe"],
|
|
||||||
])(
|
])(
|
||||||
"recovers history after %s with fresh data and the correct cursor",
|
"keeps history quiet after %s without technical retry",
|
||||||
async (code, cursor, sync) => {
|
async (code) => {
|
||||||
const controls = setup({ cursorError: code });
|
const controls = setup({ cursorError: code });
|
||||||
await screen.findByText("Зачисление дивидендов");
|
await screen.findByText("Зачисление дивидендов");
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Далее" }));
|
fireEvent.click(screen.getByRole("button", { name: "Далее" }));
|
||||||
const retry = await screen.findByRole("button", { name: "Повторить" });
|
|
||||||
controls.recoverOperations();
|
controls.recoverOperations();
|
||||||
const previousRequests = controls.requests.length;
|
expect(screen.queryByRole("button", { name: "Повторить" })).not.toBeInTheDocument();
|
||||||
fireEvent.click(retry);
|
expect(screen.getByRole("heading", { name: "Моя история событий" })).toBeVisible();
|
||||||
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();
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
it("keeps the last quote on a refresh failure", async () => {
|
it("keeps the last quote without manual refresh", 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 },
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const controls = setup({
|
const controls = setup({
|
||||||
path: `/stocks/${uid}?period=year&events=trades`,
|
path: `/stocks/${uid}?period=year&events=trades`,
|
||||||
});
|
});
|
||||||
|
|
||||||
await screen.findByText("300 ₽");
|
await screen.findByText("300 ₽");
|
||||||
controls.failQuote();
|
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(screen.getByText("300 ₽")).toBeVisible();
|
||||||
expect(scopes).toEqual([
|
expect(screen.queryByRole("button", { name: "Обновить" })).not.toBeInTheDocument();
|
||||||
{
|
|
||||||
accountId: "all",
|
|
||||||
candlePeriod: "year",
|
|
||||||
categories: ["trade"],
|
|
||||||
instrumentUid: uid,
|
|
||||||
limit: 20,
|
|
||||||
screen: "stock",
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
it("offers recovery for an unavailable direct link", async () => {
|
it("offers recovery for an unavailable direct link", async () => {
|
||||||
setup({ failStock: true });
|
setup({ failStock: true });
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ const StockPage: FC = () => {
|
|||||||
code={vm.code}
|
code={vm.code}
|
||||||
kind="stock"
|
kind="stock"
|
||||||
loading={vm.stockState.loading}
|
loading={vm.stockState.loading}
|
||||||
retry={vm.stockState.retry}
|
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
|
|
||||||
import {
|
import { Text } from "@mantine/core";
|
||||||
Alert,
|
|
||||||
Text,
|
|
||||||
} from "@mantine/core";
|
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -42,8 +39,6 @@ const StockPageView: FC<StockPageViewProps> = (props) => {
|
|||||||
<InstrumentHeader
|
<InstrumentHeader
|
||||||
logoSrc={vm.logoSrc}
|
logoSrc={vm.logoSrc}
|
||||||
name={stock.name}
|
name={stock.name}
|
||||||
onRefresh={vm.refresh}
|
|
||||||
refreshing={vm.refreshing}
|
|
||||||
subtitle={subtitle}
|
subtitle={subtitle}
|
||||||
>
|
>
|
||||||
|
|
||||||
@@ -53,12 +48,6 @@ const StockPageView: FC<StockPageViewProps> = (props) => {
|
|||||||
</Text>
|
</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} />
|
<StockQuote quote={vm.quote} quoteState={vm.quoteState} />
|
||||||
|
|
||||||
<StockCompany
|
<StockCompany
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ function useStockPageVm() {
|
|||||||
|
|
||||||
const { operations } = history;
|
const { operations } = history;
|
||||||
|
|
||||||
const sync = useScreenSync(
|
useScreenSync(
|
||||||
{
|
{
|
||||||
accountId: "all",
|
accountId: "all",
|
||||||
candlePeriod: period,
|
candlePeriod: period,
|
||||||
@@ -56,16 +56,16 @@ function useStockPageVm() {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
candles: candles.data,
|
candles: candles.data,
|
||||||
candlesState: section(candles, sync.retry),
|
candlesState: section(candles),
|
||||||
canonicalTo:
|
canonicalTo:
|
||||||
stock.data?.slug && stock.data.slug !== stockId
|
stock.data?.slug && stock.data.slug !== stockId
|
||||||
? `/stocks/${encodeURIComponent(stock.data.slug)}${search}`
|
? `/stocks/${encodeURIComponent(stock.data.slug)}${search}`
|
||||||
: null,
|
: null,
|
||||||
code: apiErrorCode(stock.error),
|
code: apiErrorCode(stock.error),
|
||||||
company: company.data,
|
company: company.data,
|
||||||
companyState: section(company, sync.retry),
|
companyState: section(company),
|
||||||
dividends: dividends.data,
|
dividends: dividends.data,
|
||||||
dividendsState: section(dividends, sync.retry),
|
dividendsState: section(dividends),
|
||||||
eventRows: toInstrumentEventRows(operations.data?.items, stock.data),
|
eventRows: toInstrumentEventRows(operations.data?.items, stock.data),
|
||||||
filter,
|
filter,
|
||||||
hasPrevious: history.hasPrevious,
|
hasPrevious: history.hasPrevious,
|
||||||
@@ -73,10 +73,7 @@ function useStockPageVm() {
|
|||||||
onNext: history.onNext,
|
onNext: history.onNext,
|
||||||
onPrevious: history.onPrevious,
|
onPrevious: history.onPrevious,
|
||||||
operations: operations.data,
|
operations: operations.data,
|
||||||
operationsState: {
|
operationsState: section(operations),
|
||||||
...section(operations, sync.retry),
|
|
||||||
retry: () => history.retry(sync.retry),
|
|
||||||
},
|
|
||||||
pastDividends:
|
pastDividends:
|
||||||
dividends.data?.dividends
|
dividends.data?.dividends
|
||||||
.filter(event => event.timing !== "upcoming")
|
.filter(event => event.timing !== "upcoming")
|
||||||
@@ -85,16 +82,13 @@ function useStockPageVm() {
|
|||||||
) ?? [],
|
) ?? [],
|
||||||
period,
|
period,
|
||||||
position: position.data,
|
position: position.data,
|
||||||
positionState: section(position, sync.retry),
|
positionState: section(position),
|
||||||
quote: quote.data,
|
quote: quote.data,
|
||||||
quoteState: section(quote, sync.retry),
|
quoteState: section(quote),
|
||||||
refresh: sync.refresh,
|
|
||||||
refreshError: sync.transportError || sync.sourceError,
|
|
||||||
refreshing: sync.refreshing,
|
|
||||||
setFilter,
|
setFilter,
|
||||||
setPeriod,
|
setPeriod,
|
||||||
stock: stock.data,
|
stock: stock.data,
|
||||||
stockState: section(stock, uid ? sync.retry : () => stock.refetch()),
|
stockState: section(stock),
|
||||||
upcoming:
|
upcoming:
|
||||||
dividends.data?.dividends
|
dividends.data?.dividends
|
||||||
.filter(event => event.timing === "upcoming")
|
.filter(event => event.timing === "upcoming")
|
||||||
|
|||||||
@@ -1,12 +1,6 @@
|
|||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
|
|
||||||
import {
|
import { Alert, Group, Stack, Text } from "@mantine/core";
|
||||||
Alert,
|
|
||||||
Button,
|
|
||||||
Group,
|
|
||||||
Stack,
|
|
||||||
Text,
|
|
||||||
} from "@mantine/core";
|
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -80,17 +74,7 @@ const StockCompany: FC<StockCompanyProps> = (props) => {
|
|||||||
<Stack gap="lg">
|
<Stack gap="lg">
|
||||||
{props.company.unavailable.length > 0 && (
|
{props.company.unavailable.length > 0 && (
|
||||||
<Alert aria-live="polite" color="orange" role="status">
|
<Alert aria-live="polite" color="orange" role="status">
|
||||||
<Group justify="space-between">
|
<Text size="sm">{t("stock.partialCompany")}</Text>
|
||||||
<Text size="sm">{t("stock.partialCompany")}</Text>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
onClick={props.companyState.retry}
|
|
||||||
size="xs"
|
|
||||||
variant="default"
|
|
||||||
>
|
|
||||||
{t("accounts.retry")}
|
|
||||||
</Button>
|
|
||||||
</Group>
|
|
||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -82,12 +82,6 @@ const StockQuote: FC<StockQuoteProps> = (props) => {
|
|||||||
{t("stock.partialQuote")}
|
{t("stock.partialQuote")}
|
||||||
</Text>
|
</Text>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!!props.quoteState.refreshing && (
|
|
||||||
<Text c="dimmed" role="status" size="xs">
|
|
||||||
{t("accounts.refreshing")}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,12 +10,14 @@ function useStocksPageVm() {
|
|||||||
const search = useInstrumentSearch(MIN_STOCK_SEARCH_LENGTH);
|
const search = useInstrumentSearch(MIN_STOCK_SEARCH_LENGTH);
|
||||||
const { canSearch, debounced, isWaiting, query } = search;
|
const { canSearch, debounced, isWaiting, query } = search;
|
||||||
const result = useStockSearch(debounced);
|
const result = useStockSearch(debounced);
|
||||||
const sync = useScreenSync({ query: debounced, screen: "stocks" }, [result]);
|
useScreenSync({ query: debounced, screen: "stocks" }, [result]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
canSearch,
|
canSearch,
|
||||||
code: apiErrorCode(result.error),
|
code: apiErrorCode(result.error),
|
||||||
error: result.isError || sync.sourceError || sync.transportError,
|
error:
|
||||||
|
!result.data
|
||||||
|
&& (result.isError || result.meta?.sync.state === "failed"),
|
||||||
items:
|
items:
|
||||||
result.data?.map(stock => ({
|
result.data?.map(stock => ({
|
||||||
...stock,
|
...stock,
|
||||||
@@ -35,10 +37,6 @@ function useStocksPageVm() {
|
|||||||
debounced.length >= MIN_STOCK_SEARCH_LENGTH
|
debounced.length >= MIN_STOCK_SEARCH_LENGTH
|
||||||
&& !isWaiting
|
&& !isWaiting
|
||||||
&& Boolean(result.data),
|
&& Boolean(result.data),
|
||||||
refreshing: sync.refreshing,
|
|
||||||
retry: () => {
|
|
||||||
void sync.retry();
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,26 @@
|
|||||||
import { http, HttpResponse } from "msw";
|
import { http, HttpResponse } from "msw";
|
||||||
import { describe, expect, it, vi } from "vitest";
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
import { resource } from "@/test/resource";
|
import { resource } from "@/test/resource";
|
||||||
import { server } from "@/test/server";
|
import { server } from "@/test/server";
|
||||||
|
|
||||||
import { apiClient, configureAuthClient } from "./client";
|
import { apiClient, configureAuthClient } from "./client";
|
||||||
|
|
||||||
|
async function advanceReadDeadlineRecovery() {
|
||||||
|
await vi.advanceTimersByTimeAsync(15_000);
|
||||||
|
await vi.advanceTimersByTimeAsync(1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function advanceTransportRecovery() {
|
||||||
|
await vi.advanceTimersByTimeAsync(1000);
|
||||||
|
await vi.advanceTimersByTimeAsync(2000);
|
||||||
|
}
|
||||||
|
|
||||||
describe("apiClient authentication", () => {
|
describe("apiClient authentication", () => {
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
it("refreshes once and retries an unauthorized protected request", async () => {
|
it("refreshes once and retries an unauthorized protected request", async () => {
|
||||||
let token = "expired";
|
let token = "expired";
|
||||||
|
|
||||||
@@ -109,3 +123,186 @@ describe("apiClient authentication", () => {
|
|||||||
await response;
|
await response;
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("apiClient transient read recovery", () => {
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("recovers a protected GET after transient server failures", async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
let requests = 0;
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/brokerage-accounts", () => {
|
||||||
|
requests += 1;
|
||||||
|
|
||||||
|
return requests < 3
|
||||||
|
? HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 })
|
||||||
|
: HttpResponse.json(resource([{ id: "account-1" }]));
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
configureAuthClient({
|
||||||
|
accessToken: () => "token",
|
||||||
|
clear: vi.fn(),
|
||||||
|
refresh: () => Promise.resolve(true),
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = apiClient.GET("/api/v1/brokerage-accounts");
|
||||||
|
await advanceTransportRecovery();
|
||||||
|
|
||||||
|
await expect(response).resolves.toMatchObject({
|
||||||
|
data: { data: [{ id: "account-1" }] },
|
||||||
|
});
|
||||||
|
expect(requests).toBe(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("recovers a protected GET after network failure", async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
let requests = 0;
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/brokerage-accounts", () => {
|
||||||
|
requests += 1;
|
||||||
|
|
||||||
|
return requests === 1
|
||||||
|
? HttpResponse.error()
|
||||||
|
: HttpResponse.json(resource([{ id: "account-1" }]));
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
configureAuthClient({
|
||||||
|
accessToken: () => "token",
|
||||||
|
clear: vi.fn(),
|
||||||
|
refresh: () => Promise.resolve(true),
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = apiClient.GET("/api/v1/brokerage-accounts");
|
||||||
|
await advanceTransportRecovery();
|
||||||
|
|
||||||
|
await expect(response).resolves.toMatchObject({
|
||||||
|
data: { data: [{ id: "account-1" }] },
|
||||||
|
});
|
||||||
|
expect(requests).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("times out a stalled response body before retrying", async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
let requests = 0;
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/brokerage-accounts", () => {
|
||||||
|
requests += 1;
|
||||||
|
|
||||||
|
return requests === 1
|
||||||
|
? new Response(new ReadableStream())
|
||||||
|
: HttpResponse.json(resource([{ id: "account-1" }]));
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
configureAuthClient({
|
||||||
|
accessToken: () => "token",
|
||||||
|
clear: vi.fn(),
|
||||||
|
refresh: () => Promise.resolve(true),
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = apiClient.GET("/api/v1/brokerage-accounts");
|
||||||
|
await advanceReadDeadlineRecovery();
|
||||||
|
|
||||||
|
await expect(response).resolves.toMatchObject({
|
||||||
|
data: { data: [{ id: "account-1" }] },
|
||||||
|
});
|
||||||
|
expect(requests).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not retry rate limited reads before the server delay", async () => {
|
||||||
|
let requests = 0;
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/brokerage-accounts", () => {
|
||||||
|
requests += 1;
|
||||||
|
|
||||||
|
return HttpResponse.json(
|
||||||
|
{ code: "RATE_LIMITED" },
|
||||||
|
{ headers: { "Retry-After": "60" }, status: 429 },
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
configureAuthClient({
|
||||||
|
accessToken: () => "token",
|
||||||
|
clear: vi.fn(),
|
||||||
|
refresh: () => Promise.resolve(true),
|
||||||
|
});
|
||||||
|
|
||||||
|
await apiClient.GET("/api/v1/brokerage-accounts");
|
||||||
|
|
||||||
|
expect(requests).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not retry malformed successful responses as transport failures", async () => {
|
||||||
|
let requests = 0;
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/brokerage-accounts", () => {
|
||||||
|
requests += 1;
|
||||||
|
|
||||||
|
return new Response("not json", {
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
status: 200,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
configureAuthClient({
|
||||||
|
accessToken: () => "token",
|
||||||
|
clear: vi.fn(),
|
||||||
|
refresh: () => Promise.resolve(true),
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
apiClient.GET("/api/v1/brokerage-accounts"),
|
||||||
|
).rejects.toThrow(SyntaxError);
|
||||||
|
|
||||||
|
expect(requests).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([401, 403, 404, 409])(
|
||||||
|
"does not retry permanent HTTP %s responses",
|
||||||
|
async (status) => {
|
||||||
|
let requests = 0;
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/brokerage-accounts", () => {
|
||||||
|
requests += 1;
|
||||||
|
|
||||||
|
return HttpResponse.json({ code: "FORBIDDEN" }, { status });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
configureAuthClient({
|
||||||
|
accessToken: () => "token",
|
||||||
|
clear: vi.fn(),
|
||||||
|
refresh: () => Promise.resolve(false),
|
||||||
|
});
|
||||||
|
|
||||||
|
await apiClient.GET("/api/v1/brokerage-accounts");
|
||||||
|
|
||||||
|
expect(requests).toBe(1);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it("does not retry mutations", async () => {
|
||||||
|
let requests = 0;
|
||||||
|
server.use(
|
||||||
|
http.put("*/api/v1/tbank-connection", () => {
|
||||||
|
requests += 1;
|
||||||
|
|
||||||
|
return HttpResponse.json(
|
||||||
|
{ code: "TBANK_UNAVAILABLE" },
|
||||||
|
{ status: 503 },
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
configureAuthClient({
|
||||||
|
accessToken: () => "token",
|
||||||
|
clear: vi.fn(),
|
||||||
|
refresh: () => Promise.resolve(true),
|
||||||
|
});
|
||||||
|
|
||||||
|
await apiClient.PUT("/api/v1/tbank-connection", {
|
||||||
|
body: { token: "token" },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(requests).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
+169
-2
@@ -6,6 +6,17 @@ import type { paths } from "./generated/schema";
|
|||||||
import { ApiErrorCode, apiErrorCode, isApiErrorCode } from "./problem-details";
|
import { ApiErrorCode, apiErrorCode, isApiErrorCode } from "./problem-details";
|
||||||
|
|
||||||
const HTTP_UNAUTHORIZED = 401;
|
const HTTP_UNAUTHORIZED = 401;
|
||||||
|
const HTTP_REQUEST_TIMEOUT = 408;
|
||||||
|
const HTTP_TOO_MANY_REQUESTS = 429;
|
||||||
|
const HTTP_INTERNAL_SERVER_ERROR = 500;
|
||||||
|
const HTTP_BAD_GATEWAY = 502;
|
||||||
|
const HTTP_SERVICE_UNAVAILABLE = 503;
|
||||||
|
const HTTP_GATEWAY_TIMEOUT = 504;
|
||||||
|
const GET_DEADLINE_MS = 15_000;
|
||||||
|
const FIRST_RETRY_DELAY_MS = 1000;
|
||||||
|
const SECOND_RETRY_DELAY_MS = 2000;
|
||||||
|
const RETRY_DELAYS_MS = [FIRST_RETRY_DELAY_MS, SECOND_RETRY_DELAY_MS] as const;
|
||||||
|
const SECONDS_TO_MS = 1000;
|
||||||
|
|
||||||
const configuredBaseUrl: unknown = import.meta.env.VITE_API_BASE_URL;
|
const configuredBaseUrl: unknown = import.meta.env.VITE_API_BASE_URL;
|
||||||
|
|
||||||
@@ -23,12 +34,22 @@ type AuthHandlers = {
|
|||||||
refresh: () => Promise<boolean>;
|
refresh: () => Promise<boolean>;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type ReadAttempt = {
|
||||||
|
problem?: unknown;
|
||||||
|
reason: "abort" | "transient";
|
||||||
|
response?: Response;
|
||||||
|
};
|
||||||
|
|
||||||
const sessionState: { handlers?: AuthHandlers; hasSession: boolean } = {
|
const sessionState: { handlers?: AuthHandlers; hasSession: boolean } = {
|
||||||
hasSession: false,
|
hasSession: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
const authSessionListeners = new Set<() => void>();
|
const authSessionListeners = new Set<() => void>();
|
||||||
|
|
||||||
|
function abortError() {
|
||||||
|
return new DOMException("Request aborted", "AbortError");
|
||||||
|
}
|
||||||
|
|
||||||
async function authenticatedFetch(request: Request): Promise<Response> {
|
async function authenticatedFetch(request: Request): Promise<Response> {
|
||||||
const isAuthRequest = new URL(request.url).pathname.startsWith(
|
const isAuthRequest = new URL(request.url).pathname.startsWith(
|
||||||
"/api/v1/auth/",
|
"/api/v1/auth/",
|
||||||
@@ -56,7 +77,7 @@ async function authenticatedFetch(request: Request): Promise<Response> {
|
|||||||
= token && !isAuthRequest ? withToken(request, token) : request;
|
= token && !isAuthRequest ? withToken(request, token) : request;
|
||||||
|
|
||||||
const retryRequest = authorized.clone();
|
const retryRequest = authorized.clone();
|
||||||
const response = await fetch(authorized);
|
const response = await fetchAppRead(authorized, isAuthRequest);
|
||||||
if (!isAuthRequest && !isCurrent())
|
if (!isAuthRequest && !isCurrent())
|
||||||
throw new DOMException("Session changed", "AbortError");
|
throw new DOMException("Session changed", "AbortError");
|
||||||
if (
|
if (
|
||||||
@@ -87,7 +108,12 @@ async function authenticatedFetch(request: Request): Promise<Response> {
|
|||||||
if (!isCurrent()) throw new DOMException("Session changed", "AbortError");
|
if (!isCurrent()) throw new DOMException("Session changed", "AbortError");
|
||||||
const refreshedToken = sessionState.handlers.accessToken();
|
const refreshedToken = sessionState.handlers.accessToken();
|
||||||
if (!refreshedToken) return response;
|
if (!refreshedToken) return response;
|
||||||
const retried = await fetch(withToken(retryRequest, refreshedToken));
|
|
||||||
|
const retried = await fetchAppRead(
|
||||||
|
withToken(retryRequest, refreshedToken),
|
||||||
|
isAuthRequest,
|
||||||
|
);
|
||||||
|
|
||||||
if (!isCurrent()) throw new DOMException("Session changed", "AbortError");
|
if (!isCurrent()) throw new DOMException("Session changed", "AbortError");
|
||||||
|
|
||||||
return retried;
|
return retried;
|
||||||
@@ -98,10 +124,138 @@ function configureAuthClient(handlers?: AuthHandlers) {
|
|||||||
setAuthenticatedSession(Boolean(sessionState.handlers?.accessToken()));
|
setAuthenticatedSession(Boolean(sessionState.handlers?.accessToken()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function fetchAppRead(
|
||||||
|
request: Request,
|
||||||
|
isAuthRequest: boolean,
|
||||||
|
): Promise<Response> {
|
||||||
|
if (isAuthRequest || request.method !== "GET") return fetch(request);
|
||||||
|
|
||||||
|
const retryableRequest = request.clone();
|
||||||
|
|
||||||
|
for (const [retryIndex, delayMs] of RETRY_DELAYS_MS.entries()) {
|
||||||
|
const attempt = await readAttempt(
|
||||||
|
retryIndex === 0 ? request : retryableRequest.clone(),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (attempt.reason === "abort") throw abortError();
|
||||||
|
const response = attempt.response;
|
||||||
|
if (response && !isTransientReadFailure(response, attempt.problem))
|
||||||
|
return response;
|
||||||
|
await waitForRetry(delayMs, request.signal);
|
||||||
|
}
|
||||||
|
|
||||||
|
const finalAttempt = await readAttempt(retryableRequest.clone());
|
||||||
|
if (finalAttempt.reason === "abort") throw abortError();
|
||||||
|
if (!finalAttempt.response) throw new TypeError("Network request failed");
|
||||||
|
|
||||||
|
return finalAttempt.response;
|
||||||
|
}
|
||||||
|
|
||||||
function hasAuthenticatedSession() {
|
function hasAuthenticatedSession() {
|
||||||
return sessionState.hasSession;
|
return sessionState.hasSession;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isNetworkFailure(error: unknown): boolean {
|
||||||
|
return error instanceof TypeError;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isPermanentCode(code?: string): boolean {
|
||||||
|
return [
|
||||||
|
ApiErrorCode.Forbidden,
|
||||||
|
ApiErrorCode.InvalidTbankToken,
|
||||||
|
ApiErrorCode.NotFound,
|
||||||
|
ApiErrorCode.TbankNotConnected,
|
||||||
|
ApiErrorCode.Unauthorized,
|
||||||
|
].some(permanent => isApiErrorCode(code, permanent));
|
||||||
|
}
|
||||||
|
|
||||||
|
function isTransientReadFailure(
|
||||||
|
response: Response | undefined,
|
||||||
|
problem: unknown,
|
||||||
|
): boolean {
|
||||||
|
if (!response) return true;
|
||||||
|
const code = apiErrorCode(problem);
|
||||||
|
if (isApiErrorCode(code, ApiErrorCode.TbankUnavailable)) return true;
|
||||||
|
if (isPermanentCode(code)) return false;
|
||||||
|
|
||||||
|
const transientStatuses = [
|
||||||
|
HTTP_BAD_GATEWAY,
|
||||||
|
HTTP_GATEWAY_TIMEOUT,
|
||||||
|
HTTP_INTERNAL_SERVER_ERROR,
|
||||||
|
HTTP_REQUEST_TIMEOUT,
|
||||||
|
HTTP_SERVICE_UNAVAILABLE,
|
||||||
|
];
|
||||||
|
|
||||||
|
return transientStatuses.includes(response.status)
|
||||||
|
|| (
|
||||||
|
response.status === HTTP_TOO_MANY_REQUESTS
|
||||||
|
&& retryAfterMs(response) === 0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseJson(body: string): unknown {
|
||||||
|
try {
|
||||||
|
return JSON.parse(body);
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readAttempt(request: Request): Promise<ReadAttempt> {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const failure: { reason?: "abort" | "timeout" } = {};
|
||||||
|
|
||||||
|
const { promise: deadline, reject: rejectDeadline }
|
||||||
|
= Promise.withResolvers<never>();
|
||||||
|
|
||||||
|
const timeout = setTimeout(() => {
|
||||||
|
failure.reason = "timeout";
|
||||||
|
controller.abort();
|
||||||
|
rejectDeadline(abortError());
|
||||||
|
}, GET_DEADLINE_MS);
|
||||||
|
|
||||||
|
const abort = () => {
|
||||||
|
failure.reason = "abort";
|
||||||
|
controller.abort();
|
||||||
|
rejectDeadline(abortError());
|
||||||
|
};
|
||||||
|
|
||||||
|
request.signal.addEventListener("abort", abort, { once: true });
|
||||||
|
const timedRequest = new Request(request, { signal: controller.signal });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await Promise.race([fetch(timedRequest), deadline]);
|
||||||
|
const body = await Promise.race([response.text(), deadline]);
|
||||||
|
const problem = parseJson(body);
|
||||||
|
|
||||||
|
return {
|
||||||
|
problem,
|
||||||
|
reason: "transient",
|
||||||
|
response: new Response(body, response),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
if (failure.reason === "abort") return { reason: "abort" };
|
||||||
|
if (failure.reason === "timeout" || isNetworkFailure(error))
|
||||||
|
return { reason: "transient" };
|
||||||
|
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
request.signal.removeEventListener("abort", abort);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function retryAfterMs(response: Response): number | undefined {
|
||||||
|
const header = response.headers.get("Retry-After");
|
||||||
|
if (!header) return undefined;
|
||||||
|
const seconds = Number(header);
|
||||||
|
|
||||||
|
return Number.isFinite(seconds) ? seconds * SECONDS_TO_MS : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
function setAuthenticatedSession(hasSession: boolean) {
|
function setAuthenticatedSession(hasSession: boolean) {
|
||||||
if (hasSession === sessionState.hasSession) return;
|
if (hasSession === sessionState.hasSession) return;
|
||||||
sessionState.hasSession = hasSession;
|
sessionState.hasSession = hasSession;
|
||||||
@@ -114,6 +268,19 @@ function subscribeAuthenticatedSession(listener: () => void) {
|
|||||||
return () => authSessionListeners.delete(listener);
|
return () => authSessionListeners.delete(listener);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function waitForRetry(ms: number, signal: AbortSignal): Promise<void> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const timeout = setTimeout(resolve, ms);
|
||||||
|
|
||||||
|
const abort = () => {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
reject(abortError());
|
||||||
|
};
|
||||||
|
|
||||||
|
signal.addEventListener("abort", abort, { once: true });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const apiClient = createClient<paths>({
|
const apiClient = createClient<paths>({
|
||||||
baseUrl: apiBaseUrl,
|
baseUrl: apiBaseUrl,
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
|
|||||||
@@ -76,9 +76,11 @@ const ru = {
|
|||||||
bankName: "Банк (необязательно)",
|
bankName: "Банк (необязательно)",
|
||||||
cancel: "Отмена",
|
cancel: "Отмена",
|
||||||
card: "Карта",
|
card: "Карта",
|
||||||
|
cardSaved: "Карта сохранена",
|
||||||
categories: "Категории",
|
categories: "Категории",
|
||||||
category: "Категория",
|
category: "Категория",
|
||||||
categoryName: "Название категории",
|
categoryName: "Название категории",
|
||||||
|
categorySaved: "Категория сохранена",
|
||||||
close: "Закрыть",
|
close: "Закрыть",
|
||||||
date: "Дата операции",
|
date: "Дата операции",
|
||||||
defaultCategory: "По умолчанию",
|
defaultCategory: "По умолчанию",
|
||||||
@@ -153,7 +155,9 @@ const ru = {
|
|||||||
openingHint:
|
openingHint:
|
||||||
"Остаток до операций с выбранной даты. Валюта — рубли (RUB).",
|
"Остаток до операций с выбранной даты. Валюта — рубли (RUB).",
|
||||||
operationCard: "Карта операции",
|
operationCard: "Карта операции",
|
||||||
|
operationDeleted: "Операция удалена",
|
||||||
operations: "Операции",
|
operations: "Операции",
|
||||||
|
operationSaved: "Операция сохранена",
|
||||||
page: "Страница {{page}}",
|
page: "Страница {{page}}",
|
||||||
pageSize: "Операций на странице",
|
pageSize: "Операций на странице",
|
||||||
pagination: "Страницы операций",
|
pagination: "Страницы операций",
|
||||||
@@ -516,6 +520,8 @@ const ru = {
|
|||||||
errorTitle: "Что-то пошло не так",
|
errorTitle: "Что-то пошло не так",
|
||||||
loadingText: "Пожалуйста, подождите.",
|
loadingText: "Пожалуйста, подождите.",
|
||||||
loadingTitle: "Загрузка",
|
loadingTitle: "Загрузка",
|
||||||
|
unavailableText: "Данные появятся здесь, когда чтение восстановится.",
|
||||||
|
unavailableTitle: "Пока недоступно",
|
||||||
},
|
},
|
||||||
stock: {
|
stock: {
|
||||||
aboutCompany: "О компании",
|
aboutCompany: "О компании",
|
||||||
@@ -696,6 +702,7 @@ const ru = {
|
|||||||
"Не удалось загрузить статус подключения. Обновите страницу.",
|
"Не удалось загрузить статус подключения. Обновите страницу.",
|
||||||
title: "T-Bank Invest",
|
title: "T-Bank Invest",
|
||||||
token: "Token T-Bank",
|
token: "Token T-Bank",
|
||||||
|
tokenReplaced: "Подключение обновлено",
|
||||||
tokenRequired: "Введите token",
|
tokenRequired: "Введите token",
|
||||||
unavailable: "T-Bank временно недоступен. Повторите попытку позже.",
|
unavailable: "T-Bank временно недоступен. Повторите попытку позже.",
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -8,4 +8,8 @@ export {
|
|||||||
formatSnapshotTime,
|
formatSnapshotTime,
|
||||||
instrumentLogoUrl,
|
instrumentLogoUrl,
|
||||||
} from "./display";
|
} from "./display";
|
||||||
|
export {
|
||||||
|
type InitialAvailability,
|
||||||
|
useInitialAvailability,
|
||||||
|
} from "./initial-availability";
|
||||||
export { useUrlPeriod } from "./useUrlPeriod";
|
export { useUrlPeriod } from "./useUrlPeriod";
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
import { act, renderHook } from "@testing-library/react";
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
import { useInitialAvailability } from "./initial-availability";
|
||||||
|
|
||||||
|
describe("useInitialAvailability", () => {
|
||||||
|
it("keeps loading until content, error, or the initial wait budget", async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { rerender, result } = renderHook(
|
||||||
|
props => useInitialAvailability(props),
|
||||||
|
{
|
||||||
|
initialProps: {
|
||||||
|
hasContent: false,
|
||||||
|
identity: "account-a",
|
||||||
|
isError: false,
|
||||||
|
isFetching: true,
|
||||||
|
timeoutMs: 100,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result.current).toBe("loading");
|
||||||
|
await act(() => vi.advanceTimersByTimeAsync(99));
|
||||||
|
expect(result.current).toBe("loading");
|
||||||
|
await act(() => vi.advanceTimersByTimeAsync(1));
|
||||||
|
expect(result.current).toBe("unavailable");
|
||||||
|
|
||||||
|
rerender({
|
||||||
|
hasContent: true,
|
||||||
|
identity: "account-a",
|
||||||
|
isError: false,
|
||||||
|
isFetching: false,
|
||||||
|
timeoutMs: 100,
|
||||||
|
});
|
||||||
|
expect(result.current).toBe("ready");
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not flash loading during retry for the same identity", async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { rerender, result } = renderHook(
|
||||||
|
props => useInitialAvailability(props),
|
||||||
|
{
|
||||||
|
initialProps: {
|
||||||
|
hasContent: false,
|
||||||
|
identity: "account-a",
|
||||||
|
isError: true,
|
||||||
|
isFetching: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
await act(() => vi.runOnlyPendingTimersAsync());
|
||||||
|
expect(result.current).toBe("unavailable");
|
||||||
|
rerender({
|
||||||
|
hasContent: false,
|
||||||
|
identity: "account-a",
|
||||||
|
isError: false,
|
||||||
|
isFetching: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current).toBe("unavailable");
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resets loading only when identity changes", async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { rerender, result } = renderHook(
|
||||||
|
props => useInitialAvailability(props),
|
||||||
|
{
|
||||||
|
initialProps: {
|
||||||
|
hasContent: false,
|
||||||
|
identity: "account-a",
|
||||||
|
isError: true,
|
||||||
|
isFetching: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
await act(() => vi.runOnlyPendingTimersAsync());
|
||||||
|
expect(result.current).toBe("unavailable");
|
||||||
|
rerender({
|
||||||
|
hasContent: false,
|
||||||
|
identity: "account-b",
|
||||||
|
isError: false,
|
||||||
|
isFetching: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current).toBe("loading");
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
const INITIAL_WAIT_BUDGET_MS = 10_000;
|
||||||
|
|
||||||
|
type InitialAvailability
|
||||||
|
= | "loading"
|
||||||
|
| "ready"
|
||||||
|
| "unavailable";
|
||||||
|
|
||||||
|
type InitialAvailabilityInput = {
|
||||||
|
hasContent: boolean;
|
||||||
|
identity: string;
|
||||||
|
isError: boolean;
|
||||||
|
isFetching: boolean;
|
||||||
|
timeoutMs?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
function useInitialAvailability(
|
||||||
|
input: InitialAvailabilityInput,
|
||||||
|
): InitialAvailability {
|
||||||
|
const timeoutMs = input.timeoutMs ?? INITIAL_WAIT_BUDGET_MS;
|
||||||
|
|
||||||
|
const [unavailableIdentity, setUnavailableIdentity] = useState<null | string>(
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (input.hasContent) return;
|
||||||
|
|
||||||
|
if (input.isError) {
|
||||||
|
const timer = setTimeout(() => setUnavailableIdentity(input.identity), 0);
|
||||||
|
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}
|
||||||
|
|
||||||
|
const timer = setTimeout(
|
||||||
|
() => setUnavailableIdentity(input.identity),
|
||||||
|
timeoutMs,
|
||||||
|
);
|
||||||
|
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [input.hasContent, input.identity, input.isError, timeoutMs]);
|
||||||
|
|
||||||
|
if (input.hasContent) return "ready";
|
||||||
|
|
||||||
|
return unavailableIdentity === input.identity ? "unavailable" : "loading";
|
||||||
|
}
|
||||||
|
|
||||||
|
export { type InitialAvailability, useInitialAvailability };
|
||||||
Reference in New Issue
Block a user