Compare commits
4
Commits
develop
...
fac27bed93
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fac27bed93 | ||
|
|
ba0a5d46cf | ||
|
|
6b1b26aa34 | ||
|
|
734c5bdc2e |
@@ -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>
|
||||
|
||||
|
||||
@@ -10,8 +10,6 @@ type BrokerageAccount = NonNullable<
|
||||
paths["/api/v1/brokerage-accounts"]["get"]["responses"][200]["content"]["application/json"]["data"]
|
||||
>[number];
|
||||
|
||||
type BrokerageAccountsResponse = paths["/api/v1/brokerage-accounts"]["get"]["responses"][200]["content"]["application/json"];
|
||||
|
||||
function useBrokerageAccounts() {
|
||||
const query = useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
@@ -21,7 +19,6 @@ function useBrokerageAccounts() {
|
||||
|
||||
return {
|
||||
...query,
|
||||
sync: query.sync as BrokerageAccountsResponse["sync"] | null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+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"}
|
||||
/>
|
||||
|
||||
@@ -6,10 +6,6 @@ import {
|
||||
|
||||
type StockCandles = NonNullable<paths["/api/v1/stocks/{uid}/candles"]["get"]["responses"][200]["content"]["application/json"]["data"]>;
|
||||
|
||||
type StockPosition = NonNullable<paths["/api/v1/stocks/{uid}/position"]["get"]["responses"][200]["content"]["application/json"]["data"]>;
|
||||
|
||||
const MIN_STOCK_SEARCH_LENGTH = 2;
|
||||
|
||||
type StockDividends = NonNullable<paths["/api/v1/stocks/{uid}/dividends"]["get"]["responses"][200]["content"]["application/json"]["data"]>;
|
||||
|
||||
type StockPeriod = NonNullable<
|
||||
@@ -18,6 +14,8 @@ type StockPeriod = NonNullable<
|
||||
>["period"]
|
||||
>;
|
||||
|
||||
type StockPosition = NonNullable<paths["/api/v1/stocks/{uid}/position"]["get"]["responses"][200]["content"]["application/json"]["data"]>;
|
||||
|
||||
const STOCK_STALE_TIME_MS = 30_000;
|
||||
|
||||
function useStock(identifier: string) {
|
||||
@@ -96,18 +94,7 @@ function useStockQuote(uid: string) {
|
||||
});
|
||||
}
|
||||
|
||||
function useStockSearch(query: string) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks", {
|
||||
params: { query: { query } },
|
||||
}),
|
||||
enabled: query.length >= MIN_STOCK_SEARCH_LENGTH,
|
||||
staleTime: STOCK_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
|
||||
export {
|
||||
MIN_STOCK_SEARCH_LENGTH,
|
||||
type StockCandles,
|
||||
type StockDividends,
|
||||
type StockPosition,
|
||||
@@ -117,5 +104,4 @@ export {
|
||||
useStockDividends,
|
||||
useStockPosition,
|
||||
useStockQuote,
|
||||
useStockSearch,
|
||||
};
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
export {
|
||||
MIN_STOCK_SEARCH_LENGTH,
|
||||
type StockCandles,
|
||||
type StockDividends,
|
||||
type StockPosition,
|
||||
@@ -9,5 +8,4 @@ export {
|
||||
useStockDividends,
|
||||
useStockPosition,
|
||||
useStockQuote,
|
||||
useStockSearch,
|
||||
} from "./api/queries";
|
||||
|
||||
@@ -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",
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -19,12 +19,14 @@ function auth() {
|
||||
}
|
||||
|
||||
describe("read-only screen synchronization", () => {
|
||||
it("retries the resource with GET and never starts a sync POST", async () => {
|
||||
it("retries the resource with GET without requesting source observation", async () => {
|
||||
auth();
|
||||
let gets = 0;
|
||||
const syncModes: (null | string)[] = [];
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", () => {
|
||||
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
||||
gets += 1;
|
||||
syncModes.push(new URL(request.url).searchParams.get("sync"));
|
||||
|
||||
return gets === 1
|
||||
? HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 })
|
||||
@@ -49,6 +51,7 @@ describe("read-only screen synchronization", () => {
|
||||
await waitFor(() => expect(result.current.accounts.data).toEqual([]));
|
||||
|
||||
expect(gets).toBe(2);
|
||||
expect(syncModes).toEqual([null, null]);
|
||||
});
|
||||
|
||||
it("refreshes the currently open resources together", async () => {
|
||||
|
||||
@@ -8,7 +8,6 @@ type ScreenResource = {
|
||||
isError: boolean;
|
||||
isFetching: boolean;
|
||||
meta?: InvestmentResourceMeta;
|
||||
observe: () => Promise<unknown>;
|
||||
queryKey: QueryKey;
|
||||
refetch: () => Promise<unknown>;
|
||||
};
|
||||
@@ -42,14 +41,12 @@ function useScreenSync(_scope: ScreenScope, resources: ScreenResource[]) {
|
||||
await Promise.allSettled(resources.map(resource => resource.refetch()));
|
||||
};
|
||||
|
||||
// Retry failed HTTP reads without asking the source to import again.
|
||||
// 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);
|
||||
|
||||
if (failed.length > 0)
|
||||
await Promise.allSettled(failed.map(resource => resource.observe()));
|
||||
await Promise.allSettled(failed.map(resource => resource.refetch()));
|
||||
else await refresh();
|
||||
};
|
||||
|
||||
@@ -57,7 +54,9 @@ function useScreenSync(_scope: ScreenScope, resources: ScreenResource[]) {
|
||||
refresh,
|
||||
refreshing: isRefreshing,
|
||||
retry,
|
||||
sourceError: resources.some(({ meta }) => meta?.sync.state === "failed"),
|
||||
sourceError: resources.some(
|
||||
({ meta }) => meta?.lastAttempt.state === "failed",
|
||||
),
|
||||
transportError: resources.some(resource => resource.isError),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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
-4
@@ -507,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",
|
||||
},
|
||||
},
|
||||
@@ -543,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,
|
||||
|
||||
@@ -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} />}
|
||||
|
||||
@@ -189,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,
|
||||
},
|
||||
})),
|
||||
),
|
||||
);
|
||||
@@ -205,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,7 +15,7 @@ const AccountsPage: FC = () => {
|
||||
return (
|
||||
<AccountsPageLoaded
|
||||
accounts={viewModel.accounts}
|
||||
sync={viewModel.sync}
|
||||
meta={viewModel.meta}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -4,17 +4,15 @@ import {
|
||||
useBrokerageAccounts,
|
||||
} from "@/entities/brokerage-account";
|
||||
import { useScreenSync } from "@/features/tbank-connection";
|
||||
import { ApiErrorCode, apiErrorCode, isApiErrorCode, type paths } from "@/shared/api";
|
||||
import { ApiErrorCode, apiErrorCode, isApiErrorCode } from "@/shared/api";
|
||||
import { useInitialAvailability } from "@/shared/lib";
|
||||
|
||||
type AccountsPageViewModel
|
||||
= | { accounts: BrokerageAccountCard[]; state: "loaded"; sync: AccountsSync }
|
||||
= | { accounts: BrokerageAccountCard[]; meta: NonNullable<ReturnType<typeof useBrokerageAccounts>["meta"]>; state: "loaded" }
|
||||
| { code?: string; state: "error" }
|
||||
| { state: "empty" }
|
||||
| { state: "loading" };
|
||||
|
||||
type AccountsSync = paths["/api/v1/brokerage-accounts"]["get"]["responses"][200]["content"]["application/json"]["sync"];
|
||||
|
||||
function isAccountsAccessFailure(code?: string) {
|
||||
return isApiErrorCode(code, ApiErrorCode.InvalidTbankToken)
|
||||
|| isApiErrorCode(code, ApiErrorCode.TbankNotConnected);
|
||||
@@ -28,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,
|
||||
});
|
||||
|
||||
@@ -49,10 +48,13 @@ 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,
|
||||
sync: accounts.sync,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,45 +1,24 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { Badge, Button, Stack, Text, Title } from "@mantine/core";
|
||||
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[];
|
||||
sync:
|
||||
| null
|
||||
| undefined
|
||||
| {
|
||||
finishedAt: null | string;
|
||||
sections: {
|
||||
accountId?: string;
|
||||
errorCode: null | string;
|
||||
section: string;
|
||||
}[];
|
||||
startedAt: string;
|
||||
state: string;
|
||||
};
|
||||
meta: InvestmentResourceMeta;
|
||||
};
|
||||
|
||||
const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
const sync = props.sync;
|
||||
|
||||
const syncLabel = sync
|
||||
? new Intl.DateTimeFormat("ru-RU", {
|
||||
dateStyle: "short",
|
||||
timeStyle: "short",
|
||||
}).format(new Date(sync.finishedAt ?? sync.startedAt))
|
||||
: null;
|
||||
|
||||
const syncColor = sync?.state === "failed" || sync?.state === "partial"
|
||||
? "red"
|
||||
: "gray";
|
||||
|
||||
return (
|
||||
<Stack gap="lg">
|
||||
@@ -50,20 +29,11 @@ const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
|
||||
{t("accounts.subtitle")}
|
||||
</Text>
|
||||
|
||||
{sync && (
|
||||
<Text c="dimmed" size="xs">
|
||||
Последний обход:
|
||||
{" "}
|
||||
{syncLabel}
|
||||
{" "}
|
||||
<Badge
|
||||
color={syncColor}
|
||||
size="xs"
|
||||
>
|
||||
{sync.state}
|
||||
</Badge>
|
||||
</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
|
||||
|
||||
@@ -1,16 +1,28 @@
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createTestQueryClient } from "@/test/query";
|
||||
import { resource } from "@/test/resource";
|
||||
import { server } from "@/test/server";
|
||||
|
||||
import { StocksPage } from "./StocksPage";
|
||||
import { useStocksPageVm } from "./StocksPage.vm";
|
||||
|
||||
const StocksPageVmProbe = () => {
|
||||
const vm = useStocksPageVm();
|
||||
|
||||
return (
|
||||
<>
|
||||
<button onClick={vm.onSearch}>search</button>
|
||||
<button onClick={() => vm.onPage(2)}>page</button>
|
||||
<output>{vm.items.map(item => item.name).join(", ")}</output>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
@@ -18,27 +30,28 @@ describe("stock search", () => {
|
||||
it("waits for a meaningful query and uses the server-verified ticker link", async () => {
|
||||
const query = vi.fn();
|
||||
server.use(
|
||||
http.get("*/api/v1/stocks", ({ request }) => {
|
||||
query(new URL(request.url).searchParams.get("query"));
|
||||
http.post("*/api/v1/stocks/screener/search", async ({ request }) => {
|
||||
query(await request.json());
|
||||
|
||||
return HttpResponse.json(
|
||||
resource([
|
||||
{
|
||||
apiTradeAvailable: true,
|
||||
classCode: "TQBR",
|
||||
instrumentUid: "unique-stock",
|
||||
isin: "RU0009029540",
|
||||
logoName: "sber.png",
|
||||
name: "Сбербанк",
|
||||
price: { currency: "RUB", value: "306.12" },
|
||||
priceAt: "2026-09-10T10:00:00Z",
|
||||
realExchange: "REAL_EXCHANGE_MOEX",
|
||||
shareType: "SHARE_TYPE_COMMON",
|
||||
slug: "SBER",
|
||||
ticker: "SBER",
|
||||
},
|
||||
]),
|
||||
);
|
||||
return HttpResponse.json({
|
||||
asOf: "2026-10-10T10:00:00Z",
|
||||
hasNext: false,
|
||||
items: [{
|
||||
countryOfRisk: "RU",
|
||||
currency: "RUB",
|
||||
instrumentUid: "e6123145-9665-43e0-8413-cd61b8aa9b13",
|
||||
isin: "RU0009029540",
|
||||
logoName: "sber.png",
|
||||
lot: 10,
|
||||
name: "Сбербанк",
|
||||
realExchange: "REAL_EXCHANGE_MOEX",
|
||||
sector: "financial",
|
||||
shareType: "SHARE_TYPE_COMMON",
|
||||
ticker: "SBER",
|
||||
}],
|
||||
page: 1,
|
||||
searchId: "search-id",
|
||||
});
|
||||
}),
|
||||
);
|
||||
configureAuthClient({
|
||||
@@ -46,7 +59,6 @@ describe("stock search", () => {
|
||||
clear: vi.fn(),
|
||||
refresh: () => Promise.resolve(false),
|
||||
});
|
||||
vi.useFakeTimers();
|
||||
render(
|
||||
<QueryClientProvider client={createTestQueryClient()}>
|
||||
<MantineProvider>
|
||||
@@ -56,23 +68,212 @@ describe("stock search", () => {
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
const input = screen.getByLabelText("Поиск акций");
|
||||
fireEvent.change(input, { target: { value: "S" } });
|
||||
await act(() => vi.advanceTimersByTimeAsync(300));
|
||||
expect(query).not.toHaveBeenCalled();
|
||||
fireEvent.change(input, { target: { value: "SB" } });
|
||||
await act(() => vi.advanceTimersByTimeAsync(299));
|
||||
expect(query).not.toHaveBeenCalled();
|
||||
// The final input uses real timers for network and query notifications.
|
||||
vi.useRealTimers();
|
||||
const input = screen.getByLabelText("Название или тикер");
|
||||
fireEvent.change(input, { target: { value: "SBER" } });
|
||||
expect(query).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Найти" }));
|
||||
expect(
|
||||
await screen.findByRole("link", { name: /Сбербанк/ }),
|
||||
).toHaveAttribute("href", "/stocks/SBER");
|
||||
expect(screen.getByText("306,12 ₽")).toBeVisible();
|
||||
expect(screen.getByText("Режим: TQBR")).toBeVisible();
|
||||
).toHaveAttribute("href", "/stocks/e6123145-9665-43e0-8413-cd61b8aa9b13");
|
||||
expect(screen.getByText("Список получен 10.10.2026, 10:00")).toBeVisible();
|
||||
expect(screen.getByText("Лот: 10 шт.")).toBeVisible();
|
||||
expect(screen.getByText("ISIN: RU0009029540")).toBeVisible();
|
||||
expect(screen.getByText("Мосбиржа")).toBeVisible();
|
||||
await waitFor(() => expect(query).toHaveBeenCalledExactlyOnceWith("SBER"));
|
||||
expect(screen.getAllByText("Мосбиржа")[0]).toBeVisible();
|
||||
expect(screen.getByAltText("")).toHaveAttribute(
|
||||
"src",
|
||||
"https://invest-brands.cdn-tinkoff.ru/sberx160.png",
|
||||
);
|
||||
await waitFor(() => expect(query).toHaveBeenCalledExactlyOnceWith({ query: "SBER" }));
|
||||
});
|
||||
|
||||
it("searches by the selected sector without a text query", async () => {
|
||||
const query = vi.fn();
|
||||
server.use(
|
||||
http.post("*/api/v1/stocks/screener/search", async ({ request }) => {
|
||||
query(await request.json());
|
||||
|
||||
return HttpResponse.json({
|
||||
asOf: "2026-10-10T10:00:00Z",
|
||||
hasNext: false,
|
||||
items: [],
|
||||
page: 1,
|
||||
searchId: "sector-search",
|
||||
});
|
||||
}),
|
||||
);
|
||||
configureAuthClient({
|
||||
accessToken: () => "synthetic",
|
||||
clear: vi.fn(),
|
||||
refresh: () => Promise.resolve(false),
|
||||
});
|
||||
render(
|
||||
<QueryClientProvider client={createTestQueryClient()}>
|
||||
<MantineProvider>
|
||||
<MemoryRouter>
|
||||
<StocksPage />
|
||||
</MemoryRouter>
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
fireEvent.click(screen.getByRole("combobox", { name: "Сектор" }));
|
||||
fireEvent.click(await screen.findByRole("option", { name: "Энергетика" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Найти" }));
|
||||
|
||||
await waitFor(() => expect(query).toHaveBeenCalledExactlyOnceWith({
|
||||
sector: "energy",
|
||||
}));
|
||||
});
|
||||
|
||||
it("shows known result pages and reads the selected page", async () => {
|
||||
const requestedPages = vi.fn();
|
||||
server.use(
|
||||
http.post("*/api/v1/stocks/screener/search", () => HttpResponse.json({
|
||||
asOf: "2026-10-10T10:00:00Z",
|
||||
hasNext: true,
|
||||
items: [],
|
||||
page: 1,
|
||||
searchId: "paged-search",
|
||||
})),
|
||||
http.get("*/api/v1/stocks/screener/search/paged-search", ({ request }) => {
|
||||
const page = Number(new URL(request.url).searchParams.get("page"));
|
||||
requestedPages(page);
|
||||
|
||||
return HttpResponse.json({
|
||||
asOf: "2026-10-10T10:00:00Z",
|
||||
hasNext: false,
|
||||
items: [],
|
||||
page,
|
||||
searchId: "paged-search",
|
||||
});
|
||||
}),
|
||||
);
|
||||
configureAuthClient({
|
||||
accessToken: () => "synthetic",
|
||||
clear: vi.fn(),
|
||||
refresh: () => Promise.resolve(false),
|
||||
});
|
||||
render(
|
||||
<QueryClientProvider client={createTestQueryClient()}>
|
||||
<MantineProvider>
|
||||
<MemoryRouter>
|
||||
<StocksPage />
|
||||
</MemoryRouter>
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Найти" }));
|
||||
fireEvent.click(await screen.findByRole(
|
||||
"button",
|
||||
{ name: "Страница 2" },
|
||||
));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(requestedPages).toHaveBeenCalledExactlyOnceWith(2),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps a newer search when an earlier page request finishes late", async () => {
|
||||
const oldPage = Promise.withResolvers<void>();
|
||||
let searches = 0;
|
||||
|
||||
server.use(
|
||||
http.post("*/api/v1/stocks/screener/search", () => {
|
||||
searches += 1;
|
||||
|
||||
return HttpResponse.json({
|
||||
asOf: "2026-10-10T10:00:00Z",
|
||||
hasNext: searches === 1,
|
||||
items: [{
|
||||
countryOfRisk: "RU",
|
||||
currency: "RUB",
|
||||
instrumentUid: searches === 1 ? "old" : "new",
|
||||
isin: null,
|
||||
logoName: null,
|
||||
lot: 1,
|
||||
name: searches === 1 ? "Старый" : "Новый",
|
||||
realExchange: "REAL_EXCHANGE_MOEX",
|
||||
sector: "financial",
|
||||
shareType: "SHARE_TYPE_COMMON",
|
||||
ticker: searches === 1 ? "OLD" : "NEW",
|
||||
}],
|
||||
page: 1,
|
||||
searchId: searches === 1 ? "old-search" : "new-search",
|
||||
});
|
||||
}),
|
||||
http.get("*/api/v1/stocks/screener/search/old-search", async () => {
|
||||
await oldPage.promise;
|
||||
|
||||
return HttpResponse.json({
|
||||
asOf: "2026-10-10T10:00:00Z",
|
||||
hasNext: false,
|
||||
items: [{
|
||||
countryOfRisk: "RU",
|
||||
currency: "RUB",
|
||||
instrumentUid: "old-page",
|
||||
isin: null,
|
||||
logoName: null,
|
||||
lot: 1,
|
||||
name: "Старый результат",
|
||||
realExchange: "REAL_EXCHANGE_MOEX",
|
||||
sector: "financial",
|
||||
shareType: "SHARE_TYPE_COMMON",
|
||||
ticker: "OLD",
|
||||
}],
|
||||
page: 2,
|
||||
searchId: "old-search",
|
||||
});
|
||||
}),
|
||||
);
|
||||
render(<StocksPageVmProbe />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "search" }));
|
||||
await screen.findByText("Старый");
|
||||
fireEvent.click(screen.getByRole("button", { name: "page" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "search" }));
|
||||
await screen.findByText("Новый");
|
||||
oldPage.resolve();
|
||||
|
||||
await waitFor(() => expect(screen.getByText("Новый")).toBeVisible());
|
||||
expect(screen.queryByText("Старый результат")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("disables filters and shows loading while searching", async () => {
|
||||
const { promise, resolve } = Promise.withResolvers<void>();
|
||||
server.use(
|
||||
http.post("*/api/v1/stocks/screener/search", async () => {
|
||||
await promise;
|
||||
|
||||
return HttpResponse.json({
|
||||
asOf: "2026-10-10T10:00:00Z",
|
||||
hasNext: false,
|
||||
items: [],
|
||||
page: 1,
|
||||
searchId: "pending-search",
|
||||
});
|
||||
}),
|
||||
);
|
||||
configureAuthClient({
|
||||
accessToken: () => "synthetic",
|
||||
clear: vi.fn(),
|
||||
refresh: () => Promise.resolve(false),
|
||||
});
|
||||
render(
|
||||
<QueryClientProvider client={createTestQueryClient()}>
|
||||
<MantineProvider>
|
||||
<MemoryRouter>
|
||||
<StocksPage />
|
||||
</MemoryRouter>
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Найти" }));
|
||||
|
||||
await waitFor(() => expect(
|
||||
screen.getByRole("combobox", { name: "Сектор" }),
|
||||
).toBeDisabled());
|
||||
expect(screen.getByRole("button", { name: "Найти" })).toHaveAttribute(
|
||||
"data-loading",
|
||||
"true",
|
||||
);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,89 +1,274 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { Badge, Group, Text } from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ChangeEvent, FC } from "react";
|
||||
|
||||
import {
|
||||
InstrumentSearch,
|
||||
InstrumentSearchCard,
|
||||
} from "@/features/instrument-search";
|
||||
import { formatMoney, formatSnapshotTime } from "@/shared/lib";
|
||||
Alert,
|
||||
Anchor,
|
||||
Avatar,
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
Fieldset,
|
||||
Group,
|
||||
NumberInput,
|
||||
Pagination,
|
||||
Select,
|
||||
SimpleGrid,
|
||||
Stack,
|
||||
Text,
|
||||
TextInput,
|
||||
Title,
|
||||
} from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
|
||||
import type { StocksPageVm } from "./StocksPage.vm";
|
||||
import { formatSnapshotTime, instrumentLogoUrl } from "@/shared/lib";
|
||||
|
||||
import type { Criteria, StocksPageVm } from "./StocksPage.vm";
|
||||
|
||||
import { useStocksPagePresentationVm } from "./StocksPagePresentation.vm";
|
||||
|
||||
type CriteriaField = {
|
||||
label: keyof Criteria;
|
||||
options?: readonly string[];
|
||||
type?: "number";
|
||||
};
|
||||
|
||||
type StockCardProps = { item: StocksPageVm["items"][number] };
|
||||
|
||||
type StockCriteriaFieldProps = {
|
||||
criteria: Criteria;
|
||||
field: CriteriaField;
|
||||
onChange: (name: keyof Criteria, value: string) => void;
|
||||
};
|
||||
|
||||
type StocksPageViewProps = { vm: StocksPageVm };
|
||||
|
||||
const criteriaFields: CriteriaField[] = [
|
||||
{ label: "query" },
|
||||
{
|
||||
label: "sector",
|
||||
options: [
|
||||
"consumer",
|
||||
"energy",
|
||||
"financial",
|
||||
"health_care",
|
||||
"industrials",
|
||||
"it",
|
||||
"materials",
|
||||
"real_estate",
|
||||
"telecom",
|
||||
"utilities",
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "shareType",
|
||||
options: [
|
||||
"SHARE_TYPE_ADR",
|
||||
"SHARE_TYPE_COMMON",
|
||||
"SHARE_TYPE_GDR",
|
||||
"SHARE_TYPE_PREFERRED",
|
||||
],
|
||||
},
|
||||
{ label: "currency", options: ["RUB", "USD", "EUR", "CNY", "HKD", "TRY"] },
|
||||
{
|
||||
label: "realExchange",
|
||||
options: [
|
||||
"REAL_EXCHANGE_MOEX",
|
||||
"REAL_EXCHANGE_RTS",
|
||||
"REAL_EXCHANGE_OTC",
|
||||
"REAL_EXCHANGE_DEALER",
|
||||
],
|
||||
},
|
||||
{ label: "countryOfRisk", options: ["RU", "US", "CN", "KZ", "HK", "TR"] },
|
||||
{ label: "maxLot", type: "number" },
|
||||
];
|
||||
|
||||
function numberChange(
|
||||
field: keyof Criteria,
|
||||
onChange: StockCriteriaFieldProps["onChange"],
|
||||
) {
|
||||
return (value: number | string) => onChange(field, String(value));
|
||||
}
|
||||
|
||||
function selectChange(
|
||||
field: keyof Criteria,
|
||||
onChange: StockCriteriaFieldProps["onChange"],
|
||||
) {
|
||||
return (value: null | string) => onChange(field, value ?? "");
|
||||
}
|
||||
|
||||
function selectOptions(field: CriteriaField, translate: ReturnType<typeof useTranslation>["t"]) {
|
||||
return field.options?.map(value => ({
|
||||
label: translate(`stock.screener.options.${field.label}.${value}`, {
|
||||
defaultValue: value,
|
||||
}),
|
||||
value,
|
||||
}));
|
||||
}
|
||||
|
||||
function textChange(
|
||||
field: keyof Criteria,
|
||||
onChange: StockCriteriaFieldProps["onChange"],
|
||||
) {
|
||||
return (event: ChangeEvent<HTMLInputElement>) =>
|
||||
onChange(field, event.currentTarget.value);
|
||||
}
|
||||
|
||||
const StockCriteriaField: FC<StockCriteriaFieldProps> = (props) => {
|
||||
const { criteria, field, onChange } = props;
|
||||
const { t } = useTranslation();
|
||||
const options = selectOptions(field, t);
|
||||
if (field.type === "number") return (
|
||||
<NumberInput
|
||||
label={t(`stock.screener.${field.label}`)}
|
||||
min={1}
|
||||
onChange={numberChange(field.label, onChange)}
|
||||
value={criteria[field.label]}
|
||||
/>
|
||||
);
|
||||
|
||||
if (options) return (
|
||||
<Select
|
||||
clearable
|
||||
data={options}
|
||||
label={t(`stock.screener.${field.label}`)}
|
||||
onChange={selectChange(field.label, onChange)}
|
||||
value={criteria[field.label] || null}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<TextInput
|
||||
label={t(`stock.screener.${field.label}`)}
|
||||
onChange={textChange(field.label, onChange)}
|
||||
value={criteria[field.label]}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const StockCard: FC<StockCardProps> = (props) => {
|
||||
const { item } = props;
|
||||
const { t } = useTranslation();
|
||||
|
||||
const exchange = item.realExchange
|
||||
? t(`stock.exchanges.${item.realExchange}`, {
|
||||
defaultValue: item.realExchange,
|
||||
})
|
||||
: undefined;
|
||||
|
||||
const lot = item.lot === null
|
||||
? undefined
|
||||
: t("stock.lot", { value: item.lot });
|
||||
|
||||
return (
|
||||
<Card p="md" withBorder>
|
||||
<Group gap="sm" wrap="nowrap">
|
||||
<Avatar alt="" radius="md" size={40} src={instrumentLogoUrl(item.logoName)}>
|
||||
{item.name[0]}
|
||||
</Avatar>
|
||||
|
||||
<Stack gap={2} miw={0}>
|
||||
<Anchor
|
||||
c="inherit"
|
||||
component={Link}
|
||||
fw={600}
|
||||
to={`/stocks/${item.instrumentUid}`}
|
||||
>
|
||||
{item.name}
|
||||
</Anchor>
|
||||
|
||||
<Text c="dimmed" size="xs">
|
||||
{item.ticker ?? "-"} · {item.shareType ?? "-"}
|
||||
</Text>
|
||||
|
||||
<Group gap="xs">
|
||||
{exchange && <Badge color="gray" variant="light">{exchange}</Badge>}
|
||||
|
||||
{item.currency && (
|
||||
<Badge color="gray" variant="light">{item.currency}</Badge>
|
||||
)}
|
||||
|
||||
{lot && <Text c="dimmed" size="xs">{lot}</Text>}
|
||||
</Group>
|
||||
|
||||
{item.isin && (
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("stock.isin", { value: item.isin })}
|
||||
</Text>
|
||||
)}
|
||||
</Stack>
|
||||
</Group>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
const StocksPageView: FC<StocksPageViewProps> = (props) => {
|
||||
const { vm } = props;
|
||||
const { t } = useTranslation();
|
||||
const { getControlProps, getItemProps } = useStocksPagePresentationVm();
|
||||
|
||||
return (
|
||||
<InstrumentSearch kind="stock" vm={vm}>
|
||||
{vm.items.map((stock) => {
|
||||
const quote = (
|
||||
<>
|
||||
<Text fw={650} size="xl">
|
||||
{stock.price ? formatMoney(stock.price) : "—"}
|
||||
</Text>
|
||||
<Stack gap="lg">
|
||||
<div>
|
||||
<Title order={1}>{t("stock.screenerTitle")}</Title>
|
||||
|
||||
<Text c="dimmed" size="xs">
|
||||
{stock.price && stock.priceAt
|
||||
? t("stock.priceAt", {
|
||||
date: formatSnapshotTime(stock.priceAt),
|
||||
})
|
||||
: t("stock.priceUnavailable")}
|
||||
</Text>
|
||||
<Text c="dimmed" mt="xs">{t("stock.screenerSubtitle")}</Text>
|
||||
</div>
|
||||
|
||||
{stock.apiTradeAvailable === true && (
|
||||
<Text c="green.8" mt="sm" size="xs">
|
||||
{t("stock.apiAvailable")}
|
||||
</Text>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
<Fieldset disabled={vm.loading} variant="unstyled">
|
||||
<SimpleGrid cols={{ base: 1, sm: 2 }}>
|
||||
{criteriaFields.map(field => (
|
||||
<StockCriteriaField
|
||||
criteria={vm.criteria}
|
||||
field={field}
|
||||
key={field.label}
|
||||
onChange={vm.onCriteriaChange}
|
||||
/>
|
||||
))}
|
||||
</SimpleGrid>
|
||||
|
||||
return (
|
||||
<InstrumentSearchCard
|
||||
instrument={stock}
|
||||
key={stock.instrumentUid}
|
||||
quote={quote}
|
||||
>
|
||||
<Text c="dimmed" size="sm">
|
||||
{stock.ticker} ·{" "}
|
||||
{t(`stock.shareTypes.${stock.shareType}`, {
|
||||
defaultValue: t("stock.share"),
|
||||
})}
|
||||
</Text>
|
||||
<Group mt="lg">
|
||||
<Button loading={vm.loading} onClick={vm.onSearch}>
|
||||
{t("stock.screener.search")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Fieldset>
|
||||
|
||||
<Group gap="xs" mt="sm">
|
||||
<Badge color="gray" variant="light">
|
||||
{t(`stock.exchanges.${stock.realExchange}`, {
|
||||
defaultValue: t("stock.exchangeUnknown"),
|
||||
})}
|
||||
</Badge>
|
||||
{!!vm.error && (
|
||||
<Alert color="orange" role="status">{t("stock.screener.error")}</Alert>
|
||||
)}
|
||||
|
||||
{!!stock.classCode && (
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("stock.classCode", { code: stock.classCode })}
|
||||
</Text>
|
||||
)}
|
||||
</Group>
|
||||
{vm.resultTime && (
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("stock.screener.asOf", {
|
||||
date: formatSnapshotTime(vm.resultTime),
|
||||
})}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
{!!stock.isin && (
|
||||
<Text c="dimmed" mt={4} size="xs">
|
||||
{t("stock.isin", { value: stock.isin })}
|
||||
</Text>
|
||||
)}
|
||||
{vm.searched && !vm.loading && !vm.error && vm.items.length === 0 && (
|
||||
<Text c="dimmed">{t("stock.screener.empty")}</Text>
|
||||
)}
|
||||
|
||||
{stock.apiTradeAvailable === false && (
|
||||
<Text c="dimmed" mt={4} size="xs">
|
||||
{t("stock.apiUnavailable")}
|
||||
</Text>
|
||||
)}
|
||||
</InstrumentSearchCard>
|
||||
);
|
||||
})}
|
||||
</InstrumentSearch>
|
||||
<Stack gap="sm">
|
||||
{vm.items.map(item => (
|
||||
<StockCard item={item} key={item.instrumentUid} />
|
||||
))}
|
||||
</Stack>
|
||||
|
||||
{vm.totalPages > 1 && (
|
||||
<Group aria-label={t("stock.screener.pagination")} component="nav" justify="center">
|
||||
<Pagination
|
||||
disabled={vm.loading}
|
||||
getControlProps={getControlProps}
|
||||
getItemProps={getItemProps}
|
||||
onChange={vm.onPage}
|
||||
total={vm.totalPages}
|
||||
value={vm.page ?? 1}
|
||||
/>
|
||||
</Group>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,43 +1,119 @@
|
||||
import { MIN_STOCK_SEARCH_LENGTH, useStockSearch } from "@/entities/stock";
|
||||
import { useInstrumentSearch } from "@/features/instrument-search";
|
||||
import { useScreenSync } from "@/features/tbank-connection";
|
||||
import { apiErrorCode } from "@/shared/api";
|
||||
import { instrumentLogoUrl } from "@/shared/lib";
|
||||
import { useRef, useState } from "react";
|
||||
|
||||
import { apiClient } from "@/shared/api";
|
||||
|
||||
type Criteria = {
|
||||
countryOfRisk: string;
|
||||
currency: string;
|
||||
maxLot: string;
|
||||
query: string;
|
||||
realExchange: string;
|
||||
sector: string;
|
||||
shareType: string;
|
||||
};
|
||||
|
||||
type ScreenerPage = Awaited<ReturnType<typeof readPage>>;
|
||||
|
||||
type StocksPageVm = ReturnType<typeof useStocksPageVm>;
|
||||
|
||||
const emptyCriteria: Criteria = {
|
||||
countryOfRisk: "",
|
||||
currency: "",
|
||||
maxLot: "",
|
||||
query: "",
|
||||
realExchange: "",
|
||||
sector: "",
|
||||
shareType: "",
|
||||
};
|
||||
|
||||
async function createSearch(criteria: Criteria) {
|
||||
const { data } = await apiClient.POST("/api/v1/stocks/screener/search", {
|
||||
body: {
|
||||
...(criteria.countryOfRisk && { countryOfRisk: criteria.countryOfRisk }),
|
||||
...(criteria.currency && { currency: criteria.currency }),
|
||||
...(criteria.maxLot && { maxLot: Number(criteria.maxLot) }),
|
||||
...(criteria.query && { query: criteria.query }),
|
||||
...(criteria.realExchange && { realExchange: criteria.realExchange }),
|
||||
...(criteria.sector && { sector: criteria.sector }),
|
||||
...(criteria.shareType && { shareType: criteria.shareType }),
|
||||
},
|
||||
});
|
||||
|
||||
if (!data) throw new Error("Stock screener search failed");
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
async function readPage(searchId: string, page: number) {
|
||||
const { data } = await apiClient.GET(
|
||||
"/api/v1/stocks/screener/search/{searchId}",
|
||||
{ params: { path: { searchId }, query: { page } } },
|
||||
);
|
||||
|
||||
if (!data) throw new Error("Stock screener page failed");
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
function useStocksPageVm() {
|
||||
const search = useInstrumentSearch(MIN_STOCK_SEARCH_LENGTH);
|
||||
const { canSearch, debounced, isWaiting, query } = search;
|
||||
const result = useStockSearch(debounced);
|
||||
useScreenSync({ query: debounced, screen: "stocks" }, [result]);
|
||||
const [criteria, setCriteria] = useState(emptyCriteria);
|
||||
const [page, setPage] = useState<null | ScreenerPage>(null);
|
||||
const [pending, setPending] = useState(false);
|
||||
const [error, setError] = useState(false);
|
||||
const requestIdRef = useRef(0);
|
||||
|
||||
const search = async () => {
|
||||
const currentRequestId = requestIdRef.current + 1;
|
||||
requestIdRef.current = currentRequestId;
|
||||
setPending(true);
|
||||
setError(false);
|
||||
|
||||
try {
|
||||
const result = await createSearch(criteria);
|
||||
if (requestIdRef.current === currentRequestId) setPage(result);
|
||||
}
|
||||
catch {
|
||||
if (requestIdRef.current === currentRequestId) setError(true);
|
||||
}
|
||||
finally {
|
||||
if (requestIdRef.current === currentRequestId) setPending(false);
|
||||
}
|
||||
};
|
||||
|
||||
const changePage = async (nextPage: number) => {
|
||||
if (!page) return;
|
||||
|
||||
const currentRequestId = requestIdRef.current + 1;
|
||||
requestIdRef.current = currentRequestId;
|
||||
setPending(true);
|
||||
setError(false);
|
||||
|
||||
try {
|
||||
const result = await readPage(page.searchId, nextPage);
|
||||
if (requestIdRef.current === currentRequestId) setPage(result);
|
||||
}
|
||||
catch {
|
||||
if (requestIdRef.current === currentRequestId) setError(true);
|
||||
}
|
||||
finally {
|
||||
if (requestIdRef.current === currentRequestId) setPending(false);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
canSearch,
|
||||
code: apiErrorCode(result.error),
|
||||
error:
|
||||
!result.data
|
||||
&& (result.isError || result.meta?.sync.state === "failed"),
|
||||
items:
|
||||
result.data?.map(stock => ({
|
||||
...stock,
|
||||
logoSrc: instrumentLogoUrl(stock.logoName),
|
||||
to: `/stocks/${encodeURIComponent(stock.slug)}`,
|
||||
})) ?? [],
|
||||
loading:
|
||||
canSearch
|
||||
&& (isWaiting
|
||||
|| (!result.data
|
||||
&& !result.isError
|
||||
&& result.meta?.sync.state !== "failed")),
|
||||
onQueryChange: search.onQueryChange,
|
||||
partial: result.meta?.availability === "partial",
|
||||
query,
|
||||
ready:
|
||||
debounced.length >= MIN_STOCK_SEARCH_LENGTH
|
||||
&& !isWaiting
|
||||
&& Boolean(result.data),
|
||||
criteria,
|
||||
error,
|
||||
items: page?.items ?? [],
|
||||
loading: pending,
|
||||
onCriteriaChange: (name: keyof Criteria, value: string) =>
|
||||
setCriteria(current => ({ ...current, [name]: value })),
|
||||
onPage: (nextPage: number) => void changePage(nextPage),
|
||||
onSearch: () => void search(),
|
||||
page: page?.page,
|
||||
resultTime: page?.asOf,
|
||||
searched: page !== null,
|
||||
totalPages: page ? page.page + Number(page.hasNext) : 0,
|
||||
};
|
||||
}
|
||||
|
||||
export { type StocksPageVm, useStocksPageVm };
|
||||
export { type Criteria, type StocksPageVm, useStocksPageVm };
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { Pagination } from "@mantine/core";
|
||||
import type { ComponentProps } from "react";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
function useStocksPagePresentationVm() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const getControlProps: ComponentProps<typeof Pagination>["getControlProps"] = control => ({
|
||||
"aria-label": t(control === "previous" ? "stock.previous" : "stock.next"),
|
||||
});
|
||||
|
||||
const getItemProps: ComponentProps<typeof Pagination>["getItemProps"] = page => ({
|
||||
"aria-label": t("stock.screener.page", { page }),
|
||||
});
|
||||
|
||||
return { getControlProps, getItemProps };
|
||||
}
|
||||
|
||||
export { useStocksPagePresentationVm };
|
||||
Vendored
+589
-381
File diff suppressed because it is too large
Load Diff
@@ -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();
|
||||
|
||||
@@ -145,7 +145,7 @@ function useResourceQuery<
|
||||
queryKey: options.queryKey,
|
||||
refetch: query.refetch,
|
||||
status: query.status,
|
||||
sync: query.data?.sync,
|
||||
sync: query.data && "sync" in query.data ? query.data.sync : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+1057
-702
File diff suppressed because it is too large
Load Diff
@@ -382,6 +382,13 @@ const ru = {
|
||||
yearUnavailable: "Сравнение с годом ранее недоступно.",
|
||||
},
|
||||
investment: {
|
||||
attempt: {
|
||||
cancelled: "Обновление отменено",
|
||||
failed: "Обновление не удалось",
|
||||
partial: "Обновлено частично",
|
||||
running: "Обновление выполняется",
|
||||
succeeded: "Обновлено",
|
||||
},
|
||||
history: "История догружается",
|
||||
partial: "Период загружен не полностью",
|
||||
refresh: "Обновить",
|
||||
@@ -629,6 +636,57 @@ const ru = {
|
||||
quantity: "Количество акций",
|
||||
record: "Дата реестра",
|
||||
refreshPrice: "Обновить цену",
|
||||
screener: {
|
||||
asOf: "Список получен {{date}}",
|
||||
countryOfRisk: "Страна риска",
|
||||
currency: "Валюта расчётов",
|
||||
empty: "Подходящие акции не найдены.",
|
||||
error: "Не удалось получить результат скринера. Попробуйте найти снова.",
|
||||
maxLot: "Максимальный размер лота",
|
||||
options: {
|
||||
countryOfRisk: {
|
||||
CN: "Китай",
|
||||
HK: "Гонконг",
|
||||
KZ: "Казахстан",
|
||||
RU: "Россия",
|
||||
TR: "Турция",
|
||||
US: "США",
|
||||
},
|
||||
realExchange: {
|
||||
REAL_EXCHANGE_DEALER: "Площадка брокера",
|
||||
REAL_EXCHANGE_MOEX: "Мосбиржа",
|
||||
REAL_EXCHANGE_OTC: "Внебиржевой рынок",
|
||||
REAL_EXCHANGE_RTS: "СПБ Биржа",
|
||||
},
|
||||
sector: {
|
||||
consumer: "Потребительский сектор",
|
||||
energy: "Энергетика",
|
||||
financial: "Финансы",
|
||||
health_care: "Здравоохранение",
|
||||
industrials: "Промышленность",
|
||||
it: "Информационные технологии",
|
||||
materials: "Материалы",
|
||||
real_estate: "Недвижимость",
|
||||
telecom: "Телекоммуникации",
|
||||
utilities: "Коммунальные услуги",
|
||||
},
|
||||
shareType: {
|
||||
SHARE_TYPE_ADR: "Депозитарная расписка",
|
||||
SHARE_TYPE_COMMON: "Обыкновенная акция",
|
||||
SHARE_TYPE_GDR: "Глобальная депозитарная расписка",
|
||||
SHARE_TYPE_PREFERRED: "Привилегированная акция",
|
||||
},
|
||||
},
|
||||
page: "Страница {{page}}",
|
||||
pagination: "Страницы результатов",
|
||||
query: "Название или тикер",
|
||||
realExchange: "Площадка",
|
||||
search: "Найти",
|
||||
sector: "Сектор",
|
||||
shareType: "Тип акции",
|
||||
},
|
||||
screenerSubtitle: "Подберите акции по данным каталога T-Bank. Доступность не гарантирует исполнение сделки.",
|
||||
screenerTitle: "Скринер акций",
|
||||
searchHint: "Введите хотя бы два символа.",
|
||||
searching: "Ищем акции",
|
||||
searchLabel: "Поиск акций",
|
||||
|
||||
@@ -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