refactor: colocate frontend component files
Frontend security / security (push) Successful in 9s
Frontend verify / verify (push) Successful in 5m10s
Conventional commits / commits (pull_request) Successful in 25s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 5m10s

This commit is contained in:
2026-09-23 08:34:58 +03:00
parent 85fcfe3d07
commit b987fd8e78
190 changed files with 131 additions and 108 deletions
@@ -0,0 +1,143 @@
.tile,
.cash {
border-color: var(--mantine-color-gray-3);
background: var(--mantine-color-gray-0);
}
.total {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 10px;
min-width: 0;
padding: 12px;
border-color: var(--mantine-color-gray-3);
border-radius: 8px;
background: var(--mantine-color-white);
}
.totalBadge {
min-width: 40px;
min-height: 24px;
max-width: 100%;
padding-inline: 8px;
border-radius: 4px;
background: var(--mantine-color-blue-0);
color: var(--mantine-color-blue-6);
font-size: 18px;
font-weight: 600;
line-height: 24px;
text-align: center;
overflow-wrap: anywhere;
}
.totalAmount {
flex-basis: max-content;
min-width: 0;
max-width: 100%;
color: var(--mantine-color-dark-7);
font-size: 20px;
font-weight: 600;
line-height: 1.55;
overflow-wrap: anywhere;
}
.totalLeadingDigits {
white-space: nowrap;
}
.totalAmountSkeleton {
max-width: calc(100% - 50px);
margin-block: 5px;
}
.tile,
.cash {
padding: var(--mantine-spacing-md);
}
.cash {
display: flex;
justify-content: space-between;
}
.positive {
color: var(--wl-color-positive);
}
.negative {
color: var(--wl-color-negative);
}
.expandedCard {
padding: var(--mantine-spacing-md);
}
.expandedMain {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
gap: var(--mantine-spacing-sm);
align-items: center;
}
.expandedIdentity,
.expandedValue {
min-width: 0;
}
.expandedIdentifiers {
overflow-wrap: anywhere;
}
.expandedValue {
white-space: nowrap;
}
.expandedMeta {
padding-top: var(--mantine-spacing-xs);
margin-top: var(--mantine-spacing-sm);
border-top: 1px solid var(--mantine-color-gray-2);
}
.mono {
font-family: var(--mantine-font-family-monospace);
}
.accordionControl {
transition:
background-color 150ms ease,
color 150ms ease;
}
.accordionLabel {
font-size: var(--mantine-h2-font-size);
font-weight: var(--mantine-h2-font-weight);
line-height: var(--mantine-h2-line-height);
}
.accordionPanel {
padding-left: 0;
padding-right: 0;
}
.accountPositions {
list-style: none;
padding: 0;
margin: var(--mantine-spacing-sm) 0 0;
}
.accountPosition {
padding-block: var(--mantine-spacing-sm);
border-top: 1px solid var(--mantine-color-gray-3);
overflow-wrap: anywhere;
}
.accountPosition:last-child {
padding-bottom: 0;
}
.accountPositionName {
min-width: 0;
overflow-wrap: anywhere;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,43 @@
import type { FC } from "react";
import { useAccountPageViewModel } from "./AccountPage.vm";
import { AccountPageEmpty } from "./components/AccountPageEmpty.view";
import { AccountPageError } from "./components/AccountPageError.view";
import { AccountPageLoaded } from "./components/AccountPageLoaded.view";
import { AccountPageLoading } from "./components/AccountPageLoading/AccountPageLoading.view";
type AccountPageProps = { accountId?: string };
const AccountPage: FC<AccountPageProps> = (props) => {
const viewModel = useAccountPageViewModel(props.accountId);
if (viewModel.state === "loading") return <AccountPageLoading />;
if (viewModel.state === "error") return <AccountPageError {...viewModel} />;
if (viewModel.state === "empty")
return (
<AccountPageEmpty
account={viewModel.account}
accountId={viewModel.accountId}
refreshing={viewModel.refreshing}
refreshError={viewModel.refreshError}
retry={viewModel.retry}
recentOperations={viewModel.recentOperations}
recentEvents={viewModel.recentEvents}
incomeSummary={viewModel.incomeSummary}
/>
);
return (
<AccountPageLoaded
account={viewModel.account}
accountId={viewModel.accountId}
portfolio={viewModel.portfolio}
positionSections={viewModel.positionSections}
refreshing={viewModel.refreshing}
refreshError={viewModel.refreshError}
retry={viewModel.retry}
recentOperations={viewModel.recentOperations}
recentEvents={viewModel.recentEvents}
incomeSummary={viewModel.incomeSummary}
/>
);
};
export { AccountPage };
@@ -0,0 +1,306 @@
import { MantineProvider } from "@mantine/core";
import { renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import type { FC, PropsWithChildren } from "react";
import { MemoryRouter, Route, Routes } from "react-router";
import { describe, expect, it, vi } from "vitest";
import type { Portfolio } from "@/entities/portfolio";
import { configureAuthClient } from "@/shared/api";
import { createQueryWrapper } from "@/test/query";
import { server } from "@/test/server";
import {
toAccountPagePositionSections,
useAccountPageViewModel,
} from "./AccountPage.vm";
const portfolio: Portfolio = {
lastSuccessfulAt: "2026-08-13T10:00:00Z",
isStale: true,
totalsByCurrency: [{ currency: "RUB", value: "150" }],
positions: [
{
figi: "FIGI-STOCK",
displayName: "Акция",
type: "STOCK",
quantity: "2",
currentValue: { currency: "RUB", value: "100" },
averagePurchasePrice: null,
absoluteReturn: { currency: "RUB", value: "10" },
isin: null,
ticker: null,
logoName: "akciya.png",
},
{
figi: "FIGI-BOND",
displayName: "Облигация",
type: "BOND",
quantity: "1",
currentValue: { currency: "RUB", value: "50" },
averagePurchasePrice: { currency: "RUB", value: "45" },
absoluteReturn: { currency: "RUB", value: "-5" },
isin: "RU000A0JX0J2",
ticker: null,
logoName: null,
},
{
figi: "FIGI-FUND",
displayName: "Фонд",
type: "FUND",
quantity: "3",
currentValue: null,
averagePurchasePrice: null,
absoluteReturn: null,
isin: null,
ticker: null,
logoName: "fond.png",
},
],
structure: { currencies: [], unvaluedCategories: [] },
cashBalances: [{ currency: "USD", value: "1" }],
};
function configureTestAuth() {
configureAuthClient({
accessToken: () => "test-token",
refresh: async () => true,
clear: vi.fn(),
});
}
function createWrapper() {
const { wrapper: QueryWrapper } = createQueryWrapper();
const Wrapper: FC<PropsWithChildren> = (props) => (
<QueryWrapper>
<MantineProvider>
<MemoryRouter initialEntries={["/accounts/account-1"]}>
<Routes>
<Route path="/accounts/:accountId" element={props.children} />
</Routes>
</MemoryRouter>
</MantineProvider>
</QueryWrapper>
);
return Wrapper;
}
function mockLoadedAccountPage() {
server.use(
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
HttpResponse.json(portfolio),
),
http.get("*/api/v1/brokerage-accounts/:accountId/operations", () =>
HttpResponse.json({
accountId: "account-1",
items: [
{
id: "operation-1",
occurredAt: "2026-08-13T10:00:00Z",
type: "Buy",
category: "trade",
description: "Покупка акции",
figi: "FIGI-STOCK",
instrumentUid: null,
ticker: "STK",
instrumentType: "share",
payment: { currency: "RUB", value: "-100" },
quantity: "1",
price: null,
accruedInterest: null,
commission: null,
},
],
nextCursor: null,
hasNext: false,
observedAt: "2026-08-13T10:00:00Z",
}),
),
http.get("*/api/v1/brokerage-accounts/:accountId/events", () =>
HttpResponse.json({
accountId: "account-1",
calculatedAt: "2026-08-13T10:00:00Z",
events: Array.from({ length: 6 }, (_, index) => ({
type: "coupon",
date: `2026-09-${String(index + 1).padStart(2, "0")}`,
dateKind: "event",
figi: `FIGI-EVENT-${index}`,
instrumentUid: null,
ticker: `BND${index}`,
displayName: `Купон ${index}`,
projectedAmount: { currency: "RUB", value: String(index + 1) },
})),
}),
),
);
}
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,
totalsByCurrency: [{ currency: "RUB", value: "1250" }],
structure: { currencies: [], unvaluedCategories: [] },
cashBalances: [{ currency: "RUB", value: "1000" }],
positions: [
...portfolio.positions,
{
...portfolio.positions[0],
figi: "FIGI-CURRENCY",
type: "CURRENCY",
currentValue: { currency: "RUB", value: "50" },
},
...otherTypes.map((type) => ({
...portfolio.positions[2],
figi: `FIGI-${type}-NEXT`,
type,
currentValue:
type === "OPTION" ? { currency: "RUB", value: "50" } : null,
})),
],
};
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", async () => {
configureTestAuth();
mockLoadedAccountPage();
const { result } = renderHook(() => useAccountPageViewModel(), {
wrapper: createWrapper(),
});
await waitFor(() => expect(result.current.state).toBe("loaded"));
const loaded = result.current as Extract<
typeof result.current,
{ state: "loaded" }
>;
expect(
loaded.positionSections.map(({ kind, groups }) => ({
kind,
positions: groups.flatMap((group) => group.positions),
})),
).toMatchObject([
{
kind: "stocks",
positions: [
{
displayName: "Акция",
shareText: "66,7 %",
returnText: "+10 ₽",
returnTone: "positive",
logoSrc: "https://invest-brands.cdn-tinkoff.ru/akciyax160.png",
},
],
},
{
kind: "bonds",
positions: [
{
displayName: "Облигация",
shareText: "33,3 %",
returnText: "-5 ₽",
returnTone: "negative",
logoSrc: null,
},
],
},
{
kind: "other",
positions: [
{
displayName: "Фонд",
shareText: null,
returnText: null,
returnTone: undefined,
logoSrc: null,
},
],
},
]);
});
it("prepares recent operations and events state for presentation views", async () => {
configureTestAuth();
mockLoadedAccountPage();
const { result } = renderHook(() => useAccountPageViewModel(), {
wrapper: createWrapper(),
});
await waitFor(() =>
expect(
(result.current as { recentEvents?: { state: string } }).recentEvents,
)?.toMatchObject({ state: "loaded" }),
);
const loaded = result.current as Extract<
typeof result.current,
{ state: "loaded" }
>;
expect(loaded.recentOperations).toMatchObject({
state: "loaded",
to: "/accounts/account-1/operations",
items: [{ id: "operation-1", description: "Покупка акции" }],
});
expect(loaded.recentEvents).toMatchObject({
state: "loaded",
to: "/accounts/account-1/events",
items: [
{ ticker: "BND0" },
{ ticker: "BND1" },
{ ticker: "BND2" },
{ ticker: "BND3" },
{ ticker: "BND4" },
],
});
});
it("keeps recent errors isolated in the ViewModel presentation state", async () => {
configureTestAuth();
server.use(
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
HttpResponse.json(portfolio),
),
http.get("*/api/v1/brokerage-accounts/:accountId/operations", () =>
HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 }),
),
http.get("*/api/v1/brokerage-accounts/:accountId/events", () =>
HttpResponse.json({ code: "MOEX_UNAVAILABLE" }, { status: 503 }),
),
);
const { result } = renderHook(() => useAccountPageViewModel(), {
wrapper: createWrapper(),
});
await waitFor(() =>
expect(result.current).toMatchObject({
state: "loaded",
recentOperations: { state: "error" },
recentEvents: { state: "error" },
}),
);
});
});
@@ -0,0 +1,317 @@
import { useQueryClient } from "@tanstack/react-query";
import { useParams } from "react-router";
import type { BrokerageOperation } from "@/entities/broker-operation";
import { useBrokerageOperations } from "@/entities/broker-operation";
import {
type BrokerageAccount,
brokerageAccountsQueryKey,
} from "@/entities/brokerage-account";
import {
type BrokerageEventsPreviewState,
useBrokerageEvents,
} from "@/entities/brokerage-event";
import { type IncomeSummary, useIncomeSummary } from "@/entities/income";
import type { Portfolio } from "@/entities/portfolio";
import { formatShare, usePortfolio } from "@/entities/portfolio";
import { useStocks } from "@/entities/stock";
import { apiErrorCode } from "@/shared/api";
import { formatMoney, instrumentLogoUrl } from "@/shared/lib";
const RECENT_EVENTS_LIMIT = 5;
type PositionSectionKind = "stocks" | "bonds" | "other";
type AccountPageReturnTone = "positive" | "negative";
type AccountPagePosition = Portfolio["positions"][number] & {
shareText: string | null;
returnText: string | null;
returnTone?: AccountPageReturnTone;
logoSrc: string | null;
instrumentTo?: string;
};
type AccountPagePositionGroup = {
key: string;
positions: AccountPagePosition[];
};
type AccountPagePositionSection = {
kind: PositionSectionKind;
groups: AccountPagePositionGroup[];
};
type AccountPageRecentOperations =
| {
state: "loading" | "error" | "empty";
to: string;
}
| {
state: "loaded";
to: string;
items: BrokerageOperation[];
};
type AccountPageRecentEvents = BrokerageEventsPreviewState;
type AccountPageIncomeSummary =
| { state: "loading" | "empty"; to: string }
| { state: "error"; to: string; retry: () => void }
| { state: "loaded"; to: string; summary: IncomeSummary };
type AccountPageContent = {
account?: BrokerageAccount;
accountId?: string;
refreshing: boolean;
refreshError: boolean;
retry: () => void;
recentOperations: AccountPageRecentOperations;
recentEvents: AccountPageRecentEvents;
incomeSummary: AccountPageIncomeSummary;
};
type AccountPageLoadedViewModel = AccountPageContent & {
state: "loaded";
portfolio: Portfolio;
positionSections: AccountPagePositionSection[];
};
type AccountPageEmptyViewModel = AccountPageContent & {
state: "empty";
};
type AccountPageViewModel =
| { state: "loading" }
| { state: "error"; code?: string; retry: () => void }
| AccountPageEmptyViewModel
| AccountPageLoadedViewModel;
function useAccountPageViewModel(scopeId?: string): AccountPageViewModel {
const { accountId: routeAccountId } = useParams();
const accountId = scopeId ?? routeAccountId;
const portfolio = usePortfolio(accountId);
const stocks = useStocks(
portfolio.data?.positions.flatMap((position) =>
position.type === "STOCK" && position.instrumentUid
? [position.instrumentUid]
: [],
) ?? [],
);
const instrumentDetails = stocks;
const operations = useBrokerageOperations(accountId, {
limit: 5,
});
const events = useBrokerageEvents(accountId);
const income = useIncomeSummary(accountId);
const account = useQueryClient()
.getQueryData<BrokerageAccount[]>(brokerageAccountsQueryKey)
?.find((item) => item.id === accountId);
const recentOperations = toRecentOperations(accountId, operations);
const recentEvents = toRecentEvents(accountId, events);
const incomeSummary = toIncomeSummary(accountId, income);
if (!portfolio.data) {
if (portfolio.isError)
return {
state: "error" as const,
code: apiErrorCode(portfolio.error),
retry: () => portfolio.refetch(),
};
return { state: "loading" as const };
}
const refresh = {
refreshing: portfolio.isFetching,
refreshError: portfolio.isError,
retry: () => portfolio.refetch(),
};
if (!portfolio.data.positions.length && !portfolio.data.cashBalances.length)
return {
state: "empty" as const,
account,
accountId,
recentOperations,
recentEvents,
incomeSummary,
...refresh,
};
return {
state: "loaded" as const,
account,
accountId,
portfolio: portfolio.data,
positionSections: toAccountPagePositionSections(
portfolio.data,
instrumentDetails,
),
recentOperations,
recentEvents,
incomeSummary,
...refresh,
};
}
function toIncomeSummary(
accountId: string | undefined,
income: ReturnType<typeof useIncomeSummary>,
): AccountPageIncomeSummary {
const to = `/accounts/${accountId}/income`;
if (income.isLoading) return { state: "loading", to };
if (income.isError)
return { state: "error", to, retry: () => income.refetch() };
if (!income.data?.totalsByCurrency.length) return { state: "empty", to };
return { state: "loaded", to, summary: income.data };
}
function toRecentOperations(
accountId: string | undefined,
operations: ReturnType<typeof useBrokerageOperations>,
): AccountPageRecentOperations {
const to = `/accounts/${accountId}/operations`;
if (operations.isLoading) return { state: "loading", to };
if (operations.isError) return { state: "error", to };
if (!operations.data?.items.length) return { state: "empty", to };
return { state: "loaded", to, items: operations.data.items };
}
function toRecentEvents(
accountId: string | undefined,
events: ReturnType<typeof useBrokerageEvents>,
): AccountPageRecentEvents {
const to = `/accounts/${accountId}/events`;
if (events.isLoading) return { state: "loading", to };
if (events.isError) return { state: "error", to };
const items = events.data?.events.slice(0, RECENT_EVENTS_LIMIT) ?? [];
if (!items.length) return { state: "empty", to };
return { state: "loaded", to, items };
}
function toAccountPagePositionSections(
portfolio: Portfolio,
instrumentDetails: Map<string, { slug: string } | undefined> = new Map(),
): AccountPagePositionSection[] {
const denominators = new Map<string, number>();
for (const position of portfolio.positions) {
if (!position.currentValue) continue;
const currency = position.currentValue.currency;
denominators.set(
currency,
(denominators.get(currency) ?? 0) + Number(position.currentValue.value),
);
}
const stocks = toSection(
"stocks",
portfolio,
denominators,
instrumentDetails,
);
const bonds = toSection("bonds", portfolio, denominators, instrumentDetails);
const other = toSection("other", portfolio, denominators, instrumentDetails);
return [stocks, bonds, other].filter((section) => section.groups.length > 0);
}
function toSection(
kind: PositionSectionKind,
portfolio: Portfolio,
denominators: Map<string, number>,
instrumentDetails: Map<string, { slug: string } | undefined>,
): AccountPagePositionSection {
return {
kind,
groups: groupPositions(
portfolio.positions
.filter((position) => {
if (kind === "stocks") return position.type === "STOCK";
if (kind === "bonds") return position.type === "BOND";
return (
position.type !== "STOCK" &&
position.type !== "BOND" &&
position.type !== "CURRENCY"
);
})
.map((position) =>
toPosition(
position,
denominators,
kind,
instrumentDetails.get(position.instrumentUid ?? "")?.slug,
),
),
),
};
}
function groupPositions(
positions: AccountPagePosition[],
): AccountPagePositionGroup[] {
const groups = new Map<string, AccountPagePositionGroup>();
for (const [index, position] of positions.entries()) {
const identity = position.instrumentUid?.trim()
? ["uid", position.instrumentUid.trim()]
: position.figi?.trim()
? ["figi", position.figi.trim()]
: position.isin?.trim()
? ["isin", position.isin.trim()]
: null;
const rowKey = JSON.stringify(["row", position.account?.id, index]);
const key =
position.account && identity
? JSON.stringify([position.type, ...identity])
: rowKey;
const group = groups.get(key);
if (
group &&
!group.positions.some((item) => item.account?.id === position.account?.id)
) {
group.positions.push(position);
} else {
const uniqueKey = group ? rowKey : key;
groups.set(uniqueKey, { key: uniqueKey, positions: [position] });
}
}
return [...groups.values()];
}
function toPosition(
position: Portfolio["positions"][number],
denominators: Map<string, number>,
kind: PositionSectionKind,
instrumentSlug: string | undefined,
): AccountPagePosition {
const expanded = kind !== "other";
const returnValue = position.absoluteReturn
? Number(position.absoluteReturn.value)
: null;
const returnTone =
returnValue === null || returnValue === 0
? undefined
: returnValue > 0
? "positive"
: "negative";
return {
...position,
instrumentTo:
(kind === "stocks" || kind === "bonds") && position.instrumentUid
? `/${kind}/${encodeURIComponent(instrumentSlug ?? position.instrumentUid)}`
: undefined,
shareText: position.currentValue?.currency
? formatShare(position.currentValue, {
currency: position.currentValue.currency,
value: String(denominators.get(position.currentValue.currency) ?? 0),
})
: null,
returnText: position.absoluteReturn
? `${expanded && returnValue !== null && returnValue > 0 ? "+" : ""}${formatMoney(position.absoluteReturn)}`
: null,
returnTone,
logoSrc: expanded ? instrumentLogoUrl(position.logoName) : null,
};
}
export {
type AccountPageIncomeSummary,
type AccountPagePosition,
type AccountPagePositionGroup,
type AccountPagePositionSection,
type AccountPageRecentEvents,
type AccountPageRecentOperations,
toAccountPagePositionSections,
useAccountPageViewModel,
};
@@ -0,0 +1,36 @@
import { Stack, Text, Title } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import type { BrokerageAccount } from "@/entities/brokerage-account";
import { accountTypeKey } from "@/entities/brokerage-account";
type AccountHeadingProps = {
account?: BrokerageAccount;
accountId?: string;
};
const AccountHeading: FC<AccountHeadingProps> = (props) => {
const { account } = props;
const { t } = useTranslation();
return (
<Stack gap={2}>
<Title order={1}>
{props.accountId === "all"
? t("accounts.all")
: (account?.name ?? t("portfolio.title"))}
</Title>
{props.accountId === "all" ? (
<Text c="dimmed" size="sm">
{t("accounts.allDescription")}
</Text>
) : account ? (
<Text c="dimmed" size="sm">
{t(accountTypeKey(account.type))}
</Text>
) : null}
</Stack>
);
};
export { AccountHeading };
@@ -0,0 +1,57 @@
import { Stack } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import type { BrokerageAccount } from "@/entities/brokerage-account";
import { BrokerageEventsPreview } from "@/entities/brokerage-event";
import type {
AccountPageIncomeSummary,
AccountPageRecentEvents,
AccountPageRecentOperations,
} from "../AccountPage.vm";
import { AccountHeading } from "./AccountHeading.view";
import { IncomeSummary } from "./IncomeSummary.view";
import { PortfolioRefreshState } from "./PortfolioRefreshState/PortfolioRefreshState.view";
import { PortfolioStructure } from "./PortfolioStructure/PortfolioStructure";
import { RecentOperations } from "./RecentOperations.view";
type AccountPageEmptyProps = {
account?: BrokerageAccount;
accountId?: string;
refreshing?: boolean;
refreshError?: boolean;
retry?: () => void;
recentOperations: AccountPageRecentOperations;
recentEvents: AccountPageRecentEvents;
incomeSummary?: AccountPageIncomeSummary;
};
const AccountPageEmpty: FC<AccountPageEmptyProps> = (props) => {
const { t } = useTranslation();
return (
<Stack>
<AccountHeading account={props.account} accountId={props.accountId} />
<PortfolioRefreshState
refreshing={props.refreshing ?? false}
refreshError={props.refreshError ?? false}
retry={props.retry}
/>
<StateView
title={t("portfolio.emptyTitle")}
text={t(
props.accountId === "all"
? "portfolio.allEmptyText"
: "portfolio.emptyText",
)}
/>
<PortfolioStructure
structure={{ currencies: [], unvaluedCategories: [] }}
/>
<RecentOperations operations={props.recentOperations} />
<BrokerageEventsPreview events={props.recentEvents} />
{props.incomeSummary ? <IncomeSummary {...props.incomeSummary} /> : null}
</Stack>
);
};
export { AccountPageEmpty };
@@ -0,0 +1,57 @@
import { Button } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
type AccountPageErrorProps = { code?: string; retry: () => void };
const AccountPageError: FC<AccountPageErrorProps> = (props) => {
const { code, retry } = props;
const { t } = useTranslation();
if (code === "NOT_FOUND")
return (
<StateView
error
title={t("portfolio.accountUnavailableTitle")}
text={t("portfolio.accountUnavailableText")}
action={
<Button component={Link} to="/accounts">
{t("portfolio.back")}
</Button>
}
/>
);
if (code === "TBANK_NOT_CONNECTED" || code === "INVALID_TBANK_TOKEN")
return (
<StateView
error
title={t("portfolio.connectionErrorTitle")}
text={t("portfolio.connectionErrorText")}
action={
<Button component={Link} to="/settings">
{t("accounts.openSettings")}
</Button>
}
/>
);
if (code === "TBANK_UNAVAILABLE")
return (
<StateView
error
title={t("accounts.unavailableTitle")}
text={t("accounts.unavailableText")}
action={<Button onClick={retry}>{t("accounts.retry")}</Button>}
/>
);
return (
<StateView
error
title={t("states.errorTitle")}
text={t("states.errorText")}
action={<Button onClick={retry}>{t("accounts.retry")}</Button>}
/>
);
};
export { AccountPageError };
@@ -0,0 +1,127 @@
import { Accordion, Alert, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import type { BrokerageAccount } from "@/entities/brokerage-account";
import { BrokerageEventsPreview } from "@/entities/brokerage-event";
import type { Portfolio } from "@/entities/portfolio";
import { formatSnapshotTime } from "@/shared/lib";
import classes from "../AccountPage.module.css";
import type {
AccountPageIncomeSummary,
AccountPagePositionSection,
AccountPageRecentEvents,
AccountPageRecentOperations,
} from "../AccountPage.vm";
import { AccountHeading } from "./AccountHeading.view";
import { CurrencyCards } from "./CurrencyCards/CurrencyCards.view";
import { IncomeSummary } from "./IncomeSummary.view";
import { PortfolioRefreshState } from "./PortfolioRefreshState/PortfolioRefreshState.view";
import { PortfolioStructure } from "./PortfolioStructure/PortfolioStructure";
import { PositionSection } from "./PositionSection.view";
import { RecentOperations } from "./RecentOperations.view";
type AccountPageLoadedProps = {
account?: BrokerageAccount;
accountId?: string;
portfolio: Portfolio;
positionSections: AccountPagePositionSection[];
refreshing?: boolean;
refreshError?: boolean;
retry?: () => void;
recentOperations: AccountPageRecentOperations;
recentEvents: AccountPageRecentEvents;
incomeSummary?: AccountPageIncomeSummary;
};
const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
const { t } = useTranslation();
return (
<Stack gap="lg">
<AccountHeading account={props.account} accountId={props.accountId} />
<PortfolioRefreshState
refreshing={props.refreshing ?? false}
refreshError={props.refreshError ?? false}
retry={props.retry}
/>
{props.portfolio.isStale ? (
<Alert color="blue">{t("portfolio.staleWarning")}</Alert>
) : null}
<Text c="dimmed" size="sm">
{t(
props.accountId === "all"
? "portfolio.allUpdatedAt"
: "portfolio.updatedAt",
{
date: formatSnapshotTime(props.portfolio.lastSuccessfulAt),
},
)}
</Text>
<CurrencyCards amounts={props.portfolio.totalsByCurrency} />
<PortfolioStructure
key={props.accountId}
structure={props.portfolio.structure}
/>
<Accordion
multiple
defaultValue={[
...props.positionSections.map((section) => section.kind),
"cash",
"recentOperations",
"recentEvents",
"incomeSummary",
]}
classNames={{
control: classes.accordionControl,
label: classes.accordionLabel,
chevron: classes.accordionChevron,
panel: classes.accordionPanel,
}}
>
{props.positionSections.map((section) => (
<Accordion.Item key={section.kind} value={section.kind}>
<Accordion.Control>
{t(positionSectionTitleKey(section.kind))}
</Accordion.Control>
<Accordion.Panel>
<PositionSection section={section} />
</Accordion.Panel>
</Accordion.Item>
))}
<Accordion.Item value="cash">
<Accordion.Control>{t("portfolio.cashBalances")}</Accordion.Control>
<Accordion.Panel>
<CurrencyCards amounts={props.portfolio.cashBalances} />
</Accordion.Panel>
</Accordion.Item>
<Accordion.Item value="recentOperations">
<Accordion.Control>{t("ledger.recentTitle")}</Accordion.Control>
<Accordion.Panel>
<RecentOperations operations={props.recentOperations} />
</Accordion.Panel>
</Accordion.Item>
<Accordion.Item value="recentEvents">
<Accordion.Control>{t("events.recentTitle")}</Accordion.Control>
<Accordion.Panel>
<BrokerageEventsPreview events={props.recentEvents} />
</Accordion.Panel>
</Accordion.Item>
<Accordion.Item value="incomeSummary">
<Accordion.Control>{t("income.summaryTitle")}</Accordion.Control>
<Accordion.Panel>
{props.incomeSummary ? (
<IncomeSummary {...props.incomeSummary} />
) : null}
</Accordion.Panel>
</Accordion.Item>
</Accordion>
</Stack>
);
};
function positionSectionTitleKey(kind: AccountPagePositionSection["kind"]) {
if (kind === "stocks") return "portfolio.stocks";
if (kind === "bonds") return "portfolio.bonds";
return "portfolio.otherPositions";
}
export { AccountPageLoaded };
@@ -0,0 +1,21 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { AccountPageLoading } from "./AccountPageLoading.view";
const meta = {
title: "Product/AccountPageLoading",
component: AccountPageLoading,
tags: ["autodocs"],
parameters: {
docs: {
description: {
component:
"Начальная загрузка страницы счёта без доступных данных: настоящий page-owned skeleton заголовка, сводки и строк. Shared LoadingSkeleton предоставляет busy-region, фигуры декоративны и не получают фокус. Не используйте вместо сохранённых данных при refetch; запросы в витрине не выполняются.",
},
},
},
} satisfies Meta<typeof AccountPageLoading>;
export default meta;
type Story = StoryObj<typeof meta>;
export const InitialLoading: Story = { name: "Начальная загрузка счёта" };
@@ -0,0 +1,37 @@
import { Paper, SimpleGrid, Skeleton } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import classes from "../../AccountPage.module.css";
const AccountPageLoading: FC = () => {
const { t } = useTranslation();
return (
<LoadingSkeleton label={t("states.loadingTitle")}>
<Skeleton height={32} width="35%" />
<SimpleGrid
cols={{ base: 1, sm: 2, md: 3 }}
spacing={10}
aria-hidden="true"
>
{[0, 1, 2].map((index) => (
<Paper key={index} className={classes.total} withBorder>
<Skeleton height={24} width={40} radius={4} />
<Skeleton
height={21}
width={180}
radius={4}
className={classes.totalAmountSkeleton}
/>
</Paper>
))}
</SimpleGrid>
<Skeleton height={260} radius="sm" />
{[0, 1, 2].map((index) => (
<Skeleton key={index} height={52} radius="sm" />
))}
</LoadingSkeleton>
);
};
export { AccountPageLoading };
@@ -0,0 +1,85 @@
import { MantineProvider } from "@mantine/core";
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { CurrencyCards } from "./CurrencyCards.view";
describe("CurrencyCards currency presentation", () => {
it.each([0, 1, 3, 5])(
"renders only the %i supplied totals in upstream order",
(count) => {
const totals = [
{ currency: "EUR", value: "3.00" },
{ currency: "USD", value: "2.00" },
{ currency: "RUB", value: "1.00" },
{ currency: "CAD", value: "4.00" },
{ currency: "XYZ", value: "5.00" },
].slice(0, count);
const { container } = render(
<MantineProvider>
<CurrencyCards amounts={totals} />
</MantineProvider>,
);
expect(
screen.queryAllByRole("definition").map((node) => node.textContent),
).toEqual(
["3,00 €", "2,00 $", "1,00 ₽", "4,00 CAD", "5,00 XYZ"].slice(0, count),
);
expect(container.querySelectorAll("dl")).toHaveLength(count);
expect(
container.querySelector("[tabindex], button, a, input"),
).toBeNull();
},
);
it.each([
["RUB", "125000.50", "125 000,50 ₽", "Российский рубль", "₽"],
["USD", "320.00", "320,00 $", "Доллар США", "$"],
["EUR", "9876.54321", "9 876,54321 €", "Евро", "€"],
[
"RUB",
"123456789012.345678901",
"123 456 789 012,345678901 ₽",
"Российский рубль",
"₽",
],
["USD", "-1234567.890123", "-1 234 567,890123 $", "Доллар США", "$"],
["EUR", "987654321.000001", "987 654 321,000001 €", "Евро", "€"],
["USD", "-0.5", "-0,5 $", "Доллар США", "$"],
["CAD", "20.00", "20,00 CAD", "CAD", "CAD"],
["XYZ", "1.000", "1,000 XYZ", "XYZ", "XYZ"],
])(
"preserves %s %s and its currency identity",
(currency, value, expected, name, symbol) => {
render(
<MantineProvider>
<CurrencyCards amounts={[{ currency, value }]} />
</MantineProvider>,
);
const term = screen.getByRole("term");
expect(term).toHaveTextContent(name);
expect(term.querySelector('[aria-hidden="true"]')).toHaveTextContent(
symbol,
);
expect(screen.getByRole("definition")).toHaveTextContent(expected);
expect(term.parentElement).toBe(
screen.getByRole("definition").parentElement,
);
},
);
it("keeps USD and CAD as distinct supplied values", () => {
render(
<MantineProvider>
<CurrencyCards
amounts={[
{ currency: "USD", value: "1.00" },
{ currency: "CAD", value: "2.00" },
]}
/>
</MantineProvider>,
);
expect(
screen.getAllByRole("definition").map((node) => node.textContent),
).toEqual(["1,00 $", "2,00 CAD"]);
});
});
@@ -0,0 +1,61 @@
import { Paper, SimpleGrid, Text, VisuallyHidden } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import type { Portfolio } from "@/entities/portfolio";
import { formatDecimal } from "@/shared/lib";
import classes from "../../AccountPage.module.css";
type CurrencyCardsProps = {
amounts: Portfolio["totalsByCurrency"];
};
const CurrencyCards: FC<CurrencyCardsProps> = (props) => {
const { amounts } = props;
const { t } = useTranslation();
const currencies: Record<string, { symbol: string; name: string }> = {
RUB: { symbol: "₽", name: t("portfolio.currencies.RUB") },
USD: { symbol: "$", name: t("portfolio.currencies.USD") },
EUR: { symbol: "€", name: t("portfolio.currencies.EUR") },
};
return (
<SimpleGrid cols={{ base: 1, sm: 2, md: 3 }} spacing={10}>
{amounts.map((money) => {
const amount = formatDecimal(money.value);
return (
<Paper
component="dl"
m={0}
className={classes.total}
key={money.currency}
withBorder
>
<Text component="dt" className={classes.totalBadge}>
<span aria-hidden="true">
{currencies[money.currency]?.symbol ?? money.currency}
</span>
<VisuallyHidden>
{currencies[money.currency]?.name ?? money.currency}
</VisuallyHidden>
</Text>
<Text component="dd" m={0} className={classes.totalAmount}>
{amount.startsWith("-") ? (
<>
<span className={classes.totalLeadingDigits}>
{amount.slice(0, 2)}
</span>
{amount.slice(2)}
</>
) : (
amount
)}{" "}
{currencies[money.currency]?.symbol ?? money.currency}
</Text>
</Paper>
);
})}
</SimpleGrid>
);
};
export { CurrencyCards };
@@ -0,0 +1,57 @@
import { Button, Paper, Stack, Text } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import type { IncomeSummary as IncomeSummaryData } from "@/entities/income";
import { formatMoney } from "@/shared/lib";
type IncomeSummaryProps =
| { state: "loading"; to: string }
| { state: "error"; to: string; retry: () => void }
| { state: "empty"; to: string }
| { state: "loaded"; to: string; summary: IncomeSummaryData };
const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
const { t } = useTranslation();
if (props.state === "loading")
return <Text c="dimmed">{t("income.summaryLoading")}</Text>;
if (props.state === "error")
return (
<StateView
error
title={t("income.summaryError")}
text={t("income.errorText")}
action={
<Button onClick={props.retry}>{t("income.summaryRetry")}</Button>
}
/>
);
if (props.state === "empty")
return (
<Stack gap="xs">
<Text c="dimmed">{t("income.summaryEmpty")}</Text>
<Button component={Link} to={props.to} variant="subtle">
{t("income.open")}
</Button>
</Stack>
);
return (
<Stack gap="xs">
{props.summary.totalsByCurrency.map((total) => (
<Paper key={total.currency} p="sm" withBorder>
<Text fw={700}>{formatMoney(total.total)}</Text>
<Text c="dimmed" size="sm">
{t("income.coupon")}: {formatMoney(total.coupon)} ·{" "}
{t("income.dividend")}: {formatMoney(total.dividend)}
</Text>
</Paper>
))}
<Button component={Link} to={props.to} variant="subtle">
{t("income.open")}
</Button>
</Stack>
);
};
export { IncomeSummary };
@@ -0,0 +1,49 @@
import { Stack } from "@mantine/core";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { fn } from "storybook/test";
import { CurrencyCards } from "../CurrencyCards/CurrencyCards.view";
import { PortfolioRefreshState } from "./PortfolioRefreshState.view";
const meta = {
title: "Product/PortfolioRefreshState",
component: PortfolioRefreshState,
tags: ["autodocs"],
args: { refreshing: false, refreshError: false, retry: fn() },
argTypes: {
refreshing: { control: "boolean" },
refreshError: { control: "boolean" },
retry: { control: false },
},
parameters: {
docs: {
description: {
component:
"Обновление уже показанных данных портфеля. Реальные CurrencyCards остаются видимыми вместе с PortfolioRefreshState при refetch и его ошибке. Суммы синтетические; это presentation Client Cached Snapshot, без QueryClient и запроса API. Retry регистрирует локальное действие в Actions и не доказывает восстановление API.",
},
},
},
render: (args) => (
<Stack>
<CurrencyCards
amounts={[
{ currency: "RUB", value: "125000.50" },
{ currency: "USD", value: "320" },
]}
/>
<PortfolioRefreshState {...args} />
</Stack>
),
} satisfies Meta<typeof PortfolioRefreshState>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Idle: Story = { name: "Сохранённые данные" };
export const Refreshing: Story = {
name: "Фоновое обновление",
args: { refreshing: true },
};
export const RefreshError: Story = {
name: "Ошибка обновления с retry",
args: { refreshError: true },
};
@@ -0,0 +1,40 @@
import { Alert, Button, Group, Loader, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
type PortfolioRefreshStateProps = {
refreshing: boolean;
refreshError: boolean;
retry?: () => void;
};
const PortfolioRefreshState: FC<PortfolioRefreshStateProps> = (props) => {
const { refreshing, refreshError, retry } = props;
const { t } = useTranslation();
if (!refreshing && !refreshError) return null;
return (
<>
{refreshing ? (
<Group gap="xs" role="status" aria-label={t("portfolio.refreshing")}>
<Loader size="sm" />
<Text c="dimmed" size="sm">
{t("portfolio.refreshing")}
</Text>
</Group>
) : null}
{refreshError ? (
<Alert color="orange">
<Stack gap="sm">
<Text>{t("portfolio.refreshError")}</Text>
<Button onClick={retry} variant="light">
{t("accounts.retry")}
</Button>
</Stack>
</Alert>
) : null}
</>
);
};
export { PortfolioRefreshState };
@@ -0,0 +1,72 @@
.section {
padding-block: var(--mantine-spacing-sm);
}
.content {
animation: currency-change 220ms ease-out;
}
@keyframes currency-change {
from {
opacity: 0;
transform: translateY(4px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@media (prefers-reduced-motion: reduce) {
.content {
animation: none;
}
}
.layout {
display: grid;
grid-template-columns: 220px minmax(0, 1fr);
align-items: center;
gap: var(--mantine-spacing-xl);
}
.list {
list-style: none;
padding: 0;
margin: 0;
min-width: 0;
}
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--mantine-spacing-md);
padding-block: var(--mantine-spacing-sm);
}
.marker {
width: 10px;
height: 10px;
border-radius: 50%;
flex-shrink: 0;
}
.values {
min-width: 0;
text-align: right;
font-variant-numeric: tabular-nums;
overflow-wrap: anywhere;
}
@media (max-width: 48em) {
.layout {
grid-template-columns: minmax(0, 1fr);
gap: var(--mantine-spacing-sm);
}
.layout > :first-child {
justify-self: center;
}
}
@@ -0,0 +1,114 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import type { Portfolio } from "@/entities/portfolio";
import { PortfolioStructure } from "./PortfolioStructure";
const rub: Portfolio["structure"]["currencies"][number] = {
currency: "RUB",
totalValue: "1250000",
hasNegativeValues: false,
categories: [
{ type: "STOCK", value: "650000", sharePercent: "52" },
{ type: "BOND", value: "375000", sharePercent: "30" },
{ type: "OTHER", value: "125000", sharePercent: "10" },
{ type: "CASH", value: "100000", sharePercent: "8" },
],
};
const meta = {
title: "Product/PortfolioStructure",
component: PortfolioStructure,
tags: ["autodocs"],
args: { structure: { currencies: [rub], unvaluedCategories: [] } },
parameters: {
docs: {
description: {
component:
"Структура по типам активов, включая доступные деньги. Синтетические серверные суммы и доли, без запросов API и финансовых расчётов на клиенте. При неполной или отрицательной оценке остаётся текстовый список.",
},
},
},
} satisfies Meta<typeof PortfolioStructure>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Regular: Story = {};
export const MultipleCurrencies: Story = {
args: {
structure: {
currencies: [
rub,
{
currency: "USD",
totalValue: "500",
hasNegativeValues: false,
categories: [{ type: "CASH", value: "500", sharePercent: "100" }],
},
],
unvaluedCategories: [],
},
},
};
export const CashOnly: Story = {
args: {
structure: {
currencies: [
{
currency: "RUB",
totalValue: "100000",
hasNegativeValues: false,
categories: rub.categories.map((row) => ({
...row,
value: row.type === "CASH" ? "100000" : "0",
sharePercent: row.type === "CASH" ? "100" : "0",
})),
},
],
unvaluedCategories: [],
},
},
};
export const Empty: Story = {
args: { structure: { currencies: [], unvaluedCategories: [] } },
};
export const Incomplete: Story = {
args: {
structure: {
currencies: [
{
...rub,
categories: rub.categories.map((row) => ({
...row,
sharePercent: null,
})),
},
],
unvaluedCategories: [{ type: "STOCK", count: 2 }],
},
},
};
export const UnknownOnly: Story = {
args: {
structure: {
currencies: [],
unvaluedCategories: [{ type: "BOND", count: 1 }],
},
},
};
export const Negative: Story = {
args: {
structure: {
currencies: [
{
...rub,
hasNegativeValues: true,
totalValue: "1150000",
categories: rub.categories.map((row) => ({
...row,
value: row.type === "OTHER" ? "25000" : row.value,
sharePercent: null,
})),
},
],
unvaluedCategories: [],
},
},
};
@@ -0,0 +1,148 @@
import { MantineProvider } from "@mantine/core";
import { fireEvent, render, screen, within } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import type { Portfolio } from "@/entities/portfolio";
import { PortfolioStructure } from "./PortfolioStructure";
const rub: Portfolio["structure"]["currencies"][number] = {
currency: "RUB",
totalValue: "100",
hasNegativeValues: false,
categories: [
{ type: "STOCK", value: "60", sharePercent: "60" },
{ type: "BOND", value: "20", sharePercent: "20" },
{ type: "OTHER", value: "0", sharePercent: "0" },
{ type: "CASH", value: "20", sharePercent: "20" },
],
};
const ui = (structure: Portfolio["structure"] | null | undefined) => (
<MantineProvider>
<PortfolioStructure structure={structure} />
</MantineProvider>
);
describe("portfolio structure", () => {
it.each([undefined, null])(
"keeps an older snapshot without structure available (%s) and recovers on refresh",
(structure) => {
const view = render(ui(structure));
expect(
screen.getByRole("region", { name: "Структура портфеля" }),
).toHaveTextContent("Данные о структуре портфеля пока недоступны.");
expect(
screen.queryByText(/Нет положительной стоимости/),
).not.toBeInTheDocument();
expect(screen.queryByRole("list")).not.toBeInTheDocument();
view.rerender(ui({ currencies: [rub], unvaluedCategories: [] }));
expect(screen.getByRole("list")).toHaveTextContent("Акции60 ₽60 %");
expect(
screen.queryByText("Данные о структуре портфеля пока недоступны."),
).not.toBeInTheDocument();
},
);
it("shows exact server amounts and cash-inclusive shares without hovering", () => {
render(ui({ currencies: [rub], unvaluedCategories: [] }));
const list = screen.getByRole("list", { name: "Категории активов" });
expect(list).toHaveTextContent("Акции60 ₽60 %");
expect(list).toHaveTextContent("Свободные деньги20 ₽20 %");
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
});
it("switches currencies and falls back when a refresh removes the selection", () => {
const usd = { ...rub, currency: "USD" };
const view = render(ui({ currencies: [rub, usd], unvaluedCategories: [] }));
fireEvent.click(
screen.getByRole("combobox", { name: "Валюта структуры портфеля" }),
);
fireEvent.click(screen.getByRole("option", { name: "USD" }));
expect(screen.getByRole("list")).toHaveTextContent("60 USD");
expect(screen.getByRole("list")).not.toHaveTextContent("₽");
view.rerender(ui({ currencies: [rub], unvaluedCategories: [] }));
expect(screen.getByRole("list")).toHaveTextContent("60 ₽");
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
});
it("retains known amounts and names unvalued categories without inventing a zero", () => {
render(
ui({
currencies: [
{
...rub,
categories: rub.categories.map((row) => ({
...row,
sharePercent: null,
})),
},
],
unvaluedCategories: [
{ type: "OTHER", count: 2 },
{ type: "STOCK", count: 1 },
],
}),
);
expect(screen.getByText(/Оценка неполная/)).toBeInTheDocument();
expect(screen.getByRole("list")).toHaveTextContent("Известно: 60 ₽");
expect(screen.getByRole("list")).toHaveTextContent(
"Другие активыНет оценки",
);
expect(
screen.queryByLabelText(/Структура по типам/),
).not.toBeInTheDocument();
});
it("keeps negative amounts visible without a donut or invented positive shares", () => {
render(
ui({
currencies: [
{
...rub,
hasNegativeValues: true,
categories: rub.categories.map((row) => ({
...row,
value: row.type === "STOCK" ? "-60" : row.value,
sharePercent: null,
})),
},
],
unvaluedCategories: [],
}),
);
expect(screen.getByText(/Есть отрицательные/)).toBeInTheDocument();
expect(screen.getByRole("list")).toHaveTextContent("-60 ₽");
expect(
within(screen.getByRole("list")).getAllByText("Доля недоступна"),
).toHaveLength(4);
expect(
screen.queryByLabelText(/Структура по типам/),
).not.toBeInTheDocument();
});
it("handles unknown-only and empty compositions", () => {
const view = render(
ui({ currencies: [], unvaluedCategories: [{ type: "BOND", count: 1 }] }),
);
expect(screen.getByText("Облигации: без оценки — 1")).toBeInTheDocument();
expect(screen.queryByRole("list")).not.toBeInTheDocument();
view.rerender(ui({ currencies: [], unvaluedCategories: [] }));
expect(screen.getByText(/Нет положительной стоимости/)).toBeInTheDocument();
});
it("keeps full decimal amounts and describes tiny shares", () => {
render(
ui({
currencies: [
{
...rub,
categories: [
{
type: "CASH",
value: "9007199254740993.000000001",
sharePercent: "0.000001",
},
],
},
],
unvaluedCategories: [],
}),
);
expect(screen.getByRole("list")).toHaveTextContent(
"9 007 199 254 740 993,000000001 ₽",
);
expect(screen.getByRole("list")).toHaveTextContent("< 0,01 %");
});
});
@@ -0,0 +1,80 @@
import { type FC, useState } from "react";
import { useTranslation } from "react-i18next";
import type { Portfolio } from "@/entities/portfolio";
import { formatMoney } from "@/shared/lib";
import { PortfolioStructureView } from "./PortfolioStructure.view";
const MIN_VISIBLE_SHARE_PERCENT = 0.01;
// A cached snapshot or an older running server can predate this response field.
type PortfolioStructureProps = { structure?: Portfolio["structure"] | null };
const categoryPresentation = {
STOCK: { label: "portfolio.stocks", color: "blue.6" },
BOND: { label: "portfolio.bonds", color: "grape.6" },
OTHER: { label: "portfolio.structure.other", color: "orange.6" },
CASH: { label: "portfolio.structure.cash", color: "green.6" },
} as const;
const PortfolioStructure: FC<PortfolioStructureProps> = (props) => {
const { structure } = props;
const { t } = useTranslation();
const [currency, setCurrency] = useState<string | null>(null);
const selected =
structure?.currencies.find((item) => item.currency === currency) ??
structure?.currencies[0];
const incomplete = (structure?.unvaluedCategories.length ?? 0) > 0;
const rows = selected
? selected.categories.map((category) => {
const presentation = categoryPresentation[category.type];
const percentage =
category.sharePercent === null ? null : Number(category.sharePercent);
const unknown = structure?.unvaluedCategories.some(
(item) => item.type === category.type,
);
const amount = formatMoney({
currency: selected.currency,
value: category.value,
});
return {
name: t(presentation.label),
color: presentation.color,
amount: unknown
? category.value === "0"
? t("portfolio.structure.unvalued")
: t("portfolio.structure.knownAmount", { amount })
: amount,
share:
percentage === null
? t("portfolio.structure.shareUnavailable")
: percentage > 0 && percentage < MIN_VISIBLE_SHARE_PERCENT
? t("portfolio.structure.smallShare")
: `${new Intl.NumberFormat("ru-RU", { maximumFractionDigits: 2 }).format(percentage)} %`,
value: percentage ?? 0,
};
})
: [];
const chartData = rows.filter((row) => row.value > 0);
return (
<PortfolioStructureView
unavailable={!structure}
currencies={structure?.currencies.map((item) => item.currency) ?? []}
currency={selected?.currency ?? null}
onCurrencyChange={setCurrency}
rows={rows}
chartData={chartData}
incomplete={incomplete}
negative={selected?.hasNegativeValues ?? false}
unvalued={
structure?.unvaluedCategories.map((category) =>
t("portfolio.structure.unvaluedCategory", {
category: t(categoryPresentation[category.type].label),
count: category.count,
}),
) ?? []
}
/>
);
};
export { PortfolioStructure };
@@ -0,0 +1,147 @@
import { DonutChart } from "@mantine/charts";
import { Box, Group, Paper, Select, Stack, Text, Title } from "@mantine/core";
import { type FC, useId } from "react";
import { useTranslation } from "react-i18next";
import classes from "./PortfolioStructure.module.css";
type StructureRow = {
name: string;
color: string;
amount: string;
share: string;
value: number;
};
type PortfolioStructureViewProps = {
unavailable: boolean;
currencies: string[];
currency: string | null;
onCurrencyChange: (currency: string | null) => void;
rows: StructureRow[];
chartData: StructureRow[];
incomplete: boolean;
negative: boolean;
unvalued: string[];
};
const PortfolioStructureView: FC<PortfolioStructureViewProps> = (props) => {
const { t } = useTranslation();
const titleId = useId();
return (
<Stack
component="section"
aria-labelledby={titleId}
gap="md"
className={classes.section}
>
<Group justify="space-between" align="center">
<Title order={2} size="h4" id={titleId}>
{t("portfolio.structure.title")}
</Title>
{props.currencies.length > 1 ? (
<Select
aria-label={t("portfolio.structure.currency")}
data={props.currencies}
value={props.currency}
onChange={props.onCurrencyChange}
allowDeselect={false}
w={112}
/>
) : null}
</Group>
<Text size="sm" c="dimmed">
{t(
props.unavailable
? "portfolio.structure.unavailable"
: "portfolio.structure.basis",
)}
</Text>
{props.incomplete ? (
<Stack gap={4}>
<Text size="sm">{t("portfolio.structure.incomplete")}</Text>
{props.unvalued.map((message) => (
<Text size="sm" c="dimmed" key={message}>
{message}
</Text>
))}
</Stack>
) : null}
{props.negative ? (
<Text size="sm">{t("portfolio.structure.negative")}</Text>
) : null}
{!props.unavailable &&
!props.chartData.length &&
!props.incomplete &&
!props.negative ? (
<Text size="sm" c="dimmed">
{t("portfolio.structure.empty")}
</Text>
) : null}
<div
key={props.currency}
className={`${classes.content} ${props.chartData.length ? classes.layout : ""}`}
>
{props.chartData.length ? (
<DonutChart
data={props.chartData}
size={220}
thickness={32}
strokeWidth={2}
startAngle={90}
endAngle={-270}
chartLabel={props.currency ?? undefined}
tooltipDataSource="segment"
pieProps={{ isAnimationActive: false }}
pieChartProps={{ title: t("portfolio.structure.chartLabel") }}
aria-label={t("portfolio.structure.chartLabel")}
tooltipProps={{
content: ({ active, payload }) => {
const row = props.chartData.find(
(item) => item.name === payload?.[0]?.name,
);
return active && row ? (
<Paper shadow="sm" p="sm" radius="md">
<Text size="sm" fw={600}>
{row.name}
</Text>
<Text size="sm">
{row.amount} · {row.share}
</Text>
</Paper>
) : null;
},
}}
/>
) : null}
{props.rows.length ? (
<ul
className={classes.list}
aria-label={t("portfolio.structure.categories")}
>
{props.rows.map((row) => (
<li key={row.name} className={classes.row}>
<Group gap="xs" wrap="nowrap">
<Box
aria-hidden="true"
bg={row.color}
className={classes.marker}
/>
<Text size="sm">{row.name}</Text>
</Group>
<div className={classes.values}>
<Text size="sm" fw={600}>
{row.amount}
</Text>
<Text size="sm" c="dimmed">
{row.share}
</Text>
</div>
</li>
))}
</ul>
) : null}
</div>
</Stack>
);
};
export { PortfolioStructureView };
@@ -0,0 +1,134 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import type { AccountPagePosition } from "../../AccountPage.vm";
import { PositionCard } from "./PositionCard.view";
const syntheticPosition = {
figi: null,
displayName: "Учебные технологии",
type: "STOCK",
quantity: "100",
currentValue: { currency: "RUB", value: "25000" },
averagePurchasePrice: { currency: "RUB", value: "200" },
absoluteReturn: { currency: "RUB", value: "5000" },
isin: null,
ticker: "DEMO",
logoName: null,
shareText: "20%",
returnText: "+5 000 ₽",
returnTone: "positive",
logoSrc: null,
} satisfies AccountPagePosition;
const meta = {
title: "Product/PositionCard",
component: PositionCard,
tags: ["autodocs"],
argTypes: {
kind: {
control: "inline-radio",
options: ["stocks", "bonds", "other"],
},
position: { control: false },
},
parameters: {
docs: {
description: {
component:
"Позиция портфеля WealthLedger: количество, стоимость, результат и доля. Доля и текст результата поступают готовыми из модели представления. Карточка не рассчитывает доходность. Все данные вымышлены; логотип заменён буквенным обозначением.",
},
},
},
args: { kind: "stocks", position: syntheticPosition },
} satisfies Meta<typeof PositionCard>;
export default meta;
type Story = StoryObj<typeof meta>;
export const StockGain: Story = {
name: "Акция с положительным результатом",
parameters: {
docs: {
description: {
story:
"Развёрнутая карточка акции показывает тикер, оценку позиции и положительный результат. Цвет дополняет знак суммы.",
},
},
},
};
export const BondLoss: Story = {
name: "Облигация с отрицательным результатом",
args: {
kind: "bonds",
position: {
...syntheticPosition,
displayName: "Учебные облигации для долгосрочных накоплений, выпуск 2030",
type: "BOND",
quantity: "10",
currentValue: { currency: "RUB", value: "9500" },
averagePurchasePrice: { currency: "RUB", value: "1000" },
absoluteReturn: { currency: "RUB", value: "-500" },
isin: "DEMO-BOND-2030",
ticker: null,
shareText: "7,6%",
returnText: "−500 ₽",
returnTone: "negative",
},
},
parameters: {
docs: {
description: {
story:
"Для облигации используется идентификатор выпуска. Длинное имя и отрицательная сумма позволяют проверить компактное представление на узком экране.",
},
},
},
};
export const Other: Story = {
name: "Прочий инструмент",
args: {
kind: "other",
position: {
...syntheticPosition,
displayName: "Учебный фонд",
type: "FUND",
isin: "DEMO-FUND",
ticker: null,
},
},
parameters: {
docs: {
description: {
story:
"Компактный вариант для остальных инструментов сохраняет количество, стоимость и пояснение результата без оформления акции или облигации.",
},
},
},
};
export const MissingValuation: Story = {
name: "Оценка и идентификаторы отсутствуют",
args: {
position: {
...syntheticPosition,
displayName: "Учебная позиция без текущей оценки",
currentValue: null,
averagePurchasePrice: null,
absoluteReturn: null,
ticker: null,
shareText: null,
returnText: null,
returnTone: undefined,
},
},
parameters: {
docs: {
description: {
story:
"При отсутствии оценки остаются название и количество. Неизвестная стоимость, доля и результат не изображаются нулевыми значениями.",
},
},
},
};
@@ -0,0 +1,159 @@
import { Anchor, Card, Group, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { formatMoney } from "@/shared/lib";
import classes from "../../AccountPage.module.css";
import type {
AccountPagePosition,
AccountPagePositionSection,
} from "../../AccountPage.vm";
import { PositionLogo } from "../PositionLogo.view";
type PositionCardProps = {
kind: AccountPagePositionSection["kind"];
position: AccountPagePosition;
};
const PositionCard: FC<PositionCardProps> = (props) => {
const { kind, position } = props;
const { t } = useTranslation();
const isExpanded = kind !== "other";
const returnClass = position.returnTone
? classes[position.returnTone]
: undefined;
const returnText =
position.returnText && isExpanded
? position.returnText
: position.returnText
? t("portfolio.return", {
value: position.returnText,
})
: null;
const instrumentTo = position.instrumentTo;
const identifier =
kind === "stocks" ? (position.ticker ?? position.isin) : position.isin;
const identifierText = [
t("portfolio.quantity", { value: position.quantity }),
identifier,
]
.filter(Boolean)
.join(" · ");
const accountLink = position.account ? (
<Anchor
component={Link}
to={`/accounts/${encodeURIComponent(position.account.id)}`}
size="xs"
>
{position.account.name}
</Anchor>
) : null;
const secondaryText = [
position.averagePurchasePrice
? t("portfolio.avgPrice", {
value: formatMoney(position.averagePurchasePrice),
})
: null,
position.shareText
? t("portfolio.share", { value: position.shareText })
: null,
]
.filter(Boolean)
.join(" · ");
if (isExpanded)
return (
<Card className={`${classes.tile} ${classes.expandedCard}`} withBorder>
<div className={classes.expandedMain}>
<PositionLogo
key={position.logoSrc ?? "no-logo"}
src={position.logoSrc}
label={position.displayName}
to={instrumentTo}
/>
<Stack gap={2} miw={0} className={classes.expandedIdentity}>
{instrumentTo ? (
<Anchor component={Link} to={instrumentTo} c="inherit" fw={600}>
{position.displayName}
</Anchor>
) : (
<Text fw={600} lineClamp={1}>
{position.displayName}
</Text>
)}
{accountLink}
<Text c="dimmed" size="xs" className={classes.expandedIdentifiers}>
{identifierText}
</Text>
</Stack>
<Stack gap={2} align="flex-end" className={classes.expandedValue}>
{position.currentValue ? (
<Text fw={700} size="lg">
{formatMoney(position.currentValue)}
</Text>
) : null}
{returnText ? (
<Text size="sm" fw={600} className={returnClass}>
{returnText}
</Text>
) : null}
</Stack>
</div>
{secondaryText ? (
<Text c="dimmed" size="xs" className={classes.expandedMeta}>
{secondaryText}
</Text>
) : null}
</Card>
);
return (
<Card className={classes.tile} withBorder>
<Group justify="space-between" align="flex-start" wrap="nowrap">
<Stack gap={2} miw={0}>
<Text fw={700} lineClamp={1}>
{position.displayName}
</Text>
{accountLink}
{position.isin ? (
<Text c="dimmed" size="xs" className={classes.mono}>
{position.isin}
</Text>
) : null}
<Text c="dimmed" size="xs">
{t("portfolio.quantity", { value: position.quantity })}
</Text>
</Stack>
<Stack gap={2} align="flex-end">
{position.currentValue ? (
<Text fw={800} size="lg">
{formatMoney(position.currentValue)}
</Text>
) : null}
{returnText ? (
<Text size="sm" fw={600} className={returnClass}>
{returnText}
</Text>
) : null}
</Stack>
</Group>
{position.averagePurchasePrice || position.shareText ? (
<Group justify="space-between" mt="xs">
{position.averagePurchasePrice ? (
<Text c="dimmed" size="xs">
{t("portfolio.avgPrice", {
value: formatMoney(position.averagePurchasePrice),
})}
</Text>
) : null}
{position.shareText ? (
<Text c="dimmed" size="xs">
{t("portfolio.share", { value: position.shareText })}
</Text>
) : null}
</Group>
) : null}
</Card>
);
};
export { PositionCard };
@@ -0,0 +1,115 @@
import { Anchor, Card, Group, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { formatMoney } from "@/shared/lib";
import classes from "../AccountPage.module.css";
import type {
AccountPagePositionGroup,
AccountPagePositionSection,
} from "../AccountPage.vm";
import { PositionLogo } from "./PositionLogo.view";
type PositionGroupCardProps = {
group: AccountPagePositionGroup;
kind: AccountPagePositionSection["kind"];
};
const PositionGroupCard: FC<PositionGroupCardProps> = (props) => {
const { group, kind } = props;
const { t } = useTranslation();
const identity = group.positions[0];
const instrumentTo = identity.instrumentTo;
return (
<Card className={classes.tile} withBorder>
<Group wrap="nowrap" gap="sm">
{kind !== "other" ? (
<PositionLogo
key={identity.logoSrc ?? "no-logo"}
src={identity.logoSrc}
label={identity.displayName}
to={instrumentTo}
/>
) : null}
<Stack gap={2} miw={0}>
{instrumentTo ? (
<Anchor component={Link} to={instrumentTo} c="inherit" fw={600}>
{identity.displayName}
</Anchor>
) : (
<Text fw={600}>{identity.displayName}</Text>
)}
<Text c="dimmed" size="xs">
{identity.ticker ?? identity.isin ?? identity.figi}
</Text>
</Stack>
</Group>
<Stack
component="ul"
gap={0}
className={classes.accountPositions}
aria-label={t("portfolio.byAccount")}
>
{group.positions.map((position) => (
<Stack
component="li"
key={position.account?.id}
gap={4}
className={classes.accountPosition}
>
<Group justify="space-between" align="flex-start" gap="xs">
{position.account ? (
<Anchor
component={Link}
to={`/accounts/${encodeURIComponent(position.account.id)}`}
size="sm"
className={classes.accountPositionName}
>
{position.account.name}
</Anchor>
) : null}
<Text size="sm" fw={600}>
{t("portfolio.quantity", { value: position.quantity })}
</Text>
</Group>
<Group justify="space-between" gap="xs">
{position.currentValue ? (
<Text size="sm">{formatMoney(position.currentValue)}</Text>
) : null}
{position.returnText ? (
<Text
size="sm"
className={
position.returnTone
? classes[position.returnTone]
: undefined
}
>
{kind === "other"
? t("portfolio.return", { value: position.returnText })
: position.returnText}
</Text>
) : null}
</Group>
<Group gap="xs">
{position.averagePurchasePrice ? (
<Text c="dimmed" size="xs">
{t("portfolio.avgPrice", {
value: formatMoney(position.averagePurchasePrice),
})}
</Text>
) : null}
{position.shareText ? (
<Text c="dimmed" size="xs">
{t("portfolio.share", { value: position.shareText })}
</Text>
) : null}
</Group>
</Stack>
))}
</Stack>
</Card>
);
};
export { PositionGroupCard };
@@ -0,0 +1,47 @@
import { Anchor, Avatar } from "@mantine/core";
import type { FC } from "react";
import { useState } from "react";
import { Link } from "react-router";
type PositionLogoProps = {
src: string | null;
label: string;
to?: string;
};
const PositionLogo: FC<PositionLogoProps> = (props) => {
const { src, label } = props;
const [failed, setFailed] = useState(false);
const logo =
src && !failed ? (
<Avatar
src={src}
alt={label}
size={40}
radius="md"
onError={() => setFailed(true)}
/>
) : (
<Avatar size={40} radius="md">
{(label.trim()[0] ?? "?").toUpperCase()}
</Avatar>
);
return props.to ? (
<Anchor
component={Link}
to={props.to}
aria-label={label}
c="inherit"
underline="never"
display="block"
style={{ borderRadius: "var(--mantine-radius-md)" }}
>
{logo}
</Anchor>
) : (
logo
);
};
export { PositionLogo };
@@ -0,0 +1,36 @@
import { SimpleGrid } from "@mantine/core";
import type { FC } from "react";
import type { AccountPagePositionSection } from "../AccountPage.vm";
import { PositionCard } from "./PositionCard/PositionCard.view";
import { PositionGroupCard } from "./PositionGroupCard.view";
type PositionSectionProps = {
section: AccountPagePositionSection;
};
const PositionSection: FC<PositionSectionProps> = (props) => {
const { section } = props;
const expanded = section.kind !== "other";
return (
<SimpleGrid cols={expanded ? 1 : { base: 1, sm: 2, md: 3 }}>
{section.groups.map((group) =>
group.positions.length > 1 ? (
<PositionGroupCard
key={group.key}
group={group}
kind={section.kind}
/>
) : (
<PositionCard
key={group.key}
position={group.positions[0]}
kind={section.kind}
/>
),
)}
</SimpleGrid>
);
};
export { PositionSection };
@@ -0,0 +1,51 @@
import { Alert, Button, Skeleton, Stack, Text } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { LedgerEntryRow } from "@/entities/broker-operation";
import type { AccountPageRecentOperations } from "../AccountPage.vm";
type RecentOperationsProps = {
operations: AccountPageRecentOperations;
};
const RecentOperations: FC<RecentOperationsProps> = (props) => {
const { operations } = props;
const { t } = useTranslation();
return (
<Stack gap="sm">
{operations.state === "loading" ? (
<LoadingSkeleton label={t("ledger.recentLoading")}>
{[0, 1, 2].map((index) => (
<Skeleton key={index} height={48} radius="sm" />
))}
</LoadingSkeleton>
) : null}
{operations.state === "error" ? (
<Alert color="red">{t("ledger.recentError")}</Alert>
) : null}
{operations.state === "empty" ? (
<Text c="dimmed">{t("ledger.recentEmpty")}</Text>
) : null}
{operations.state === "loaded"
? operations.items.map((operation) => (
<LedgerEntryRow
key={JSON.stringify([
operation.account?.id,
operation.id,
operation.logoName,
])}
operation={operation}
/>
))
: null}
<Button component={Link} to={operations.to} variant="subtle">
{t("ledger.open")}
</Button>
</Stack>
);
};
export { RecentOperations };
@@ -0,0 +1,128 @@
import { MantineProvider } from "@mantine/core";
import { render, screen, within } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { describe, expect, it } from "vitest";
import type { Portfolio } from "@/entities/portfolio";
import { toAccountPagePositionSections } from "./AccountPage.vm";
import { PositionSection } from "./components/PositionSection.view";
const position: Portfolio["positions"][number] = {
account: { id: "a", name: "Основной" },
figi: "FIGI-SBER",
displayName: "Сбербанк",
type: "STOCK",
quantity: "1.25",
currentValue: { currency: "RUB", value: "375" },
averagePurchasePrice: { currency: "RUB", value: "280" },
absoluteReturn: { currency: "RUB", value: "25" },
isin: "RU0009029540",
ticker: "SBER",
logoName: null,
};
const second = {
...position,
account: { id: "b", name: "ИИС" },
quantity: "-2",
currentValue: null,
averagePurchasePrice: null,
absoluteReturn: null,
};
function sections(positions: Portfolio["positions"]) {
return toAccountPagePositionSections({
lastSuccessfulAt: "2026-09-09T12:00:00Z",
isStale: false,
totalsByCurrency: [],
structure: { currencies: [], unvaluedCategories: [] },
cashBalances: [],
positions,
});
}
describe("Positions grouped by security", () => {
it("shows one security with exact per-account quantities and valuations", () => {
const section = sections([position, second])[0];
render(
<MantineProvider>
<MemoryRouter>
<PositionSection section={section} />
</MemoryRouter>
</MantineProvider>,
);
expect(screen.getAllByText("Сбербанк")).toHaveLength(1);
const rows = within(
screen.getByRole("list", { name: "Позиции по счетам" }),
).getAllByRole("listitem");
expect(rows).toHaveLength(2);
expect(
within(rows[0]).getByRole("link", { name: "Основной" }),
).toHaveAttribute("href", "/accounts/a");
expect(within(rows[0]).getByText("Количество: 1.25")).toBeInTheDocument();
expect(within(rows[0]).getByText("375 ₽")).toBeInTheDocument();
expect(
within(rows[0]).getByText("Средняя цена: 280 ₽"),
).toBeInTheDocument();
expect(within(rows[1]).getByRole("link", { name: "ИИС" })).toHaveAttribute(
"href",
"/accounts/b",
);
expect(within(rows[1]).getByText("Количество: -2")).toBeInTheDocument();
expect(rows[1]).not.toHaveTextContent("₽");
});
it("uses ISIN only when FIGI is absent, never merging by name or ticker", () => {
expect(
sections([
{ ...position, figi: null },
{ ...second, figi: null },
])[0].groups,
).toHaveLength(1);
expect(
sections([position, { ...second, figi: "OTHER-FIGI" }])[0].groups,
).toHaveLength(2);
expect(
sections([
{ ...position, figi: null, isin: null },
{ ...second, figi: null, isin: null },
])[0].groups,
).toHaveLength(2);
});
it("preserves one-account cards and does not merge repeated rows on the same account", () => {
expect(
sections([position, { ...second, account: position.account }])[0].groups,
).toHaveLength(2);
expect(
sections([
{ ...position, account: undefined },
{ ...second, account: undefined },
])[0].groups,
).toHaveLength(2);
});
it("keeps currencies and purchase prices attached to their source positions", () => {
const source = [
position,
{
...second,
currentValue: { currency: "USD", value: "1.01" },
averagePurchasePrice: { currency: "USD", value: "0.99" },
},
];
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);
});
});