refactor: simplify frontend and clarify module ownership #45
@@ -3,7 +3,7 @@ import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { cssVariablesResolver, theme } from "@wealthledger/ui/theme";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import { type InitialEntry, MemoryRouter } from "react-router";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { AuthProvider } from "@/features/auth";
|
||||
@@ -12,7 +12,7 @@ import { server } from "@/test/server";
|
||||
|
||||
import { AppRoutes } from "./AppRoutes";
|
||||
|
||||
function renderRoutes(path: string) {
|
||||
function renderRoutes(path: InitialEntry) {
|
||||
return render(
|
||||
<QueryClientProvider client={createTestQueryClient()}>
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
@@ -57,10 +57,18 @@ describe("AppRoutes", () => {
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("logs in through the public form and reaches the protected landing", async () => {
|
||||
it.each([
|
||||
{ endpoint: "login", path: "/accounts", title: "Вход" },
|
||||
{ endpoint: "register", path: "/register", title: "Регистрация" },
|
||||
{
|
||||
endpoint: "login",
|
||||
path: { pathname: "/login", state: { returnTo: "//example.com" } },
|
||||
title: "Вход",
|
||||
},
|
||||
])("authenticates via $endpoint and reaches the protected landing from $path", async ({ endpoint, path, title }) => {
|
||||
let credentials: unknown;
|
||||
server.use(
|
||||
http.post("*/api/v1/auth/login", async ({ request }) => {
|
||||
http.post(`*/api/v1/auth/${endpoint}`, async ({ request }) => {
|
||||
credentials = await request.json();
|
||||
|
||||
return HttpResponse.json({
|
||||
@@ -69,16 +77,23 @@ describe("AppRoutes", () => {
|
||||
});
|
||||
}),
|
||||
);
|
||||
renderRoutes("/accounts");
|
||||
renderRoutes(path);
|
||||
|
||||
await screen.findByRole("heading", { level: 1, name: "Вход" });
|
||||
await screen.findByRole("heading", { level: 1, name: title });
|
||||
fireEvent.change(screen.getByLabelText("Email"), {
|
||||
target: { value: " User@Example.com " },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("Пароль"), {
|
||||
target: { value: "a secure password" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Вход" }));
|
||||
|
||||
if (endpoint === "register") {
|
||||
fireEvent.change(screen.getByLabelText("Подтвердите пароль"), {
|
||||
target: { value: "a secure password" },
|
||||
});
|
||||
}
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: title }));
|
||||
|
||||
expect(
|
||||
await screen.findByRole("heading", {
|
||||
|
||||
@@ -24,7 +24,7 @@ function useBankPeriodPickerVm(props: BankPeriodPickerProps) {
|
||||
onChange(next);
|
||||
};
|
||||
|
||||
return { onChange, onPeriodChange, t, value };
|
||||
return { onPeriodChange, t, value };
|
||||
}
|
||||
|
||||
export { useBankPeriodPickerVm };
|
||||
|
||||
@@ -14,35 +14,28 @@ type BondPeriod = NonNullable<
|
||||
|
||||
const BOND_STALE_TIME_MS = 30_000;
|
||||
|
||||
function bondQueryOptions(uid: string) {
|
||||
return {
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
};
|
||||
}
|
||||
|
||||
function useBond(identifier: string) {
|
||||
const isUid
|
||||
= /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
|
||||
identifier,
|
||||
);
|
||||
|
||||
const byUid = useResourceQuery({
|
||||
...bondQueryOptions(identifier),
|
||||
enabled: Boolean(identifier) && isUid,
|
||||
});
|
||||
// eslint-disable-next-line unicorn/prefer-minimal-ternary -- Hoisting params breaks the generated union of endpoint request shapes.
|
||||
const init = isUid
|
||||
? { params: { path: { uid: identifier } } }
|
||||
: { params: { path: { ticker: identifier } } };
|
||||
|
||||
const byTicker = useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/by-ticker/{ticker}", {
|
||||
params: { path: { ticker: identifier } },
|
||||
}),
|
||||
enabled: Boolean(identifier) && !isUid,
|
||||
const options = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
isUid ? "/api/v1/bonds/{uid}" : "/api/v1/bonds/by-ticker/{ticker}",
|
||||
init,
|
||||
);
|
||||
|
||||
return useResourceQuery({
|
||||
...options,
|
||||
enabled: Boolean(identifier),
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
});
|
||||
|
||||
return isUid ? byUid : byTicker;
|
||||
}
|
||||
|
||||
function useBondCandles(uid: string, period: BondPeriod) {
|
||||
@@ -110,7 +103,6 @@ function useBondSearch(query: string) {
|
||||
export {
|
||||
type BondCoupons,
|
||||
type BondMetrics,
|
||||
type BondPeriod,
|
||||
MIN_BOND_SEARCH_LENGTH,
|
||||
useBond,
|
||||
useBondCandles,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
export {
|
||||
type BondCoupons,
|
||||
type BondMetrics,
|
||||
type BondPeriod,
|
||||
MIN_BOND_SEARCH_LENGTH,
|
||||
useBond,
|
||||
useBondCandles,
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import {
|
||||
apiQueryClient,
|
||||
type paths,
|
||||
unwrapResourceResult,
|
||||
useAuthenticatedQueries,
|
||||
useResourceQuery,
|
||||
} from "@/shared/api";
|
||||
|
||||
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<
|
||||
NonNullable<
|
||||
paths["/api/v1/stocks/{uid}/candles"]["get"]["parameters"]["query"]
|
||||
@@ -16,35 +16,28 @@ type StockPeriod = NonNullable<
|
||||
|
||||
const STOCK_STALE_TIME_MS = 30_000;
|
||||
|
||||
function stockQueryOptions(uid: string) {
|
||||
return {
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
staleTime: STOCK_STALE_TIME_MS,
|
||||
};
|
||||
}
|
||||
|
||||
function useStock(identifier: string) {
|
||||
const isUid
|
||||
= /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
|
||||
identifier,
|
||||
);
|
||||
|
||||
const byUid = useResourceQuery({
|
||||
...stockQueryOptions(identifier),
|
||||
enabled: Boolean(identifier) && isUid,
|
||||
});
|
||||
// eslint-disable-next-line unicorn/prefer-minimal-ternary -- Hoisting params breaks the generated union of endpoint request shapes.
|
||||
const init = isUid
|
||||
? { params: { path: { uid: identifier } } }
|
||||
: { params: { path: { ticker: identifier } } };
|
||||
|
||||
const byTicker = useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/by-ticker/{ticker}", {
|
||||
params: { path: { ticker: identifier } },
|
||||
}),
|
||||
enabled: Boolean(identifier) && !isUid,
|
||||
const options = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
isUid ? "/api/v1/stocks/{uid}" : "/api/v1/stocks/by-ticker/{ticker}",
|
||||
init,
|
||||
);
|
||||
|
||||
return useResourceQuery({
|
||||
...options,
|
||||
enabled: Boolean(identifier),
|
||||
staleTime: STOCK_STALE_TIME_MS,
|
||||
});
|
||||
|
||||
return isUid ? byUid : byTicker;
|
||||
}
|
||||
|
||||
function useStockCandles(uid: string, period: StockPeriod) {
|
||||
@@ -99,22 +92,6 @@ function useStockQuote(uid: string) {
|
||||
});
|
||||
}
|
||||
|
||||
function useStocks(uids: string[]) {
|
||||
const uniqueUids = [...new Set(uids)];
|
||||
|
||||
const queries = useAuthenticatedQueries(
|
||||
uniqueUids.map(uniqueUid => stockQueryOptions(uniqueUid)),
|
||||
);
|
||||
|
||||
return new Map(
|
||||
queries.map((query, index) => [
|
||||
// eslint-disable-next-line security/detect-object-injection -- This is a positional index into the local array, not a user-supplied object key.
|
||||
uniqueUids[index],
|
||||
unwrapResourceResult(query).data,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
function useStockSearch(query: string) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks", {
|
||||
@@ -127,13 +104,12 @@ function useStockSearch(query: string) {
|
||||
|
||||
export {
|
||||
MIN_STOCK_SEARCH_LENGTH,
|
||||
type StockPeriod,
|
||||
type StockDividends,
|
||||
useStock,
|
||||
useStockCandles,
|
||||
useStockCompany,
|
||||
useStockDividends,
|
||||
useStockPosition,
|
||||
useStockQuote,
|
||||
useStocks,
|
||||
useStockSearch,
|
||||
};
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
export {
|
||||
MIN_STOCK_SEARCH_LENGTH,
|
||||
type StockPeriod,
|
||||
type StockDividends,
|
||||
useStock,
|
||||
useStockCandles,
|
||||
useStockCompany,
|
||||
useStockDividends,
|
||||
useStockPosition,
|
||||
useStockQuote,
|
||||
useStocks,
|
||||
useStockSearch,
|
||||
} from "./api/queries";
|
||||
|
||||
@@ -3,11 +3,9 @@ import { createContext, use } from "react";
|
||||
import type { paths } from "@/shared/api";
|
||||
|
||||
type AuthContextValue = {
|
||||
accessToken: string | undefined;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
ready: boolean;
|
||||
refresh: () => Promise<boolean>;
|
||||
register: (email: string, password: string) => Promise<void>;
|
||||
user: undefined | User;
|
||||
};
|
||||
|
||||
@@ -27,6 +27,32 @@ function createAuthWrapper(
|
||||
);
|
||||
}
|
||||
|
||||
async function expireSession() {
|
||||
server.use(http.get("*/api/v1/brokerage-accounts", () =>
|
||||
HttpResponse.json({ code: "UNAUTHORIZED" }, { status: 401 }),
|
||||
{ once: true }));
|
||||
|
||||
try {
|
||||
await apiClient.GET("/api/v1/brokerage-accounts");
|
||||
}
|
||||
catch (error) {
|
||||
// A refresh that changes identity cancels the original user's request.
|
||||
if (!(error instanceof DOMException && error.name === "AbortError")) throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function requestAuthorization() {
|
||||
let authorization: null | string = null;
|
||||
server.use(http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
||||
authorization = request.headers.get("Authorization");
|
||||
|
||||
return HttpResponse.json(resource([]));
|
||||
}, { once: true }));
|
||||
await apiClient.GET("/api/v1/brokerage-accounts");
|
||||
|
||||
return authorization;
|
||||
}
|
||||
|
||||
describe("AuthProvider", () => {
|
||||
it("authorizes requests after restoring the initial session", async () => {
|
||||
let authorization: null | string
|
||||
@@ -77,7 +103,7 @@ describe("AuthProvider", () => {
|
||||
await waitFor(() => expect(result.current.ready).toBe(true));
|
||||
|
||||
expect(result.current.user).toBeUndefined();
|
||||
expect(result.current.accessToken).toBeUndefined();
|
||||
expect(await requestAuthorization()).toBeNull();
|
||||
expect(queryClient.getQueryData(["cached-query"])).toBeUndefined();
|
||||
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
|
||||
});
|
||||
@@ -106,13 +132,13 @@ describe("AuthProvider", () => {
|
||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.accessToken).toBe("restored-token"),
|
||||
expect(result.current.ready).toBe(true),
|
||||
);
|
||||
const response = await apiClient.GET("/api/v1/brokerage-accounts");
|
||||
|
||||
expect(response.response.status).toBe(401);
|
||||
await waitFor(() => expect(result.current.user).toBeUndefined());
|
||||
expect(result.current.accessToken).toBeUndefined();
|
||||
expect(await requestAuthorization()).toBeNull();
|
||||
expect(queryClient.getQueryData(["cached-query"])).toBeUndefined();
|
||||
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
|
||||
});
|
||||
@@ -147,7 +173,7 @@ describe("AuthProvider", () => {
|
||||
queryClient.setQueryData(bankCardsKey, [{ id: "bank-card-1" }]);
|
||||
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
|
||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||
await waitFor(() => expect(result.current.accessToken).toBe("test-token"));
|
||||
await waitFor(() => expect(result.current.ready).toBe(true));
|
||||
|
||||
expect(queryClient.getQueryData(bankCardsKey)).toEqual([
|
||||
{ id: "bank-card-1" },
|
||||
@@ -155,7 +181,7 @@ describe("AuthProvider", () => {
|
||||
await act(() => result.current.logout());
|
||||
|
||||
expect(result.current.user).toBeUndefined();
|
||||
expect(result.current.accessToken).toBeUndefined();
|
||||
expect(await requestAuthorization()).toBeNull();
|
||||
expect(queryClient.getQueryData(statusKey)).toBeUndefined();
|
||||
expect(queryClient.getQueryData(portfolioKey)).toBeUndefined();
|
||||
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
|
||||
@@ -265,7 +291,7 @@ describe("AuthProvider", () => {
|
||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||
await waitFor(() => expect(result.current.ready).toBe(true));
|
||||
queryClient.setQueryData(bankCardsKey, [{ id: "a-card" }]);
|
||||
await act(() => result.current.refresh());
|
||||
await act(() => expireSession());
|
||||
expect(queryClient.getQueryData(bankCardsKey)).toEqual([{ id: "a-card" }]);
|
||||
let release!: (value: string) => void;
|
||||
|
||||
@@ -283,7 +309,7 @@ describe("AuthProvider", () => {
|
||||
.catch(() => {});
|
||||
|
||||
identity = "b";
|
||||
await act(() => result.current.refresh());
|
||||
await act(() => expireSession());
|
||||
release("a-data");
|
||||
await pending;
|
||||
expect(result.current.user?.id).toBe("b");
|
||||
@@ -322,7 +348,7 @@ describe("AuthProvider", () => {
|
||||
expect(result.current.cards.data?.[0].id).toBe("a-card"),
|
||||
);
|
||||
identity = "b";
|
||||
await act(() => result.current.auth.refresh());
|
||||
await act(() => expireSession());
|
||||
await waitFor(() =>
|
||||
expect(result.current.cards.data?.[0].id).toBe("b-card"),
|
||||
);
|
||||
|
||||
@@ -29,7 +29,6 @@ async function request(
|
||||
function useAuthProviderVm() {
|
||||
const queryClient = useQueryClient();
|
||||
const [user, setUser] = useState<undefined | User>(undefined);
|
||||
const [accessToken, setAccessToken] = useState<string | undefined>(undefined);
|
||||
const accessTokenRef = useRef<string | undefined>(undefined);
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
@@ -69,7 +68,6 @@ function useAuthProviderVm() {
|
||||
|
||||
userRef.current = authentication.user;
|
||||
setUser(authentication.user);
|
||||
setAccessToken(authentication.accessToken);
|
||||
},
|
||||
[queryClient],
|
||||
);
|
||||
@@ -78,7 +76,6 @@ function useAuthProviderVm() {
|
||||
generationRef.current += 1;
|
||||
userRef.current = undefined;
|
||||
setUser(undefined);
|
||||
setAccessToken(undefined);
|
||||
accessTokenRef.current = undefined;
|
||||
queryClient.clear();
|
||||
}, [queryClient]);
|
||||
@@ -156,12 +153,10 @@ function useAuthProviderVm() {
|
||||
useEffect(() => () => configureAuthClient(), []);
|
||||
|
||||
const authContextValue = {
|
||||
accessToken,
|
||||
login: (email: string, password: string) =>
|
||||
authenticate("/api/v1/auth/login", email, password),
|
||||
logout,
|
||||
ready,
|
||||
refresh,
|
||||
register: (email: string, password: string) =>
|
||||
authenticate("/api/v1/auth/register", email, password),
|
||||
user,
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { useAuth } from "../../model/auth-context";
|
||||
import { AuthForm } from "../AuthForm/AuthForm";
|
||||
import { useLoginFormVm } from "./LoginForm.vm";
|
||||
|
||||
const LoginForm: FC = () => {
|
||||
const { onSubmit } = useLoginFormVm();
|
||||
const { login } = useAuth();
|
||||
|
||||
return <AuthForm onSubmit={onSubmit} />;
|
||||
return <AuthForm onSubmit={login} />;
|
||||
};
|
||||
|
||||
export { LoginForm };
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { ComponentProps } from "react";
|
||||
|
||||
import { useLocation, useNavigate } from "react-router";
|
||||
|
||||
import { useAuth } from "../../model/auth-context";
|
||||
import { AuthForm } from "../AuthForm/AuthForm";
|
||||
|
||||
function useLoginFormVm() {
|
||||
const { login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
|
||||
const returnTo
|
||||
= (location.state as null
|
||||
| { returnTo?: string })?.returnTo ?? "/accounts";
|
||||
|
||||
const onSubmit: ComponentProps<typeof AuthForm>["onSubmit"] = async (
|
||||
email,
|
||||
password,
|
||||
) => {
|
||||
await login(email, password);
|
||||
await navigate(returnTo, { replace: true });
|
||||
};
|
||||
|
||||
return { onSubmit };
|
||||
}
|
||||
|
||||
export { useLoginFormVm };
|
||||
@@ -1,12 +1,12 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { useAuth } from "../../model/auth-context";
|
||||
import { AuthForm } from "../AuthForm/AuthForm";
|
||||
import { useRegisterFormVm } from "./RegisterForm.vm";
|
||||
|
||||
const RegisterForm: FC = () => {
|
||||
const { onSubmit } = useRegisterFormVm();
|
||||
const { register } = useAuth();
|
||||
|
||||
return <AuthForm onSubmit={onSubmit} register />;
|
||||
return <AuthForm onSubmit={register} register />;
|
||||
};
|
||||
|
||||
export { RegisterForm };
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { ComponentProps } from "react";
|
||||
|
||||
import { useLocation, useNavigate } from "react-router";
|
||||
|
||||
import { useAuth } from "../../model/auth-context";
|
||||
import { AuthForm } from "../AuthForm/AuthForm";
|
||||
|
||||
function useRegisterFormVm() {
|
||||
const { register } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
|
||||
const returnTo
|
||||
= (location.state as null
|
||||
| { returnTo?: string })?.returnTo ?? "/accounts";
|
||||
|
||||
const onSubmit: ComponentProps<typeof AuthForm>["onSubmit"] = async (
|
||||
email,
|
||||
password,
|
||||
) => {
|
||||
await register(email, password);
|
||||
await navigate(returnTo, { replace: true });
|
||||
};
|
||||
|
||||
return { onSubmit, register };
|
||||
}
|
||||
|
||||
export { useRegisterFormVm };
|
||||
@@ -1,5 +1,8 @@
|
||||
export { section, type SectionState } from "./model/section";
|
||||
export { useInstrumentParameters } from "./model/useInstrumentParameters";
|
||||
export { InstrumentChart } from "./ui/InstrumentChart/InstrumentChart.view";
|
||||
export { InstrumentEvents } from "./ui/InstrumentEvents.view";
|
||||
export { InstrumentHeader } from "./ui/InstrumentHeader/InstrumentHeader.view";
|
||||
export { InstrumentPageState } from "./ui/InstrumentPageState.view";
|
||||
export { InstrumentPosition } from "./ui/InstrumentPosition.view";
|
||||
export { InstrumentSection } from "./ui/InstrumentSection.view";
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useSearchParams } from "react-router";
|
||||
|
||||
import type { OperationCategory } from "@/entities/broker-operation";
|
||||
|
||||
const instrumentPeriods = ["month", "halfYear", "year", "all"] as const;
|
||||
|
||||
function useInstrumentParameters(incomeFilter: "coupons" | "dividends") {
|
||||
const [parameters, setParameters] = useSearchParams();
|
||||
|
||||
const period = instrumentPeriods.find(
|
||||
value => value === parameters.get("period"),
|
||||
) ?? "month";
|
||||
|
||||
const filters: { categories: OperationCategory[]; value: string }[] = [
|
||||
{ categories: [], value: "all" },
|
||||
{ categories: ["trade"], value: "trades" },
|
||||
{ categories: ["income"], value: incomeFilter },
|
||||
{ categories: ["tax", "fee", "transfer", "other"], value: "other" },
|
||||
];
|
||||
|
||||
const { categories, value: filter } = filters.find(
|
||||
item => item.value === parameters.get("events"),
|
||||
) ?? filters[0];
|
||||
|
||||
const setParameter = (key: string, value: string) => {
|
||||
const next = new URLSearchParams(parameters);
|
||||
next.set(key, value);
|
||||
setParameters(next, { replace: true });
|
||||
};
|
||||
|
||||
return {
|
||||
categories,
|
||||
filter,
|
||||
period,
|
||||
search: parameters.size > 0 ? `?${parameters.toString()}` : "",
|
||||
setFilter: (value: string) => setParameter("events", value),
|
||||
setPeriod: (value: string) => setParameter("period", value),
|
||||
};
|
||||
}
|
||||
|
||||
export { instrumentPeriods, useInstrumentParameters };
|
||||
@@ -4,6 +4,8 @@ import { formatDate, formatDecimal, formatMoney } from "@/shared/lib";
|
||||
|
||||
import type { InstrumentChartProps } from "../../model/types";
|
||||
|
||||
import { instrumentPeriods } from "../../model/useInstrumentParameters";
|
||||
|
||||
function useInstrumentChartVm(props: InstrumentChartProps) {
|
||||
const { vm } = props;
|
||||
const { t } = useTranslation();
|
||||
@@ -34,7 +36,7 @@ function useInstrumentChartVm(props: InstrumentChartProps) {
|
||||
return { ...candle, price };
|
||||
});
|
||||
|
||||
const periodOptions = ["month", "halfYear", "year", "all"].map(value => ({
|
||||
const periodOptions = instrumentPeriods.map(value => ({
|
||||
label: t(`stock.periods.${value}`),
|
||||
value,
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
.header {
|
||||
padding: var(--mantine-spacing-lg);
|
||||
border-radius: var(--mantine-radius-lg);
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.identity {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--mantine-spacing-md);
|
||||
min-width: 0;
|
||||
}
|
||||
@media (max-width: 48em) {
|
||||
.header {
|
||||
padding: var(--mantine-spacing-md);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { FC, PropsWithChildren, ReactNode } from "react";
|
||||
|
||||
import { Avatar, Button, Group, Paper, Text, Title } from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import classes from "./InstrumentHeader.module.css";
|
||||
|
||||
type InstrumentHeaderProps = PropsWithChildren<{
|
||||
logoSrc: null | string;
|
||||
name: string;
|
||||
onRefresh: () => void;
|
||||
refreshing: boolean;
|
||||
subtitle: ReactNode;
|
||||
}>;
|
||||
|
||||
const InstrumentHeader: FC<InstrumentHeaderProps> = (props) => {
|
||||
const { children, logoSrc, name, onRefresh, refreshing, subtitle } = props;
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Paper className={classes.header} component="header" withBorder>
|
||||
<Group align="start" justify="space-between">
|
||||
<div className={classes.identity}>
|
||||
<Avatar alt="" key={logoSrc} radius="md" size={56} src={logoSrc}>
|
||||
{name[0]}
|
||||
</Avatar>
|
||||
|
||||
<div>
|
||||
<Title order={1} size="h2">{name}</Title>
|
||||
|
||||
<Text c="dimmed" size="sm">{subtitle}</Text>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button disabled={refreshing} onClick={onRefresh} variant="subtle">
|
||||
{t("investment.refresh")}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
{children}
|
||||
</Paper>
|
||||
);
|
||||
};
|
||||
|
||||
export { InstrumentHeader };
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { Anchor, Button, Skeleton, Stack, Text, Title } from "@mantine/core";
|
||||
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
|
||||
import { ApiErrorCode, isApiErrorCode } from "@/shared/api";
|
||||
|
||||
type InstrumentPageStateProps = {
|
||||
code?: string;
|
||||
kind: "bond" | "stock";
|
||||
loading: boolean;
|
||||
retry: () => void;
|
||||
};
|
||||
|
||||
const InstrumentPageState: FC<InstrumentPageStateProps> = (props) => {
|
||||
const { code, kind, loading, retry } = props;
|
||||
const { t } = useTranslation();
|
||||
if (loading) return (
|
||||
<LoadingSkeleton label={t(`${kind}.loading`)}>
|
||||
<Stack>
|
||||
<Skeleton h={110} />
|
||||
|
||||
<Skeleton h={350} />
|
||||
|
||||
<Skeleton h={170} />
|
||||
</Stack>
|
||||
</LoadingSkeleton>
|
||||
);
|
||||
|
||||
const ambiguousCode = kind === "stock"
|
||||
? ApiErrorCode.StockTickerAmbiguous
|
||||
: ApiErrorCode.BondTickerAmbiguous;
|
||||
|
||||
let message = t(`${kind}.unavailableText`);
|
||||
if (isApiErrorCode(code, ambiguousCode))
|
||||
message = t(`${kind}.ambiguousTicker`);
|
||||
if (
|
||||
isApiErrorCode(code, ApiErrorCode.TbankNotConnected)
|
||||
|| isApiErrorCode(code, ApiErrorCode.InvalidTbankToken)
|
||||
)
|
||||
message = t(`${kind}.connect`);
|
||||
|
||||
return (
|
||||
<Stack role="alert">
|
||||
<Title order={1}>{t(`${kind}.unavailable`)}</Title>
|
||||
|
||||
<Text>{message}</Text>
|
||||
|
||||
<Anchor component={Link} to={`/${kind}s`}>
|
||||
{t(`${kind}.backToSearch`)}
|
||||
</Anchor>
|
||||
|
||||
<Anchor component={Link} to="/settings">
|
||||
{t("accounts.openSettings")}
|
||||
</Anchor>
|
||||
|
||||
<Button onClick={retry} variant="default">
|
||||
{t("accounts.retry")}
|
||||
</Button>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export { InstrumentPageState };
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { Portfolio } from "@/entities/portfolio";
|
||||
|
||||
const portfolio: Portfolio
|
||||
= {
|
||||
cashBalances: [{ currency: "USD", value: "1" }],
|
||||
isStale: true,
|
||||
lastSuccessfulAt: "2026-08-13T10:00:00Z",
|
||||
positions: [
|
||||
{
|
||||
absoluteReturn: { currency: "RUB", value: "10" },
|
||||
averagePurchasePrice: null,
|
||||
currentValue: { currency: "RUB", value: "100" },
|
||||
displayName: "Акция",
|
||||
figi: "FIGI-STOCK",
|
||||
isin: null,
|
||||
logoName: "akciya.png",
|
||||
quantity: "2",
|
||||
ticker: null,
|
||||
type: "STOCK",
|
||||
},
|
||||
{
|
||||
absoluteReturn: { currency: "RUB", value: "-5" },
|
||||
averagePurchasePrice: { currency: "RUB", value: "45" },
|
||||
currentValue: { currency: "RUB", value: "50" },
|
||||
displayName: "Облигация",
|
||||
figi: "FIGI-BOND",
|
||||
isin: "RU000A0JX0J2",
|
||||
logoName: null,
|
||||
quantity: "1",
|
||||
ticker: null,
|
||||
type: "BOND",
|
||||
},
|
||||
{
|
||||
absoluteReturn: null,
|
||||
averagePurchasePrice: null,
|
||||
currentValue: null,
|
||||
displayName: "Фонд",
|
||||
figi: "FIGI-FUND",
|
||||
isin: null,
|
||||
logoName: "fond.png",
|
||||
quantity: "3",
|
||||
ticker: null,
|
||||
type: "FUND",
|
||||
},
|
||||
],
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
totalsByCurrency: [{ currency: "RUB", value: "150" }],
|
||||
};
|
||||
|
||||
const position: Portfolio["positions"][number] = {
|
||||
...portfolio.positions[0],
|
||||
absoluteReturn: { currency: "RUB", value: "25" },
|
||||
account: { id: "a", name: "Основной" },
|
||||
averagePurchasePrice: { currency: "RUB", value: "280" },
|
||||
currentValue: { currency: "RUB", value: "375" },
|
||||
displayName: "Сбербанк",
|
||||
figi: "FIGI-SBER",
|
||||
isin: "RU0009029540",
|
||||
logoName: null,
|
||||
quantity: "1.25",
|
||||
ticker: "SBER",
|
||||
};
|
||||
|
||||
const second = {
|
||||
...position,
|
||||
absoluteReturn: null,
|
||||
account: { id: "b", name: "ИИС" },
|
||||
averagePurchasePrice: null,
|
||||
currentValue: null,
|
||||
quantity: "-2",
|
||||
};
|
||||
|
||||
export { portfolio, position, second };
|
||||
@@ -0,0 +1,189 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { Portfolio } from "@/entities/portfolio";
|
||||
|
||||
import { toAccountPagePositionSections } from "./positions";
|
||||
import { portfolio, position, second } from "./positions.fixtures";
|
||||
|
||||
function sections(positions: Portfolio["positions"]) {
|
||||
return toAccountPagePositionSections({
|
||||
...portfolio,
|
||||
positions,
|
||||
});
|
||||
}
|
||||
|
||||
describe("account position sections", () => {
|
||||
it("excludes currency instruments only from display, preserving order and share denominators", () => {
|
||||
const otherTypes = [
|
||||
"OPTION",
|
||||
"OTHER",
|
||||
"FUTURE",
|
||||
"STRUCTURED_NOTE",
|
||||
"DIGITAL_FINANCIAL_ASSET",
|
||||
"FUND",
|
||||
] as const;
|
||||
|
||||
const snapshot: Portfolio = {
|
||||
...portfolio,
|
||||
cashBalances: [{ currency: "RUB", value: "1000" }],
|
||||
positions: [
|
||||
...portfolio.positions,
|
||||
{
|
||||
...portfolio.positions[0],
|
||||
currentValue: { currency: "RUB", value: "50" },
|
||||
figi: "FIGI-CURRENCY",
|
||||
type: "CURRENCY",
|
||||
},
|
||||
...otherTypes.map(
|
||||
|
||||
type =>
|
||||
({
|
||||
...portfolio.positions[2],
|
||||
currentValue:
|
||||
type === "OPTION" ? { currency: "RUB", value: "50" } : null,
|
||||
figi: `FIGI-${type}-NEXT`,
|
||||
type,
|
||||
}),
|
||||
),
|
||||
],
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
totalsByCurrency: [{ currency: "RUB", value: "1250" }],
|
||||
};
|
||||
|
||||
const original = structuredClone(snapshot);
|
||||
|
||||
const sections = toAccountPagePositionSections(snapshot);
|
||||
|
||||
expect(sections.map(section => section.kind)).toEqual([
|
||||
"stocks",
|
||||
"bonds",
|
||||
"other",
|
||||
]);
|
||||
expect(sections[2].groups.map(group => group.positions[0].figi)).toEqual([
|
||||
"FIGI-FUND",
|
||||
...otherTypes.map(type => `FIGI-${type}-NEXT`),
|
||||
]);
|
||||
expect(sections[0].groups[0].positions[0].shareText).toBe("40 %");
|
||||
expect(sections[1].groups[0].positions[0].shareText).toBe("20 %");
|
||||
expect(sections[2].groups[1].positions[0].shareText).toBe("20 %");
|
||||
expect(snapshot).toEqual(original);
|
||||
});
|
||||
|
||||
it("prepares grouped position sections with derived display data", () => {
|
||||
expect(
|
||||
toAccountPagePositionSections(portfolio).map(({ groups, kind }) => ({
|
||||
kind,
|
||||
positions: groups.flatMap(group => group.positions),
|
||||
})),
|
||||
).toMatchObject([
|
||||
{
|
||||
kind: "stocks",
|
||||
positions: [
|
||||
{
|
||||
displayName: "Акция",
|
||||
logoSrc: "https://invest-brands.cdn-tinkoff.ru/akciyax160.png",
|
||||
returnText: "+10 ₽",
|
||||
returnTone: "positive",
|
||||
shareText: "66,7 %",
|
||||
},
|
||||
],
|
||||
|
||||
},
|
||||
{
|
||||
kind: "bonds",
|
||||
positions: [
|
||||
{
|
||||
displayName: "Облигация",
|
||||
logoSrc: null,
|
||||
returnText: "-5 ₽",
|
||||
returnTone: "negative",
|
||||
shareText: "33,3 %",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: "other",
|
||||
positions: [
|
||||
{
|
||||
displayName: "Фонд",
|
||||
logoSrc: null,
|
||||
returnText: null,
|
||||
returnTone: undefined,
|
||||
shareText: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses ISIN only when FIGI is absent, never merging by name or ticker", () => {
|
||||
expect(
|
||||
|
||||
sections([
|
||||
{
|
||||
...position,
|
||||
figi: null,
|
||||
},
|
||||
{ ...second, figi: null },
|
||||
])[0].groups,
|
||||
).toHaveLength(1);
|
||||
expect(
|
||||
sections([position, { ...second, figi: "OTHER-FIGI" }])[0].groups,
|
||||
).toHaveLength(2);
|
||||
expect(
|
||||
|
||||
sections([
|
||||
{
|
||||
...position,
|
||||
figi: null,
|
||||
isin: null,
|
||||
},
|
||||
{
|
||||
...second,
|
||||
figi: null,
|
||||
isin: null,
|
||||
},
|
||||
])[0].groups,
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("preserves one-account cards and does not merge repeated rows on the same account", () => {
|
||||
expect(
|
||||
sections([position, { ...second, account: position.account }])[0].groups,
|
||||
).toHaveLength(2);
|
||||
expect(
|
||||
sections([
|
||||
{ ...position, account: undefined },
|
||||
{ ...second, account: undefined },
|
||||
])[0].groups,
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("keeps currencies and purchase prices attached to their source positions", () => {
|
||||
const source = [
|
||||
position,
|
||||
{
|
||||
...second,
|
||||
averagePurchasePrice: { currency: "USD", value: "0.99" },
|
||||
currentValue: { currency: "USD", value: "1.01" },
|
||||
},
|
||||
];
|
||||
|
||||
const before = structuredClone(source);
|
||||
const [group] = sections(source)[0].groups;
|
||||
expect(
|
||||
group.positions.map(item => [
|
||||
item.quantity,
|
||||
item.currentValue,
|
||||
item.averagePurchasePrice,
|
||||
]),
|
||||
).toEqual(
|
||||
source.map(item => [
|
||||
item.quantity,
|
||||
item.currentValue,
|
||||
item.averagePurchasePrice,
|
||||
]),
|
||||
);
|
||||
expect(source).toEqual(before);
|
||||
});
|
||||
});
|
||||
@@ -69,8 +69,6 @@ function positionIdentity(position: AccountPagePosition) {
|
||||
|
||||
function toAccountPagePositionSections(
|
||||
portfolio: Portfolio,
|
||||
instrumentDetails: Map<string, undefined
|
||||
| { slug: string }> = new Map(),
|
||||
): AccountPagePositionSection[] {
|
||||
const denominators = new Map<string, number>();
|
||||
|
||||
@@ -87,11 +85,10 @@ function toAccountPagePositionSections(
|
||||
"stocks",
|
||||
portfolio,
|
||||
denominators,
|
||||
instrumentDetails,
|
||||
);
|
||||
|
||||
const bonds = toSection("bonds", portfolio, denominators, instrumentDetails);
|
||||
const other = toSection("other", portfolio, denominators, instrumentDetails);
|
||||
const bonds = toSection("bonds", portfolio, denominators);
|
||||
const other = toSection("other", portfolio, denominators);
|
||||
|
||||
return [stocks, bonds, other].filter(section => section.groups.length > 0);
|
||||
}
|
||||
@@ -100,7 +97,6 @@ function toPosition(
|
||||
position: Portfolio["positions"][number],
|
||||
denominators: Map<string, number>,
|
||||
kind: PositionSectionKind,
|
||||
instrumentSlug?: string,
|
||||
): AccountPagePosition {
|
||||
const isExpanded = kind !== "other";
|
||||
|
||||
@@ -119,7 +115,7 @@ function toPosition(
|
||||
...position,
|
||||
instrumentTo:
|
||||
(kind === "stocks" || kind === "bonds") && position.instrumentUid
|
||||
? `/${kind}/${encodeURIComponent(instrumentSlug ?? position.instrumentUid)}`
|
||||
? `/${kind}/${encodeURIComponent(position.instrumentUid)}`
|
||||
: undefined,
|
||||
logoSrc: isExpanded
|
||||
? instrumentLogoUrl(position.logoName)
|
||||
@@ -141,8 +137,6 @@ function toSection(
|
||||
kind: PositionSectionKind,
|
||||
portfolio: Portfolio,
|
||||
denominators: Map<string, number>,
|
||||
instrumentDetails: Map<string, undefined
|
||||
| { slug: string }>,
|
||||
): AccountPagePositionSection {
|
||||
return {
|
||||
groups: groupPositions(
|
||||
@@ -161,7 +155,6 @@ function toSection(
|
||||
position,
|
||||
denominators,
|
||||
kind,
|
||||
instrumentDetails.get(position.instrumentUid ?? "")?.slug,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
.tile,
|
||||
.cash {
|
||||
.tile {
|
||||
border-color: var(--mantine-color-gray-3);
|
||||
background: var(--mantine-color-gray-0);
|
||||
}
|
||||
@@ -52,15 +51,10 @@
|
||||
margin-block: 5px;
|
||||
}
|
||||
|
||||
.tile,
|
||||
.cash {
|
||||
.tile {
|
||||
padding: var(--mantine-spacing-md);
|
||||
}
|
||||
|
||||
.cash {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.positive {
|
||||
color: var(--wl-color-positive);
|
||||
|
||||
@@ -212,10 +212,10 @@ describe("AccountPage states", () => {
|
||||
for (const link of links)
|
||||
expect(link).toHaveAttribute(
|
||||
"href",
|
||||
`/${collection}/${type === "STOCK" ? slug : uid}`,
|
||||
`/${collection}/${uid}`,
|
||||
);
|
||||
});
|
||||
expect(requests).toHaveBeenCalledTimes(type === "STOCK" ? 1 : 0);
|
||||
expect(requests).not.toHaveBeenCalled();
|
||||
expect(
|
||||
screen.queryByText("Название из карточки инструмента"),
|
||||
).not.toBeInTheDocument();
|
||||
@@ -234,43 +234,6 @@ describe("AccountPage states", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["unavailable", "noncanonical"])(
|
||||
"keeps exact UID links and the portfolio visible when ticker is %s",
|
||||
async (scenario) => {
|
||||
const uid = "c190ff1f-1447-4227-b543-316332699ca5";
|
||||
const requests = vi.fn();
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
|
||||
HttpResponse.json(
|
||||
resource({
|
||||
...portfolio,
|
||||
positions: [
|
||||
{
|
||||
...portfolio.positions[0],
|
||||
instrumentUid: uid,
|
||||
ticker: "SBERP",
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
),
|
||||
http.get("*/api/v1/stocks/:uid", () => {
|
||||
requests();
|
||||
|
||||
return scenario === "unavailable"
|
||||
? HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 })
|
||||
: HttpResponse.json(resource({ instrumentUid: uid, slug: uid }));
|
||||
}),
|
||||
);
|
||||
renderAccountRoute(createTestQueryClient());
|
||||
await waitFor(() => expect(requests).toHaveBeenCalledOnce());
|
||||
const links = await screen.findAllByRole("link", { name: "Вторая" });
|
||||
expect(links).toHaveLength(2);
|
||||
for (const link of links)
|
||||
expect(link).toHaveAttribute("href", `/stocks/${uid}`);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps the account and positions visible for an older HTTP response without structure", async () => {
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
|
||||
|
||||
@@ -6,63 +6,14 @@ import { http, HttpResponse } from "msw";
|
||||
import { MemoryRouter, Route, Routes } from "react-router";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { Portfolio } from "@/entities/portfolio";
|
||||
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createQueryWrapper } from "@/test/query";
|
||||
import { resource } from "@/test/resource";
|
||||
import { server } from "@/test/server";
|
||||
|
||||
import { toAccountPagePositionSections } from "../../model/positions";
|
||||
import { portfolio } from "../../model/positions.fixtures";
|
||||
import { useAccountPageViewModel } from "./AccountPage.vm";
|
||||
|
||||
const portfolio: Portfolio
|
||||
= {
|
||||
cashBalances: [{ currency: "USD", value: "1" }],
|
||||
isStale: true,
|
||||
lastSuccessfulAt: "2026-08-13T10:00:00Z",
|
||||
positions: [
|
||||
{
|
||||
absoluteReturn: { currency: "RUB", value: "10" },
|
||||
averagePurchasePrice: null,
|
||||
currentValue: { currency: "RUB", value: "100" },
|
||||
displayName: "Акция",
|
||||
figi: "FIGI-STOCK",
|
||||
isin: null,
|
||||
logoName: "akciya.png",
|
||||
quantity: "2",
|
||||
ticker: null,
|
||||
type: "STOCK",
|
||||
},
|
||||
{
|
||||
absoluteReturn: { currency: "RUB", value: "-5" },
|
||||
averagePurchasePrice: { currency: "RUB", value: "45" },
|
||||
currentValue: { currency: "RUB", value: "50" },
|
||||
displayName: "Облигация",
|
||||
figi: "FIGI-BOND",
|
||||
isin: "RU000A0JX0J2",
|
||||
logoName: null,
|
||||
quantity: "1",
|
||||
ticker: null,
|
||||
type: "BOND",
|
||||
},
|
||||
{
|
||||
absoluteReturn: null,
|
||||
averagePurchasePrice: null,
|
||||
currentValue: null,
|
||||
displayName: "Фонд",
|
||||
figi: "FIGI-FUND",
|
||||
isin: null,
|
||||
logoName: "fond.png",
|
||||
quantity: "3",
|
||||
ticker: null,
|
||||
type: "FUND",
|
||||
},
|
||||
],
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
totalsByCurrency: [{ currency: "RUB", value: "150" }],
|
||||
};
|
||||
|
||||
function configureTestAuth() {
|
||||
configureAuthClient({
|
||||
accessToken: () => "test-token",
|
||||
@@ -152,109 +103,6 @@ function mockLoadedAccountPage() {
|
||||
}
|
||||
|
||||
describe("useAccountPageViewModel", () => {
|
||||
it("excludes currency instruments only from display, preserving order and share denominators", () => {
|
||||
const otherTypes = [
|
||||
"OPTION",
|
||||
"OTHER",
|
||||
"FUTURE",
|
||||
"STRUCTURED_NOTE",
|
||||
"DIGITAL_FINANCIAL_ASSET",
|
||||
"FUND",
|
||||
] as const;
|
||||
|
||||
const snapshot: Portfolio = {
|
||||
...portfolio,
|
||||
cashBalances: [{ currency: "RUB", value: "1000" }],
|
||||
positions: [
|
||||
...portfolio.positions,
|
||||
{
|
||||
...portfolio.positions[0],
|
||||
currentValue: { currency: "RUB", value: "50" },
|
||||
figi: "FIGI-CURRENCY",
|
||||
type: "CURRENCY",
|
||||
},
|
||||
...otherTypes.map(
|
||||
|
||||
type =>
|
||||
({
|
||||
...portfolio.positions[2],
|
||||
currentValue:
|
||||
type === "OPTION" ? { currency: "RUB", value: "50" } : null,
|
||||
figi: `FIGI-${type}-NEXT`,
|
||||
type,
|
||||
}),
|
||||
),
|
||||
],
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
totalsByCurrency: [{ currency: "RUB", value: "1250" }],
|
||||
};
|
||||
|
||||
const original = structuredClone(snapshot);
|
||||
|
||||
const sections = toAccountPagePositionSections(snapshot);
|
||||
|
||||
expect(sections.map(section => section.kind)).toEqual([
|
||||
"stocks",
|
||||
"bonds",
|
||||
"other",
|
||||
]);
|
||||
expect(sections[2].groups.map(group => group.positions[0].figi)).toEqual([
|
||||
"FIGI-FUND",
|
||||
...otherTypes.map(type => `FIGI-${type}-NEXT`),
|
||||
]);
|
||||
expect(sections[0].groups[0].positions[0].shareText).toBe("40 %");
|
||||
expect(sections[1].groups[0].positions[0].shareText).toBe("20 %");
|
||||
expect(sections[2].groups[1].positions[0].shareText).toBe("20 %");
|
||||
expect(snapshot).toEqual(original);
|
||||
});
|
||||
|
||||
it("prepares grouped position sections with derived display data", () => {
|
||||
expect(
|
||||
toAccountPagePositionSections(portfolio).map(({ groups, kind }) => ({
|
||||
kind,
|
||||
positions: groups.flatMap(group => group.positions),
|
||||
})),
|
||||
).toMatchObject([
|
||||
{
|
||||
kind: "stocks",
|
||||
positions: [
|
||||
{
|
||||
displayName: "Акция",
|
||||
logoSrc: "https://invest-brands.cdn-tinkoff.ru/akciyax160.png",
|
||||
returnText: "+10 ₽",
|
||||
returnTone: "positive",
|
||||
shareText: "66,7 %",
|
||||
},
|
||||
],
|
||||
|
||||
},
|
||||
{
|
||||
kind: "bonds",
|
||||
positions: [
|
||||
{
|
||||
displayName: "Облигация",
|
||||
logoSrc: null,
|
||||
returnText: "-5 ₽",
|
||||
returnTone: "negative",
|
||||
shareText: "33,3 %",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: "other",
|
||||
positions: [
|
||||
{
|
||||
displayName: "Фонд",
|
||||
logoSrc: null,
|
||||
returnText: null,
|
||||
returnTone: undefined,
|
||||
shareText: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("prepares recent operations and events state for presentation views", async () => {
|
||||
configureTestAuth();
|
||||
mockLoadedAccountPage();
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
} from "@/entities/brokerage-event";
|
||||
import { type IncomeSummary, useIncomeSummary } from "@/entities/income";
|
||||
import { usePortfolio } from "@/entities/portfolio";
|
||||
import { useStocks } from "@/entities/stock";
|
||||
import { useScreenSync } from "@/features/tbank-connection";
|
||||
import { apiErrorCode } from "@/shared/api";
|
||||
|
||||
@@ -168,14 +167,6 @@ function useAccountPageViewModel(): AccountPageViewModel {
|
||||
const { accountId } = useParams();
|
||||
const portfolio = usePortfolio(accountId);
|
||||
|
||||
const stocks = useStocks(
|
||||
portfolio.data?.positions.flatMap(position =>
|
||||
position.type === "STOCK" && position.instrumentUid
|
||||
? [position.instrumentUid]
|
||||
: [],
|
||||
) ?? [],
|
||||
);
|
||||
|
||||
const operations = useBrokerageOperations(accountId, {
|
||||
limit: 5,
|
||||
});
|
||||
@@ -236,10 +227,7 @@ function useAccountPageViewModel(): AccountPageViewModel {
|
||||
accountId,
|
||||
incomeSummary,
|
||||
portfolio: portfolio.data,
|
||||
positionSections: toAccountPagePositionSections(
|
||||
portfolio.data,
|
||||
stocks,
|
||||
),
|
||||
positionSections: toAccountPagePositionSections(portfolio.data),
|
||||
recentEvents,
|
||||
recentOperations,
|
||||
state: "loaded" as const,
|
||||
|
||||
@@ -3,50 +3,16 @@ import { render, screen, within } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { Portfolio } from "@/entities/portfolio";
|
||||
|
||||
import { toAccountPagePositionSections } from "../../model/positions";
|
||||
import { portfolio, position, second } from "../../model/positions.fixtures";
|
||||
import { PositionSection } from "./components/PositionSection.view";
|
||||
|
||||
const position: Portfolio["positions"][number]
|
||||
= {
|
||||
absoluteReturn: { currency: "RUB", value: "25" },
|
||||
account: { id: "a", name: "Основной" },
|
||||
averagePurchasePrice: { currency: "RUB", value: "280" },
|
||||
currentValue: { currency: "RUB", value: "375" },
|
||||
displayName: "Сбербанк",
|
||||
figi: "FIGI-SBER",
|
||||
isin: "RU0009029540",
|
||||
logoName: null,
|
||||
quantity: "1.25",
|
||||
ticker: "SBER",
|
||||
type: "STOCK",
|
||||
};
|
||||
|
||||
const second
|
||||
= {
|
||||
...position,
|
||||
absoluteReturn: null,
|
||||
account: { id: "b", name: "ИИС" },
|
||||
averagePurchasePrice: null,
|
||||
currentValue: null,
|
||||
quantity: "-2",
|
||||
};
|
||||
|
||||
function sections(positions: Portfolio["positions"]) {
|
||||
return toAccountPagePositionSections({
|
||||
cashBalances: [],
|
||||
isStale: false,
|
||||
lastSuccessfulAt: "2026-09-09T12:00:00Z",
|
||||
positions,
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
totalsByCurrency: [],
|
||||
});
|
||||
}
|
||||
|
||||
describe("Positions grouped by security", () => {
|
||||
it("shows one security with exact per-account quantities and valuations", () => {
|
||||
const section = sections([position, second])[0];
|
||||
const section = toAccountPagePositionSections({
|
||||
...portfolio, positions: [position, second],
|
||||
})[0];
|
||||
|
||||
render(
|
||||
<MantineProvider>
|
||||
<MemoryRouter>
|
||||
@@ -76,75 +42,4 @@ describe("Positions grouped by security", () => {
|
||||
expect(within(rows[1]).getByText("Количество: -2")).toBeInTheDocument();
|
||||
expect(rows[1]).not.toHaveTextContent("₽");
|
||||
});
|
||||
|
||||
it("uses ISIN only when FIGI is absent, never merging by name or ticker", () => {
|
||||
expect(
|
||||
|
||||
sections([
|
||||
{
|
||||
...position,
|
||||
figi: null,
|
||||
},
|
||||
{ ...second, figi: null },
|
||||
])[0].groups,
|
||||
).toHaveLength(1);
|
||||
expect(
|
||||
sections([position, { ...second, figi: "OTHER-FIGI" }])[0].groups,
|
||||
).toHaveLength(2);
|
||||
expect(
|
||||
|
||||
sections([
|
||||
{
|
||||
...position,
|
||||
figi: null,
|
||||
isin: null,
|
||||
},
|
||||
{
|
||||
...second,
|
||||
figi: null,
|
||||
isin: null,
|
||||
},
|
||||
])[0].groups,
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("preserves one-account cards and does not merge repeated rows on the same account", () => {
|
||||
expect(
|
||||
sections([position, { ...second, account: position.account }])[0].groups,
|
||||
).toHaveLength(2);
|
||||
expect(
|
||||
sections([
|
||||
{ ...position, account: undefined },
|
||||
{ ...second, account: undefined },
|
||||
])[0].groups,
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("keeps currencies and purchase prices attached to their source positions", () => {
|
||||
const source = [
|
||||
position,
|
||||
{
|
||||
...second,
|
||||
averagePurchasePrice: { currency: "USD", value: "0.99" },
|
||||
currentValue: { currency: "USD", value: "1.01" },
|
||||
},
|
||||
];
|
||||
|
||||
const before = structuredClone(source);
|
||||
const [group] = sections(source)[0].groups;
|
||||
expect(
|
||||
group.positions.map(item => [
|
||||
item.quantity,
|
||||
item.currentValue,
|
||||
item.averagePurchasePrice,
|
||||
]),
|
||||
).toEqual(
|
||||
source.map(item => [
|
||||
item.quantity,
|
||||
item.currentValue,
|
||||
item.averagePurchasePrice,
|
||||
]),
|
||||
);
|
||||
expect(source).toEqual(before);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,17 +3,6 @@
|
||||
margin: 0 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
.section {
|
||||
padding: var(--mantine-spacing-lg);
|
||||
border-radius: var(--mantine-radius-lg);
|
||||
min-width: 0;
|
||||
}
|
||||
.identity {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--mantine-spacing-md);
|
||||
min-width: 0;
|
||||
}
|
||||
.price {
|
||||
font-size: clamp(2rem, 4vw, 3.2rem);
|
||||
font-weight: 700;
|
||||
@@ -38,9 +27,6 @@
|
||||
border-radius: var(--mantine-radius-md);
|
||||
}
|
||||
@media (max-width: 48em) {
|
||||
.section {
|
||||
padding: var(--mantine-spacing-md);
|
||||
}
|
||||
.companyMetrics {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
@@ -1,66 +1,23 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { Anchor, Button, Skeleton, Stack, Text, Title } from "@mantine/core";
|
||||
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link, Navigate } from "react-router";
|
||||
import { Navigate } from "react-router";
|
||||
|
||||
import { ApiErrorCode, isApiErrorCode } from "@/shared/api";
|
||||
import { InstrumentPageState } from "@/features/instrument-details";
|
||||
|
||||
import { BondPageView } from "./BondPage.view";
|
||||
import { useBondPageVm } from "./BondPage.vm";
|
||||
|
||||
const BondPage: FC = () => {
|
||||
const vm = useBondPageVm();
|
||||
const { t } = useTranslation();
|
||||
if (vm.canonicalTo) return <Navigate replace to={vm.canonicalTo} />;
|
||||
if (vm.bondState.loading)
|
||||
return (
|
||||
<LoadingSkeleton label={t("bond.loading")}>
|
||||
<Stack>
|
||||
<Skeleton h={110} />
|
||||
|
||||
<Skeleton h={350} />
|
||||
|
||||
<Skeleton h={170} />
|
||||
</Stack>
|
||||
</LoadingSkeleton>
|
||||
);
|
||||
|
||||
const unavailableMessage = isApiErrorCode(
|
||||
vm.code,
|
||||
ApiErrorCode.BondTickerAmbiguous,
|
||||
)
|
||||
? "bond.ambiguousTicker"
|
||||
: "bond.unavailableText";
|
||||
|
||||
if (!vm.bond)
|
||||
return (
|
||||
<Stack role="alert">
|
||||
<Title order={1}>{t("bond.unavailable")}</Title>
|
||||
|
||||
<Text>
|
||||
{t(
|
||||
isApiErrorCode(vm.code, ApiErrorCode.TbankNotConnected)
|
||||
|| isApiErrorCode(vm.code, ApiErrorCode.InvalidTbankToken)
|
||||
? "bond.connect"
|
||||
: unavailableMessage,
|
||||
)}
|
||||
</Text>
|
||||
|
||||
<Anchor component={Link} to="/bonds">
|
||||
{t("bond.backToSearch")}
|
||||
</Anchor>
|
||||
|
||||
<Anchor component={Link} to="/settings">
|
||||
{t("accounts.openSettings")}
|
||||
</Anchor>
|
||||
|
||||
<Button onClick={vm.bondState.retry} variant="default">
|
||||
{t("accounts.retry")}
|
||||
</Button>
|
||||
</Stack>
|
||||
);
|
||||
if (vm.bondState.loading || !vm.bond) return (
|
||||
<InstrumentPageState
|
||||
code={vm.code}
|
||||
kind="bond"
|
||||
loading={vm.bondState.loading}
|
||||
retry={vm.bondState.retry}
|
||||
/>
|
||||
);
|
||||
|
||||
return <BondPageView vm={vm} />;
|
||||
};
|
||||
|
||||
@@ -2,11 +2,8 @@ import type { FC } from "react";
|
||||
|
||||
import {
|
||||
Alert,
|
||||
Avatar,
|
||||
Badge,
|
||||
Button,
|
||||
Group,
|
||||
Paper,
|
||||
Skeleton,
|
||||
Stack,
|
||||
Text,
|
||||
@@ -18,6 +15,7 @@ import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
InstrumentChart,
|
||||
InstrumentEvents,
|
||||
InstrumentHeader,
|
||||
InstrumentPosition,
|
||||
} from "@/features/instrument-details";
|
||||
import {
|
||||
@@ -42,6 +40,8 @@ const BondPageView: FC<BondPageViewProps> = (props) => {
|
||||
const bond = vm.bond;
|
||||
if (!bond) return;
|
||||
|
||||
const subtitle = `${bond.ticker ?? ""} · ${bond.isin ?? ""}`;
|
||||
|
||||
const maturity = bond.maturityDate
|
||||
? formatDate(bond.maturityDate)
|
||||
: t("bond.unknown");
|
||||
@@ -144,32 +144,13 @@ const BondPageView: FC<BondPageViewProps> = (props) => {
|
||||
|
||||
return (
|
||||
<Stack className={classes.page} gap="lg">
|
||||
<Paper className={classes.section} component="header" withBorder>
|
||||
<Group align="start" justify="space-between">
|
||||
<div className={classes.identity}>
|
||||
<Avatar alt="" radius="md" size={56} src={vm.logoSrc}>
|
||||
{bond.name[0]}
|
||||
</Avatar>
|
||||
|
||||
<div>
|
||||
<Title order={1} size="h2">
|
||||
{bond.name}
|
||||
</Title>
|
||||
|
||||
<Text c="dimmed" size="sm">
|
||||
{bond.ticker} · {bond.isin}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
disabled={vm.refreshing}
|
||||
onClick={vm.refresh}
|
||||
variant="subtle"
|
||||
>
|
||||
{t("investment.refresh")}
|
||||
</Button>
|
||||
</Group>
|
||||
<InstrumentHeader
|
||||
logoSrc={vm.logoSrc}
|
||||
name={bond.name}
|
||||
onRefresh={vm.refresh}
|
||||
refreshing={vm.refreshing}
|
||||
subtitle={subtitle}
|
||||
>
|
||||
|
||||
<Group gap="xs" mt="md">
|
||||
{!!bond.floatingCoupon && <Badge variant="light">{t("bond.floatingCoupon")}</Badge>}
|
||||
@@ -224,7 +205,7 @@ const BondPageView: FC<BondPageViewProps> = (props) => {
|
||||
<Metric label={t("bond.lot")} value={lotSize} />
|
||||
</div>
|
||||
</div>
|
||||
</Paper>
|
||||
</InstrumentHeader>
|
||||
|
||||
<BondMetrics metrics={vm.metrics} state={vm.metricsState} />
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useParams, useSearchParams } from "react-router";
|
||||
import { useParams } from "react-router";
|
||||
|
||||
import {
|
||||
type BondPeriod,
|
||||
useBond,
|
||||
useBondCandles,
|
||||
useBondCoupons,
|
||||
@@ -9,37 +8,21 @@ import {
|
||||
useBondPosition,
|
||||
useBondQuote,
|
||||
} from "@/entities/bond";
|
||||
import { type OperationCategory, useBrokerageOperationHistory } from "@/entities/broker-operation";
|
||||
import { section } from "@/features/instrument-details";
|
||||
import { useBrokerageOperationHistory } from "@/entities/broker-operation";
|
||||
import { section, useInstrumentParameters } from "@/features/instrument-details";
|
||||
import { useScreenSync } from "@/features/tbank-connection";
|
||||
import { apiErrorCode } from "@/shared/api";
|
||||
import { instrumentLogoUrl } from "@/shared/lib";
|
||||
|
||||
const periods: BondPeriod[] = ["month", "halfYear", "year", "all"];
|
||||
const filters = ["all", "trades", "coupons", "other"] as const;
|
||||
|
||||
type BondEventFilter = (typeof filters)[number];
|
||||
|
||||
const categories: Record<BondEventFilter, OperationCategory[]> = {
|
||||
all: [],
|
||||
coupons: ["income"],
|
||||
other: ["tax", "fee", "transfer", "other"],
|
||||
trades: ["trade"],
|
||||
};
|
||||
|
||||
type BondPageVm = ReturnType<typeof useBondPageVm>;
|
||||
|
||||
function useBondPageVm() {
|
||||
const { bondId = "" } = useParams();
|
||||
const bond = useBond(bondId);
|
||||
const uid = bond.data?.instrumentUid ?? "";
|
||||
const [parameters, setParameters] = useSearchParams();
|
||||
|
||||
const period
|
||||
= periods.find(value => value === parameters.get("period")) ?? "month";
|
||||
|
||||
const filter
|
||||
= filters.find(value => value === parameters.get("events")) ?? "all";
|
||||
const { categories, filter, period, search, setFilter, setPeriod }
|
||||
= useInstrumentParameters("coupons");
|
||||
|
||||
const quote = useBondQuote(uid);
|
||||
const metrics = useBondMetrics(uid);
|
||||
@@ -48,8 +31,7 @@ function useBondPageVm() {
|
||||
const coupons = useBondCoupons(uid);
|
||||
|
||||
const history = useBrokerageOperationHistory(uid ? "all" : undefined, {
|
||||
// eslint-disable-next-line security/detect-object-injection -- This lookup uses a fixed typed key set, not an arbitrary external property name.
|
||||
categories: categories[filter],
|
||||
categories,
|
||||
instrumentUid: uid,
|
||||
limit: 20,
|
||||
});
|
||||
@@ -60,9 +42,7 @@ function useBondPageVm() {
|
||||
{
|
||||
accountId: "all",
|
||||
candlePeriod: period,
|
||||
categories:
|
||||
// eslint-disable-next-line security/detect-object-injection -- This lookup uses a fixed typed key set, not an arbitrary external property name.
|
||||
categories[filter],
|
||||
categories,
|
||||
instrumentUid: uid,
|
||||
limit: 20,
|
||||
screen: "bond",
|
||||
@@ -70,14 +50,6 @@ function useBondPageVm() {
|
||||
[bond, quote, candles, position, metrics, coupons, operations],
|
||||
);
|
||||
|
||||
const setParameter = (key: string, value: string) => {
|
||||
const next = new URLSearchParams(parameters);
|
||||
next.set(key, value);
|
||||
setParameters(next, { replace: true });
|
||||
};
|
||||
|
||||
const search = parameters.size > 0 ? `?${parameters.toString()}` : "";
|
||||
|
||||
return {
|
||||
bond: bond.data,
|
||||
bondState: section(bond, uid ? sync.retry : () => bond.refetch()),
|
||||
@@ -132,8 +104,8 @@ function useBondPageVm() {
|
||||
refresh: sync.refresh,
|
||||
refreshError: sync.transportError || sync.sourceError,
|
||||
refreshing: sync.refreshing,
|
||||
setFilter: (value: string) => setParameter("events", value),
|
||||
setPeriod: (value: string) => setParameter("period", value),
|
||||
setFilter,
|
||||
setPeriod,
|
||||
upcoming:
|
||||
coupons.data?.coupons
|
||||
.filter(event => event.timing === "upcoming")
|
||||
|
||||
@@ -3,17 +3,6 @@
|
||||
margin: 0 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
.section {
|
||||
padding: var(--mantine-spacing-lg);
|
||||
border-radius: var(--mantine-radius-lg);
|
||||
min-width: 0;
|
||||
}
|
||||
.identity {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--mantine-spacing-md);
|
||||
min-width: 0;
|
||||
}
|
||||
.price {
|
||||
font-size: clamp(2rem, 4vw, 3.2rem);
|
||||
font-weight: 700;
|
||||
@@ -38,20 +27,12 @@
|
||||
grid-template-columns: repeat(auto-fit, minmax(135px, 1fr));
|
||||
gap: var(--mantine-spacing-lg);
|
||||
}
|
||||
.embeddedSection {
|
||||
margin-top: var(--mantine-spacing-lg);
|
||||
padding-top: var(--mantine-spacing-lg);
|
||||
border-top: 1px solid var(--wl-color-border);
|
||||
}
|
||||
.companyMetrics > div {
|
||||
padding: var(--mantine-spacing-sm);
|
||||
background: var(--wl-color-subtle);
|
||||
border-radius: var(--mantine-radius-md);
|
||||
}
|
||||
@media (max-width: 48em) {
|
||||
.section {
|
||||
padding: var(--mantine-spacing-md);
|
||||
}
|
||||
.companyMetrics {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
@@ -1,66 +1,23 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { Anchor, Button, Skeleton, Stack, Text, Title } from "@mantine/core";
|
||||
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link, Navigate } from "react-router";
|
||||
import { Navigate } from "react-router";
|
||||
|
||||
import { ApiErrorCode, isApiErrorCode } from "@/shared/api";
|
||||
import { InstrumentPageState } from "@/features/instrument-details";
|
||||
|
||||
import { StockPageView } from "./StockPage.view";
|
||||
import { useStockPageVm } from "./StockPage.vm";
|
||||
|
||||
const StockPage: FC = () => {
|
||||
const vm = useStockPageVm();
|
||||
const { t } = useTranslation();
|
||||
if (vm.canonicalTo) return <Navigate replace to={vm.canonicalTo} />;
|
||||
if (vm.stockState.loading)
|
||||
return (
|
||||
<LoadingSkeleton label={t("stock.loading")}>
|
||||
<Stack>
|
||||
<Skeleton h={110} />
|
||||
|
||||
<Skeleton h={350} />
|
||||
|
||||
<Skeleton h={170} />
|
||||
</Stack>
|
||||
</LoadingSkeleton>
|
||||
);
|
||||
|
||||
const unavailableMessage = isApiErrorCode(
|
||||
vm.code,
|
||||
ApiErrorCode.StockTickerAmbiguous,
|
||||
)
|
||||
? "stock.ambiguousTicker"
|
||||
: "stock.unavailableText";
|
||||
|
||||
if (!vm.stock)
|
||||
return (
|
||||
<Stack role="alert">
|
||||
<Title order={1}>{t("stock.unavailable")}</Title>
|
||||
|
||||
<Text>
|
||||
{t(
|
||||
isApiErrorCode(vm.code, ApiErrorCode.TbankNotConnected)
|
||||
|| isApiErrorCode(vm.code, ApiErrorCode.InvalidTbankToken)
|
||||
? "stock.connect"
|
||||
: unavailableMessage,
|
||||
)}
|
||||
</Text>
|
||||
|
||||
<Anchor component={Link} to="/stocks">
|
||||
{t("stock.backToSearch")}
|
||||
</Anchor>
|
||||
|
||||
<Anchor component={Link} to="/settings">
|
||||
{t("accounts.openSettings")}
|
||||
</Anchor>
|
||||
|
||||
<Button onClick={vm.stockState.retry} variant="default">
|
||||
{t("accounts.retry")}
|
||||
</Button>
|
||||
</Stack>
|
||||
);
|
||||
if (vm.stockState.loading || !vm.stock) return (
|
||||
<InstrumentPageState
|
||||
code={vm.code}
|
||||
kind="stock"
|
||||
loading={vm.stockState.loading}
|
||||
retry={vm.stockState.retry}
|
||||
/>
|
||||
);
|
||||
|
||||
return <StockPageView vm={vm} />;
|
||||
};
|
||||
|
||||
@@ -2,20 +2,18 @@ import type { FC } from "react";
|
||||
|
||||
import {
|
||||
Alert,
|
||||
Avatar,
|
||||
Badge,
|
||||
Button,
|
||||
Group,
|
||||
Paper,
|
||||
Skeleton,
|
||||
Stack,
|
||||
Text,
|
||||
Title,
|
||||
} from "@mantine/core";
|
||||
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import {
|
||||
InstrumentHeader,
|
||||
InstrumentChart as StockChart,
|
||||
InstrumentEvents as StockEvents,
|
||||
InstrumentPosition as StockPosition,
|
||||
@@ -30,7 +28,7 @@ import {
|
||||
|
||||
import type { StockPageVm } from "./StockPage.vm";
|
||||
|
||||
import { StockDividends } from "./components/StockEvents.view";
|
||||
import { StockDividends } from "./components/StockDividends.view";
|
||||
import classes from "./StockPage.module.css";
|
||||
|
||||
type StockPageViewProps = { vm: StockPageVm };
|
||||
@@ -41,6 +39,15 @@ const StockPageView: FC<StockPageViewProps> = (props) => {
|
||||
const stock = vm.stock;
|
||||
if (!stock) return;
|
||||
|
||||
const subtitle = (
|
||||
<>
|
||||
{stock.ticker} ·{" "}
|
||||
{t(`stock.shareTypes.${stock.shareType}`, {
|
||||
defaultValue: t("stock.share"),
|
||||
})}
|
||||
</>
|
||||
);
|
||||
|
||||
const appearanceClass = vm.quote?.change?.value.startsWith("-")
|
||||
? classes.negative
|
||||
: classes.positive;
|
||||
@@ -152,41 +159,13 @@ const StockPageView: FC<StockPageViewProps> = (props) => {
|
||||
|
||||
return (
|
||||
<Stack className={classes.page} gap="lg">
|
||||
<Paper className={classes.section} component="header" withBorder>
|
||||
<Group align="start" justify="space-between">
|
||||
<div className={classes.identity}>
|
||||
<Avatar
|
||||
alt=""
|
||||
key={vm.logoSrc}
|
||||
radius="md"
|
||||
size={56}
|
||||
src={vm.logoSrc}
|
||||
>
|
||||
{stock.name[0]}
|
||||
</Avatar>
|
||||
|
||||
<div>
|
||||
<Title order={1} size="h2">
|
||||
{stock.name}
|
||||
</Title>
|
||||
|
||||
<Text c="dimmed" size="sm">
|
||||
{stock.ticker} ·{" "}
|
||||
{t(`stock.shareTypes.${stock.shareType}`, {
|
||||
defaultValue: t("stock.share"),
|
||||
})}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
disabled={vm.refreshing}
|
||||
onClick={vm.refresh}
|
||||
variant="subtle"
|
||||
>
|
||||
{t("investment.refresh")}
|
||||
</Button>
|
||||
</Group>
|
||||
<InstrumentHeader
|
||||
logoSrc={vm.logoSrc}
|
||||
name={stock.name}
|
||||
onRefresh={vm.refresh}
|
||||
refreshing={vm.refreshing}
|
||||
subtitle={subtitle}
|
||||
>
|
||||
|
||||
{!!vm.company?.description && (
|
||||
<Text mt="md" size="sm" style={{ whiteSpace: "pre-line" }}>
|
||||
@@ -246,13 +225,18 @@ const StockPageView: FC<StockPageViewProps> = (props) => {
|
||||
</Stack>
|
||||
)}
|
||||
</StockSection>
|
||||
</Paper>
|
||||
</InstrumentHeader>
|
||||
|
||||
<StockChart vm={vm} />
|
||||
|
||||
<StockPosition vm={vm} />
|
||||
|
||||
<StockDividends vm={vm} />
|
||||
<StockDividends
|
||||
dividends={vm.dividends}
|
||||
pastDividends={vm.pastDividends}
|
||||
state={vm.dividendsState}
|
||||
upcoming={vm.upcoming}
|
||||
/>
|
||||
|
||||
<StockEvents vm={vm} />
|
||||
</Stack>
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { useParams, useSearchParams } from "react-router";
|
||||
import { useParams } from "react-router";
|
||||
|
||||
import { type OperationCategory, useBrokerageOperationHistory } from "@/entities/broker-operation";
|
||||
import { useBrokerageOperationHistory } from "@/entities/broker-operation";
|
||||
import {
|
||||
type StockPeriod,
|
||||
useStock,
|
||||
useStockCandles,
|
||||
useStockCompany,
|
||||
@@ -12,36 +11,21 @@ import {
|
||||
} from "@/entities/stock";
|
||||
import {
|
||||
section,
|
||||
useInstrumentParameters,
|
||||
} from "@/features/instrument-details";
|
||||
import { useScreenSync } from "@/features/tbank-connection";
|
||||
import { apiErrorCode } from "@/shared/api";
|
||||
import { instrumentLogoUrl } from "@/shared/lib";
|
||||
|
||||
const periods: StockPeriod[] = ["month", "halfYear", "year", "all"];
|
||||
const filters = ["all", "trades", "dividends", "other"] as const;
|
||||
|
||||
type StockEventFilter = (typeof filters)[number];
|
||||
|
||||
const categories: Record<StockEventFilter, OperationCategory[]> = {
|
||||
all: [],
|
||||
dividends: ["income"],
|
||||
other: ["tax", "fee", "transfer", "other"],
|
||||
trades: ["trade"],
|
||||
};
|
||||
|
||||
type StockPageVm = ReturnType<typeof useStockPageVm>;
|
||||
|
||||
function useStockPageVm() {
|
||||
const { stockId = "" } = useParams();
|
||||
const stock = useStock(stockId);
|
||||
const uid = stock.data?.instrumentUid ?? "";
|
||||
const [parameters, setParameters] = useSearchParams();
|
||||
|
||||
const period
|
||||
= periods.find(value => value === parameters.get("period")) ?? "month";
|
||||
|
||||
const filter
|
||||
= filters.find(value => value === parameters.get("events")) ?? "all";
|
||||
const { categories, filter, period, search, setFilter, setPeriod }
|
||||
= useInstrumentParameters("dividends");
|
||||
|
||||
const quote = useStockQuote(uid);
|
||||
const candles = useStockCandles(uid, period);
|
||||
@@ -50,8 +34,7 @@ function useStockPageVm() {
|
||||
const dividends = useStockDividends(uid);
|
||||
|
||||
const history = useBrokerageOperationHistory(uid ? "all" : undefined, {
|
||||
// eslint-disable-next-line security/detect-object-injection -- This lookup uses a fixed typed key set, not an arbitrary external property name.
|
||||
categories: categories[filter],
|
||||
categories,
|
||||
instrumentUid: uid,
|
||||
limit: 20,
|
||||
});
|
||||
@@ -62,9 +45,7 @@ function useStockPageVm() {
|
||||
{
|
||||
accountId: "all",
|
||||
candlePeriod: period,
|
||||
categories:
|
||||
// eslint-disable-next-line security/detect-object-injection -- This lookup uses a fixed typed key set, not an arbitrary external property name.
|
||||
categories[filter],
|
||||
categories,
|
||||
instrumentUid: uid,
|
||||
limit: 20,
|
||||
screen: "stock",
|
||||
@@ -72,15 +53,6 @@ function useStockPageVm() {
|
||||
[stock, quote, candles, position, company, dividends, operations],
|
||||
);
|
||||
|
||||
const setParameter = (key: string, value: string) => {
|
||||
const next = new URLSearchParams(parameters);
|
||||
next.set(key, value);
|
||||
setParameters(next, { replace: true });
|
||||
};
|
||||
|
||||
const companyData = company.data;
|
||||
const search = parameters.size > 0 ? `?${parameters.toString()}` : "";
|
||||
|
||||
return {
|
||||
candles: candles.data,
|
||||
candlesState: section(candles, sync.retry),
|
||||
@@ -89,7 +61,7 @@ function useStockPageVm() {
|
||||
? `/stocks/${encodeURIComponent(stock.data.slug)}${search}`
|
||||
: null,
|
||||
code: apiErrorCode(stock.error),
|
||||
company: companyData,
|
||||
company: company.data,
|
||||
companyState: section(company, sync.retry),
|
||||
dividends: dividends.data,
|
||||
dividendsState: section(dividends, sync.retry),
|
||||
@@ -133,8 +105,8 @@ function useStockPageVm() {
|
||||
refresh: sync.refresh,
|
||||
refreshError: sync.transportError || sync.sourceError,
|
||||
refreshing: sync.refreshing,
|
||||
setFilter: (value: string) => setParameter("events", value),
|
||||
setPeriod: (value: string) => setParameter("period", value),
|
||||
setFilter,
|
||||
setPeriod,
|
||||
stock: stock.data,
|
||||
stockState: section(stock, uid ? sync.retry : () => stock.refetch()),
|
||||
upcoming:
|
||||
|
||||
+25
-20
@@ -11,25 +11,30 @@ import {
|
||||
} from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { InstrumentSection as StockSection } from "@/features/instrument-details";
|
||||
import { formatDate, formatMoney, formatSnapshotTime } from "@/shared/lib";
|
||||
import type { StockDividends as Dividends } from "@/entities/stock";
|
||||
|
||||
import type { StockPageVm } from "../StockPage.vm";
|
||||
import { InstrumentSection, type SectionState } from "@/features/instrument-details";
|
||||
import { formatDate, formatMoney, formatSnapshotTime } from "@/shared/lib";
|
||||
|
||||
import classes from "../StockPage.module.css";
|
||||
|
||||
type StockEventsProps = { vm: StockPageVm };
|
||||
type StockDividendsProps = {
|
||||
dividends?: Dividends;
|
||||
pastDividends: Dividends["dividends"];
|
||||
state: SectionState;
|
||||
upcoming: Dividends["dividends"];
|
||||
};
|
||||
|
||||
const StockDividends: FC<StockEventsProps> = (props) => {
|
||||
const { vm } = props;
|
||||
const StockDividends: FC<StockDividendsProps> = (props) => {
|
||||
const { dividends, pastDividends, state, upcoming } = props;
|
||||
const { t } = useTranslation();
|
||||
|
||||
let upcomingContent;
|
||||
|
||||
if (vm.dividends) {
|
||||
if (vm.upcoming.length > 0) {
|
||||
if (dividends) {
|
||||
if (upcoming.length > 0) {
|
||||
upcomingContent = (
|
||||
vm.upcoming.map(event => (
|
||||
upcoming.map(event => (
|
||||
<div
|
||||
className={classes.dividend}
|
||||
key={JSON.stringify([
|
||||
@@ -104,7 +109,7 @@ const StockDividends: FC<StockEventsProps> = (props) => {
|
||||
else {
|
||||
upcomingContent = (
|
||||
<Text c="dimmed">
|
||||
{t("stock.noUpcoming", { to: formatDate(vm.dividends.to) })}
|
||||
{t("stock.noUpcoming", { to: formatDate(dividends.to) })}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
@@ -112,10 +117,10 @@ const StockDividends: FC<StockEventsProps> = (props) => {
|
||||
|
||||
let pastDividendsContent;
|
||||
|
||||
if (vm.pastDividends.length > 0) {
|
||||
if (pastDividends.length > 0) {
|
||||
pastDividendsContent = (
|
||||
<Stack gap="sm">
|
||||
{vm.pastDividends.map(event => (
|
||||
{pastDividends.map(event => (
|
||||
<Paper
|
||||
key={JSON.stringify([
|
||||
event.recordDate,
|
||||
@@ -166,11 +171,11 @@ const StockDividends: FC<StockEventsProps> = (props) => {
|
||||
}
|
||||
|
||||
return (
|
||||
<StockSection state={vm.dividendsState} title={t("stock.upcoming")}>
|
||||
{!!vm.dividends && (
|
||||
<InstrumentSection state={state} title={t("stock.upcoming")}>
|
||||
{!!dividends && (
|
||||
<Stack gap="md">
|
||||
{!!(
|
||||
vm.dividends.estimateUnavailable || vm.dividends.positionIsStale
|
||||
dividends.estimateUnavailable || dividends.positionIsStale
|
||||
) && (
|
||||
<Alert aria-live="polite" color="orange" role="status">
|
||||
{t("stock.estimateUnavailable")}
|
||||
@@ -183,10 +188,10 @@ const StockDividends: FC<StockEventsProps> = (props) => {
|
||||
{t("stock.dividendNote")}
|
||||
</Text>
|
||||
|
||||
{!!vm.dividends.positionAt && (
|
||||
{!!dividends.positionAt && (
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("stock.snapshotAt", {
|
||||
date: formatSnapshotTime(vm.dividends.positionAt),
|
||||
date: formatSnapshotTime(dividends.positionAt),
|
||||
})}
|
||||
</Text>
|
||||
)}
|
||||
@@ -200,8 +205,8 @@ const StockDividends: FC<StockEventsProps> = (props) => {
|
||||
<Accordion.Panel>
|
||||
<Text c="dimmed" my="sm" size="xs">
|
||||
{t("stock.dividendWindow", {
|
||||
from: formatDate(vm.dividends.from),
|
||||
to: formatDate(vm.dividends.to),
|
||||
from: formatDate(dividends.from),
|
||||
to: formatDate(dividends.to),
|
||||
})}
|
||||
</Text>
|
||||
|
||||
@@ -211,7 +216,7 @@ const StockDividends: FC<StockEventsProps> = (props) => {
|
||||
</Accordion>
|
||||
</Stack>
|
||||
)}
|
||||
</StockSection>
|
||||
</InstrumentSection>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -14,6 +14,5 @@ export { ApiErrorCode, apiErrorCode, isApiErrorCode } from "./problem-details";
|
||||
export {
|
||||
invalidateResourceAccess,
|
||||
type InvestmentResourceMeta,
|
||||
unwrapResourceResult,
|
||||
useResourceQuery,
|
||||
} from "./resource-query";
|
||||
|
||||
@@ -188,6 +188,5 @@ function useResourceQuery<T extends Resource, E, K extends QueryKey>(
|
||||
export {
|
||||
invalidateResourceAccess,
|
||||
type InvestmentResourceMeta,
|
||||
unwrapResourceResult,
|
||||
useResourceQuery,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user