refactor: simplify auth and instrument pages
This commit is contained in:
@@ -3,7 +3,7 @@ import { QueryClientProvider } from "@tanstack/react-query";
|
|||||||
import { fireEvent, render, screen } from "@testing-library/react";
|
import { fireEvent, render, screen } from "@testing-library/react";
|
||||||
import { cssVariablesResolver, theme } from "@wealthledger/ui/theme";
|
import { cssVariablesResolver, theme } from "@wealthledger/ui/theme";
|
||||||
import { http, HttpResponse } from "msw";
|
import { http, HttpResponse } from "msw";
|
||||||
import { MemoryRouter } from "react-router";
|
import { type InitialEntry, MemoryRouter } from "react-router";
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import { AuthProvider } from "@/features/auth";
|
import { AuthProvider } from "@/features/auth";
|
||||||
@@ -12,7 +12,7 @@ import { server } from "@/test/server";
|
|||||||
|
|
||||||
import { AppRoutes } from "./AppRoutes";
|
import { AppRoutes } from "./AppRoutes";
|
||||||
|
|
||||||
function renderRoutes(path: string) {
|
function renderRoutes(path: InitialEntry) {
|
||||||
return render(
|
return render(
|
||||||
<QueryClientProvider client={createTestQueryClient()}>
|
<QueryClientProvider client={createTestQueryClient()}>
|
||||||
<MemoryRouter initialEntries={[path]}>
|
<MemoryRouter initialEntries={[path]}>
|
||||||
@@ -57,10 +57,18 @@ describe("AppRoutes", () => {
|
|||||||
).toBeInTheDocument();
|
).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;
|
let credentials: unknown;
|
||||||
server.use(
|
server.use(
|
||||||
http.post("*/api/v1/auth/login", async ({ request }) => {
|
http.post(`*/api/v1/auth/${endpoint}`, async ({ request }) => {
|
||||||
credentials = await request.json();
|
credentials = await request.json();
|
||||||
|
|
||||||
return HttpResponse.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"), {
|
fireEvent.change(screen.getByLabelText("Email"), {
|
||||||
target: { value: " User@Example.com " },
|
target: { value: " User@Example.com " },
|
||||||
});
|
});
|
||||||
fireEvent.change(screen.getByLabelText("Пароль"), {
|
fireEvent.change(screen.getByLabelText("Пароль"), {
|
||||||
target: { value: "a secure password" },
|
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(
|
expect(
|
||||||
await screen.findByRole("heading", {
|
await screen.findByRole("heading", {
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ function useBankPeriodPickerVm(props: BankPeriodPickerProps) {
|
|||||||
onChange(next);
|
onChange(next);
|
||||||
};
|
};
|
||||||
|
|
||||||
return { onChange, onPeriodChange, t, value };
|
return { onPeriodChange, t, value };
|
||||||
}
|
}
|
||||||
|
|
||||||
export { useBankPeriodPickerVm };
|
export { useBankPeriodPickerVm };
|
||||||
|
|||||||
@@ -14,35 +14,28 @@ type BondPeriod = NonNullable<
|
|||||||
|
|
||||||
const BOND_STALE_TIME_MS = 30_000;
|
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) {
|
function useBond(identifier: string) {
|
||||||
const isUid
|
const isUid
|
||||||
= /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
|
= /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
|
||||||
identifier,
|
identifier,
|
||||||
);
|
);
|
||||||
|
|
||||||
const byUid = useResourceQuery({
|
// eslint-disable-next-line unicorn/prefer-minimal-ternary -- Hoisting params breaks the generated union of endpoint request shapes.
|
||||||
...bondQueryOptions(identifier),
|
const init = isUid
|
||||||
enabled: Boolean(identifier) && isUid,
|
? { params: { path: { uid: identifier } } }
|
||||||
});
|
: { params: { path: { ticker: identifier } } };
|
||||||
|
|
||||||
const byTicker = useResourceQuery({
|
const options = apiQueryClient.queryOptions(
|
||||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/by-ticker/{ticker}", {
|
"get",
|
||||||
params: { path: { ticker: identifier } },
|
isUid ? "/api/v1/bonds/{uid}" : "/api/v1/bonds/by-ticker/{ticker}",
|
||||||
}),
|
init,
|
||||||
enabled: Boolean(identifier) && !isUid,
|
);
|
||||||
|
|
||||||
|
return useResourceQuery({
|
||||||
|
...options,
|
||||||
|
enabled: Boolean(identifier),
|
||||||
staleTime: BOND_STALE_TIME_MS,
|
staleTime: BOND_STALE_TIME_MS,
|
||||||
});
|
});
|
||||||
|
|
||||||
return isUid ? byUid : byTicker;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function useBondCandles(uid: string, period: BondPeriod) {
|
function useBondCandles(uid: string, period: BondPeriod) {
|
||||||
@@ -110,7 +103,6 @@ function useBondSearch(query: string) {
|
|||||||
export {
|
export {
|
||||||
type BondCoupons,
|
type BondCoupons,
|
||||||
type BondMetrics,
|
type BondMetrics,
|
||||||
type BondPeriod,
|
|
||||||
MIN_BOND_SEARCH_LENGTH,
|
MIN_BOND_SEARCH_LENGTH,
|
||||||
useBond,
|
useBond,
|
||||||
useBondCandles,
|
useBondCandles,
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
export {
|
export {
|
||||||
type BondCoupons,
|
type BondCoupons,
|
||||||
type BondMetrics,
|
type BondMetrics,
|
||||||
type BondPeriod,
|
|
||||||
MIN_BOND_SEARCH_LENGTH,
|
MIN_BOND_SEARCH_LENGTH,
|
||||||
useBond,
|
useBond,
|
||||||
useBondCandles,
|
useBondCandles,
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
import {
|
import {
|
||||||
apiQueryClient,
|
apiQueryClient,
|
||||||
type paths,
|
type paths,
|
||||||
unwrapResourceResult,
|
|
||||||
useAuthenticatedQueries,
|
|
||||||
useResourceQuery,
|
useResourceQuery,
|
||||||
} from "@/shared/api";
|
} from "@/shared/api";
|
||||||
|
|
||||||
const MIN_STOCK_SEARCH_LENGTH = 2;
|
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<
|
type StockPeriod = NonNullable<
|
||||||
NonNullable<
|
NonNullable<
|
||||||
paths["/api/v1/stocks/{uid}/candles"]["get"]["parameters"]["query"]
|
paths["/api/v1/stocks/{uid}/candles"]["get"]["parameters"]["query"]
|
||||||
@@ -16,35 +16,28 @@ type StockPeriod = NonNullable<
|
|||||||
|
|
||||||
const STOCK_STALE_TIME_MS = 30_000;
|
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) {
|
function useStock(identifier: string) {
|
||||||
const isUid
|
const isUid
|
||||||
= /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
|
= /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
|
||||||
identifier,
|
identifier,
|
||||||
);
|
);
|
||||||
|
|
||||||
const byUid = useResourceQuery({
|
// eslint-disable-next-line unicorn/prefer-minimal-ternary -- Hoisting params breaks the generated union of endpoint request shapes.
|
||||||
...stockQueryOptions(identifier),
|
const init = isUid
|
||||||
enabled: Boolean(identifier) && isUid,
|
? { params: { path: { uid: identifier } } }
|
||||||
});
|
: { params: { path: { ticker: identifier } } };
|
||||||
|
|
||||||
const byTicker = useResourceQuery({
|
const options = apiQueryClient.queryOptions(
|
||||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/by-ticker/{ticker}", {
|
"get",
|
||||||
params: { path: { ticker: identifier } },
|
isUid ? "/api/v1/stocks/{uid}" : "/api/v1/stocks/by-ticker/{ticker}",
|
||||||
}),
|
init,
|
||||||
enabled: Boolean(identifier) && !isUid,
|
);
|
||||||
|
|
||||||
|
return useResourceQuery({
|
||||||
|
...options,
|
||||||
|
enabled: Boolean(identifier),
|
||||||
staleTime: STOCK_STALE_TIME_MS,
|
staleTime: STOCK_STALE_TIME_MS,
|
||||||
});
|
});
|
||||||
|
|
||||||
return isUid ? byUid : byTicker;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function useStockCandles(uid: string, period: StockPeriod) {
|
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) {
|
function useStockSearch(query: string) {
|
||||||
return useResourceQuery({
|
return useResourceQuery({
|
||||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks", {
|
...apiQueryClient.queryOptions("get", "/api/v1/stocks", {
|
||||||
@@ -127,13 +104,12 @@ function useStockSearch(query: string) {
|
|||||||
|
|
||||||
export {
|
export {
|
||||||
MIN_STOCK_SEARCH_LENGTH,
|
MIN_STOCK_SEARCH_LENGTH,
|
||||||
type StockPeriod,
|
type StockDividends,
|
||||||
useStock,
|
useStock,
|
||||||
useStockCandles,
|
useStockCandles,
|
||||||
useStockCompany,
|
useStockCompany,
|
||||||
useStockDividends,
|
useStockDividends,
|
||||||
useStockPosition,
|
useStockPosition,
|
||||||
useStockQuote,
|
useStockQuote,
|
||||||
useStocks,
|
|
||||||
useStockSearch,
|
useStockSearch,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
export {
|
export {
|
||||||
MIN_STOCK_SEARCH_LENGTH,
|
MIN_STOCK_SEARCH_LENGTH,
|
||||||
type StockPeriod,
|
type StockDividends,
|
||||||
useStock,
|
useStock,
|
||||||
useStockCandles,
|
useStockCandles,
|
||||||
useStockCompany,
|
useStockCompany,
|
||||||
useStockDividends,
|
useStockDividends,
|
||||||
useStockPosition,
|
useStockPosition,
|
||||||
useStockQuote,
|
useStockQuote,
|
||||||
useStocks,
|
|
||||||
useStockSearch,
|
useStockSearch,
|
||||||
} from "./api/queries";
|
} from "./api/queries";
|
||||||
|
|||||||
@@ -3,11 +3,9 @@ import { createContext, use } from "react";
|
|||||||
import type { paths } from "@/shared/api";
|
import type { paths } from "@/shared/api";
|
||||||
|
|
||||||
type AuthContextValue = {
|
type AuthContextValue = {
|
||||||
accessToken: string | undefined;
|
|
||||||
login: (email: string, password: string) => Promise<void>;
|
login: (email: string, password: string) => Promise<void>;
|
||||||
logout: () => Promise<void>;
|
logout: () => Promise<void>;
|
||||||
ready: boolean;
|
ready: boolean;
|
||||||
refresh: () => Promise<boolean>;
|
|
||||||
register: (email: string, password: string) => Promise<void>;
|
register: (email: string, password: string) => Promise<void>;
|
||||||
user: undefined | User;
|
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", () => {
|
describe("AuthProvider", () => {
|
||||||
it("authorizes requests after restoring the initial session", async () => {
|
it("authorizes requests after restoring the initial session", async () => {
|
||||||
let authorization: null | string
|
let authorization: null | string
|
||||||
@@ -77,7 +103,7 @@ describe("AuthProvider", () => {
|
|||||||
await waitFor(() => expect(result.current.ready).toBe(true));
|
await waitFor(() => expect(result.current.ready).toBe(true));
|
||||||
|
|
||||||
expect(result.current.user).toBeUndefined();
|
expect(result.current.user).toBeUndefined();
|
||||||
expect(result.current.accessToken).toBeUndefined();
|
expect(await requestAuthorization()).toBeNull();
|
||||||
expect(queryClient.getQueryData(["cached-query"])).toBeUndefined();
|
expect(queryClient.getQueryData(["cached-query"])).toBeUndefined();
|
||||||
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
|
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
|
||||||
});
|
});
|
||||||
@@ -106,13 +132,13 @@ describe("AuthProvider", () => {
|
|||||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||||
|
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(result.current.accessToken).toBe("restored-token"),
|
expect(result.current.ready).toBe(true),
|
||||||
);
|
);
|
||||||
const response = await apiClient.GET("/api/v1/brokerage-accounts");
|
const response = await apiClient.GET("/api/v1/brokerage-accounts");
|
||||||
|
|
||||||
expect(response.response.status).toBe(401);
|
expect(response.response.status).toBe(401);
|
||||||
await waitFor(() => expect(result.current.user).toBeUndefined());
|
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(["cached-query"])).toBeUndefined();
|
||||||
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
|
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
|
||||||
});
|
});
|
||||||
@@ -147,7 +173,7 @@ describe("AuthProvider", () => {
|
|||||||
queryClient.setQueryData(bankCardsKey, [{ id: "bank-card-1" }]);
|
queryClient.setQueryData(bankCardsKey, [{ id: "bank-card-1" }]);
|
||||||
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
|
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
|
||||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
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([
|
expect(queryClient.getQueryData(bankCardsKey)).toEqual([
|
||||||
{ id: "bank-card-1" },
|
{ id: "bank-card-1" },
|
||||||
@@ -155,7 +181,7 @@ describe("AuthProvider", () => {
|
|||||||
await act(() => result.current.logout());
|
await act(() => result.current.logout());
|
||||||
|
|
||||||
expect(result.current.user).toBeUndefined();
|
expect(result.current.user).toBeUndefined();
|
||||||
expect(result.current.accessToken).toBeUndefined();
|
expect(await requestAuthorization()).toBeNull();
|
||||||
expect(queryClient.getQueryData(statusKey)).toBeUndefined();
|
expect(queryClient.getQueryData(statusKey)).toBeUndefined();
|
||||||
expect(queryClient.getQueryData(portfolioKey)).toBeUndefined();
|
expect(queryClient.getQueryData(portfolioKey)).toBeUndefined();
|
||||||
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
|
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
|
||||||
@@ -265,7 +291,7 @@ describe("AuthProvider", () => {
|
|||||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||||
await waitFor(() => expect(result.current.ready).toBe(true));
|
await waitFor(() => expect(result.current.ready).toBe(true));
|
||||||
queryClient.setQueryData(bankCardsKey, [{ id: "a-card" }]);
|
queryClient.setQueryData(bankCardsKey, [{ id: "a-card" }]);
|
||||||
await act(() => result.current.refresh());
|
await act(() => expireSession());
|
||||||
expect(queryClient.getQueryData(bankCardsKey)).toEqual([{ id: "a-card" }]);
|
expect(queryClient.getQueryData(bankCardsKey)).toEqual([{ id: "a-card" }]);
|
||||||
let release!: (value: string) => void;
|
let release!: (value: string) => void;
|
||||||
|
|
||||||
@@ -283,7 +309,7 @@ describe("AuthProvider", () => {
|
|||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
|
|
||||||
identity = "b";
|
identity = "b";
|
||||||
await act(() => result.current.refresh());
|
await act(() => expireSession());
|
||||||
release("a-data");
|
release("a-data");
|
||||||
await pending;
|
await pending;
|
||||||
expect(result.current.user?.id).toBe("b");
|
expect(result.current.user?.id).toBe("b");
|
||||||
@@ -322,7 +348,7 @@ describe("AuthProvider", () => {
|
|||||||
expect(result.current.cards.data?.[0].id).toBe("a-card"),
|
expect(result.current.cards.data?.[0].id).toBe("a-card"),
|
||||||
);
|
);
|
||||||
identity = "b";
|
identity = "b";
|
||||||
await act(() => result.current.auth.refresh());
|
await act(() => expireSession());
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(result.current.cards.data?.[0].id).toBe("b-card"),
|
expect(result.current.cards.data?.[0].id).toBe("b-card"),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -29,7 +29,6 @@ async function request(
|
|||||||
function useAuthProviderVm() {
|
function useAuthProviderVm() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const [user, setUser] = useState<undefined | User>(undefined);
|
const [user, setUser] = useState<undefined | User>(undefined);
|
||||||
const [accessToken, setAccessToken] = useState<string | undefined>(undefined);
|
|
||||||
const accessTokenRef = useRef<string | undefined>(undefined);
|
const accessTokenRef = useRef<string | undefined>(undefined);
|
||||||
const [ready, setReady] = useState(false);
|
const [ready, setReady] = useState(false);
|
||||||
|
|
||||||
@@ -69,7 +68,6 @@ function useAuthProviderVm() {
|
|||||||
|
|
||||||
userRef.current = authentication.user;
|
userRef.current = authentication.user;
|
||||||
setUser(authentication.user);
|
setUser(authentication.user);
|
||||||
setAccessToken(authentication.accessToken);
|
|
||||||
},
|
},
|
||||||
[queryClient],
|
[queryClient],
|
||||||
);
|
);
|
||||||
@@ -78,7 +76,6 @@ function useAuthProviderVm() {
|
|||||||
generationRef.current += 1;
|
generationRef.current += 1;
|
||||||
userRef.current = undefined;
|
userRef.current = undefined;
|
||||||
setUser(undefined);
|
setUser(undefined);
|
||||||
setAccessToken(undefined);
|
|
||||||
accessTokenRef.current = undefined;
|
accessTokenRef.current = undefined;
|
||||||
queryClient.clear();
|
queryClient.clear();
|
||||||
}, [queryClient]);
|
}, [queryClient]);
|
||||||
@@ -156,12 +153,10 @@ function useAuthProviderVm() {
|
|||||||
useEffect(() => () => configureAuthClient(), []);
|
useEffect(() => () => configureAuthClient(), []);
|
||||||
|
|
||||||
const authContextValue = {
|
const authContextValue = {
|
||||||
accessToken,
|
|
||||||
login: (email: string, password: string) =>
|
login: (email: string, password: string) =>
|
||||||
authenticate("/api/v1/auth/login", email, password),
|
authenticate("/api/v1/auth/login", email, password),
|
||||||
logout,
|
logout,
|
||||||
ready,
|
ready,
|
||||||
refresh,
|
|
||||||
register: (email: string, password: string) =>
|
register: (email: string, password: string) =>
|
||||||
authenticate("/api/v1/auth/register", email, password),
|
authenticate("/api/v1/auth/register", email, password),
|
||||||
user,
|
user,
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
|
|
||||||
|
import { useAuth } from "../../model/auth-context";
|
||||||
import { AuthForm } from "../AuthForm/AuthForm";
|
import { AuthForm } from "../AuthForm/AuthForm";
|
||||||
import { useLoginFormVm } from "./LoginForm.vm";
|
|
||||||
|
|
||||||
const LoginForm: FC = () => {
|
const LoginForm: FC = () => {
|
||||||
const { onSubmit } = useLoginFormVm();
|
const { login } = useAuth();
|
||||||
|
|
||||||
return <AuthForm onSubmit={onSubmit} />;
|
return <AuthForm onSubmit={login} />;
|
||||||
};
|
};
|
||||||
|
|
||||||
export { LoginForm };
|
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 type { FC } from "react";
|
||||||
|
|
||||||
|
import { useAuth } from "../../model/auth-context";
|
||||||
import { AuthForm } from "../AuthForm/AuthForm";
|
import { AuthForm } from "../AuthForm/AuthForm";
|
||||||
import { useRegisterFormVm } from "./RegisterForm.vm";
|
|
||||||
|
|
||||||
const RegisterForm: FC = () => {
|
const RegisterForm: FC = () => {
|
||||||
const { onSubmit } = useRegisterFormVm();
|
const { register } = useAuth();
|
||||||
|
|
||||||
return <AuthForm onSubmit={onSubmit} register />;
|
return <AuthForm onSubmit={register} register />;
|
||||||
};
|
};
|
||||||
|
|
||||||
export { RegisterForm };
|
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 { section, type SectionState } from "./model/section";
|
||||||
|
export { useInstrumentParameters } from "./model/useInstrumentParameters";
|
||||||
export { InstrumentChart } from "./ui/InstrumentChart/InstrumentChart.view";
|
export { InstrumentChart } from "./ui/InstrumentChart/InstrumentChart.view";
|
||||||
export { InstrumentEvents } from "./ui/InstrumentEvents.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 { InstrumentPosition } from "./ui/InstrumentPosition.view";
|
||||||
export { InstrumentSection } from "./ui/InstrumentSection.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 type { InstrumentChartProps } from "../../model/types";
|
||||||
|
|
||||||
|
import { instrumentPeriods } from "../../model/useInstrumentParameters";
|
||||||
|
|
||||||
function useInstrumentChartVm(props: InstrumentChartProps) {
|
function useInstrumentChartVm(props: InstrumentChartProps) {
|
||||||
const { vm } = props;
|
const { vm } = props;
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -34,7 +36,7 @@ function useInstrumentChartVm(props: InstrumentChartProps) {
|
|||||||
return { ...candle, price };
|
return { ...candle, price };
|
||||||
});
|
});
|
||||||
|
|
||||||
const periodOptions = ["month", "halfYear", "year", "all"].map(value => ({
|
const periodOptions = instrumentPeriods.map(value => ({
|
||||||
label: t(`stock.periods.${value}`),
|
label: t(`stock.periods.${value}`),
|
||||||
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(
|
function toAccountPagePositionSections(
|
||||||
portfolio: Portfolio,
|
portfolio: Portfolio,
|
||||||
instrumentDetails: Map<string, undefined
|
|
||||||
| { slug: string }> = new Map(),
|
|
||||||
): AccountPagePositionSection[] {
|
): AccountPagePositionSection[] {
|
||||||
const denominators = new Map<string, number>();
|
const denominators = new Map<string, number>();
|
||||||
|
|
||||||
@@ -87,11 +85,10 @@ function toAccountPagePositionSections(
|
|||||||
"stocks",
|
"stocks",
|
||||||
portfolio,
|
portfolio,
|
||||||
denominators,
|
denominators,
|
||||||
instrumentDetails,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const bonds = toSection("bonds", portfolio, denominators, instrumentDetails);
|
const bonds = toSection("bonds", portfolio, denominators);
|
||||||
const other = toSection("other", portfolio, denominators, instrumentDetails);
|
const other = toSection("other", portfolio, denominators);
|
||||||
|
|
||||||
return [stocks, bonds, other].filter(section => section.groups.length > 0);
|
return [stocks, bonds, other].filter(section => section.groups.length > 0);
|
||||||
}
|
}
|
||||||
@@ -100,7 +97,6 @@ function toPosition(
|
|||||||
position: Portfolio["positions"][number],
|
position: Portfolio["positions"][number],
|
||||||
denominators: Map<string, number>,
|
denominators: Map<string, number>,
|
||||||
kind: PositionSectionKind,
|
kind: PositionSectionKind,
|
||||||
instrumentSlug?: string,
|
|
||||||
): AccountPagePosition {
|
): AccountPagePosition {
|
||||||
const isExpanded = kind !== "other";
|
const isExpanded = kind !== "other";
|
||||||
|
|
||||||
@@ -119,7 +115,7 @@ function toPosition(
|
|||||||
...position,
|
...position,
|
||||||
instrumentTo:
|
instrumentTo:
|
||||||
(kind === "stocks" || kind === "bonds") && position.instrumentUid
|
(kind === "stocks" || kind === "bonds") && position.instrumentUid
|
||||||
? `/${kind}/${encodeURIComponent(instrumentSlug ?? position.instrumentUid)}`
|
? `/${kind}/${encodeURIComponent(position.instrumentUid)}`
|
||||||
: undefined,
|
: undefined,
|
||||||
logoSrc: isExpanded
|
logoSrc: isExpanded
|
||||||
? instrumentLogoUrl(position.logoName)
|
? instrumentLogoUrl(position.logoName)
|
||||||
@@ -141,8 +137,6 @@ function toSection(
|
|||||||
kind: PositionSectionKind,
|
kind: PositionSectionKind,
|
||||||
portfolio: Portfolio,
|
portfolio: Portfolio,
|
||||||
denominators: Map<string, number>,
|
denominators: Map<string, number>,
|
||||||
instrumentDetails: Map<string, undefined
|
|
||||||
| { slug: string }>,
|
|
||||||
): AccountPagePositionSection {
|
): AccountPagePositionSection {
|
||||||
return {
|
return {
|
||||||
groups: groupPositions(
|
groups: groupPositions(
|
||||||
@@ -161,7 +155,6 @@ function toSection(
|
|||||||
position,
|
position,
|
||||||
denominators,
|
denominators,
|
||||||
kind,
|
kind,
|
||||||
instrumentDetails.get(position.instrumentUid ?? "")?.slug,
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
.tile,
|
.tile {
|
||||||
.cash {
|
|
||||||
border-color: var(--mantine-color-gray-3);
|
border-color: var(--mantine-color-gray-3);
|
||||||
background: var(--mantine-color-gray-0);
|
background: var(--mantine-color-gray-0);
|
||||||
}
|
}
|
||||||
@@ -52,15 +51,10 @@
|
|||||||
margin-block: 5px;
|
margin-block: 5px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.tile,
|
.tile {
|
||||||
.cash {
|
|
||||||
padding: var(--mantine-spacing-md);
|
padding: var(--mantine-spacing-md);
|
||||||
}
|
}
|
||||||
|
|
||||||
.cash {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
}
|
|
||||||
|
|
||||||
.positive {
|
.positive {
|
||||||
color: var(--wl-color-positive);
|
color: var(--wl-color-positive);
|
||||||
|
|||||||
@@ -212,10 +212,10 @@ describe("AccountPage states", () => {
|
|||||||
for (const link of links)
|
for (const link of links)
|
||||||
expect(link).toHaveAttribute(
|
expect(link).toHaveAttribute(
|
||||||
"href",
|
"href",
|
||||||
`/${collection}/${type === "STOCK" ? slug : uid}`,
|
`/${collection}/${uid}`,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
expect(requests).toHaveBeenCalledTimes(type === "STOCK" ? 1 : 0);
|
expect(requests).not.toHaveBeenCalled();
|
||||||
expect(
|
expect(
|
||||||
screen.queryByText("Название из карточки инструмента"),
|
screen.queryByText("Название из карточки инструмента"),
|
||||||
).not.toBeInTheDocument();
|
).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 () => {
|
it("keeps the account and positions visible for an older HTTP response without structure", async () => {
|
||||||
server.use(
|
server.use(
|
||||||
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
|
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 { MemoryRouter, Route, Routes } from "react-router";
|
||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
import type { Portfolio } from "@/entities/portfolio";
|
|
||||||
|
|
||||||
import { configureAuthClient } from "@/shared/api";
|
import { configureAuthClient } from "@/shared/api";
|
||||||
import { createQueryWrapper } from "@/test/query";
|
import { createQueryWrapper } from "@/test/query";
|
||||||
import { resource } from "@/test/resource";
|
import { resource } from "@/test/resource";
|
||||||
import { server } from "@/test/server";
|
import { server } from "@/test/server";
|
||||||
|
|
||||||
import { toAccountPagePositionSections } from "../../model/positions";
|
import { portfolio } from "../../model/positions.fixtures";
|
||||||
import { useAccountPageViewModel } from "./AccountPage.vm";
|
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() {
|
function configureTestAuth() {
|
||||||
configureAuthClient({
|
configureAuthClient({
|
||||||
accessToken: () => "test-token",
|
accessToken: () => "test-token",
|
||||||
@@ -152,109 +103,6 @@ function mockLoadedAccountPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("useAccountPageViewModel", () => {
|
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 () => {
|
it("prepares recent operations and events state for presentation views", async () => {
|
||||||
configureTestAuth();
|
configureTestAuth();
|
||||||
mockLoadedAccountPage();
|
mockLoadedAccountPage();
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import {
|
|||||||
} from "@/entities/brokerage-event";
|
} from "@/entities/brokerage-event";
|
||||||
import { type IncomeSummary, useIncomeSummary } from "@/entities/income";
|
import { type IncomeSummary, useIncomeSummary } from "@/entities/income";
|
||||||
import { usePortfolio } from "@/entities/portfolio";
|
import { usePortfolio } from "@/entities/portfolio";
|
||||||
import { useStocks } from "@/entities/stock";
|
|
||||||
import { useScreenSync } from "@/features/tbank-connection";
|
import { useScreenSync } from "@/features/tbank-connection";
|
||||||
import { apiErrorCode } from "@/shared/api";
|
import { apiErrorCode } from "@/shared/api";
|
||||||
|
|
||||||
@@ -168,14 +167,6 @@ function useAccountPageViewModel(): AccountPageViewModel {
|
|||||||
const { accountId } = useParams();
|
const { accountId } = useParams();
|
||||||
const portfolio = usePortfolio(accountId);
|
const portfolio = usePortfolio(accountId);
|
||||||
|
|
||||||
const stocks = useStocks(
|
|
||||||
portfolio.data?.positions.flatMap(position =>
|
|
||||||
position.type === "STOCK" && position.instrumentUid
|
|
||||||
? [position.instrumentUid]
|
|
||||||
: [],
|
|
||||||
) ?? [],
|
|
||||||
);
|
|
||||||
|
|
||||||
const operations = useBrokerageOperations(accountId, {
|
const operations = useBrokerageOperations(accountId, {
|
||||||
limit: 5,
|
limit: 5,
|
||||||
});
|
});
|
||||||
@@ -236,10 +227,7 @@ function useAccountPageViewModel(): AccountPageViewModel {
|
|||||||
accountId,
|
accountId,
|
||||||
incomeSummary,
|
incomeSummary,
|
||||||
portfolio: portfolio.data,
|
portfolio: portfolio.data,
|
||||||
positionSections: toAccountPagePositionSections(
|
positionSections: toAccountPagePositionSections(portfolio.data),
|
||||||
portfolio.data,
|
|
||||||
stocks,
|
|
||||||
),
|
|
||||||
recentEvents,
|
recentEvents,
|
||||||
recentOperations,
|
recentOperations,
|
||||||
state: "loaded" as const,
|
state: "loaded" as const,
|
||||||
|
|||||||
@@ -3,50 +3,16 @@ import { render, screen, within } from "@testing-library/react";
|
|||||||
import { MemoryRouter } from "react-router";
|
import { MemoryRouter } from "react-router";
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import type { Portfolio } from "@/entities/portfolio";
|
|
||||||
|
|
||||||
import { toAccountPagePositionSections } from "../../model/positions";
|
import { toAccountPagePositionSections } from "../../model/positions";
|
||||||
|
import { portfolio, position, second } from "../../model/positions.fixtures";
|
||||||
import { PositionSection } from "./components/PositionSection.view";
|
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", () => {
|
describe("Positions grouped by security", () => {
|
||||||
it("shows one security with exact per-account quantities and valuations", () => {
|
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(
|
render(
|
||||||
<MantineProvider>
|
<MantineProvider>
|
||||||
<MemoryRouter>
|
<MemoryRouter>
|
||||||
@@ -76,75 +42,4 @@ describe("Positions grouped by security", () => {
|
|||||||
expect(within(rows[1]).getByText("Количество: -2")).toBeInTheDocument();
|
expect(within(rows[1]).getByText("Количество: -2")).toBeInTheDocument();
|
||||||
expect(rows[1]).not.toHaveTextContent("₽");
|
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;
|
margin: 0 auto;
|
||||||
min-width: 0;
|
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 {
|
.price {
|
||||||
font-size: clamp(2rem, 4vw, 3.2rem);
|
font-size: clamp(2rem, 4vw, 3.2rem);
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
@@ -38,9 +27,6 @@
|
|||||||
border-radius: var(--mantine-radius-md);
|
border-radius: var(--mantine-radius-md);
|
||||||
}
|
}
|
||||||
@media (max-width: 48em) {
|
@media (max-width: 48em) {
|
||||||
.section {
|
|
||||||
padding: var(--mantine-spacing-md);
|
|
||||||
}
|
|
||||||
.companyMetrics {
|
.companyMetrics {
|
||||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,66 +1,23 @@
|
|||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
|
|
||||||
import { Anchor, Button, Skeleton, Stack, Text, Title } from "@mantine/core";
|
import { Navigate } from "react-router";
|
||||||
import { LoadingSkeleton } from "@wealthledger/ui";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { Link, Navigate } from "react-router";
|
|
||||||
|
|
||||||
import { ApiErrorCode, isApiErrorCode } from "@/shared/api";
|
import { InstrumentPageState } from "@/features/instrument-details";
|
||||||
|
|
||||||
import { BondPageView } from "./BondPage.view";
|
import { BondPageView } from "./BondPage.view";
|
||||||
import { useBondPageVm } from "./BondPage.vm";
|
import { useBondPageVm } from "./BondPage.vm";
|
||||||
|
|
||||||
const BondPage: FC = () => {
|
const BondPage: FC = () => {
|
||||||
const vm = useBondPageVm();
|
const vm = useBondPageVm();
|
||||||
const { t } = useTranslation();
|
|
||||||
if (vm.canonicalTo) return <Navigate replace to={vm.canonicalTo} />;
|
if (vm.canonicalTo) return <Navigate replace to={vm.canonicalTo} />;
|
||||||
if (vm.bondState.loading)
|
if (vm.bondState.loading || !vm.bond) return (
|
||||||
return (
|
<InstrumentPageState
|
||||||
<LoadingSkeleton label={t("bond.loading")}>
|
code={vm.code}
|
||||||
<Stack>
|
kind="bond"
|
||||||
<Skeleton h={110} />
|
loading={vm.bondState.loading}
|
||||||
|
retry={vm.bondState.retry}
|
||||||
<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>
|
|
||||||
);
|
|
||||||
|
|
||||||
return <BondPageView vm={vm} />;
|
return <BondPageView vm={vm} />;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,11 +2,8 @@ import type { FC } from "react";
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
Alert,
|
Alert,
|
||||||
Avatar,
|
|
||||||
Badge,
|
Badge,
|
||||||
Button,
|
|
||||||
Group,
|
Group,
|
||||||
Paper,
|
|
||||||
Skeleton,
|
Skeleton,
|
||||||
Stack,
|
Stack,
|
||||||
Text,
|
Text,
|
||||||
@@ -18,6 +15,7 @@ import { useTranslation } from "react-i18next";
|
|||||||
import {
|
import {
|
||||||
InstrumentChart,
|
InstrumentChart,
|
||||||
InstrumentEvents,
|
InstrumentEvents,
|
||||||
|
InstrumentHeader,
|
||||||
InstrumentPosition,
|
InstrumentPosition,
|
||||||
} from "@/features/instrument-details";
|
} from "@/features/instrument-details";
|
||||||
import {
|
import {
|
||||||
@@ -42,6 +40,8 @@ const BondPageView: FC<BondPageViewProps> = (props) => {
|
|||||||
const bond = vm.bond;
|
const bond = vm.bond;
|
||||||
if (!bond) return;
|
if (!bond) return;
|
||||||
|
|
||||||
|
const subtitle = `${bond.ticker ?? ""} · ${bond.isin ?? ""}`;
|
||||||
|
|
||||||
const maturity = bond.maturityDate
|
const maturity = bond.maturityDate
|
||||||
? formatDate(bond.maturityDate)
|
? formatDate(bond.maturityDate)
|
||||||
: t("bond.unknown");
|
: t("bond.unknown");
|
||||||
@@ -144,32 +144,13 @@ const BondPageView: FC<BondPageViewProps> = (props) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack className={classes.page} gap="lg">
|
<Stack className={classes.page} gap="lg">
|
||||||
<Paper className={classes.section} component="header" withBorder>
|
<InstrumentHeader
|
||||||
<Group align="start" justify="space-between">
|
logoSrc={vm.logoSrc}
|
||||||
<div className={classes.identity}>
|
name={bond.name}
|
||||||
<Avatar alt="" radius="md" size={56} src={vm.logoSrc}>
|
onRefresh={vm.refresh}
|
||||||
{bond.name[0]}
|
refreshing={vm.refreshing}
|
||||||
</Avatar>
|
subtitle={subtitle}
|
||||||
|
>
|
||||||
<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>
|
|
||||||
|
|
||||||
<Group gap="xs" mt="md">
|
<Group gap="xs" mt="md">
|
||||||
{!!bond.floatingCoupon && <Badge variant="light">{t("bond.floatingCoupon")}</Badge>}
|
{!!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} />
|
<Metric label={t("bond.lot")} value={lotSize} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Paper>
|
</InstrumentHeader>
|
||||||
|
|
||||||
<BondMetrics metrics={vm.metrics} state={vm.metricsState} />
|
<BondMetrics metrics={vm.metrics} state={vm.metricsState} />
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { useParams, useSearchParams } from "react-router";
|
import { useParams } from "react-router";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
type BondPeriod,
|
|
||||||
useBond,
|
useBond,
|
||||||
useBondCandles,
|
useBondCandles,
|
||||||
useBondCoupons,
|
useBondCoupons,
|
||||||
@@ -9,37 +8,21 @@ import {
|
|||||||
useBondPosition,
|
useBondPosition,
|
||||||
useBondQuote,
|
useBondQuote,
|
||||||
} from "@/entities/bond";
|
} from "@/entities/bond";
|
||||||
import { type OperationCategory, useBrokerageOperationHistory } from "@/entities/broker-operation";
|
import { useBrokerageOperationHistory } from "@/entities/broker-operation";
|
||||||
import { section } from "@/features/instrument-details";
|
import { section, useInstrumentParameters } from "@/features/instrument-details";
|
||||||
import { useScreenSync } from "@/features/tbank-connection";
|
import { useScreenSync } from "@/features/tbank-connection";
|
||||||
import { apiErrorCode } from "@/shared/api";
|
import { apiErrorCode } from "@/shared/api";
|
||||||
import { instrumentLogoUrl } from "@/shared/lib";
|
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>;
|
type BondPageVm = ReturnType<typeof useBondPageVm>;
|
||||||
|
|
||||||
function useBondPageVm() {
|
function useBondPageVm() {
|
||||||
const { bondId = "" } = useParams();
|
const { bondId = "" } = useParams();
|
||||||
const bond = useBond(bondId);
|
const bond = useBond(bondId);
|
||||||
const uid = bond.data?.instrumentUid ?? "";
|
const uid = bond.data?.instrumentUid ?? "";
|
||||||
const [parameters, setParameters] = useSearchParams();
|
|
||||||
|
|
||||||
const period
|
const { categories, filter, period, search, setFilter, setPeriod }
|
||||||
= periods.find(value => value === parameters.get("period")) ?? "month";
|
= useInstrumentParameters("coupons");
|
||||||
|
|
||||||
const filter
|
|
||||||
= filters.find(value => value === parameters.get("events")) ?? "all";
|
|
||||||
|
|
||||||
const quote = useBondQuote(uid);
|
const quote = useBondQuote(uid);
|
||||||
const metrics = useBondMetrics(uid);
|
const metrics = useBondMetrics(uid);
|
||||||
@@ -48,8 +31,7 @@ function useBondPageVm() {
|
|||||||
const coupons = useBondCoupons(uid);
|
const coupons = useBondCoupons(uid);
|
||||||
|
|
||||||
const history = useBrokerageOperationHistory(uid ? "all" : undefined, {
|
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: categories[filter],
|
|
||||||
instrumentUid: uid,
|
instrumentUid: uid,
|
||||||
limit: 20,
|
limit: 20,
|
||||||
});
|
});
|
||||||
@@ -60,9 +42,7 @@ function useBondPageVm() {
|
|||||||
{
|
{
|
||||||
accountId: "all",
|
accountId: "all",
|
||||||
candlePeriod: period,
|
candlePeriod: period,
|
||||||
categories:
|
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],
|
|
||||||
instrumentUid: uid,
|
instrumentUid: uid,
|
||||||
limit: 20,
|
limit: 20,
|
||||||
screen: "bond",
|
screen: "bond",
|
||||||
@@ -70,14 +50,6 @@ function useBondPageVm() {
|
|||||||
[bond, quote, candles, position, metrics, coupons, operations],
|
[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 {
|
return {
|
||||||
bond: bond.data,
|
bond: bond.data,
|
||||||
bondState: section(bond, uid ? sync.retry : () => bond.refetch()),
|
bondState: section(bond, uid ? sync.retry : () => bond.refetch()),
|
||||||
@@ -132,8 +104,8 @@ function useBondPageVm() {
|
|||||||
refresh: sync.refresh,
|
refresh: sync.refresh,
|
||||||
refreshError: sync.transportError || sync.sourceError,
|
refreshError: sync.transportError || sync.sourceError,
|
||||||
refreshing: sync.refreshing,
|
refreshing: sync.refreshing,
|
||||||
setFilter: (value: string) => setParameter("events", value),
|
setFilter,
|
||||||
setPeriod: (value: string) => setParameter("period", value),
|
setPeriod,
|
||||||
upcoming:
|
upcoming:
|
||||||
coupons.data?.coupons
|
coupons.data?.coupons
|
||||||
.filter(event => event.timing === "upcoming")
|
.filter(event => event.timing === "upcoming")
|
||||||
|
|||||||
@@ -3,17 +3,6 @@
|
|||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
min-width: 0;
|
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 {
|
.price {
|
||||||
font-size: clamp(2rem, 4vw, 3.2rem);
|
font-size: clamp(2rem, 4vw, 3.2rem);
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
@@ -38,20 +27,12 @@
|
|||||||
grid-template-columns: repeat(auto-fit, minmax(135px, 1fr));
|
grid-template-columns: repeat(auto-fit, minmax(135px, 1fr));
|
||||||
gap: var(--mantine-spacing-lg);
|
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 {
|
.companyMetrics > div {
|
||||||
padding: var(--mantine-spacing-sm);
|
padding: var(--mantine-spacing-sm);
|
||||||
background: var(--wl-color-subtle);
|
background: var(--wl-color-subtle);
|
||||||
border-radius: var(--mantine-radius-md);
|
border-radius: var(--mantine-radius-md);
|
||||||
}
|
}
|
||||||
@media (max-width: 48em) {
|
@media (max-width: 48em) {
|
||||||
.section {
|
|
||||||
padding: var(--mantine-spacing-md);
|
|
||||||
}
|
|
||||||
.companyMetrics {
|
.companyMetrics {
|
||||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,66 +1,23 @@
|
|||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
|
|
||||||
import { Anchor, Button, Skeleton, Stack, Text, Title } from "@mantine/core";
|
import { Navigate } from "react-router";
|
||||||
import { LoadingSkeleton } from "@wealthledger/ui";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { Link, Navigate } from "react-router";
|
|
||||||
|
|
||||||
import { ApiErrorCode, isApiErrorCode } from "@/shared/api";
|
import { InstrumentPageState } from "@/features/instrument-details";
|
||||||
|
|
||||||
import { StockPageView } from "./StockPage.view";
|
import { StockPageView } from "./StockPage.view";
|
||||||
import { useStockPageVm } from "./StockPage.vm";
|
import { useStockPageVm } from "./StockPage.vm";
|
||||||
|
|
||||||
const StockPage: FC = () => {
|
const StockPage: FC = () => {
|
||||||
const vm = useStockPageVm();
|
const vm = useStockPageVm();
|
||||||
const { t } = useTranslation();
|
|
||||||
if (vm.canonicalTo) return <Navigate replace to={vm.canonicalTo} />;
|
if (vm.canonicalTo) return <Navigate replace to={vm.canonicalTo} />;
|
||||||
if (vm.stockState.loading)
|
if (vm.stockState.loading || !vm.stock) return (
|
||||||
return (
|
<InstrumentPageState
|
||||||
<LoadingSkeleton label={t("stock.loading")}>
|
code={vm.code}
|
||||||
<Stack>
|
kind="stock"
|
||||||
<Skeleton h={110} />
|
loading={vm.stockState.loading}
|
||||||
|
retry={vm.stockState.retry}
|
||||||
<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>
|
|
||||||
);
|
|
||||||
|
|
||||||
return <StockPageView vm={vm} />;
|
return <StockPageView vm={vm} />;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,20 +2,18 @@ import type { FC } from "react";
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
Alert,
|
Alert,
|
||||||
Avatar,
|
|
||||||
Badge,
|
Badge,
|
||||||
Button,
|
Button,
|
||||||
Group,
|
Group,
|
||||||
Paper,
|
|
||||||
Skeleton,
|
Skeleton,
|
||||||
Stack,
|
Stack,
|
||||||
Text,
|
Text,
|
||||||
Title,
|
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
import { LoadingSkeleton } from "@wealthledger/ui";
|
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
|
InstrumentHeader,
|
||||||
InstrumentChart as StockChart,
|
InstrumentChart as StockChart,
|
||||||
InstrumentEvents as StockEvents,
|
InstrumentEvents as StockEvents,
|
||||||
InstrumentPosition as StockPosition,
|
InstrumentPosition as StockPosition,
|
||||||
@@ -30,7 +28,7 @@ import {
|
|||||||
|
|
||||||
import type { StockPageVm } from "./StockPage.vm";
|
import type { StockPageVm } from "./StockPage.vm";
|
||||||
|
|
||||||
import { StockDividends } from "./components/StockEvents.view";
|
import { StockDividends } from "./components/StockDividends.view";
|
||||||
import classes from "./StockPage.module.css";
|
import classes from "./StockPage.module.css";
|
||||||
|
|
||||||
type StockPageViewProps = { vm: StockPageVm };
|
type StockPageViewProps = { vm: StockPageVm };
|
||||||
@@ -41,6 +39,15 @@ const StockPageView: FC<StockPageViewProps> = (props) => {
|
|||||||
const stock = vm.stock;
|
const stock = vm.stock;
|
||||||
if (!stock) return;
|
if (!stock) return;
|
||||||
|
|
||||||
|
const subtitle = (
|
||||||
|
<>
|
||||||
|
{stock.ticker} ·{" "}
|
||||||
|
{t(`stock.shareTypes.${stock.shareType}`, {
|
||||||
|
defaultValue: t("stock.share"),
|
||||||
|
})}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
const appearanceClass = vm.quote?.change?.value.startsWith("-")
|
const appearanceClass = vm.quote?.change?.value.startsWith("-")
|
||||||
? classes.negative
|
? classes.negative
|
||||||
: classes.positive;
|
: classes.positive;
|
||||||
@@ -152,41 +159,13 @@ const StockPageView: FC<StockPageViewProps> = (props) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack className={classes.page} gap="lg">
|
<Stack className={classes.page} gap="lg">
|
||||||
<Paper className={classes.section} component="header" withBorder>
|
<InstrumentHeader
|
||||||
<Group align="start" justify="space-between">
|
logoSrc={vm.logoSrc}
|
||||||
<div className={classes.identity}>
|
name={stock.name}
|
||||||
<Avatar
|
onRefresh={vm.refresh}
|
||||||
alt=""
|
refreshing={vm.refreshing}
|
||||||
key={vm.logoSrc}
|
subtitle={subtitle}
|
||||||
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>
|
|
||||||
|
|
||||||
{!!vm.company?.description && (
|
{!!vm.company?.description && (
|
||||||
<Text mt="md" size="sm" style={{ whiteSpace: "pre-line" }}>
|
<Text mt="md" size="sm" style={{ whiteSpace: "pre-line" }}>
|
||||||
@@ -246,13 +225,18 @@ const StockPageView: FC<StockPageViewProps> = (props) => {
|
|||||||
</Stack>
|
</Stack>
|
||||||
)}
|
)}
|
||||||
</StockSection>
|
</StockSection>
|
||||||
</Paper>
|
</InstrumentHeader>
|
||||||
|
|
||||||
<StockChart vm={vm} />
|
<StockChart vm={vm} />
|
||||||
|
|
||||||
<StockPosition vm={vm} />
|
<StockPosition vm={vm} />
|
||||||
|
|
||||||
<StockDividends vm={vm} />
|
<StockDividends
|
||||||
|
dividends={vm.dividends}
|
||||||
|
pastDividends={vm.pastDividends}
|
||||||
|
state={vm.dividendsState}
|
||||||
|
upcoming={vm.upcoming}
|
||||||
|
/>
|
||||||
|
|
||||||
<StockEvents vm={vm} />
|
<StockEvents vm={vm} />
|
||||||
</Stack>
|
</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 {
|
import {
|
||||||
type StockPeriod,
|
|
||||||
useStock,
|
useStock,
|
||||||
useStockCandles,
|
useStockCandles,
|
||||||
useStockCompany,
|
useStockCompany,
|
||||||
@@ -12,36 +11,21 @@ import {
|
|||||||
} from "@/entities/stock";
|
} from "@/entities/stock";
|
||||||
import {
|
import {
|
||||||
section,
|
section,
|
||||||
|
useInstrumentParameters,
|
||||||
} from "@/features/instrument-details";
|
} from "@/features/instrument-details";
|
||||||
import { useScreenSync } from "@/features/tbank-connection";
|
import { useScreenSync } from "@/features/tbank-connection";
|
||||||
import { apiErrorCode } from "@/shared/api";
|
import { apiErrorCode } from "@/shared/api";
|
||||||
import { instrumentLogoUrl } from "@/shared/lib";
|
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>;
|
type StockPageVm = ReturnType<typeof useStockPageVm>;
|
||||||
|
|
||||||
function useStockPageVm() {
|
function useStockPageVm() {
|
||||||
const { stockId = "" } = useParams();
|
const { stockId = "" } = useParams();
|
||||||
const stock = useStock(stockId);
|
const stock = useStock(stockId);
|
||||||
const uid = stock.data?.instrumentUid ?? "";
|
const uid = stock.data?.instrumentUid ?? "";
|
||||||
const [parameters, setParameters] = useSearchParams();
|
|
||||||
|
|
||||||
const period
|
const { categories, filter, period, search, setFilter, setPeriod }
|
||||||
= periods.find(value => value === parameters.get("period")) ?? "month";
|
= useInstrumentParameters("dividends");
|
||||||
|
|
||||||
const filter
|
|
||||||
= filters.find(value => value === parameters.get("events")) ?? "all";
|
|
||||||
|
|
||||||
const quote = useStockQuote(uid);
|
const quote = useStockQuote(uid);
|
||||||
const candles = useStockCandles(uid, period);
|
const candles = useStockCandles(uid, period);
|
||||||
@@ -50,8 +34,7 @@ function useStockPageVm() {
|
|||||||
const dividends = useStockDividends(uid);
|
const dividends = useStockDividends(uid);
|
||||||
|
|
||||||
const history = useBrokerageOperationHistory(uid ? "all" : undefined, {
|
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: categories[filter],
|
|
||||||
instrumentUid: uid,
|
instrumentUid: uid,
|
||||||
limit: 20,
|
limit: 20,
|
||||||
});
|
});
|
||||||
@@ -62,9 +45,7 @@ function useStockPageVm() {
|
|||||||
{
|
{
|
||||||
accountId: "all",
|
accountId: "all",
|
||||||
candlePeriod: period,
|
candlePeriod: period,
|
||||||
categories:
|
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],
|
|
||||||
instrumentUid: uid,
|
instrumentUid: uid,
|
||||||
limit: 20,
|
limit: 20,
|
||||||
screen: "stock",
|
screen: "stock",
|
||||||
@@ -72,15 +53,6 @@ function useStockPageVm() {
|
|||||||
[stock, quote, candles, position, company, dividends, operations],
|
[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 {
|
return {
|
||||||
candles: candles.data,
|
candles: candles.data,
|
||||||
candlesState: section(candles, sync.retry),
|
candlesState: section(candles, sync.retry),
|
||||||
@@ -89,7 +61,7 @@ function useStockPageVm() {
|
|||||||
? `/stocks/${encodeURIComponent(stock.data.slug)}${search}`
|
? `/stocks/${encodeURIComponent(stock.data.slug)}${search}`
|
||||||
: null,
|
: null,
|
||||||
code: apiErrorCode(stock.error),
|
code: apiErrorCode(stock.error),
|
||||||
company: companyData,
|
company: company.data,
|
||||||
companyState: section(company, sync.retry),
|
companyState: section(company, sync.retry),
|
||||||
dividends: dividends.data,
|
dividends: dividends.data,
|
||||||
dividendsState: section(dividends, sync.retry),
|
dividendsState: section(dividends, sync.retry),
|
||||||
@@ -133,8 +105,8 @@ function useStockPageVm() {
|
|||||||
refresh: sync.refresh,
|
refresh: sync.refresh,
|
||||||
refreshError: sync.transportError || sync.sourceError,
|
refreshError: sync.transportError || sync.sourceError,
|
||||||
refreshing: sync.refreshing,
|
refreshing: sync.refreshing,
|
||||||
setFilter: (value: string) => setParameter("events", value),
|
setFilter,
|
||||||
setPeriod: (value: string) => setParameter("period", value),
|
setPeriod,
|
||||||
stock: stock.data,
|
stock: stock.data,
|
||||||
stockState: section(stock, uid ? sync.retry : () => stock.refetch()),
|
stockState: section(stock, uid ? sync.retry : () => stock.refetch()),
|
||||||
upcoming:
|
upcoming:
|
||||||
|
|||||||
+25
-20
@@ -11,25 +11,30 @@ import {
|
|||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import { InstrumentSection as StockSection } from "@/features/instrument-details";
|
import type { StockDividends as Dividends } from "@/entities/stock";
|
||||||
import { formatDate, formatMoney, formatSnapshotTime } from "@/shared/lib";
|
|
||||||
|
|
||||||
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";
|
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 StockDividends: FC<StockDividendsProps> = (props) => {
|
||||||
const { vm } = props;
|
const { dividends, pastDividends, state, upcoming } = props;
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
let upcomingContent;
|
let upcomingContent;
|
||||||
|
|
||||||
if (vm.dividends) {
|
if (dividends) {
|
||||||
if (vm.upcoming.length > 0) {
|
if (upcoming.length > 0) {
|
||||||
upcomingContent = (
|
upcomingContent = (
|
||||||
vm.upcoming.map(event => (
|
upcoming.map(event => (
|
||||||
<div
|
<div
|
||||||
className={classes.dividend}
|
className={classes.dividend}
|
||||||
key={JSON.stringify([
|
key={JSON.stringify([
|
||||||
@@ -104,7 +109,7 @@ const StockDividends: FC<StockEventsProps> = (props) => {
|
|||||||
else {
|
else {
|
||||||
upcomingContent = (
|
upcomingContent = (
|
||||||
<Text c="dimmed">
|
<Text c="dimmed">
|
||||||
{t("stock.noUpcoming", { to: formatDate(vm.dividends.to) })}
|
{t("stock.noUpcoming", { to: formatDate(dividends.to) })}
|
||||||
</Text>
|
</Text>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -112,10 +117,10 @@ const StockDividends: FC<StockEventsProps> = (props) => {
|
|||||||
|
|
||||||
let pastDividendsContent;
|
let pastDividendsContent;
|
||||||
|
|
||||||
if (vm.pastDividends.length > 0) {
|
if (pastDividends.length > 0) {
|
||||||
pastDividendsContent = (
|
pastDividendsContent = (
|
||||||
<Stack gap="sm">
|
<Stack gap="sm">
|
||||||
{vm.pastDividends.map(event => (
|
{pastDividends.map(event => (
|
||||||
<Paper
|
<Paper
|
||||||
key={JSON.stringify([
|
key={JSON.stringify([
|
||||||
event.recordDate,
|
event.recordDate,
|
||||||
@@ -166,11 +171,11 @@ const StockDividends: FC<StockEventsProps> = (props) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<StockSection state={vm.dividendsState} title={t("stock.upcoming")}>
|
<InstrumentSection state={state} title={t("stock.upcoming")}>
|
||||||
{!!vm.dividends && (
|
{!!dividends && (
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
{!!(
|
{!!(
|
||||||
vm.dividends.estimateUnavailable || vm.dividends.positionIsStale
|
dividends.estimateUnavailable || dividends.positionIsStale
|
||||||
) && (
|
) && (
|
||||||
<Alert aria-live="polite" color="orange" role="status">
|
<Alert aria-live="polite" color="orange" role="status">
|
||||||
{t("stock.estimateUnavailable")}
|
{t("stock.estimateUnavailable")}
|
||||||
@@ -183,10 +188,10 @@ const StockDividends: FC<StockEventsProps> = (props) => {
|
|||||||
{t("stock.dividendNote")}
|
{t("stock.dividendNote")}
|
||||||
</Text>
|
</Text>
|
||||||
|
|
||||||
{!!vm.dividends.positionAt && (
|
{!!dividends.positionAt && (
|
||||||
<Text c="dimmed" size="xs">
|
<Text c="dimmed" size="xs">
|
||||||
{t("stock.snapshotAt", {
|
{t("stock.snapshotAt", {
|
||||||
date: formatSnapshotTime(vm.dividends.positionAt),
|
date: formatSnapshotTime(dividends.positionAt),
|
||||||
})}
|
})}
|
||||||
</Text>
|
</Text>
|
||||||
)}
|
)}
|
||||||
@@ -200,8 +205,8 @@ const StockDividends: FC<StockEventsProps> = (props) => {
|
|||||||
<Accordion.Panel>
|
<Accordion.Panel>
|
||||||
<Text c="dimmed" my="sm" size="xs">
|
<Text c="dimmed" my="sm" size="xs">
|
||||||
{t("stock.dividendWindow", {
|
{t("stock.dividendWindow", {
|
||||||
from: formatDate(vm.dividends.from),
|
from: formatDate(dividends.from),
|
||||||
to: formatDate(vm.dividends.to),
|
to: formatDate(dividends.to),
|
||||||
})}
|
})}
|
||||||
</Text>
|
</Text>
|
||||||
|
|
||||||
@@ -211,7 +216,7 @@ const StockDividends: FC<StockEventsProps> = (props) => {
|
|||||||
</Accordion>
|
</Accordion>
|
||||||
</Stack>
|
</Stack>
|
||||||
)}
|
)}
|
||||||
</StockSection>
|
</InstrumentSection>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -14,6 +14,5 @@ export { ApiErrorCode, apiErrorCode, isApiErrorCode } from "./problem-details";
|
|||||||
export {
|
export {
|
||||||
invalidateResourceAccess,
|
invalidateResourceAccess,
|
||||||
type InvestmentResourceMeta,
|
type InvestmentResourceMeta,
|
||||||
unwrapResourceResult,
|
|
||||||
useResourceQuery,
|
useResourceQuery,
|
||||||
} from "./resource-query";
|
} from "./resource-query";
|
||||||
|
|||||||
@@ -188,6 +188,5 @@ function useResourceQuery<T extends Resource, E, K extends QueryKey>(
|
|||||||
export {
|
export {
|
||||||
invalidateResourceAccess,
|
invalidateResourceAccess,
|
||||||
type InvestmentResourceMeta,
|
type InvestmentResourceMeta,
|
||||||
unwrapResourceResult,
|
|
||||||
useResourceQuery,
|
useResourceQuery,
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user