Compare commits
5
Commits
v1.0.0
..
3782b249c3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3782b249c3 | ||
|
|
3c226f8c29 | ||
|
|
20b2cdfd43 | ||
|
|
dcd1e3c278 | ||
|
|
432cca299f |
+1
-1
@@ -19,7 +19,7 @@ COPY . .
|
||||
ENV VITE_API_BASE_URL=""
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:1.28.0-alpine AS production
|
||||
FROM nginx:1.31.6-alpine AS production
|
||||
ARG VERSION
|
||||
ARG REVISION
|
||||
LABEL org.opencontainers.image.version=$VERSION \
|
||||
|
||||
Generated
+1514
-1525
File diff suppressed because it is too large
Load Diff
+42
-42
@@ -38,54 +38,54 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "5.9.1",
|
||||
"@mantine/charts": "9.6.1",
|
||||
"@mantine/core": "9.6.1",
|
||||
"@mantine/dates": "9.6.1",
|
||||
"@mantine/hooks": "9.6.1",
|
||||
"@mantine/notifications": "9.6.1",
|
||||
"@tanstack/react-query": "5.102.8",
|
||||
"@mantine/charts": "9.7.1",
|
||||
"@mantine/core": "9.7.1",
|
||||
"@mantine/dates": "9.7.1",
|
||||
"@mantine/hooks": "9.7.1",
|
||||
"@mantine/notifications": "9.7.1",
|
||||
"@tanstack/react-query": "5.104.1",
|
||||
"@wealthledger/icons": "file:packages/icons",
|
||||
"@wealthledger/tokens": "file:packages/tokens",
|
||||
"@wealthledger/ui": "file:packages/ui",
|
||||
"dayjs": "1.11.23",
|
||||
"i18next": "26.4.2",
|
||||
"motion": "13.2.0",
|
||||
"i18next": "26.4.3",
|
||||
"motion": "13.5.1",
|
||||
"openapi-fetch": "0.17.0",
|
||||
"openapi-react-query": "0.5.4",
|
||||
"react": "19.3.0",
|
||||
"react-dom": "19.3.0",
|
||||
"react-hook-form": "7.88.0",
|
||||
"react-i18next": "17.0.14",
|
||||
"react-hook-form": "7.89.0",
|
||||
"react-i18next": "17.0.16",
|
||||
"react-is": "19.3.0",
|
||||
"react-router": "8.3.1",
|
||||
"react-router": "8.4.0",
|
||||
"recharts": "3.10.1",
|
||||
"zod": "4.6.4"
|
||||
"zod": "4.6.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "8.0.5",
|
||||
"@commitlint/cli": "21.2.2",
|
||||
"@commitlint/config-conventional": "21.2.2",
|
||||
"@eslint-react/eslint-plugin": "5.21.0",
|
||||
"@babel/core": "8.0.7",
|
||||
"@commitlint/cli": "21.2.3",
|
||||
"@commitlint/config-conventional": "21.2.3",
|
||||
"@eslint-react/eslint-plugin": "5.24.10",
|
||||
"@eslint/js": "10.0.1",
|
||||
"@release-it/conventional-changelog": "12.0.0",
|
||||
"@release-it/conventional-changelog": "12.0.2",
|
||||
"@rolldown/plugin-babel": "0.2.4",
|
||||
"@storybook/addon-docs": "10.6.0",
|
||||
"@storybook/react-vite": "10.6.0",
|
||||
"@storybook/addon-docs": "10.6.1",
|
||||
"@storybook/react-vite": "10.6.1",
|
||||
"@stylistic/eslint-plugin": "5.10.0",
|
||||
"@tanstack/eslint-plugin-query": "5.104.0",
|
||||
"@tanstack/eslint-plugin-query": "5.104.1",
|
||||
"@testing-library/jest-dom": "7.0.1",
|
||||
"@testing-library/react": "16.3.3",
|
||||
"@types/node": "24.13.4",
|
||||
"@types/node": "24.19.2",
|
||||
"@types/react": "19.3.0",
|
||||
"@types/react-dom": "19.3.0",
|
||||
"@vitejs/plugin-react": "6.1.1",
|
||||
"@vitest/browser-playwright": "5.0.0",
|
||||
"@vitest/coverage-v8": "5.0.0",
|
||||
"@vitejs/plugin-react": "6.1.2",
|
||||
"@vitest/browser-playwright": "5.0.3",
|
||||
"@vitest/coverage-v8": "5.0.3",
|
||||
"@vitest/eslint-plugin": "1.6.27",
|
||||
"babel-plugin-react-compiler": "1.0.0",
|
||||
"conventional-changelog-conventionalcommits": "10.4.0",
|
||||
"dependency-cruiser": "18.2.0",
|
||||
"eslint": "10.11.0",
|
||||
"conventional-changelog-conventionalcommits": "10.4.1",
|
||||
"dependency-cruiser": "18.5.0",
|
||||
"eslint": "10.12.0",
|
||||
"eslint-import-resolver-typescript": "4.4.5",
|
||||
"eslint-plugin-import-x": "4.17.1",
|
||||
"eslint-plugin-jest-dom": "5.10.1",
|
||||
@@ -94,31 +94,31 @@
|
||||
"eslint-plugin-react-hooks": "7.1.1",
|
||||
"eslint-plugin-react-refresh": "0.5.7",
|
||||
"eslint-plugin-regexp": "3.3.1",
|
||||
"eslint-plugin-security": "4.1.0",
|
||||
"eslint-plugin-sonarjs": "4.2.1",
|
||||
"eslint-plugin-storybook": "10.6.0",
|
||||
"eslint-plugin-security": "4.2.0",
|
||||
"eslint-plugin-sonarjs": "4.2.2",
|
||||
"eslint-plugin-storybook": "10.6.1",
|
||||
"eslint-plugin-testing-library": "7.16.2",
|
||||
"eslint-plugin-unicorn": "76.0.0",
|
||||
"globals": "17.12.0",
|
||||
"globals": "17.13.0",
|
||||
"husky": "9.1.7",
|
||||
"jsdom": "30.0.1",
|
||||
"knip": "6.35.1",
|
||||
"lint-staged": "17.5.1",
|
||||
"jsdom": "30.1.2",
|
||||
"knip": "6.41.0",
|
||||
"lint-staged": "17.6.0",
|
||||
"msw": "2.15.0",
|
||||
"openapi-typescript": "7.13.0",
|
||||
"playwright": "1.63.0",
|
||||
"release-it": "21.0.2",
|
||||
"storybook": "10.6.0",
|
||||
"playwright": "1.64.0",
|
||||
"release-it": "21.1.1",
|
||||
"storybook": "10.6.1",
|
||||
"typescript": "5.9.3",
|
||||
"typescript-eslint": "8.70.1",
|
||||
"vite": "8.3.0",
|
||||
"typescript-eslint": "8.71.1",
|
||||
"vite": "8.3.4",
|
||||
"vite-plugin-pwa": "1.3.0",
|
||||
"vitest": "5.0.0"
|
||||
"vitest": "5.0.3"
|
||||
},
|
||||
"overrides": {
|
||||
"release-it": {
|
||||
"basic-ftp": "6.2.1",
|
||||
"undici": "7.29.1"
|
||||
"basic-ftp": "6.2.3",
|
||||
"undici": "7.30.0"
|
||||
}
|
||||
},
|
||||
"allowScripts": {
|
||||
|
||||
@@ -23,11 +23,11 @@
|
||||
"react": "19.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@storybook/react-vite": "10.6.0",
|
||||
"@storybook/react-vite": "10.6.1",
|
||||
"@testing-library/react": "16.3.3",
|
||||
"@types/react": "19.3.0",
|
||||
"typescript": "5.9.3",
|
||||
"vite": "8.3.0",
|
||||
"vitest": "5.0.0"
|
||||
"vite": "8.3.4",
|
||||
"vitest": "5.0.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,18 +27,18 @@
|
||||
"@wealthledger/tokens": "0.3.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@mantine/core": "9.6.1",
|
||||
"@mantine/hooks": "9.6.1",
|
||||
"@mantine/core": "9.7.1",
|
||||
"@mantine/hooks": "9.7.1",
|
||||
"react": "19.3.0",
|
||||
"react-dom": "19.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@storybook/react-vite": "10.6.0",
|
||||
"@storybook/react-vite": "10.6.1",
|
||||
"@testing-library/react": "16.3.3",
|
||||
"@types/react": "19.3.0",
|
||||
"storybook": "10.6.0",
|
||||
"storybook": "10.6.1",
|
||||
"typescript": "5.9.3",
|
||||
"vite": "8.3.0",
|
||||
"vitest": "5.0.0"
|
||||
"vite": "8.3.4",
|
||||
"vitest": "5.0.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,28 @@
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.totals {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--mantine-spacing-xs) var(--mantine-spacing-lg);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.totals > div {
|
||||
display: grid;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.totals dt {
|
||||
color: var(--mantine-color-dimmed);
|
||||
font-size: var(--mantine-font-size-xs);
|
||||
}
|
||||
|
||||
.totals dd {
|
||||
margin: 0;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.categories {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { BankSummaryView } from "./BankSummary.view";
|
||||
|
||||
const money = (value: string) => ({ currency: "RUB", value });
|
||||
|
||||
describe("BankSummaryView", () => {
|
||||
it("shows expenses, refunds, and net monthly totals", () => {
|
||||
render(
|
||||
<MantineProvider env="test">
|
||||
<BankSummaryView
|
||||
data={{
|
||||
cardId: "card-1",
|
||||
categories: [],
|
||||
expenses: money("1000"),
|
||||
net: money("800"),
|
||||
refunds: money("200"),
|
||||
}}
|
||||
error={false}
|
||||
fetching={false}
|
||||
loading={false}
|
||||
/>
|
||||
</MantineProvider>,
|
||||
);
|
||||
|
||||
expect(screen.getAllByText("Расходы")).toHaveLength(2);
|
||||
expect(screen.getByText("Возвращено")).toBeInTheDocument();
|
||||
expect(screen.getByText("После возвратов")).toBeInTheDocument();
|
||||
expect(screen.getByText("1 000,00 ₽")).toBeInTheDocument();
|
||||
expect(screen.getByText("200,00 ₽")).toBeInTheDocument();
|
||||
expect(screen.getByText("800,00 ₽")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -92,9 +92,31 @@ const BankSummaryView: FC<BankSummaryViewProps> = (props) => {
|
||||
</Title>
|
||||
|
||||
{props.data && (
|
||||
<Text className={classes.total}>
|
||||
{formatMoney(props.data.net, { withZeroCents: true })}
|
||||
</Text>
|
||||
<dl className={classes.totals}>
|
||||
<div>
|
||||
<dt>{t("bank.summary")}</dt>
|
||||
|
||||
<dd>
|
||||
{formatMoney(props.data.expenses, { withZeroCents: true })}
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<dt>{t("bank.refunds")}</dt>
|
||||
|
||||
<dd>
|
||||
{formatMoney(props.data.refunds, { withZeroCents: true })}
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<dt>{t("bank.net")}</dt>
|
||||
|
||||
<dd className={classes.total}>
|
||||
{formatMoney(props.data.net, { withZeroCents: true })}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -4,17 +4,22 @@ const brokerageAccountsQueryOptions = () =>
|
||||
apiQueryClient.queryOptions("get", "/api/v1/brokerage-accounts");
|
||||
|
||||
const brokerageAccountsQueryKey = brokerageAccountsQueryOptions().queryKey;
|
||||
const BROKERAGE_ACCOUNTS_STALE_TIME_MS = 1_800_000;
|
||||
|
||||
type BrokerageAccount = NonNullable<
|
||||
paths["/api/v1/brokerage-accounts"]["get"]["responses"][200]["content"]["application/json"]["data"]
|
||||
>[number];
|
||||
|
||||
function useBrokerageAccounts() {
|
||||
return useResourceQuery({
|
||||
const query = useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...brokerageAccountsQueryOptions(),
|
||||
staleTime: 60_000,
|
||||
staleTime: BROKERAGE_ACCOUNTS_STALE_TIME_MS,
|
||||
});
|
||||
|
||||
return {
|
||||
...query,
|
||||
};
|
||||
}
|
||||
|
||||
export {
|
||||
|
||||
+16
-8
@@ -205,24 +205,32 @@ export const IndependentFreshness: Story
|
||||
],
|
||||
[
|
||||
{
|
||||
availability: "complete",
|
||||
availability: "available",
|
||||
completeness: "complete",
|
||||
dataRevision: "1",
|
||||
freshness: "stale",
|
||||
lastSuccessfulAt: "2026-09-24T10:30:00Z",
|
||||
resourceKey: "portfolio/storybook-account",
|
||||
sync: {
|
||||
errorCode: "TBANK_UNAVAILABLE",
|
||||
id: "failed",
|
||||
lastAttempt: {
|
||||
finishedAt: "2026-09-24T10:31:00Z",
|
||||
problems: [],
|
||||
startedAt: "2026-09-24T10:30:00Z",
|
||||
state: "failed",
|
||||
},
|
||||
lastSuccessfulAt: "2026-09-24T10:30:00Z",
|
||||
resourceKey: "portfolio/storybook-account",
|
||||
},
|
||||
{
|
||||
availability: "missing",
|
||||
availability: "initial-loading",
|
||||
completeness: "incomplete",
|
||||
dataRevision: "0",
|
||||
freshness: "unknown",
|
||||
lastAttempt: {
|
||||
finishedAt: null,
|
||||
problems: [],
|
||||
startedAt: "2026-09-24T10:30:00Z",
|
||||
state: "running",
|
||||
},
|
||||
lastSuccessfulAt: null,
|
||||
resourceKey: "portfolio/waiting",
|
||||
sync: { errorCode: null, id: "waiting", state: "running" },
|
||||
},
|
||||
],
|
||||
),
|
||||
|
||||
@@ -64,15 +64,16 @@ const BrokerageAccountSourceStatus: FC<BrokerageAccountSourceStatusProps> = (
|
||||
const { source } = props;
|
||||
const { t } = useTranslation();
|
||||
|
||||
const isSyncing = source?.sync.state === "running";
|
||||
const isSyncing = source?.lastAttempt.state === "running";
|
||||
|
||||
const errorText
|
||||
= source?.sync.state === "failed" ? t("accounts.refreshError") : null;
|
||||
= source?.lastAttempt.state === "failed" ? t("accounts.refreshError") : null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<SourceSyncStatus
|
||||
errorText={errorText}
|
||||
lastAttempt={source?.lastAttempt}
|
||||
lastSuccessfulAt={source?.lastSuccessfulAt}
|
||||
stale={source?.freshness === "stale"}
|
||||
/>
|
||||
|
||||
@@ -5,20 +5,23 @@ import { resource } from "@/test/resource";
|
||||
import { section } from "./section";
|
||||
|
||||
describe("instrument source and transport presentation", () => {
|
||||
it.each(["missing", "partial", "complete"] as const)(
|
||||
it.each([
|
||||
["initial-loading", "incomplete"],
|
||||
["available", "complete"],
|
||||
] as const)(
|
||||
"keeps %s separate from successful transport",
|
||||
(availability) => {
|
||||
const data = availability === "missing" ? undefined : { rows: [] };
|
||||
(availability, completeness) => {
|
||||
const data = availability === "initial-loading" ? undefined : { rows: [] };
|
||||
|
||||
const state = section({
|
||||
data,
|
||||
isError: false,
|
||||
meta: resource(data, { availability }).meta,
|
||||
meta: resource(data, { availability, completeness }).meta,
|
||||
});
|
||||
|
||||
expect(state.loading).toBe(availability === "missing");
|
||||
expect(state.partial).toBe(availability === "partial");
|
||||
expect(state.hasData).toBe(availability !== "missing");
|
||||
expect(state.loading).toBe(availability === "initial-loading");
|
||||
expect(state.partial).toBe(completeness === "incomplete");
|
||||
expect(state.hasData).toBe(availability !== "initial-loading");
|
||||
},
|
||||
);
|
||||
it("preserves empty successful data instead of treating it as missing", () => {
|
||||
@@ -37,7 +40,12 @@ describe("instrument source and transport presentation", () => {
|
||||
|
||||
it("preserves a full source when force fails", () => {
|
||||
const meta = resource([], {
|
||||
sync: { errorCode: "TBANK_UNAVAILABLE", id: "work", state: "failed" },
|
||||
lastAttempt: {
|
||||
finishedAt: "2026-08-14T00:01:00Z",
|
||||
problems: [],
|
||||
startedAt: "2026-08-14T00:00:00Z",
|
||||
state: "failed",
|
||||
},
|
||||
}).meta;
|
||||
|
||||
const state = section({ data: [], isError: false, meta });
|
||||
@@ -53,7 +61,12 @@ describe("instrument source and transport presentation", () => {
|
||||
data: undefined,
|
||||
isError: false,
|
||||
meta: resource(null, {
|
||||
sync: { errorCode: "TBANK_UNAVAILABLE", id: "work", state: "failed" },
|
||||
lastAttempt: {
|
||||
finishedAt: "2026-08-14T00:01:00Z",
|
||||
problems: [],
|
||||
startedAt: "2026-08-14T00:00:00Z",
|
||||
state: "failed",
|
||||
},
|
||||
}).meta,
|
||||
});
|
||||
|
||||
|
||||
@@ -16,14 +16,14 @@ function section(query: {
|
||||
isError: boolean;
|
||||
meta?: InvestmentResourceMeta;
|
||||
}): SectionState {
|
||||
const isError = query.isError || query.meta?.sync.state === "failed";
|
||||
const isError = query.isError || query.meta?.lastAttempt.state === "failed";
|
||||
const hasData = hasSectionData(query.data);
|
||||
|
||||
return {
|
||||
error: isError,
|
||||
hasData,
|
||||
loading: !hasData && !isError,
|
||||
partial: query.meta?.availability === "partial",
|
||||
partial: query.meta?.completeness === "incomplete",
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ function isInvestmentPath(path: string) {
|
||||
"/api/v1/brokerage-accounts",
|
||||
"/api/v1/stocks",
|
||||
"/api/v1/bonds",
|
||||
"/api/v1/tbank-sync",
|
||||
].some(root => path === root || path.startsWith(`${root}/`));
|
||||
}
|
||||
|
||||
|
||||
@@ -3,14 +3,12 @@ import { http, HttpResponse } from "msw";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { useBrokerageAccounts } from "@/entities/brokerage-account";
|
||||
import { useStockQuote } from "@/entities/stock";
|
||||
import { configureAuthClient, invalidateResourceAccess } from "@/shared/api";
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createQueryWrapper } from "@/test/query";
|
||||
import { resource } from "@/test/resource";
|
||||
import { server } from "@/test/server";
|
||||
|
||||
import { useScreenSync } from "../index";
|
||||
import { commitTbankConnectionBoundary } from "./connection-boundary";
|
||||
|
||||
function auth() {
|
||||
configureAuthClient({
|
||||
@@ -20,364 +18,23 @@ function auth() {
|
||||
});
|
||||
}
|
||||
|
||||
describe("page-owned screen synchronization", () => {
|
||||
it("keeps the current scope when an older sync acceptance arrives last", async () => {
|
||||
describe("read-only screen synchronization", () => {
|
||||
it("retries the resource with GET without requesting source observation", async () => {
|
||||
auth();
|
||||
|
||||
const { promise: blocked, resolve: release }
|
||||
= Promise.withResolvers<void>();
|
||||
|
||||
const posted: string[] = [];
|
||||
const polled: string[] = [];
|
||||
server.use(
|
||||
http.post("*/api/v1/tbank-sync", async ({ request }) => {
|
||||
const scope = (await request.json()) as {
|
||||
accountId: string;
|
||||
screen: "account";
|
||||
};
|
||||
|
||||
posted.push(scope.accountId);
|
||||
if (scope.accountId === "old") await blocked;
|
||||
|
||||
return HttpResponse.json(
|
||||
{ id: scope.accountId, now: "2026-09-25T00:00:00Z", scope },
|
||||
{ status: 202 },
|
||||
);
|
||||
}),
|
||||
http.get("*/api/v1/tbank-sync/:id", ({ params }) => {
|
||||
polled.push(String(params.id));
|
||||
|
||||
return HttpResponse.json({
|
||||
id: params.id,
|
||||
state: "succeeded",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const { rerender, result } = renderHook(
|
||||
({ accountId }) => useScreenSync({ accountId, screen: "account" }, []),
|
||||
{
|
||||
initialProps: { accountId: "old" },
|
||||
wrapper: createQueryWrapper().wrapper,
|
||||
},
|
||||
);
|
||||
|
||||
let pending!: Promise<void>;
|
||||
act(() => {
|
||||
pending = result.current.refresh();
|
||||
});
|
||||
await waitFor(() => expect(posted).toEqual(["old"]));
|
||||
rerender({ accountId: "new" });
|
||||
await act(() => result.current.refresh());
|
||||
await waitFor(() => expect(polled).toEqual(["new"]));
|
||||
await act(async () => {
|
||||
release();
|
||||
await pending;
|
||||
});
|
||||
expect(polled).toEqual(["new"]);
|
||||
expect(posted).toEqual(["old", "new"]);
|
||||
});
|
||||
it.each([false, true])(
|
||||
"recovers a failed GET without forcing the source (cached=%s)",
|
||||
async (cached) => {
|
||||
auth();
|
||||
const modes: (null | string)[] = [];
|
||||
let isUnavailable = !cached;
|
||||
let posts = 0;
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
||||
modes.push(new URL(request.url).searchParams.get("sync"));
|
||||
|
||||
return isUnavailable
|
||||
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
|
||||
: HttpResponse.json(
|
||||
resource([], { dataRevision: String(modes.length) }),
|
||||
);
|
||||
}),
|
||||
http.post("*/api/v1/tbank-sync", () => {
|
||||
posts += 1;
|
||||
|
||||
return new HttpResponse(null, { status: 500 });
|
||||
}),
|
||||
);
|
||||
const { queryClient, wrapper } = createQueryWrapper();
|
||||
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
const disabled = useStockQuote("");
|
||||
|
||||
return {
|
||||
accounts,
|
||||
disabled,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts, disabled]),
|
||||
};
|
||||
},
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
if (cached) {
|
||||
await waitFor(() =>
|
||||
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
|
||||
expect(result.current.accounts.isSuccess).toBe(true),
|
||||
);
|
||||
isUnavailable = true;
|
||||
void result.current.accounts.refetch();
|
||||
}
|
||||
|
||||
isUnavailable = false;
|
||||
await waitFor(() => expect(result.current.accounts.isSuccess).toBe(true));
|
||||
expect(posts).toBe(0);
|
||||
expect(modes.every(mode => mode === null)).toBe(true);
|
||||
expect(result.current.disabled.data).toBeUndefined();
|
||||
expect(
|
||||
queryClient
|
||||
.getQueryCache()
|
||||
.findAll({ queryKey: ["get", "/api/v1/brokerage-accounts"] }),
|
||||
).toHaveLength(1);
|
||||
},
|
||||
);
|
||||
it.each([
|
||||
["logout", true],
|
||||
["connection", true],
|
||||
["session", false],
|
||||
["connection", false],
|
||||
["access", false],
|
||||
] as const)(
|
||||
"discards source recovery after %s changes (HTTP already pending=%s)",
|
||||
async (boundary, pending) => {
|
||||
auth();
|
||||
|
||||
const { promise: blocked, resolve: release }
|
||||
= Promise.withResolvers<void>();
|
||||
|
||||
let recoveryRequests = 0;
|
||||
let isChanged = false;
|
||||
|
||||
try {
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", async () => {
|
||||
if (isChanged)
|
||||
return HttpResponse.json(
|
||||
resource([], { dataRevision: "current" }),
|
||||
);
|
||||
|
||||
if (recoveryRequests > 0) {
|
||||
recoveryRequests += 1;
|
||||
await blocked;
|
||||
|
||||
return HttpResponse.json(resource([], { dataRevision: "old" }));
|
||||
}
|
||||
|
||||
recoveryRequests += 1;
|
||||
|
||||
return HttpResponse.json(
|
||||
resource(null, {
|
||||
sync: {
|
||||
errorCode: "TBANK_UNAVAILABLE",
|
||||
id: "failed",
|
||||
state: "failed",
|
||||
},
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const { queryClient, wrapper } = createQueryWrapper();
|
||||
const published: unknown[] = [];
|
||||
|
||||
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
|
||||
if (event.type === "updated" && event.action.type === "success")
|
||||
published.push(event.query.state.data);
|
||||
});
|
||||
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
|
||||
return {
|
||||
accounts,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts]),
|
||||
};
|
||||
},
|
||||
{ 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])(
|
||||
"recovers an initial GET failure without forced sync (status retry=%s)",
|
||||
async (retryStatus) => {
|
||||
auth();
|
||||
const modes: (null | string)[] = [];
|
||||
let posts = 0;
|
||||
let polls = 0;
|
||||
|
||||
try {
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
||||
modes.push(new URL(request.url).searchParams.get("sync"));
|
||||
|
||||
return modes.length === 1
|
||||
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
|
||||
: HttpResponse.json(resource([]));
|
||||
}),
|
||||
http.post("*/api/v1/tbank-sync", () => {
|
||||
posts += 1;
|
||||
|
||||
return HttpResponse.json({ id: "recover" }, { status: 202 });
|
||||
}),
|
||||
http.get("*/api/v1/tbank-sync/:id", () => {
|
||||
polls += 1;
|
||||
|
||||
return retryStatus && polls === 1
|
||||
? HttpResponse.json({ code: "UNAVAILABLE" }, { status: 503 })
|
||||
: HttpResponse.json({
|
||||
id: "recover",
|
||||
state: "succeeded",
|
||||
});
|
||||
}),
|
||||
);
|
||||
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();
|
||||
}
|
||||
},
|
||||
);
|
||||
it("posts only its scope once and observes completion without importing again", async () => {
|
||||
auth();
|
||||
const modes: (null | string)[] = [];
|
||||
const bodies: unknown[] = [];
|
||||
let isCompleted = false;
|
||||
let polls = 0;
|
||||
|
||||
const meta = () =>
|
||||
resource([], { dataRevision: isCompleted ? "2" : "1" }).meta;
|
||||
|
||||
let gets = 0;
|
||||
const syncModes: (null | string)[] = [];
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
||||
modes.push(new URL(request.url).searchParams.get("sync"));
|
||||
gets += 1;
|
||||
syncModes.push(new URL(request.url).searchParams.get("sync"));
|
||||
|
||||
return HttpResponse.json(resource([], meta()));
|
||||
}),
|
||||
http.post("*/api/v1/tbank-sync", async ({ request }) => {
|
||||
bodies.push(await request.json());
|
||||
isCompleted = true;
|
||||
|
||||
return HttpResponse.json(
|
||||
{
|
||||
id: "screen",
|
||||
now: "2026-09-25T00:00:00Z",
|
||||
scope: { screen: "accounts" },
|
||||
},
|
||||
{ status: 202 },
|
||||
);
|
||||
}),
|
||||
http.get("*/api/v1/tbank-sync/:id", () => {
|
||||
polls++;
|
||||
|
||||
return HttpResponse.json(
|
||||
{
|
||||
errorCode: null,
|
||||
id: "screen",
|
||||
now: "2026-09-25T00:00:00Z",
|
||||
scope: { screen: "accounts" },
|
||||
state: "succeeded",
|
||||
},
|
||||
);
|
||||
return gets === 1
|
||||
? HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 })
|
||||
: HttpResponse.json(resource([]));
|
||||
}),
|
||||
);
|
||||
|
||||
const { result, unmount } = renderHook(
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
|
||||
@@ -389,382 +46,36 @@ describe("page-owned screen synchronization", () => {
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
|
||||
await waitFor(() => expect(gets).toBe(1));
|
||||
await act(async () => result.current.sync.retry());
|
||||
await waitFor(() => expect(result.current.accounts.data).toEqual([]));
|
||||
await act(async () => {
|
||||
await Promise.all([
|
||||
result.current.sync.refresh(),
|
||||
result.current.sync.refresh(),
|
||||
]);
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current.accounts.meta?.dataRevision).toBe("2"),
|
||||
);
|
||||
expect(bodies).toEqual([{ screen: "accounts" }]);
|
||||
|
||||
expect(modes).toEqual([null, "observe"]);
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
await act(() => vi.advanceTimersByTimeAsync(120_000));
|
||||
expect(polls).toBe(1);
|
||||
|
||||
expect(modes).toEqual([null, "observe"]);
|
||||
unmount();
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
expect(polls).toBe(1);
|
||||
}
|
||||
finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
it.each(["leave", "logout"])(
|
||||
"publishes completed empty coverage while history runs, then stops on %s",
|
||||
async (boundary) => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
auth();
|
||||
let isCompleted = false;
|
||||
let polls = 0;
|
||||
const modes: (null | string)[] = [];
|
||||
|
||||
const snapshot = () =>
|
||||
resource(isCompleted ? [] : null, {
|
||||
dataRevision: isCompleted ? "covered" : "initial",
|
||||
sync: { errorCode: null, id: "history", state: "running" },
|
||||
unavailableReason: isCompleted
|
||||
? undefined
|
||||
: "CALENDAR_OR_ACCOUNT_HISTORY",
|
||||
});
|
||||
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
||||
modes.push(new URL(request.url).searchParams.get("sync"));
|
||||
|
||||
return HttpResponse.json(snapshot());
|
||||
}),
|
||||
http.get("*/api/v1/tbank-sync/:id", () => {
|
||||
polls++;
|
||||
|
||||
return HttpResponse.json(
|
||||
{
|
||||
errorCode: null,
|
||||
id: "history",
|
||||
now: "2026-09-25T00:00:00Z",
|
||||
scope: null,
|
||||
state: "running",
|
||||
},
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const { result, unmount } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
|
||||
return {
|
||||
accounts,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts]),
|
||||
};
|
||||
},
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
|
||||
await vi.waitFor(() => expect(modes).toEqual([null, "observe"]));
|
||||
expect(polls).toBe(1);
|
||||
expect(result.current.sync.refreshing).toBe(true);
|
||||
expect(result.current.accounts.data).toBeUndefined();
|
||||
|
||||
isCompleted = true;
|
||||
await act(() => vi.advanceTimersByTimeAsync(5000));
|
||||
await vi.waitFor(() =>
|
||||
expect(result.current.accounts.data).toEqual([]),
|
||||
);
|
||||
|
||||
expect(result.current.sync.refreshing).toBe(true);
|
||||
expect(modes).toEqual([null, "observe", "observe"]);
|
||||
|
||||
if (boundary === "leave") unmount();
|
||||
else act(() => configureAuthClient());
|
||||
|
||||
await act(() => vi.advanceTimersByTimeAsync(60_000));
|
||||
expect(polls).toBe(2);
|
||||
expect(modes).toHaveLength(3);
|
||||
}
|
||||
finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("runs the next status poll and observe read only after five seconds", async () => {
|
||||
auth();
|
||||
const modes: (null | string)[] = [];
|
||||
const pollGaps: number[] = [];
|
||||
let polls = 0;
|
||||
let previousPollAt = 0;
|
||||
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
||||
modes.push(new URL(request.url).searchParams.get("sync"));
|
||||
|
||||
return HttpResponse.json(
|
||||
resource([], {
|
||||
sync: { errorCode: null, id: "history", state: "running" },
|
||||
}),
|
||||
);
|
||||
}),
|
||||
http.get("*/api/v1/tbank-sync/:id", () => {
|
||||
const now = Date.now();
|
||||
if (previousPollAt) pollGaps.push(now - previousPollAt);
|
||||
previousPollAt = now;
|
||||
polls++;
|
||||
|
||||
return HttpResponse.json({
|
||||
errorCode: null,
|
||||
id: "history",
|
||||
now: "2026-09-25T00:00:00Z",
|
||||
scope: null,
|
||||
state: "running",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
const { unmount } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
|
||||
return {
|
||||
accounts,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts]),
|
||||
};
|
||||
},
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
|
||||
await vi.waitFor(() => expect(modes).toEqual([null, "observe"]));
|
||||
expect(polls).toBe(1);
|
||||
|
||||
await act(() => vi.advanceTimersByTimeAsync(2500));
|
||||
expect(polls).toBe(1);
|
||||
expect(modes).toEqual([null, "observe"]);
|
||||
|
||||
await act(() => vi.advanceTimersByTimeAsync(5000));
|
||||
await vi.waitFor(() => expect(polls).toBe(2));
|
||||
|
||||
expect(modes).toEqual([null, "observe", "observe"]);
|
||||
expect(pollGaps).toHaveLength(1);
|
||||
expect(pollGaps[0]).toBeGreaterThanOrEqual(5000);
|
||||
|
||||
unmount();
|
||||
await act(() => vi.advanceTimersByTimeAsync(60_000));
|
||||
expect(polls).toBe(2);
|
||||
expect(modes).toHaveLength(3);
|
||||
}
|
||||
finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
it("observes resources immediately when a status response turns terminal", async () => {
|
||||
auth();
|
||||
const modes: (null | string)[] = [];
|
||||
let isCompleted = false;
|
||||
let polls = 0;
|
||||
|
||||
const meta = () =>
|
||||
resource([], {
|
||||
dataRevision: isCompleted ? "covered" : "initial",
|
||||
sync: { errorCode: null, id: "history", state: "running" },
|
||||
});
|
||||
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
||||
modes.push(new URL(request.url).searchParams.get("sync"));
|
||||
|
||||
return HttpResponse.json(meta());
|
||||
}),
|
||||
http.get("*/api/v1/tbank-sync/:id", () => {
|
||||
polls++;
|
||||
|
||||
return HttpResponse.json({
|
||||
errorCode: null,
|
||||
id: "history",
|
||||
now: "2026-09-25T00:00:00Z",
|
||||
scope: null,
|
||||
state: isCompleted ? "succeeded" : "running",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
|
||||
return {
|
||||
accounts,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts]),
|
||||
};
|
||||
},
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
|
||||
await vi.waitFor(() => expect(modes).toEqual([null, "observe"]));
|
||||
expect(polls).toBe(1);
|
||||
expect(result.current.sync.refreshing).toBe(true);
|
||||
|
||||
isCompleted = true;
|
||||
await act(() => vi.advanceTimersByTimeAsync(5000));
|
||||
await vi.waitFor(() => expect(modes).toEqual([null, "observe", "observe"]));
|
||||
|
||||
expect(polls).toBe(2);
|
||||
expect(result.current.accounts.meta?.dataRevision).toBe("covered");
|
||||
expect(result.current.sync.refreshing).toBe(false);
|
||||
|
||||
await act(() => vi.advanceTimersByTimeAsync(60_000));
|
||||
expect(polls).toBe(2);
|
||||
expect(modes).toHaveLength(3);
|
||||
}
|
||||
finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
expect(gets).toBe(2);
|
||||
expect(syncModes).toEqual([null, null]);
|
||||
});
|
||||
|
||||
it("clears private snapshots when status confirms access loss", async () => {
|
||||
it("refreshes the currently open resources together", async () => {
|
||||
auth();
|
||||
let gets = 0;
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", () =>
|
||||
HttpResponse.json(
|
||||
resource(
|
||||
http.get("*/api/v1/brokerage-accounts", () => {
|
||||
gets += 1;
|
||||
|
||||
[],
|
||||
{
|
||||
sync: { errorCode: null, id: "revoked", state: "running" },
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
http.get("*/api/v1/tbank-sync/:id", () =>
|
||||
HttpResponse.json({ code: "INVALID_TBANK_TOKEN" }, { status: 400 }),
|
||||
),
|
||||
return HttpResponse.json(resource([]));
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
|
||||
return {
|
||||
accounts,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts]),
|
||||
};
|
||||
return useScreenSync({ screen: "accounts" }, [accounts]);
|
||||
},
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
|
||||
await waitFor(() => expect(result.current.accounts.isError).toBe(true));
|
||||
expect(result.current.accounts.data).toBeUndefined();
|
||||
});
|
||||
it("observes a projection when only its dependency reports new coverage", async () => {
|
||||
auth();
|
||||
let isObserved = false;
|
||||
const modes: (null | string)[] = [];
|
||||
|
||||
const dependency = resource(
|
||||
|
||||
[],
|
||||
{
|
||||
dataRevision: isObserved ? "covered" : "initial",
|
||||
resourceKey: "operations",
|
||||
sync: {
|
||||
errorCode: null,
|
||||
id: "dependency",
|
||||
state: isObserved ? "idle" : "running",
|
||||
},
|
||||
},
|
||||
).meta;
|
||||
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
||||
const mode = new URL(request.url).searchParams.get("sync");
|
||||
modes.push(mode);
|
||||
if (mode) isObserved = true;
|
||||
|
||||
return HttpResponse.json(
|
||||
resource(
|
||||
isObserved
|
||||
? []
|
||||
: null,
|
||||
{
|
||||
dependencies: [
|
||||
{
|
||||
...dependency,
|
||||
dataRevision: isObserved ? "covered" : "initial",
|
||||
},
|
||||
],
|
||||
resourceKey: "projection",
|
||||
},
|
||||
),
|
||||
);
|
||||
}),
|
||||
http.get("*/api/v1/tbank-sync/:id", () =>
|
||||
|
||||
HttpResponse.json(
|
||||
{
|
||||
errorCode: null,
|
||||
id: "dependency",
|
||||
now: "2026-09-25T00:00:00Z",
|
||||
scope: null,
|
||||
state: "succeeded",
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
useScreenSync({ screen: "accounts" }, [accounts]);
|
||||
|
||||
return accounts;
|
||||
},
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
|
||||
await waitFor(() => expect(result.current.data).toEqual([]));
|
||||
|
||||
expect(modes).toEqual([null, "observe"]);
|
||||
});
|
||||
|
||||
it("preserves a fresh snapshot and timestamp after a failed force", async () => {
|
||||
auth();
|
||||
const saved = resource([], { lastSuccessfulAt: "2026-09-25T01:00:00Z" });
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", () => HttpResponse.json(saved)),
|
||||
http.post("*/api/v1/tbank-sync", () =>
|
||||
HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }),
|
||||
),
|
||||
);
|
||||
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
|
||||
return {
|
||||
accounts,
|
||||
sync: useScreenSync({ screen: "accounts" }, [accounts]),
|
||||
};
|
||||
},
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
|
||||
await waitFor(() => expect(result.current.accounts.data).toEqual([]));
|
||||
await act(() => result.current.sync.refresh());
|
||||
await waitFor(() => expect(result.current.sync.transportError).toBe(true));
|
||||
expect(result.current.accounts.meta).toEqual(saved.meta);
|
||||
await waitFor(() => expect(gets).toBe(1));
|
||||
await act(async () => result.current.refresh());
|
||||
await waitFor(() => expect(gets).toBe(2));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,269 +1,52 @@
|
||||
import {
|
||||
focusManager,
|
||||
onlineManager,
|
||||
type QueryKey,
|
||||
useQueryClient,
|
||||
} from "@tanstack/react-query";
|
||||
import type { QueryKey } from "@tanstack/react-query";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
import {
|
||||
ApiErrorCode,
|
||||
apiErrorCode,
|
||||
apiQueryClient,
|
||||
invalidateResourceAccess,
|
||||
type InvestmentResourceMeta,
|
||||
isApiErrorCode,
|
||||
type paths,
|
||||
useAuthenticatedQueries,
|
||||
} from "@/shared/api";
|
||||
|
||||
type InvestmentScreen
|
||||
= paths["/api/v1/tbank-sync"]["post"]["requestBody"]["content"]["application/json"];
|
||||
import type { InvestmentResourceMeta } from "@/shared/api";
|
||||
|
||||
type ScreenResource = {
|
||||
isError: boolean;
|
||||
isFetching: boolean;
|
||||
meta?: InvestmentResourceMeta;
|
||||
observe: () => Promise<unknown>;
|
||||
queryKey: QueryKey;
|
||||
refetch: () => Promise<unknown>;
|
||||
};
|
||||
|
||||
const STATUS_INTERVAL_MS = 5000;
|
||||
const FIRST_SOURCE_RECOVERY_DELAY_MS = 5000;
|
||||
const SECOND_SOURCE_RECOVERY_DELAY_MS = 15_000;
|
||||
type ScreenScope = {
|
||||
[key: string]: unknown;
|
||||
screen: string;
|
||||
};
|
||||
|
||||
function requiresSourceRecovery(meta?: InvestmentResourceMeta): boolean {
|
||||
if (!meta || meta.unavailableReason) return false;
|
||||
const READ_INTERVAL_MS = 1_800_000;
|
||||
|
||||
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[]) {
|
||||
const mutation = apiQueryClient.useMutation("post", "/api/v1/tbank-sync", {
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const client = useQueryClient();
|
||||
const deniedRef = useRef(new Set<unknown>());
|
||||
const scopeKey = JSON.stringify(scope);
|
||||
|
||||
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
|
||||
= JSON.stringify(mutation.variables?.body) === scopeKey;
|
||||
|
||||
const observedRef = useRef("");
|
||||
|
||||
const ids = [
|
||||
...new Set([
|
||||
...(isCurrentMutation && mutation.data ? [mutation.data.id] : []),
|
||||
...resources
|
||||
.flatMap(({ meta }) =>
|
||||
meta ? [meta, ...(meta.dependencies ?? [])] : [],
|
||||
)
|
||||
.flatMap(meta =>
|
||||
meta.sync.id
|
||||
&& meta.sync.state === "running"
|
||||
? [meta.sync.id]
|
||||
: [],
|
||||
),
|
||||
]),
|
||||
];
|
||||
|
||||
const statuses = useAuthenticatedQueries(
|
||||
ids.map(id => ({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/tbank-sync/{id}", {
|
||||
params: { path: { id } },
|
||||
}),
|
||||
refetchInterval: (query: {
|
||||
state: { data?: { state: string }; error: unknown };
|
||||
}) =>
|
||||
!(
|
||||
query.state.error
|
||||
|| (query.state.data && query.state.data.state !== "running")
|
||||
) && STATUS_INTERVAL_MS,
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
retry: false,
|
||||
})),
|
||||
);
|
||||
function useScreenSync(_scope: ScreenScope, resources: ScreenResource[]) {
|
||||
const resourcesRef = useRef(resources);
|
||||
useEffect(() => {
|
||||
resourcesRef.current = resources;
|
||||
}, [resources]);
|
||||
|
||||
useEffect(() => {
|
||||
for (const status of statuses) {
|
||||
if (!status.error || deniedRef.current.has(status.error)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
deniedRef.current.add(status.error);
|
||||
if (!isApiErrorCode(apiErrorCode(status.error), ApiErrorCode.NotFound))
|
||||
invalidateResourceAccess(client, "brokerage", status.error);
|
||||
}
|
||||
|
||||
if (statuses.every(status => !status.data)) return;
|
||||
|
||||
const observation = JSON.stringify([
|
||||
scopeKey,
|
||||
statuses.map(status => [
|
||||
status.data?.id,
|
||||
status.data?.state,
|
||||
status.dataUpdatedAt,
|
||||
]),
|
||||
resources.map(resource => resource.queryKey),
|
||||
]);
|
||||
|
||||
if (observedRef.current === observation) return;
|
||||
observedRef.current = observation;
|
||||
|
||||
const isCompleted = statuses.every(
|
||||
status => status.data && status.data.state !== "running",
|
||||
);
|
||||
|
||||
for (const resource of resources)
|
||||
if (isCompleted || !resource.isFetching)
|
||||
void resource.observe().catch(() => {});
|
||||
}, [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);
|
||||
const timer = setInterval(() => {
|
||||
for (const resource of resourcesRef.current)
|
||||
void resource.refetch().catch(() => {});
|
||||
}, delay);
|
||||
}, READ_INTERVAL_MS);
|
||||
|
||||
sourceTimersRef.current.add(timer);
|
||||
}
|
||||
}, [resources, scopeKey]);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
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
|
||||
= (isCurrentMutation && mutation.isPending)
|
||||
|| statuses.some(
|
||||
status => !status.isError && status.data?.state === "running",
|
||||
)
|
||||
|| resources.some(({ meta }) => {
|
||||
const status = statuses[ids.indexOf(meta?.sync.id ?? "")];
|
||||
|
||||
return (
|
||||
!status?.isError
|
||||
&& (!status?.data || status.data.state === "running")
|
||||
&& meta?.sync.state === "running"
|
||||
);
|
||||
});
|
||||
const isRefreshing = resources.some(resource => resource.isFetching);
|
||||
|
||||
const refresh = async () => {
|
||||
if (isRefreshing || requestInFlightRef.current === scopeKey) return;
|
||||
requestInFlightRef.current = scopeKey;
|
||||
|
||||
try {
|
||||
await mutation.mutateAsync({ body: scope });
|
||||
}
|
||||
catch {
|
||||
/*
|
||||
The mutation retains the transport error for presentation.
|
||||
*/
|
||||
}
|
||||
finally {
|
||||
if (requestInFlightRef.current === scopeKey)
|
||||
requestInFlightRef.current
|
||||
|
||||
= null;
|
||||
}
|
||||
if (isRefreshing) return;
|
||||
await Promise.allSettled(resources.map(resource => resource.refetch()));
|
||||
};
|
||||
|
||||
// Retry failed HTTP reads without asking the source to import again.
|
||||
// A source failure (or explicit refresh with no read error) still needs a sync.
|
||||
// Retry only the HTTP read; source attempts are reported in resource metadata.
|
||||
const retry = async () => {
|
||||
const failed = resources.filter(
|
||||
resource => resource.isError,
|
||||
);
|
||||
const failed = resources.filter(resource => resource.isError);
|
||||
|
||||
const failedStatuses = statuses.filter(status => status.isError);
|
||||
if (failed.length > 0 || failedStatuses.length > 0) {
|
||||
await Promise.allSettled([
|
||||
...failed.map(resource => resource.observe()),
|
||||
...failedStatuses.map(status => status.refetch()),
|
||||
]);
|
||||
}
|
||||
if (failed.length > 0)
|
||||
await Promise.allSettled(failed.map(resource => resource.refetch()));
|
||||
else await refresh();
|
||||
};
|
||||
|
||||
@@ -271,13 +54,11 @@ function useScreenSync(scope: InvestmentScreen, resources: ScreenResource[]) {
|
||||
refresh,
|
||||
refreshing: isRefreshing,
|
||||
retry,
|
||||
sourceError:
|
||||
statuses.some(status => status.data?.state === "failed")
|
||||
|| resources.some(({ meta }) => meta?.sync.state === "failed"),
|
||||
transportError:
|
||||
(isCurrentMutation && mutation.isError)
|
||||
|| statuses.some(status => status.isError),
|
||||
sourceError: resources.some(
|
||||
({ meta }) => meta?.lastAttempt.state === "failed",
|
||||
),
|
||||
transportError: resources.some(resource => resource.isError),
|
||||
};
|
||||
}
|
||||
|
||||
export { type InvestmentScreen, useScreenSync };
|
||||
export { useScreenSync };
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { useBrokerageAccounts } from "@/entities/brokerage-account";
|
||||
import { apiQueryClient, configureAuthClient } from "@/shared/api";
|
||||
import { createQueryWrapper } from "@/test/query";
|
||||
import { resource } from "@/test/resource";
|
||||
import { server } from "@/test/server";
|
||||
|
||||
import type { InvestmentScreen } from "./screen-sync";
|
||||
|
||||
import { useScreenSync } from "../index";
|
||||
import { commitTbankConnectionBoundary } from "./connection-boundary";
|
||||
|
||||
describe("sync connection and session boundaries", () => {
|
||||
it.each(["connection", "session"])(
|
||||
"keeps old status out of the cache after %s changes",
|
||||
async (boundary) => {
|
||||
let generation = 0;
|
||||
configureAuthClient({
|
||||
accessToken: () => "synthetic",
|
||||
clear: vi.fn(),
|
||||
generation: () => generation,
|
||||
refresh: () => Promise.resolve(true),
|
||||
});
|
||||
|
||||
const { promise: blocked, resolve: release }
|
||||
= Promise.withResolvers<void>();
|
||||
|
||||
const accepted = {
|
||||
id: "work",
|
||||
now: "2026-09-25T12:00:00Z",
|
||||
scope: { screen: "accounts" },
|
||||
};
|
||||
|
||||
let started = 0;
|
||||
let isChanged = false;
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", () =>
|
||||
HttpResponse.json(resource([], {
|
||||
sync: { errorCode: null, id: "work", state: "running" },
|
||||
})),
|
||||
),
|
||||
http.post("*/api/v1/tbank-sync", async () => {
|
||||
started += 1;
|
||||
await blocked;
|
||||
|
||||
return HttpResponse.json(accepted, { status: 202 });
|
||||
}),
|
||||
http.get("*/api/v1/tbank-sync/:id", async () => {
|
||||
const now = isChanged ? "2026-09-25T12:01:00Z" : accepted.now;
|
||||
started += 1;
|
||||
await blocked;
|
||||
|
||||
return HttpResponse.json(
|
||||
{
|
||||
...accepted,
|
||||
errorCode: null,
|
||||
now,
|
||||
state: "succeeded",
|
||||
},
|
||||
);
|
||||
}),
|
||||
);
|
||||
const { queryClient, wrapper } = createQueryWrapper();
|
||||
const published: string[] = [];
|
||||
|
||||
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
|
||||
if (
|
||||
(event.query.queryKey as readonly unknown[])[1]
|
||||
!== "/api/v1/tbank-sync/{id}"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const data = event.query.state.data as undefined | { now?: string };
|
||||
if (data?.now) published.push(data.now);
|
||||
});
|
||||
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const accounts = useBrokerageAccounts();
|
||||
useScreenSync({ screen: "accounts" }, [accounts]);
|
||||
|
||||
return {
|
||||
mutation: apiQueryClient.useMutation("post", "/api/v1/tbank-sync", {
|
||||
retry: false,
|
||||
}),
|
||||
};
|
||||
},
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
const screen: InvestmentScreen = { screen: "accounts" };
|
||||
let mutation!: Promise<unknown>;
|
||||
act(() => {
|
||||
mutation = result.current.mutation.mutateAsync({ body: screen });
|
||||
});
|
||||
|
||||
// eslint-disable-next-line unicorn/prefer-await -- Handle rejection before changing the boundary and releasing the pending response.
|
||||
const settled = mutation.catch(() => {});
|
||||
|
||||
await waitFor(() => expect(started).toBe(2));
|
||||
await act(async () => {
|
||||
isChanged = true;
|
||||
|
||||
if (boundary === "connection")
|
||||
commitTbankConnectionBoundary(
|
||||
|
||||
queryClient,
|
||||
{
|
||||
connected: false,
|
||||
connectedAt: null,
|
||||
},
|
||||
);
|
||||
else {
|
||||
generation += 1;
|
||||
queryClient.clear();
|
||||
}
|
||||
|
||||
release();
|
||||
await blocked;
|
||||
});
|
||||
await settled;
|
||||
|
||||
const key = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/tbank-sync/{id}",
|
||||
{ params: { path: { id: "work" } } },
|
||||
).queryKey;
|
||||
|
||||
// A new request may start after a successful connection boundary; an old result cannot win it.
|
||||
if (boundary === "session")
|
||||
// eslint-disable-next-line vitest/no-conditional-expect -- The fixed table case selects the expected outcome; every case asserts its own branch.
|
||||
expect(queryClient.getQueryData(key)).toBeUndefined();
|
||||
else
|
||||
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(queryClient.getQueryData(key)).toMatchObject({
|
||||
now: "2026-09-25T12:01:00Z",
|
||||
}),
|
||||
);
|
||||
expect(published).not.toContain(accepted.now);
|
||||
unsubscribe();
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -123,9 +123,10 @@ describe("Upcoming event date filters", () => {
|
||||
resource(
|
||||
null,
|
||||
{
|
||||
sync: {
|
||||
errorCode: "TBANK_UNAVAILABLE",
|
||||
id: null,
|
||||
lastAttempt: {
|
||||
finishedAt: "2026-08-14T00:01:00Z",
|
||||
problems: [],
|
||||
startedAt: "2026-08-14T00:00:00Z",
|
||||
state: "failed",
|
||||
},
|
||||
},
|
||||
@@ -309,7 +310,14 @@ it("retains the previous complete forecast when its source refresh fails", async
|
||||
|
||||
const snapshot = resource(
|
||||
{ events, incomeTotalsByCurrency: [{ currency: "RUB", value: "123.45" }] },
|
||||
{ sync: { errorCode: "TBANK_UNAVAILABLE", id: "failed", state: "failed" } },
|
||||
{
|
||||
lastAttempt: {
|
||||
finishedAt: "2026-08-14T00:01:00Z",
|
||||
problems: [],
|
||||
startedAt: "2026-08-14T00:00:00Z",
|
||||
state: "failed",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
server.use(
|
||||
|
||||
@@ -51,8 +51,9 @@ describe("AccountEventsPage", () => {
|
||||
isError: false,
|
||||
isLoading: false,
|
||||
meta: {
|
||||
availability: "complete",
|
||||
sync: { errorCode: null, id: null, state: "idle" },
|
||||
availability: "available",
|
||||
completeness: "complete",
|
||||
lastAttempt: { finishedAt: null, problems: [], startedAt: null, state: "none" },
|
||||
},
|
||||
refetch: vi.fn(),
|
||||
} as never,
|
||||
@@ -85,8 +86,9 @@ describe("AccountEventsPage", () => {
|
||||
isError: false,
|
||||
isLoading: false,
|
||||
meta: {
|
||||
availability: "complete",
|
||||
sync: { errorCode: null, id: null, state: "idle" },
|
||||
availability: "available",
|
||||
completeness: "complete",
|
||||
lastAttempt: { finishedAt: null, problems: [], startedAt: null, state: "none" },
|
||||
},
|
||||
refetch: vi.fn(),
|
||||
} as never,
|
||||
@@ -138,8 +140,9 @@ describe("AccountEventsPage", () => {
|
||||
isError: false,
|
||||
isLoading: false,
|
||||
meta: {
|
||||
availability: "complete",
|
||||
sync: { errorCode: null, id: null, state: "idle" },
|
||||
availability: "available",
|
||||
completeness: "complete",
|
||||
lastAttempt: { finishedAt: null, problems: [], startedAt: null, state: "none" },
|
||||
},
|
||||
refetch: vi.fn(),
|
||||
} as never,
|
||||
@@ -194,8 +197,9 @@ describe("AccountEventsPage", () => {
|
||||
isError: false,
|
||||
isLoading: true,
|
||||
meta: {
|
||||
availability: "complete",
|
||||
sync: { errorCode: null, id: null, state: "idle" },
|
||||
availability: "available",
|
||||
completeness: "complete",
|
||||
lastAttempt: { finishedAt: null, problems: [], startedAt: null, state: "none" },
|
||||
},
|
||||
refetch: vi.fn(),
|
||||
} as never,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useState } from "react";
|
||||
import { useParams } from "react-router";
|
||||
|
||||
import type { InvestmentResourceMeta } from "@/shared/api";
|
||||
|
||||
import {
|
||||
type BrokerageEvent,
|
||||
useBrokerageEvents,
|
||||
@@ -25,6 +27,7 @@ type AccountEventsPageViewModel
|
||||
onPeriodPopoverOpen: () => void;
|
||||
onReset: () => void;
|
||||
partial?: boolean;
|
||||
source?: InvestmentResourceMeta;
|
||||
state: "loaded";
|
||||
}
|
||||
| { onReset: () => void; state: "error" }
|
||||
@@ -74,7 +77,7 @@ function useAccountEventsPageViewModel(): AccountEventsPageViewModel {
|
||||
const availability = useInitialAvailability({
|
||||
hasContent: !!events.data,
|
||||
identity: scope,
|
||||
isError: events.isError || events.meta?.sync.state === "failed",
|
||||
isError: events.isError || events.meta?.lastAttempt.state === "failed",
|
||||
isFetching: events.isFetching,
|
||||
});
|
||||
|
||||
@@ -86,7 +89,7 @@ function useAccountEventsPageViewModel(): AccountEventsPageViewModel {
|
||||
setSearchParameters({});
|
||||
};
|
||||
|
||||
if ((events.isError || events.meta?.sync.state === "failed") && !events.data)
|
||||
if ((events.isError || events.meta?.lastAttempt.state === "failed") && !events.data)
|
||||
return {
|
||||
onReset,
|
||||
state: "error",
|
||||
@@ -115,7 +118,8 @@ function useAccountEventsPageViewModel(): AccountEventsPageViewModel {
|
||||
),
|
||||
onPeriodPopoverOpen: () => setMaxDate(moscowDate(new Date())),
|
||||
onReset,
|
||||
partial: events.meta?.availability !== "complete",
|
||||
partial: events.meta?.completeness === "incomplete",
|
||||
source: events.meta,
|
||||
state: "loaded",
|
||||
};
|
||||
}
|
||||
|
||||
+7
@@ -15,6 +15,7 @@ import {
|
||||
BrokerageEventCard,
|
||||
brokerageEventKey,
|
||||
} from "@/entities/brokerage-event";
|
||||
import { SourceSyncStatus } from "@/shared/ui";
|
||||
|
||||
import type { AccountEventsPageViewModel } from "../AccountEventsPage.vm";
|
||||
|
||||
@@ -55,6 +56,12 @@ const AccountEventsPageLoaded: FC<AccountEventsPageLoadedProps> = (props) => {
|
||||
<Stack gap="lg">
|
||||
<Title order={1}>{t("events.title")}</Title>
|
||||
|
||||
<SourceSyncStatus
|
||||
lastAttempt={props.source?.lastAttempt}
|
||||
lastSuccessfulAt={props.source?.lastSuccessfulAt}
|
||||
stale={props.source?.freshness === "stale"}
|
||||
/>
|
||||
|
||||
{!!props.partial && <Alert role="status">{t("investment.partial")}</Alert>}
|
||||
|
||||
<Text c="dimmed">{t("events.hint")}</Text>
|
||||
|
||||
@@ -136,13 +136,14 @@ it("maps comparison notices by role regardless of dependency order or resource k
|
||||
const previous
|
||||
= {
|
||||
...resource(null).meta,
|
||||
resourceKey: "opaque/year-looking-key",
|
||||
role: "previous" as const,
|
||||
sync: {
|
||||
errorCode: "TBANK_UNAVAILABLE",
|
||||
id: null,
|
||||
lastAttempt: {
|
||||
finishedAt: "2026-08-14T00:01:00Z",
|
||||
problems: [],
|
||||
startedAt: "2026-08-14T00:00:00Z",
|
||||
state: "failed" as const,
|
||||
},
|
||||
resourceKey: "opaque/year-looking-key",
|
||||
role: "previous" as const,
|
||||
};
|
||||
|
||||
const year = {
|
||||
|
||||
@@ -66,7 +66,7 @@ function comparisonNotice(
|
||||
): ComparisonNotice {
|
||||
if (!dependency || dependency.unavailableReason) return unavailable;
|
||||
|
||||
return dependency.sync.state === "failed"
|
||||
return dependency.lastAttempt.state === "failed"
|
||||
? "comparisonFailed"
|
||||
: "comparisonPending";
|
||||
}
|
||||
|
||||
@@ -205,9 +205,10 @@ describe("AccountIncomePage", () => {
|
||||
resource(
|
||||
null,
|
||||
{
|
||||
sync: {
|
||||
errorCode: "TBANK_UNAVAILABLE",
|
||||
id: null,
|
||||
lastAttempt: {
|
||||
finishedAt: "2026-08-14T00:01:00Z",
|
||||
problems: [],
|
||||
startedAt: "2026-08-14T00:00:00Z",
|
||||
state: "failed",
|
||||
},
|
||||
},
|
||||
@@ -832,12 +833,13 @@ it("keeps complete previous comparison while year source failed without inventin
|
||||
},
|
||||
{
|
||||
...resource(null).meta,
|
||||
role: "year" as const,
|
||||
sync: {
|
||||
errorCode: "TBANK_UNAVAILABLE",
|
||||
id: null,
|
||||
lastAttempt: {
|
||||
finishedAt: "2026-08-14T00:01:00Z",
|
||||
problems: [],
|
||||
startedAt: "2026-08-14T00:00:00Z",
|
||||
state: "failed" as const,
|
||||
},
|
||||
role: "year" as const,
|
||||
},
|
||||
{
|
||||
...resource(analytics).meta,
|
||||
|
||||
@@ -79,7 +79,7 @@ const useAccountIncomePageViewModel = (): AccountIncomePageViewModel => {
|
||||
const availability = useInitialAvailability({
|
||||
hasContent: !!analytics.data,
|
||||
identity: `${accountId}:${period.from}:${period.to}`,
|
||||
isError: analytics.isError || analytics.meta?.sync.state === "failed",
|
||||
isError: analytics.isError || analytics.meta?.lastAttempt.state === "failed",
|
||||
isFetching: analytics.isFetching,
|
||||
});
|
||||
|
||||
@@ -114,7 +114,7 @@ const useAccountIncomePageViewModel = (): AccountIncomePageViewModel => {
|
||||
formRevision: `${accountId}:${period.from}:${period.to}:${resetRevision}`,
|
||||
onReset,
|
||||
onSubmit,
|
||||
partial: analytics.meta?.availability !== "complete",
|
||||
partial: analytics.meta?.completeness === "incomplete",
|
||||
state: "loaded",
|
||||
};
|
||||
};
|
||||
|
||||
+5
-11
@@ -497,7 +497,6 @@ describe("AccountOperationsPage", () => {
|
||||
it("keeps UTC operation boundaries in GET and source sync requests", async () => {
|
||||
configureTestAuth();
|
||||
const requested: Record<string, string>[] = [];
|
||||
const syncRequests: unknown[] = [];
|
||||
server.use(
|
||||
http.get(
|
||||
"*/api/v1/brokerage-accounts/:accountId/operations",
|
||||
@@ -508,9 +507,10 @@ it("keeps UTC operation boundaries in GET and source sync requests", async () =>
|
||||
resource(
|
||||
null,
|
||||
{
|
||||
sync: {
|
||||
errorCode: "TBANK_UNAVAILABLE",
|
||||
id: null,
|
||||
lastAttempt: {
|
||||
finishedAt: "2026-08-14T00:01:00Z",
|
||||
problems: [],
|
||||
startedAt: "2026-08-14T00:00:00Z",
|
||||
state: "failed",
|
||||
},
|
||||
},
|
||||
@@ -518,11 +518,6 @@ it("keeps UTC operation boundaries in GET and source sync requests", async () =>
|
||||
);
|
||||
},
|
||||
),
|
||||
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&categories=trade");
|
||||
await screen.findByRole("button", { name: "Сбросить" });
|
||||
@@ -534,7 +529,6 @@ it("keeps UTC operation boundaries in GET and source sync requests", async () =>
|
||||
to: "2024-03-01T23:59:59.999Z",
|
||||
},
|
||||
]);
|
||||
expect(syncRequests).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not label incomplete empty operations as a confirmed empty period", async () => {
|
||||
@@ -550,7 +544,7 @@ it("does not label incomplete empty operations as a confirmed empty period", asy
|
||||
items: [],
|
||||
nextCursor: null,
|
||||
},
|
||||
{ availability: "partial" },
|
||||
{ completeness: "incomplete" },
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -2,6 +2,8 @@ import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
import { useParams } from "react-router";
|
||||
|
||||
import type { InvestmentResourceMeta } from "@/shared/api";
|
||||
|
||||
import {
|
||||
type BrokerageOperation,
|
||||
brokerageOperationsQueryOptions,
|
||||
@@ -39,6 +41,7 @@ type AccountOperationsPageViewModel
|
||||
onPrevious: () => void;
|
||||
onReset: () => void;
|
||||
partial?: boolean;
|
||||
source?: InvestmentResourceMeta;
|
||||
state: "loaded";
|
||||
}
|
||||
| { onReset: () => void; state: "error" }
|
||||
@@ -98,7 +101,7 @@ const useAccountOperationsPageVm = (): AccountOperationsPageViewModel => {
|
||||
const availability = useInitialAvailability({
|
||||
hasContent: !!operations.data,
|
||||
identity: scope,
|
||||
isError: operations.isError || operations.meta?.sync.state === "failed",
|
||||
isError: operations.isError || operations.meta?.lastAttempt.state === "failed",
|
||||
isFetching: operations.isFetching,
|
||||
});
|
||||
|
||||
@@ -127,7 +130,7 @@ const useAccountOperationsPageVm = (): AccountOperationsPageViewModel => {
|
||||
|
||||
if (
|
||||
(isInvalidCursor || !operations.data)
|
||||
&& (operations.isError || operations.meta?.sync.state === "failed")
|
||||
&& (operations.isError || operations.meta?.lastAttempt.state === "failed")
|
||||
)
|
||||
return { onReset, state: "error" };
|
||||
|
||||
@@ -177,7 +180,8 @@ const useAccountOperationsPageVm = (): AccountOperationsPageViewModel => {
|
||||
onPeriodPopoverOpen: () => setMaxDate(moscowDate(new Date())),
|
||||
onPrevious: history.onPrevious,
|
||||
onReset,
|
||||
partial: operations.meta?.availability !== "complete",
|
||||
partial: operations.meta?.completeness === "incomplete",
|
||||
source: operations.meta,
|
||||
state: "loaded",
|
||||
};
|
||||
};
|
||||
|
||||
+7
@@ -13,6 +13,7 @@ import { StateView } from "@wealthledger/ui";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { LedgerEntryRow, operationCategories } from "@/entities/broker-operation";
|
||||
import { SourceSyncStatus } from "@/shared/ui";
|
||||
|
||||
import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm";
|
||||
|
||||
@@ -62,6 +63,12 @@ const AccountOperationsPageLoaded: FC<AccountOperationsPageLoadedProps> = (
|
||||
<Stack gap="lg">
|
||||
<Title order={1}>{t("ledger.title")}</Title>
|
||||
|
||||
<SourceSyncStatus
|
||||
lastAttempt={props.source?.lastAttempt}
|
||||
lastSuccessfulAt={props.source?.lastSuccessfulAt}
|
||||
stale={props.source?.freshness === "stale"}
|
||||
/>
|
||||
|
||||
{!!props.partial && <Alert role="status">{t("investment.partial")}</Alert>}
|
||||
|
||||
{!!props.historyLoading && <Alert>{t("investment.history")}</Alert>}
|
||||
|
||||
@@ -46,9 +46,10 @@ type PreviewResource<T> = {
|
||||
isError: boolean;
|
||||
meta?: Pick<InvestmentResourceMeta,
|
||||
"availability"
|
||||
| "completeness"
|
||||
| "freshness"
|
||||
| "lastAttempt"
|
||||
| "lastSuccessfulAt"
|
||||
| "sync"
|
||||
>;
|
||||
};
|
||||
|
||||
@@ -57,10 +58,10 @@ function toIncomeSummary(
|
||||
income: PreviewResource<IncomeSummary>,
|
||||
): AccountPageIncomeSummary {
|
||||
const to = `/accounts/${accountId}/income`;
|
||||
if (!income.data && !income.isError && income.meta?.sync.state !== "failed")
|
||||
if (!income.data && !income.isError && income.meta?.lastAttempt.state !== "failed")
|
||||
return { state: "loading", to };
|
||||
if (income.meta?.availability === "partial") return { state: "partial", to };
|
||||
if (!income.data && (income.isError || income.meta?.sync.state === "failed"))
|
||||
if (income.meta?.completeness === "incomplete") return { state: "partial", to };
|
||||
if (!income.data && (income.isError || income.meta?.lastAttempt.state === "failed"))
|
||||
return { state: "error", to };
|
||||
if (!income.data?.totalsByCurrency.length) return { state: "empty", to };
|
||||
|
||||
@@ -76,15 +77,15 @@ function toRecentEvents(
|
||||
events: PreviewResource<{ events: BrokerageEvent[] }>,
|
||||
): AccountPageRecentEvents {
|
||||
const to = `/accounts/${accountId}/events`;
|
||||
if (!events.data && !events.isError && events.meta?.sync.state !== "failed")
|
||||
if (!events.data && !events.isError && events.meta?.lastAttempt.state !== "failed")
|
||||
return { state: "loading", to };
|
||||
if (events.meta?.availability === "partial")
|
||||
if (events.meta?.completeness === "incomplete")
|
||||
return {
|
||||
items: events.data?.events.slice(0, RECENT_EVENTS_LIMIT) ?? [],
|
||||
state: "partial",
|
||||
to,
|
||||
};
|
||||
if (!events.data && (events.isError || events.meta?.sync.state === "failed"))
|
||||
if (!events.data && (events.isError || events.meta?.lastAttempt.state === "failed"))
|
||||
return { state: "error", to };
|
||||
const items = events.data?.events.slice(0, RECENT_EVENTS_LIMIT) ?? [];
|
||||
if (items.length === 0) return { state: "empty", to };
|
||||
@@ -104,14 +105,14 @@ function toRecentOperations(
|
||||
if (
|
||||
!operations.data
|
||||
&& !operations.isError
|
||||
&& operations.meta?.sync.state !== "failed"
|
||||
&& operations.meta?.lastAttempt.state !== "failed"
|
||||
)
|
||||
return { state: "loading", to };
|
||||
if (operations.meta?.availability === "partial")
|
||||
if (operations.meta?.completeness === "incomplete")
|
||||
return { items: operations.data?.items ?? [], state: "partial", to };
|
||||
if (
|
||||
!operations.data
|
||||
&& (operations.isError || operations.meta?.sync.state === "failed")
|
||||
&& (operations.isError || operations.meta?.lastAttempt.state === "failed")
|
||||
)
|
||||
return { state: "error", to };
|
||||
if (!operations.data?.items.length) return { state: "empty", to };
|
||||
@@ -120,7 +121,7 @@ function toRecentOperations(
|
||||
items: operations.data.items,
|
||||
lastSuccessfulAt: operations.meta?.lastSuccessfulAt,
|
||||
refreshError:
|
||||
operations.isError || operations.meta?.sync.state === "failed",
|
||||
operations.isError || operations.meta?.lastAttempt.state === "failed",
|
||||
stale: operations.meta?.freshness === "stale",
|
||||
state: "loaded",
|
||||
to,
|
||||
|
||||
@@ -770,28 +770,6 @@ describe("AccountPage states", () => {
|
||||
let requestCount = 0;
|
||||
let resolveRetry: ((response: Response) => void) | undefined;
|
||||
server.use(
|
||||
http.post("*/api/v1/tbank-sync", () =>
|
||||
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: { accountId: "account-1", screen: "account" },
|
||||
state: "succeeded",
|
||||
},
|
||||
),
|
||||
),
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () => {
|
||||
requestCount += 1;
|
||||
if (requestCount === 1)
|
||||
|
||||
@@ -173,14 +173,14 @@ it("keeps overview sections independent when their source data is incomplete", a
|
||||
mockLoadedAccountPage();
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
|
||||
HttpResponse.json(resource(portfolio, { availability: "partial" })),
|
||||
HttpResponse.json(resource(portfolio, { completeness: "incomplete" })),
|
||||
),
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/operations", () =>
|
||||
HttpResponse.json(
|
||||
|
||||
resource(
|
||||
{ hasNext: false, items: [], nextCursor: null },
|
||||
{ availability: "partial" },
|
||||
{ completeness: "incomplete" },
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -188,7 +188,7 @@ it("keeps overview sections independent when their source data is incomplete", a
|
||||
HttpResponse.json(
|
||||
resource(
|
||||
{ events: [], incomeTotalsByCurrency: [] },
|
||||
{ availability: "partial" },
|
||||
{ completeness: "incomplete" },
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useParams } from "react-router";
|
||||
|
||||
import type { Portfolio } from "@/entities/portfolio";
|
||||
import type { InvestmentResourceMeta } from "@/shared/api";
|
||||
|
||||
import { useBrokerageOperations } from "@/entities/broker-operation";
|
||||
import {
|
||||
@@ -45,6 +46,7 @@ type AccountPageEmptyViewModel = AccountPageContent & {
|
||||
type AccountPageLoadedViewModel = AccountPageContent & {
|
||||
portfolio: Portfolio;
|
||||
positionSections: AccountPagePositionSection[];
|
||||
source?: InvestmentResourceMeta;
|
||||
state: "loaded";
|
||||
};
|
||||
|
||||
@@ -87,7 +89,7 @@ function useAccountPageViewModel(): AccountPageViewModel {
|
||||
const availability = useInitialAvailability({
|
||||
hasContent: !!portfolio.data,
|
||||
identity: accountId ?? "account",
|
||||
isError: portfolio.isError || portfolio.meta?.sync.state === "failed",
|
||||
isError: portfolio.isError || portfolio.meta?.lastAttempt.state === "failed",
|
||||
isFetching: portfolio.isFetching,
|
||||
});
|
||||
|
||||
@@ -105,7 +107,7 @@ function useAccountPageViewModel(): AccountPageViewModel {
|
||||
const incomeSummary = toIncomeSummary(accountId, income);
|
||||
|
||||
if (
|
||||
portfolio.meta?.availability === "complete"
|
||||
portfolio.meta?.availability === "available"
|
||||
&& portfolio.data.positions.length === 0
|
||||
&& portfolio.data.cashBalances.length === 0
|
||||
)
|
||||
@@ -118,7 +120,7 @@ function useAccountPageViewModel(): AccountPageViewModel {
|
||||
state: "empty" as const,
|
||||
};
|
||||
|
||||
const isPartial = portfolio.meta?.availability === "partial";
|
||||
const isPartial = portfolio.meta?.completeness === "incomplete";
|
||||
|
||||
return {
|
||||
account,
|
||||
@@ -129,6 +131,7 @@ function useAccountPageViewModel(): AccountPageViewModel {
|
||||
positionSections: toAccountPagePositionSections(portfolio.data),
|
||||
recentEvents,
|
||||
recentOperations,
|
||||
source: portfolio.meta,
|
||||
state: "loaded" as const,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -5,8 +5,10 @@ import { useTranslation } from "react-i18next";
|
||||
|
||||
import type { BrokerageAccount } from "@/entities/brokerage-account";
|
||||
import type { Portfolio } from "@/entities/portfolio";
|
||||
import type { InvestmentResourceMeta } from "@/shared/api";
|
||||
|
||||
import { BrokerageEventsPreview } from "@/entities/brokerage-event";
|
||||
import { SourceSyncStatus } from "@/shared/ui";
|
||||
import { PortfolioStructure } from "@/widgets/portfolio-structure";
|
||||
|
||||
import type { AccountPagePositionSection } from "../../../model/positions";
|
||||
@@ -32,6 +34,7 @@ type AccountPageLoadedProps = {
|
||||
positionSections: AccountPagePositionSection[];
|
||||
recentEvents: AccountPageRecentEvents;
|
||||
recentOperations: AccountPageRecentOperations;
|
||||
source?: InvestmentResourceMeta;
|
||||
};
|
||||
|
||||
const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
|
||||
@@ -49,6 +52,12 @@ const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
|
||||
<Stack gap="lg">
|
||||
<AccountHeading account={props.account} accountId={props.accountId} />
|
||||
|
||||
<SourceSyncStatus
|
||||
lastAttempt={props.source?.lastAttempt}
|
||||
lastSuccessfulAt={props.source?.lastSuccessfulAt}
|
||||
stale={props.source?.freshness === "stale"}
|
||||
/>
|
||||
|
||||
{props.partial
|
||||
? <Alert role="status">{t("investment.partial")}</Alert>
|
||||
: <CurrencyCards amounts={props.portfolio.totalsByCurrency} />}
|
||||
|
||||
@@ -130,17 +130,6 @@ describe("AccountsPage", () => {
|
||||
});
|
||||
|
||||
it("keeps the cached account list quietly after a refresh error", async () => {
|
||||
const requests: unknown[] = [];
|
||||
server.use(
|
||||
http.post("*/api/v1/tbank-sync", async ({ request }) => {
|
||||
requests.push(await request.json());
|
||||
|
||||
return HttpResponse.json(
|
||||
{ code: "TBANK_UNAVAILABLE" },
|
||||
{ status: 503 },
|
||||
);
|
||||
}),
|
||||
);
|
||||
let requestCount = 0;
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", () => {
|
||||
@@ -169,7 +158,6 @@ describe("AccountsPage", () => {
|
||||
expect(screen.queryByRole("button", { name: "Повторить" }))
|
||||
.not.toBeInTheDocument();
|
||||
expect(screen.getByText(account.name)).toBeInTheDocument();
|
||||
expect(requests).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps a cached empty account list visible after a refresh error", async () => {
|
||||
@@ -201,14 +189,19 @@ describe("AccountsPage", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["idle", "failed"] as const)(
|
||||
"keeps partial empty membership distinct from no accounts (sync=%s)",
|
||||
it.each(["none", "failed"] as const)(
|
||||
"keeps incomplete empty membership distinct from no accounts (attempt=%s)",
|
||||
async (state) => {
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", () =>
|
||||
HttpResponse.json(resource([], {
|
||||
availability: "partial",
|
||||
sync: { errorCode: null, id: null, state },
|
||||
completeness: "incomplete",
|
||||
lastAttempt: {
|
||||
finishedAt: state === "failed" ? "2026-08-14T00:01:00Z" : null,
|
||||
problems: [],
|
||||
startedAt: state === "none" ? null : "2026-08-14T00:00:00Z",
|
||||
state,
|
||||
},
|
||||
})),
|
||||
),
|
||||
);
|
||||
@@ -217,7 +210,7 @@ it.each(["idle", "failed"] as const)(
|
||||
await waitFor(() =>
|
||||
expect(client.getQueryData(brokerageAccountsQueryKey)).toMatchObject({
|
||||
data: [],
|
||||
meta: { availability: "partial" },
|
||||
meta: { completeness: "incomplete" },
|
||||
}),
|
||||
);
|
||||
expect(screen.queryByText("Нет инвестиционных счетов"))
|
||||
|
||||
@@ -15,6 +15,7 @@ const AccountsPage: FC = () => {
|
||||
return (
|
||||
<AccountsPageLoaded
|
||||
accounts={viewModel.accounts}
|
||||
meta={viewModel.meta}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -8,7 +8,7 @@ import { ApiErrorCode, apiErrorCode, isApiErrorCode } from "@/shared/api";
|
||||
import { useInitialAvailability } from "@/shared/lib";
|
||||
|
||||
type AccountsPageViewModel
|
||||
= | { accounts: BrokerageAccountCard[]; state: "loaded" }
|
||||
= | { accounts: BrokerageAccountCard[]; meta: NonNullable<ReturnType<typeof useBrokerageAccounts>["meta"]>; state: "loaded" }
|
||||
| { code?: string; state: "error" }
|
||||
| { state: "empty" }
|
||||
| { state: "loading" };
|
||||
@@ -26,12 +26,13 @@ function useAccountsPageViewModel(): AccountsPageViewModel {
|
||||
const isAccessFailure = isAccountsAccessFailure(code);
|
||||
|
||||
const hasResult = !!accounts.data
|
||||
&& !(accounts.meta?.availability === "partial" && accounts.data.length === 0);
|
||||
&& !!accounts.meta
|
||||
&& !(accounts.meta.completeness === "incomplete" && accounts.data.length === 0);
|
||||
|
||||
const availability = useInitialAvailability({
|
||||
hasContent: hasResult,
|
||||
identity: "accounts",
|
||||
isError: accounts.isError || accounts.meta?.sync.state === "failed",
|
||||
isError: accounts.isError || accounts.meta?.lastAttempt.state === "failed",
|
||||
isFetching: accounts.isFetching,
|
||||
});
|
||||
|
||||
@@ -47,8 +48,12 @@ function useAccountsPageViewModel(): AccountsPageViewModel {
|
||||
state: "empty" as const,
|
||||
};
|
||||
|
||||
const meta = accounts.meta;
|
||||
if (!meta) return { state: "loading" as const };
|
||||
|
||||
return {
|
||||
accounts: brokerageAccountCards(accounts.data, accounts.meta?.dependencies),
|
||||
accounts: brokerageAccountCards(accounts.data, meta.dependencies),
|
||||
meta,
|
||||
state: "loaded" as const,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,13 +4,17 @@ import { Button, Stack, Text, Title } from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
|
||||
import type { InvestmentResourceMeta } from "@/shared/api";
|
||||
|
||||
import {
|
||||
type BrokerageAccountCard,
|
||||
BrokerageAccountList,
|
||||
} from "@/entities/brokerage-account";
|
||||
import { SourceSyncStatus } from "@/shared/ui";
|
||||
|
||||
type AccountsPageLoadedProps = {
|
||||
accounts: BrokerageAccountCard[];
|
||||
meta: InvestmentResourceMeta;
|
||||
};
|
||||
|
||||
const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
|
||||
@@ -24,6 +28,12 @@ const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("accounts.subtitle")}
|
||||
</Text>
|
||||
|
||||
<SourceSyncStatus
|
||||
lastAttempt={props.meta.lastAttempt}
|
||||
lastSuccessfulAt={props.meta.lastSuccessfulAt}
|
||||
stale={props.meta.freshness === "stale"}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<Button
|
||||
|
||||
@@ -17,7 +17,7 @@ function useBondsPageVm() {
|
||||
code: apiErrorCode(result.error),
|
||||
error:
|
||||
!result.data
|
||||
&& (result.isError || result.meta?.sync.state === "failed"),
|
||||
&& (result.isError || result.meta?.lastAttempt.state === "failed"),
|
||||
items:
|
||||
result.data?.map(bond => ({
|
||||
...bond,
|
||||
@@ -29,9 +29,9 @@ function useBondsPageVm() {
|
||||
&& (isWaiting
|
||||
|| (!result.data
|
||||
&& !result.isError
|
||||
&& result.meta?.sync.state !== "failed")),
|
||||
&& result.meta?.lastAttempt.state !== "failed")),
|
||||
onQueryChange: search.onQueryChange,
|
||||
partial: result.meta?.availability === "partial",
|
||||
partial: result.meta?.completeness === "incomplete",
|
||||
query,
|
||||
ready:
|
||||
debounced.length >= MIN_BOND_SEARCH_LENGTH
|
||||
|
||||
@@ -17,7 +17,7 @@ function useStocksPageVm() {
|
||||
code: apiErrorCode(result.error),
|
||||
error:
|
||||
!result.data
|
||||
&& (result.isError || result.meta?.sync.state === "failed"),
|
||||
&& (result.isError || result.meta?.lastAttempt.state === "failed"),
|
||||
items:
|
||||
result.data?.map(stock => ({
|
||||
...stock,
|
||||
@@ -29,9 +29,9 @@ function useStocksPageVm() {
|
||||
&& (isWaiting
|
||||
|| (!result.data
|
||||
&& !result.isError
|
||||
&& result.meta?.sync.state !== "failed")),
|
||||
&& result.meta?.lastAttempt.state !== "failed")),
|
||||
onQueryChange: search.onQueryChange,
|
||||
partial: result.meta?.availability === "partial",
|
||||
partial: result.meta?.completeness === "incomplete",
|
||||
query,
|
||||
ready:
|
||||
debounced.length >= MIN_STOCK_SEARCH_LENGTH
|
||||
|
||||
Vendored
+69
-138
@@ -676,22 +676,6 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/tbank-sync": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
post: operations["TbankSyncController_request"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/tbank-sync/{id}": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -725,7 +709,10 @@ export interface components {
|
||||
* }
|
||||
* ]
|
||||
*/
|
||||
errors?: string[];
|
||||
errors?: {
|
||||
pointer: string;
|
||||
detail: string;
|
||||
}[];
|
||||
};
|
||||
CredentialsDto: {
|
||||
/** @example user@example.com */
|
||||
@@ -912,24 +899,35 @@ export interface components {
|
||||
/** @enum {string} */
|
||||
historyState: "missing" | "loading" | "partial" | "complete" | "failed";
|
||||
};
|
||||
InvestmentSyncDto: {
|
||||
id: string | null;
|
||||
InvestmentAttemptProblemDto: {
|
||||
/** @enum {string} */
|
||||
state: "idle" | "running" | "failed";
|
||||
section: "membership" | "portfolio" | "operations" | "events";
|
||||
accountId: string | null;
|
||||
errorCode: string | null;
|
||||
};
|
||||
InvestmentAttemptDto: {
|
||||
/** @enum {string} */
|
||||
state: "none" | "running" | "succeeded" | "partial" | "failed";
|
||||
/** Format: date-time */
|
||||
startedAt: string | null;
|
||||
/** Format: date-time */
|
||||
finishedAt: string | null;
|
||||
problems: components["schemas"]["InvestmentAttemptProblemDto"][];
|
||||
};
|
||||
InvestmentDependencyDto: {
|
||||
dataRevision: string;
|
||||
unavailableReason?: string;
|
||||
coverage?: components["schemas"]["InvestmentCoverageDto"];
|
||||
resourceKey: string;
|
||||
/** @enum {string} */
|
||||
availability: "missing" | "partial" | "complete";
|
||||
availability: "available" | "initial-loading" | "temporarily-unavailable" | "connection-unavailable";
|
||||
/** @enum {string} */
|
||||
completeness: "complete" | "incomplete";
|
||||
/** @enum {string} */
|
||||
freshness: "unknown" | "fresh" | "stale";
|
||||
/** Format: date-time */
|
||||
lastSuccessfulAt: string | null;
|
||||
sync: components["schemas"]["InvestmentSyncDto"];
|
||||
lastAttempt: components["schemas"]["InvestmentAttemptDto"];
|
||||
};
|
||||
InvestmentResourceMetaDto: {
|
||||
dataRevision: string;
|
||||
@@ -937,17 +935,33 @@ export interface components {
|
||||
coverage?: components["schemas"]["InvestmentCoverageDto"];
|
||||
resourceKey: string;
|
||||
/** @enum {string} */
|
||||
availability: "missing" | "partial" | "complete";
|
||||
availability: "available" | "initial-loading" | "temporarily-unavailable" | "connection-unavailable";
|
||||
/** @enum {string} */
|
||||
completeness: "complete" | "incomplete";
|
||||
/** @enum {string} */
|
||||
freshness: "unknown" | "fresh" | "stale";
|
||||
/** Format: date-time */
|
||||
lastSuccessfulAt: string | null;
|
||||
sync: components["schemas"]["InvestmentSyncDto"];
|
||||
lastAttempt: components["schemas"]["InvestmentAttemptDto"];
|
||||
dependencies?: components["schemas"]["InvestmentDependencyDto"][];
|
||||
};
|
||||
HourlySyncStatusDto: {
|
||||
/**
|
||||
* @description Last hourly walk state. Cancelled means an interrupted attempt; its start still delays the next term.
|
||||
* @enum {string}
|
||||
*/
|
||||
state: "running" | "succeeded" | "partial" | "failed" | "cancelled";
|
||||
/** Format: date-time */
|
||||
startedAt: string;
|
||||
/** Format: date-time */
|
||||
finishedAt: string | null;
|
||||
problems: components["schemas"]["InvestmentAttemptProblemDto"][];
|
||||
};
|
||||
BrokerageAccountsResourceDto: {
|
||||
data: components["schemas"]["BrokerageAccountDto"][] | null;
|
||||
meta: components["schemas"]["InvestmentResourceMetaDto"];
|
||||
/** @description Read-only status of the last hourly walk for the current connection. Null when no walk attempt exists yet. */
|
||||
sync: components["schemas"]["HourlySyncStatusDto"] | null;
|
||||
};
|
||||
AccountReferenceDto: {
|
||||
id: string;
|
||||
@@ -1128,12 +1142,14 @@ export interface components {
|
||||
coverage?: components["schemas"]["InvestmentCoverageDto"];
|
||||
resourceKey: string;
|
||||
/** @enum {string} */
|
||||
availability: "missing" | "partial" | "complete";
|
||||
availability: "available" | "initial-loading" | "temporarily-unavailable" | "connection-unavailable";
|
||||
/** @enum {string} */
|
||||
completeness: "complete" | "incomplete";
|
||||
/** @enum {string} */
|
||||
freshness: "unknown" | "fresh" | "stale";
|
||||
/** Format: date-time */
|
||||
lastSuccessfulAt: string | null;
|
||||
sync: components["schemas"]["InvestmentSyncDto"];
|
||||
lastAttempt: components["schemas"]["InvestmentAttemptDto"];
|
||||
/** @enum {string} */
|
||||
role: "selected" | "previous" | "year";
|
||||
};
|
||||
@@ -1143,12 +1159,14 @@ export interface components {
|
||||
coverage?: components["schemas"]["InvestmentCoverageDto"];
|
||||
resourceKey: string;
|
||||
/** @enum {string} */
|
||||
availability: "missing" | "partial" | "complete";
|
||||
availability: "available" | "initial-loading" | "temporarily-unavailable" | "connection-unavailable";
|
||||
/** @enum {string} */
|
||||
completeness: "complete" | "incomplete";
|
||||
/** @enum {string} */
|
||||
freshness: "unknown" | "fresh" | "stale";
|
||||
/** Format: date-time */
|
||||
lastSuccessfulAt: string | null;
|
||||
sync: components["schemas"]["InvestmentSyncDto"];
|
||||
lastAttempt: components["schemas"]["InvestmentAttemptDto"];
|
||||
/** @description Dependencies identified by role, not array order or resourceKey. A missing role is unavailable. */
|
||||
dependencies: components["schemas"]["IncomeDependencyDto"][];
|
||||
};
|
||||
@@ -1543,24 +1561,6 @@ export interface components {
|
||||
PutTbankConnectionDto: {
|
||||
token: string;
|
||||
};
|
||||
IncomeInvestmentScreenDto: {
|
||||
accountId: string;
|
||||
/**
|
||||
* @description discriminator enum property added by openapi-typescript
|
||||
* @enum {string}
|
||||
*/
|
||||
screen: "income";
|
||||
/**
|
||||
* Format: date
|
||||
* @description Inclusive start calendar date in Europe/Moscow (YYYY-MM-DD). Supply both from and to, or neither for the current Moscow month.
|
||||
*/
|
||||
from?: string;
|
||||
/**
|
||||
* Format: date
|
||||
* @description Inclusive end calendar date in Europe/Moscow (YYYY-MM-DD). Supply both from and to, or neither. Timestamp queries use the start of the following Moscow day as the exclusive end, capped at now.
|
||||
*/
|
||||
to?: string;
|
||||
};
|
||||
EventsInvestmentScreenDto: {
|
||||
accountId: string;
|
||||
/**
|
||||
@@ -1579,6 +1579,24 @@ export interface components {
|
||||
*/
|
||||
to?: string;
|
||||
};
|
||||
IncomeInvestmentScreenDto: {
|
||||
accountId: string;
|
||||
/**
|
||||
* @description discriminator enum property added by openapi-typescript
|
||||
* @enum {string}
|
||||
*/
|
||||
screen: "income";
|
||||
/**
|
||||
* Format: date
|
||||
* @description Inclusive start calendar date in Europe/Moscow (YYYY-MM-DD). Supply both from and to, or neither for the current Moscow month.
|
||||
*/
|
||||
from?: string;
|
||||
/**
|
||||
* Format: date
|
||||
* @description Inclusive end calendar date in Europe/Moscow (YYYY-MM-DD). Supply both from and to, or neither. Timestamp queries use the start of the following Moscow day as the exclusive end, capped at now.
|
||||
*/
|
||||
to?: string;
|
||||
};
|
||||
SyncCandleRangeDto: {
|
||||
/** Format: date-time */
|
||||
from: string;
|
||||
@@ -1611,13 +1629,6 @@ export interface components {
|
||||
*/
|
||||
to?: string;
|
||||
};
|
||||
TbankSyncAcceptedDto: {
|
||||
/** Format: uuid */
|
||||
id: string;
|
||||
scope: components["schemas"]["IncomeInvestmentScreenDto"] | components["schemas"]["EventsInvestmentScreenDto"] | components["schemas"]["TimestampInvestmentScreenDto"];
|
||||
/** Format: date-time */
|
||||
now: string;
|
||||
};
|
||||
TbankSyncStatusDto: {
|
||||
/** Format: uuid */
|
||||
id: string;
|
||||
@@ -3175,9 +3186,7 @@ export interface operations {
|
||||
};
|
||||
BrokerageAccountsController_list: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
};
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
@@ -3241,9 +3250,7 @@ export interface operations {
|
||||
};
|
||||
PortfolioController_all: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
};
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
@@ -3307,9 +3314,7 @@ export interface operations {
|
||||
};
|
||||
PortfolioController_get: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
};
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
accountId: string;
|
||||
@@ -3376,7 +3381,6 @@ export interface operations {
|
||||
BrokerageOperationsController_all: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
/** @description Instrument UID. Without from, includes history since the earliest available account opening. */
|
||||
instrumentUid?: string;
|
||||
from?: string;
|
||||
@@ -3449,7 +3453,6 @@ export interface operations {
|
||||
BrokerageOperationsController_get: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
/** @description Instrument UID. Without from, includes history since the earliest available account opening. */
|
||||
instrumentUid?: string;
|
||||
from?: string;
|
||||
@@ -4281,9 +4284,7 @@ export interface operations {
|
||||
};
|
||||
StockController_position: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
};
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
uid: string;
|
||||
@@ -4893,9 +4894,7 @@ export interface operations {
|
||||
};
|
||||
BondController_position: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
};
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
uid: string;
|
||||
@@ -5221,74 +5220,6 @@ export interface operations {
|
||||
};
|
||||
};
|
||||
};
|
||||
TbankSyncController_request: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["IncomeInvestmentScreenDto"] | components["schemas"]["EventsInvestmentScreenDto"] | components["schemas"]["TimestampInvestmentScreenDto"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
202: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["TbankSyncAcceptedDto"];
|
||||
};
|
||||
};
|
||||
/** @description Invalid request */
|
||||
400: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
/** @description Authentication required */
|
||||
401: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
/** @description Resource not found */
|
||||
404: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
/** @description Internal server error */
|
||||
500: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
/** @description Upstream service unavailable */
|
||||
503: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
TbankSyncController_status: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
export {
|
||||
useAuthenticatedQueries,
|
||||
useAuthenticatedQuery,
|
||||
} from "./authenticated-query";
|
||||
export {
|
||||
@@ -11,7 +10,6 @@ export type { paths } from "./generated/schema";
|
||||
export { ApiErrorCode, apiErrorCode, isApiErrorCode } from "./problem-details";
|
||||
|
||||
export {
|
||||
invalidateResourceAccess,
|
||||
type InvestmentResourceMeta,
|
||||
useResourceQuery,
|
||||
} from "./resource-query";
|
||||
|
||||
@@ -75,9 +75,10 @@ describe("persistent resource query lifecycle", () => {
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
|
||||
HttpResponse.json(
|
||||
resource(null, {
|
||||
sync: {
|
||||
errorCode: "TBANK_UNAVAILABLE",
|
||||
id: "work",
|
||||
lastAttempt: {
|
||||
finishedAt: "2026-08-14T00:01:00Z",
|
||||
problems: [],
|
||||
startedAt: "2026-08-14T00:00:00Z",
|
||||
state: "failed",
|
||||
},
|
||||
}),
|
||||
@@ -89,14 +90,16 @@ describe("persistent resource query lifecycle", () => {
|
||||
wrapper: createQueryWrapper().wrapper,
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.meta?.sync.state).toBe("failed"));
|
||||
await waitFor(() =>
|
||||
expect(result.current.meta?.lastAttempt.state).toBe("failed"),
|
||||
);
|
||||
expect(result.current.data).toBeUndefined();
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
expect(result.current.status).toBe("success");
|
||||
expect(result.current.isPending).toBe(false);
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
|
||||
expect(result.current.meta?.availability).toBe("missing");
|
||||
expect(result.current.meta?.availability).toBe("initial-loading");
|
||||
});
|
||||
it("keeps the refetch envelope while exposing the refreshed resource payload", async () => {
|
||||
auth();
|
||||
|
||||
@@ -15,8 +15,10 @@ import { ApiErrorCode, apiErrorCode, isApiErrorCode } from "./problem-details";
|
||||
type InvestmentResourceMeta = components["schemas"]["InvestmentResourceMetaDto"];
|
||||
|
||||
type Resource = {
|
||||
[key: string]: unknown;
|
||||
data: unknown;
|
||||
meta: InvestmentResourceMeta;
|
||||
sync?: unknown;
|
||||
};
|
||||
|
||||
type ResourcePath = {
|
||||
@@ -66,8 +68,12 @@ function invalidateResourceAccess(
|
||||
|
||||
// Keep endpoint and parameters intact. The generated queryFn accepts the
|
||||
// optional sync mode even for a cache key originally created without init.
|
||||
function observationKey<K extends ResourceQueryKey>(key: K): K {
|
||||
const [method, path, init] = key;
|
||||
function observationKey<K extends readonly unknown[]>(key: K): K {
|
||||
const [method, path, init] = key as unknown as [
|
||||
string,
|
||||
string,
|
||||
{ params?: { path?: object; query?: object } }?,
|
||||
];
|
||||
|
||||
return [method, path, {
|
||||
...init,
|
||||
@@ -76,7 +82,11 @@ function observationKey<K extends ResourceQueryKey>(key: K): K {
|
||||
}
|
||||
|
||||
// Observation changes transport mode, never the generated cache identity.
|
||||
function useResourceQuery<T extends Resource, E, K extends ResourceQueryKey>(
|
||||
function useResourceQuery<
|
||||
T extends Resource,
|
||||
E = unknown,
|
||||
K extends readonly unknown[] = ResourceQueryKey,
|
||||
>(
|
||||
options: UseQueryOptions<T, E, T, K>,
|
||||
) {
|
||||
const client = useQueryClient();
|
||||
@@ -135,11 +145,11 @@ function useResourceQuery<T extends Resource, E, K extends ResourceQueryKey>(
|
||||
queryKey: options.queryKey,
|
||||
refetch: query.refetch,
|
||||
status: query.status,
|
||||
sync: query.data && "sync" in query.data ? query.data.sync : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export {
|
||||
invalidateResourceAccess,
|
||||
type InvestmentResourceMeta,
|
||||
useResourceQuery,
|
||||
};
|
||||
|
||||
+205
-305
@@ -1976,19 +1976,7 @@
|
||||
"/api/v1/brokerage-accounts": {
|
||||
"get": {
|
||||
"operationId": "BrokerageAccountsController_list",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "sync",
|
||||
"required": false,
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"observe"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"parameters": [],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "",
|
||||
@@ -2064,19 +2052,7 @@
|
||||
"/api/v1/brokerage-accounts/all/portfolio": {
|
||||
"get": {
|
||||
"operationId": "PortfolioController_all",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "sync",
|
||||
"required": false,
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"observe"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"parameters": [],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "",
|
||||
@@ -2160,17 +2136,6 @@
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "sync",
|
||||
"required": false,
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"observe"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
@@ -2249,17 +2214,6 @@
|
||||
"get": {
|
||||
"operationId": "BrokerageOperationsController_all",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "sync",
|
||||
"required": false,
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"observe"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "instrumentUid",
|
||||
"required": false,
|
||||
@@ -2411,17 +2365,6 @@
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "sync",
|
||||
"required": false,
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"observe"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "instrumentUid",
|
||||
"required": false,
|
||||
@@ -3704,17 +3647,6 @@
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "sync",
|
||||
"required": false,
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"observe"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
@@ -4588,17 +4520,6 @@
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "sync",
|
||||
"required": false,
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"observe"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
@@ -4996,116 +4917,6 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/tbank-sync": {
|
||||
"post": {
|
||||
"operationId": "TbankSyncController_request",
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"oneOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/IncomeInvestmentScreenDto"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/EventsInvestmentScreenDto"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/TimestampInvestmentScreenDto"
|
||||
}
|
||||
],
|
||||
"discriminator": {
|
||||
"propertyName": "screen",
|
||||
"mapping": {
|
||||
"income": "#/components/schemas/IncomeInvestmentScreenDto",
|
||||
"events": "#/components/schemas/EventsInvestmentScreenDto",
|
||||
"accounts": "#/components/schemas/TimestampInvestmentScreenDto",
|
||||
"account": "#/components/schemas/TimestampInvestmentScreenDto",
|
||||
"operations": "#/components/schemas/TimestampInvestmentScreenDto",
|
||||
"stocks": "#/components/schemas/TimestampInvestmentScreenDto",
|
||||
"bonds": "#/components/schemas/TimestampInvestmentScreenDto",
|
||||
"stock": "#/components/schemas/TimestampInvestmentScreenDto",
|
||||
"bond": "#/components/schemas/TimestampInvestmentScreenDto"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"202": {
|
||||
"description": "",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/TbankSyncAcceptedDto"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Invalid request",
|
||||
"content": {
|
||||
"application/problem+json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetailsDto"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Authentication required",
|
||||
"content": {
|
||||
"application/problem+json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetailsDto"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Resource not found",
|
||||
"content": {
|
||||
"application/problem+json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetailsDto"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal server error",
|
||||
"content": {
|
||||
"application/problem+json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetailsDto"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"503": {
|
||||
"description": "Upstream service unavailable",
|
||||
"content": {
|
||||
"application/problem+json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetailsDto"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"security": [
|
||||
{
|
||||
"bearer": []
|
||||
}
|
||||
],
|
||||
"tags": [
|
||||
"tbank-sync"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/tbank-sync/{id}": {
|
||||
"get": {
|
||||
"operationId": "TbankSyncController_status",
|
||||
@@ -5214,16 +5025,28 @@
|
||||
"example": "UNAUTHORIZED"
|
||||
},
|
||||
"errors": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"pointer",
|
||||
"detail"
|
||||
],
|
||||
"properties": {
|
||||
"pointer": {
|
||||
"type": "string"
|
||||
},
|
||||
"detail": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"example": [
|
||||
{
|
||||
"pointer": "#/email",
|
||||
"detail": "must be a valid email address"
|
||||
}
|
||||
],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -5936,32 +5759,70 @@
|
||||
"historyState"
|
||||
]
|
||||
},
|
||||
"InvestmentSyncDto": {
|
||||
"InvestmentAttemptProblemDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
},
|
||||
"state": {
|
||||
"section": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"idle",
|
||||
"running",
|
||||
"failed"
|
||||
"membership",
|
||||
"portfolio",
|
||||
"operations",
|
||||
"events"
|
||||
]
|
||||
},
|
||||
"accountId": {
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
},
|
||||
"errorCode": {
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"state",
|
||||
"section",
|
||||
"accountId",
|
||||
"errorCode"
|
||||
]
|
||||
},
|
||||
"InvestmentAttemptDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"state": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"none",
|
||||
"running",
|
||||
"succeeded",
|
||||
"partial",
|
||||
"failed"
|
||||
]
|
||||
},
|
||||
"startedAt": {
|
||||
"type": "string",
|
||||
"nullable": true,
|
||||
"format": "date-time"
|
||||
},
|
||||
"finishedAt": {
|
||||
"type": "string",
|
||||
"nullable": true,
|
||||
"format": "date-time"
|
||||
},
|
||||
"problems": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/InvestmentAttemptProblemDto"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"state",
|
||||
"startedAt",
|
||||
"finishedAt",
|
||||
"problems"
|
||||
]
|
||||
},
|
||||
"InvestmentDependencyDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -5980,9 +5841,17 @@
|
||||
"availability": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"missing",
|
||||
"partial",
|
||||
"complete"
|
||||
"available",
|
||||
"initial-loading",
|
||||
"temporarily-unavailable",
|
||||
"connection-unavailable"
|
||||
]
|
||||
},
|
||||
"completeness": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"complete",
|
||||
"incomplete"
|
||||
]
|
||||
},
|
||||
"freshness": {
|
||||
@@ -5998,17 +5867,18 @@
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
},
|
||||
"sync": {
|
||||
"$ref": "#/components/schemas/InvestmentSyncDto"
|
||||
"lastAttempt": {
|
||||
"$ref": "#/components/schemas/InvestmentAttemptDto"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"dataRevision",
|
||||
"resourceKey",
|
||||
"availability",
|
||||
"completeness",
|
||||
"freshness",
|
||||
"lastSuccessfulAt",
|
||||
"sync"
|
||||
"lastAttempt"
|
||||
]
|
||||
},
|
||||
"InvestmentResourceMetaDto": {
|
||||
@@ -6029,9 +5899,17 @@
|
||||
"availability": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"missing",
|
||||
"partial",
|
||||
"complete"
|
||||
"available",
|
||||
"initial-loading",
|
||||
"temporarily-unavailable",
|
||||
"connection-unavailable"
|
||||
]
|
||||
},
|
||||
"completeness": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"complete",
|
||||
"incomplete"
|
||||
]
|
||||
},
|
||||
"freshness": {
|
||||
@@ -6047,8 +5925,8 @@
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
},
|
||||
"sync": {
|
||||
"$ref": "#/components/schemas/InvestmentSyncDto"
|
||||
"lastAttempt": {
|
||||
"$ref": "#/components/schemas/InvestmentAttemptDto"
|
||||
},
|
||||
"dependencies": {
|
||||
"type": "array",
|
||||
@@ -6061,9 +5939,47 @@
|
||||
"dataRevision",
|
||||
"resourceKey",
|
||||
"availability",
|
||||
"completeness",
|
||||
"freshness",
|
||||
"lastSuccessfulAt",
|
||||
"sync"
|
||||
"lastAttempt"
|
||||
]
|
||||
},
|
||||
"HourlySyncStatusDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"state": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"running",
|
||||
"succeeded",
|
||||
"partial",
|
||||
"failed",
|
||||
"cancelled"
|
||||
],
|
||||
"description": "Last hourly walk state. Cancelled means an interrupted attempt; its start still delays the next term."
|
||||
},
|
||||
"startedAt": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"finishedAt": {
|
||||
"type": "string",
|
||||
"nullable": true,
|
||||
"format": "date-time"
|
||||
},
|
||||
"problems": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/InvestmentAttemptProblemDto"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"state",
|
||||
"startedAt",
|
||||
"finishedAt",
|
||||
"problems"
|
||||
]
|
||||
},
|
||||
"BrokerageAccountsResourceDto": {
|
||||
@@ -6078,11 +5994,22 @@
|
||||
},
|
||||
"meta": {
|
||||
"$ref": "#/components/schemas/InvestmentResourceMetaDto"
|
||||
},
|
||||
"sync": {
|
||||
"nullable": true,
|
||||
"description": "Read-only status of the last hourly walk for the current connection. Null when no walk attempt exists yet.",
|
||||
"type": "object",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/HourlySyncStatusDto"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"data",
|
||||
"meta"
|
||||
"meta",
|
||||
"sync"
|
||||
]
|
||||
},
|
||||
"AccountReferenceDto": {
|
||||
@@ -6915,9 +6842,17 @@
|
||||
"availability": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"missing",
|
||||
"partial",
|
||||
"complete"
|
||||
"available",
|
||||
"initial-loading",
|
||||
"temporarily-unavailable",
|
||||
"connection-unavailable"
|
||||
]
|
||||
},
|
||||
"completeness": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"complete",
|
||||
"incomplete"
|
||||
]
|
||||
},
|
||||
"freshness": {
|
||||
@@ -6933,8 +6868,8 @@
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
},
|
||||
"sync": {
|
||||
"$ref": "#/components/schemas/InvestmentSyncDto"
|
||||
"lastAttempt": {
|
||||
"$ref": "#/components/schemas/InvestmentAttemptDto"
|
||||
},
|
||||
"role": {
|
||||
"type": "string",
|
||||
@@ -6949,9 +6884,10 @@
|
||||
"dataRevision",
|
||||
"resourceKey",
|
||||
"availability",
|
||||
"completeness",
|
||||
"freshness",
|
||||
"lastSuccessfulAt",
|
||||
"sync",
|
||||
"lastAttempt",
|
||||
"role"
|
||||
]
|
||||
},
|
||||
@@ -6973,9 +6909,17 @@
|
||||
"availability": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"missing",
|
||||
"partial",
|
||||
"complete"
|
||||
"available",
|
||||
"initial-loading",
|
||||
"temporarily-unavailable",
|
||||
"connection-unavailable"
|
||||
]
|
||||
},
|
||||
"completeness": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"complete",
|
||||
"incomplete"
|
||||
]
|
||||
},
|
||||
"freshness": {
|
||||
@@ -6991,8 +6935,8 @@
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
},
|
||||
"sync": {
|
||||
"$ref": "#/components/schemas/InvestmentSyncDto"
|
||||
"lastAttempt": {
|
||||
"$ref": "#/components/schemas/InvestmentAttemptDto"
|
||||
},
|
||||
"dependencies": {
|
||||
"description": "Dependencies identified by role, not array order or resourceKey. A missing role is unavailable.",
|
||||
@@ -7006,9 +6950,10 @@
|
||||
"dataRevision",
|
||||
"resourceKey",
|
||||
"availability",
|
||||
"completeness",
|
||||
"freshness",
|
||||
"lastSuccessfulAt",
|
||||
"sync",
|
||||
"lastAttempt",
|
||||
"dependencies"
|
||||
]
|
||||
},
|
||||
@@ -8811,34 +8756,6 @@
|
||||
"token"
|
||||
]
|
||||
},
|
||||
"IncomeInvestmentScreenDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"accountId": {
|
||||
"type": "string"
|
||||
},
|
||||
"screen": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"income"
|
||||
]
|
||||
},
|
||||
"from": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"description": "Inclusive start calendar date in Europe/Moscow (YYYY-MM-DD). Supply both from and to, or neither for the current Moscow month."
|
||||
},
|
||||
"to": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"description": "Inclusive end calendar date in Europe/Moscow (YYYY-MM-DD). Supply both from and to, or neither. Timestamp queries use the start of the following Moscow day as the exclusive end, capped at now."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"accountId",
|
||||
"screen"
|
||||
]
|
||||
},
|
||||
"EventsInvestmentScreenDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -8867,6 +8784,34 @@
|
||||
"screen"
|
||||
]
|
||||
},
|
||||
"IncomeInvestmentScreenDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"accountId": {
|
||||
"type": "string"
|
||||
},
|
||||
"screen": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"income"
|
||||
]
|
||||
},
|
||||
"from": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"description": "Inclusive start calendar date in Europe/Moscow (YYYY-MM-DD). Supply both from and to, or neither for the current Moscow month."
|
||||
},
|
||||
"to": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"description": "Inclusive end calendar date in Europe/Moscow (YYYY-MM-DD). Supply both from and to, or neither. Timestamp queries use the start of the following Moscow day as the exclusive end, capped at now."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"accountId",
|
||||
"screen"
|
||||
]
|
||||
},
|
||||
"SyncCandleRangeDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -8955,51 +8900,6 @@
|
||||
"screen"
|
||||
]
|
||||
},
|
||||
"TbankSyncAcceptedDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"format": "uuid"
|
||||
},
|
||||
"scope": {
|
||||
"oneOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/IncomeInvestmentScreenDto"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/EventsInvestmentScreenDto"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/TimestampInvestmentScreenDto"
|
||||
}
|
||||
],
|
||||
"discriminator": {
|
||||
"propertyName": "screen",
|
||||
"mapping": {
|
||||
"income": "#/components/schemas/IncomeInvestmentScreenDto",
|
||||
"events": "#/components/schemas/EventsInvestmentScreenDto",
|
||||
"accounts": "#/components/schemas/TimestampInvestmentScreenDto",
|
||||
"account": "#/components/schemas/TimestampInvestmentScreenDto",
|
||||
"operations": "#/components/schemas/TimestampInvestmentScreenDto",
|
||||
"stocks": "#/components/schemas/TimestampInvestmentScreenDto",
|
||||
"bonds": "#/components/schemas/TimestampInvestmentScreenDto",
|
||||
"stock": "#/components/schemas/TimestampInvestmentScreenDto",
|
||||
"bond": "#/components/schemas/TimestampInvestmentScreenDto"
|
||||
}
|
||||
}
|
||||
},
|
||||
"now": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"scope",
|
||||
"now"
|
||||
]
|
||||
},
|
||||
"TbankSyncStatusDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -382,6 +382,13 @@ const ru = {
|
||||
yearUnavailable: "Сравнение с годом ранее недоступно.",
|
||||
},
|
||||
investment: {
|
||||
attempt: {
|
||||
cancelled: "Обновление отменено",
|
||||
failed: "Обновление не удалось",
|
||||
partial: "Обновлено частично",
|
||||
running: "Обновление выполняется",
|
||||
succeeded: "Обновлено",
|
||||
},
|
||||
history: "История догружается",
|
||||
partial: "Период загружен не полностью",
|
||||
refresh: "Обновить",
|
||||
|
||||
@@ -32,6 +32,21 @@ describe("SourceSyncStatus", () => {
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Обновление не удалось");
|
||||
});
|
||||
|
||||
it("announces an active or failed source attempt with text", () => {
|
||||
renderStatus({
|
||||
lastAttempt: {
|
||||
finishedAt: null,
|
||||
problems: [],
|
||||
startedAt: "2026-02-03T10:15:00.000Z",
|
||||
state: "running",
|
||||
},
|
||||
});
|
||||
|
||||
expect(screen.getByRole("status")).toHaveTextContent(
|
||||
"Обновление выполняется",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the notices next to the timestamp they belong to", () => {
|
||||
renderStatus({
|
||||
errorText: "Обновление не удалось",
|
||||
|
||||
@@ -3,6 +3,8 @@ import type { FC } from "react";
|
||||
import { Text } from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import type { InvestmentResourceMeta } from "@/shared/api";
|
||||
|
||||
import { formatSnapshotTime } from "@/shared/lib";
|
||||
|
||||
// Owns the "when did the source last answer" line and the two notices that
|
||||
@@ -10,6 +12,7 @@ import { formatSnapshotTime } from "@/shared/lib";
|
||||
// shows a muted line, a page header a progress bar — that is a product call.
|
||||
type SourceSyncStatusProps = {
|
||||
errorText?: null | string;
|
||||
lastAttempt?: InvestmentResourceMeta["lastAttempt"];
|
||||
lastSuccessfulAt?: null | string;
|
||||
stale?: boolean;
|
||||
};
|
||||
@@ -17,6 +20,12 @@ type SourceSyncStatusProps = {
|
||||
const SourceSyncStatus: FC<SourceSyncStatusProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const attempt = props.lastAttempt;
|
||||
|
||||
const attemptText = attempt && attempt.state !== "none"
|
||||
? t(`investment.attempt.${attempt.state}`)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{!!props.lastSuccessfulAt && (
|
||||
@@ -29,6 +38,12 @@ const SourceSyncStatus: FC<SourceSyncStatusProps> = (props) => {
|
||||
|
||||
{!!props.stale && <Text size="xs">{t("investment.stale")}</Text>}
|
||||
|
||||
{!!attemptText && (
|
||||
<Text role="status" size="xs">
|
||||
{attemptText}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
{!!props.errorText && <Text role="status">{props.errorText}</Text>}
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -7,12 +7,18 @@ function resource<T>(data: T, meta: Partial<Meta> = {}) {
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
availability: data === null ? "missing" : "complete",
|
||||
availability: data === null ? "initial-loading" : "available",
|
||||
completeness: "complete",
|
||||
dataRevision: "1",
|
||||
freshness: "fresh",
|
||||
lastAttempt: {
|
||||
finishedAt: null,
|
||||
problems: [],
|
||||
startedAt: null,
|
||||
state: "none",
|
||||
},
|
||||
lastSuccessfulAt: "2026-08-14T00:00:00Z",
|
||||
resourceKey: "fixture",
|
||||
sync: { errorCode: null, id: null, state: "idle" },
|
||||
...meta,
|
||||
} satisfies Meta,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user