refactor!: support RUB only (WealthLedger/main#55) (#168)
Frontend verify / commits (push) Skipped
Frontend verify / security (push) Successful in 11s
Frontend verify / verify (push) Failing after 9m0s

This commit was merged in pull request #168.
This commit is contained in:
2026-11-11 09:36:29 +03:00
parent e2062ce837
commit 2b94a16ae5
55 changed files with 540 additions and 1153 deletions
@@ -96,7 +96,7 @@ function renderPage(ui: React.ReactNode) {
const portfolio
= {
cashBalances: [{ currency: "USD", value: "0.5" }],
cash: { currency: "RUB", value: "0.5" },
isStale: true,
lastSuccessfulAt: "2026-08-13T10:00:00Z",
positions: [
@@ -129,8 +129,8 @@ const portfolio
type: "BOND",
},
] satisfies [Portfolio["positions"][number], ...Portfolio["positions"]],
structure: { currencies: [], unvaluedCategories: [] },
totalsByCurrency: [{ currency: "RUB", value: "1234.5" }],
structure: { categories: [], hasNegativeValues: false, totalValue: "0", unvaluedCategories: [] },
totals: { currency: "RUB", value: "1234.5" },
} satisfies Portfolio;
function position(
@@ -201,8 +201,6 @@ const LoadedHarness = (
function loadedProps(nextPortfolio: Portfolio = portfolio) {
return {
concentration: null,
currency: null,
onCurrencyChange: vi.fn(),
onSliceChange: vi.fn(),
portfolio: nextPortfolio,
positionSections: toAccountPagePositionSections(nextPortfolio),
@@ -242,10 +240,10 @@ describe("AccountPage states", () => {
HttpResponse.json(resource(
{
...portfolio,
cashBalances: [],
cash: { currency: "RUB", value: "0" },
isStale: false,
positions: [],
totalsByCurrency: [],
totals: { currency: "RUB", value: "0" },
},
{
lastAttempt: {
@@ -278,7 +276,7 @@ describe("AccountPage states", () => {
const data = { ...portfolio, positions };
const model = toConcentration(
data, "stocks", "RUB", concentrationLabels(),
data, "stocks", concentrationLabels(),
);
const props = loadedProps(data);
@@ -287,7 +285,6 @@ describe("AccountPage states", () => {
{...props}
accountId="a"
concentration={model}
currency="RUB"
tab="concentration"
/>,
);
@@ -326,10 +323,8 @@ describe("AccountPage states", () => {
concentration={toConcentration(
{ ...portfolio, positions },
"stocks",
"RUB",
concentrationLabels(),
)}
currency="RUB"
tab="concentration"
/>,
);
@@ -354,9 +349,8 @@ describe("AccountPage states", () => {
{...loadedProps(data)}
accountId="a"
concentration={toConcentration(
data, "stocks", "RUB", concentrationLabels(),
data, "stocks", concentrationLabels(),
)}
currency="RUB"
tab="concentration"
/>,
);
@@ -370,9 +364,8 @@ describe("AccountPage states", () => {
{...loadedProps(data)}
accountId="a"
concentration={toConcentration(
data, "issuers", "RUB", concentrationLabels(),
data, "issuers", concentrationLabels(),
)}
currency="RUB"
slice="issuers"
tab="concentration"
/>,
@@ -392,9 +385,8 @@ describe("AccountPage states", () => {
{...loadedProps(data)}
accountId="a"
concentration={toConcentration(
data, "stocks", "RUB", concentrationLabels(),
data, "stocks", concentrationLabels(),
)}
currency="RUB"
tab="concentration"
/>,
);
@@ -424,9 +416,8 @@ describe("AccountPage states", () => {
{...loadedProps(data)}
accountId="a"
concentration={toConcentration(
data, "sectors", "RUB", concentrationLabels(),
data, "sectors", concentrationLabels(),
)}
currency="RUB"
slice="sectors"
tab="concentration"
/>,
@@ -457,9 +448,8 @@ describe("AccountPage states", () => {
{...loadedProps(data)}
accountId="a"
concentration={toConcentration(
data, "stocks", "RUB", concentrationLabels(),
data, "stocks", concentrationLabels(),
)}
currency="RUB"
tab="concentration"
/>,
);
@@ -484,9 +474,8 @@ describe("AccountPage states", () => {
{...loadedProps(data)}
accountId="a"
concentration={toConcentration(
data, "stocks", "RUB", concentrationLabels(),
data, "stocks", concentrationLabels(),
)}
currency="RUB"
partial
tab="concentration"
/>,
@@ -496,16 +485,14 @@ describe("AccountPage states", () => {
.toHaveLength(1);
});
it("keeps slice and currency while switching page tabs and resets on account change", async () => {
it("keeps the slice while switching page tabs and resets on account change", async () => {
const multiCurrency = { ...portfolio, positions:
["RUB", "USD"].flatMap(currency =>
[400, 250, 150, 100, 50, 30, 20].map((value, index) =>
position({
currentValue: { currency, value: String(value) },
displayName: `${currency} акция ${index + 1}`,
sector: "energy", type: "STOCK",
}),
),
[400, 250, 150, 100, 50, 30, 20].map((value, index) =>
position({
currentValue: { currency: "RUB", value: String(value) },
displayName: `Акция ${index + 1}`,
sector: "energy", type: "STOCK",
}),
) };
server.use(
@@ -520,37 +507,27 @@ describe("AccountPage states", () => {
fireEvent.click(screen.getByRole("button", { name: /Прочее/ }));
expect(screen.getByRole("button", { name: /Прочее/ }))
.toHaveAttribute("aria-expanded", "true");
fireEvent.click(screen.getByRole("combobox", { name: "Валюта концентрации" }));
fireEvent.click(screen.getByRole("option", { name: "USD" }));
expect(screen.getByRole("button", { name: /Прочее/ }))
.toHaveAttribute("aria-expanded", "false");
fireEvent.click(screen.getByRole("button", { name: /Прочее/ }));
fireEvent.click(screen.getByRole("radio", { name: "Секторы" }));
fireEvent.click(screen.getByRole("radio", { name: "Акции" }));
expect(screen.getByRole("button", { name: /Прочее/ }))
.toHaveAttribute("aria-expanded", "false");
fireEvent.click(screen.getByRole("radio", { name: "Секторы" }));
expect(screen.getByRole("combobox", { name: "Валюта концентрации" }))
.toHaveValue("USD");
fireEvent.click(screen.getByRole("tab", { name: "Позиции" }));
fireEvent.click(screen.getByRole("tab", { name: "Концентрация" }));
expect(screen.getByRole("radio", { name: "Секторы" }))
.toBeChecked();
expect(screen.getByRole("combobox", { name: "Валюта концентрации" }))
.toHaveValue("USD");
fireEvent.click(screen.getByRole("button", { name: "Другой счёт" }));
fireEvent.click(await screen.findByRole("tab", { name: "Концентрация" }));
expect(screen.getByRole("radio", { name: "Акции" })).toBeChecked();
expect(screen.getByRole("combobox", { name: "Валюта концентрации" }))
.toHaveValue("RUB");
});
it("falls back to the first currency when the selected one disappears", () => {
it("includes all ruble positions in concentration", () => {
const data = { ...portfolio, positions: [
position({
currentValue: { currency: "USD", value: "200" },
currentValue: { currency: "RUB", value: "200" },
}),
position({
currentValue: { currency: "RUB", value: "100" },
@@ -558,12 +535,11 @@ describe("AccountPage states", () => {
] };
const model = toConcentration(
data, "stocks", "EUR", concentrationLabels(),
data, "stocks", concentrationLabels(),
);
expect(model.currencies).toEqual(["RUB", "USD"]);
expect(model.total).toBe("100");
expect(model.items.map(item => item.amount)).toEqual(["100"]);
expect(model.total).toBe("300");
expect(model.items.map(item => item.amount)).toEqual(["200", "100"]);
});
it("shows the loaded portfolio source sync status", async () => {
server.use(
@@ -679,7 +655,7 @@ describe("AccountPage states", () => {
).toHaveTextContent("Данные о структуре портфеля пока недоступны.");
expect(
screen.getAllByRole("definition").map(node => node.textContent),
).toEqual(["1 234,5 ₽"]);
).toEqual(["1 234,50 ₽"]);
});
it("keeps initial placeholders decorative without amounts or focus targets", () => {
const { container } = renderPage(<AccountPageLoading />);
@@ -722,11 +698,7 @@ describe("AccountPage states", () => {
<LoadedHarness
{...loadedProps({
...portfolio,
cashBalances: [
{ currency: "RUB", value: "234.500000000000000001" },
{ currency: "USD", value: "-0.5" },
{ currency: "XYZ", value: "3.00" },
],
cash: { currency: "RUB", value: "234.500000000000000001" },
positions: [
...portfolio.positions,
{
@@ -737,7 +709,7 @@ describe("AccountPage states", () => {
type: "CURRENCY",
},
],
structure: { currencies: [], unvaluedCategories: [] },
structure: { categories: [], hasNegativeValues: false, totalValue: "0", unvaluedCategories: [] },
})}
/>,
);
@@ -750,14 +722,12 @@ describe("AccountPage states", () => {
expect(
balances.getAllByRole("definition").map(node => node.textContent),
).toEqual(["234,500000000000000001 ₽", "-0,5 $", "3,00 XYZ"]);
).toEqual(["234,50 ₽"]);
expect(
screen.getAllByRole("definition").map(node => node.textContent),
).toEqual([
"1 234,5 ₽",
"234,500000000000000001 ₽",
"-0,5 $",
"3,00 XYZ",
"1 234,50 ₽",
"234,50 ₽",
]);
expect(screen.queryByText("Торгуемая валюта")).not.toBeInTheDocument();
expect(
@@ -774,7 +744,7 @@ describe("AccountPage states", () => {
resource({
...portfolio,
positions: hasPositions ? portfolio.positions : [],
totalsByCurrency: [],
totals: { currency: "RUB", value: "0" },
}),
),
),
@@ -782,20 +752,20 @@ describe("AccountPage states", () => {
renderAccountRoute(createTestQueryClient());
await screen.findByRole("heading", { level: 1, name: "Портфель" });
fireEvent.click(screen.getByRole("tab", { name: "Деньги" }));
expect(screen.getByRole("definition")).toHaveTextContent("0,5 $");
expect(screen.getByText("0,50 ₽")).toBeInTheDocument();
expect(screen.queryByText("Портфель пока пуст")).not.toBeInTheDocument();
},
);
it.each([
{ totalsByCurrency: [] },
{ totalsByCurrency: [{ currency: "RUB", value: "100" }] },
{ empty: true, totals: { currency: "RUB", value: "0" } },
{ empty: false, totals: { currency: "RUB", value: "100" } },
])(
"hides the empty other section without emptying a currency-only portfolio (totals: $totalsByCurrency)",
async ({ totalsByCurrency }) => {
"hides the empty other section without emptying a currency-only portfolio (totals: $totals.value)",
async ({ empty, totals }) => {
const snapshot: Portfolio = {
...portfolio,
cashBalances: [],
cash: { currency: "RUB", value: "0" },
positions: [
{
...portfolio.positions[0],
@@ -804,8 +774,8 @@ describe("AccountPage states", () => {
type: "CURRENCY",
},
],
structure: { currencies: [], unvaluedCategories: [] },
totalsByCurrency,
structure: { categories: [], hasNegativeValues: false, totalValue: "0", unvaluedCategories: [] },
totals,
};
server.use(
@@ -826,11 +796,11 @@ describe("AccountPage states", () => {
expect(
within(
screen.getByRole("tabpanel", { name: "Деньги" }),
).queryByRole("definition"),
).not.toBeInTheDocument();
).getByRole("definition"),
).toHaveTextContent("0,00 ₽");
expect(
screen.queryAllByRole("definition").map(node => node.textContent),
).toEqual(totalsByCurrency.length > 0 ? ["100 ₽"] : []);
).toEqual([empty ? "0,00 ₽" : "100,00 ₽", "0,00 ₽"]);
expect(
queryClient.getQueryData(portfolioQueryOptions("account-1").queryKey),
).toEqual(resource(snapshot));
@@ -1147,7 +1117,7 @@ describe("AccountPage states", () => {
date: "2026-09-11",
dateKind: "registry",
displayName: "Акция",
projectedAmount: { currency: "USD", value: "0" },
projectedAmount: { currency: "RUB", value: "0" },
type: "dividend",
},
{
@@ -1191,7 +1161,7 @@ describe("AccountPage states", () => {
expect(
content.getByText("11.09.2026 · Дата реестра · RU000A0JX0J2"),
).toBeVisible();
for (const amount of ["850,50 ₽", "0 $", "1 000 ₽", "Сумма неизвестна"])
for (const amount of ["850,50 ₽", "0 ₽", "1 000 ₽", "Сумма неизвестна"])
expect(content.getByText(amount)).toBeVisible();
expect(content.getAllByText("Прогноз")).toHaveLength(4);
expect(content.queryByText("Без движения денег")).not.toBeInTheDocument();
@@ -1277,7 +1247,7 @@ describe("AccountPage states", () => {
return HttpResponse.json(resource(
requests === 1
? portfolio
: { ...portfolio, totalsByCurrency: [{ currency: "RUB", value: "999" }] },
: { ...portfolio, totals: { currency: "RUB", value: "999" } },
{ resourceKey: "portfolio" },
));
}),
@@ -1301,14 +1271,14 @@ describe("AccountPage states", () => {
expect(screen.getByText("Не удалось обновить данные")).toBeInTheDocument();
expect(screen.getByText("Вторая")).toBeInTheDocument();
expect(screen.getByText("1 234,5 ₽")).toBeInTheDocument();
expect(screen.getByText("1 234,50 ₽")).toBeInTheDocument();
// One cached read plus the three automatic attempts.
expect(requests).toBe(4);
isFailing = false;
fireEvent.click(retry);
expect(await screen.findByText("999 ₽")).toBeInTheDocument();
expect(await screen.findByText("999,00 ₽")).toBeInTheDocument();
expect(requests).toBe(5);
expect(screen.queryByText("Не удалось обновить данные"))
.not.toBeInTheDocument();
@@ -1370,14 +1340,9 @@ describe("AccountPage states", () => {
= {
...portfolio,
structure: {
currencies: [
{
categories: [{ sharePercent: null, type: "BOND", value: "10" }],
currency: "RUB",
hasNegativeValues: false,
totalValue: "10",
},
],
categories: [{ sharePercent: null, type: "BOND", value: "10" }],
hasNegativeValues: false,
totalValue: "10",
unvaluedCategories: [{ count: 1, type: "STOCK" }],
},
};
@@ -1428,7 +1393,7 @@ describe("AccountPage states", () => {
expect(screen.getByText("Вторая")).toBeInTheDocument();
expect(
screen.getAllByRole("definition").map(node => node.textContent),
).toEqual(["1 234,5 ₽"]);
).toEqual(["1 234,50 ₽"]);
expect(screen.queryByRole("button", { name: "Повторить" }))
.not.toBeInTheDocument();
void queryClient.invalidateQueries({
@@ -1438,17 +1403,17 @@ describe("AccountPage states", () => {
expect(structure).toHaveTextContent("10 ₽");
expect(
screen.getAllByRole("definition").map(node => node.textContent),
).toEqual(["1 234,5 ₽"]);
).toEqual(["1 234,50 ₽"]);
resolveRetry?.(
HttpResponse.json(
resource(
{
...portfolio,
cashBalances: [{ currency: "EUR", value: "2.50" }],
cash: { currency: "RUB", value: "2.50" },
isStale: false,
lastSuccessfulAt: "2026-08-14T11:30:00Z",
structure: { currencies: [], unvaluedCategories: [] },
totalsByCurrency: [{ currency: "USD", value: "-0.5" }],
structure: { categories: [], hasNegativeValues: false, totalValue: "0", unvaluedCategories: [] },
totals: { currency: "RUB", value: "-0.5" },
},
{ dataRevision: "2", resourceKey: "portfolio" },
),
@@ -1457,7 +1422,7 @@ describe("AccountPage states", () => {
await waitFor(() =>
expect(
screen.getAllByRole("definition").map(node => node.textContent),
).toEqual(["-0,5 $"]),
).toEqual(["-0,50 ₽"]),
);
expect(screen.getByText(/^Данные на /)).toHaveTextContent("Данные на");
expect(structure).not.toHaveTextContent("10 ₽");
@@ -1499,7 +1464,7 @@ describe("AccountPage states", () => {
expect(screen.getByText("Вторая")).toBeInTheDocument();
expect(
screen.getAllByRole("definition").map(node => node.textContent),
).toEqual(["1 234,5 ₽"]);
).toEqual(["1 234,50 ₽"]);
expect(screen.getByText(/^Данные на /)).toBeInTheDocument();
expect(
screen.queryByRole("status", { name: "Загрузка" }),
@@ -28,9 +28,7 @@ const AccountPage: FC = () => {
account={vm.account}
accountId={vm.accountId}
concentration={vm.concentration}
currency={vm.currency}
incomeSummary={vm.incomeSummary}
onCurrencyChange={vm.onCurrencyChange}
onSliceChange={vm.onSliceChange}
onTabChange={vm.onTabChange}
partial={vm.partial}
@@ -187,7 +187,7 @@ it("keeps overview sections independent when their source data is incomplete", a
http.get("*/api/v1/brokerage-accounts/:accountId/events", () =>
HttpResponse.json(
resource(
{ events: [], incomeTotalsByCurrency: [] },
{ events: [], incomeTotal: { currency: "RUB", value: "0" } },
{ completeness: "incomplete" },
),
),
@@ -213,8 +213,8 @@ it("keeps overview sections loaded without exposing technical retry", async () =
const sections: Record<string, unknown>
= {
"events": { events: [], incomeTotalsByCurrency: [] },
"income-summary": { totalsByCurrency: [] },
"events": { events: [], incomeTotal: { currency: "RUB", value: "0" } },
"income-summary": { total: { coupon: { currency: "RUB", value: "0" }, dividend: { currency: "RUB", value: "0" }, total: { currency: "RUB", value: "0" } } },
"operations": { hasNext: false, items: [], nextCursor: null },
portfolio,
};
@@ -238,7 +238,7 @@ it("keeps overview sections loaded without exposing technical retry", async () =
await waitFor(() =>
expect(result.current).toMatchObject({
incomeSummary: { state: "empty" },
incomeSummary: { state: "loaded" },
recentEvents: { state: "empty" },
recentOperations: { state: "empty" },
state: "loaded",
@@ -21,7 +21,6 @@ import { useInitialAvailability } from "@/shared/lib";
import {
type Concentration,
concentrationCurrencies,
type ConcentrationLabels,
type Slice,
toConcentration,
@@ -57,8 +56,6 @@ type AccountPageEmptyViewModel = AccountPageContent & {
type AccountPageLoadedViewModel = AccountPageContent & {
concentration: Concentration | null;
currency: null | string;
onCurrencyChange: (currency: null | string) => void;
onSliceChange: (slice: Slice) => void;
onTabChange: (tab: null | string) => void;
portfolio: Portfolio;
@@ -66,7 +63,9 @@ type AccountPageLoadedViewModel = AccountPageContent & {
slice: Slice;
state: "loaded";
tab: string;
unrealizedReturns: Portfolio["totalsByCurrency"];
unrealizedReturns:
| null
| { currency: string; value: string };
};
type AccountPageReadRetry = ReturnType<typeof readRetry>;
@@ -83,15 +82,14 @@ function useAccountPageVm(): AccountPageViewModel {
const [selection, setSelection] = useState<{
accountId?: string;
currency: null | string;
slice: Slice;
tab: string;
}>({ accountId, currency: null, slice: "stocks", tab: "positions" });
}>({ accountId, slice: "stocks", tab: "positions" });
const current = selection.accountId === accountId
? selection
: {
accountId, currency: null, slice: "stocks" as const, tab: "positions",
accountId, slice: "stocks" as const, tab: "positions",
};
const updateSelection = (change: Partial<typeof selection>) =>
@@ -144,7 +142,7 @@ function useAccountPageVm(): AccountPageViewModel {
if (
portfolio.meta?.availability === "available"
&& portfolio.data.positions.length === 0
&& portfolio.data.cashBalances.length === 0
&& Number(portfolio.data.cash.value) === 0
)
return {
account,
@@ -158,11 +156,6 @@ function useAccountPageVm(): AccountPageViewModel {
};
const isPartial = portfolio.meta?.completeness === "incomplete";
const currencies = concentrationCurrencies(portfolio.data);
const currency = current.currency && currencies.includes(current.currency)
? current.currency
: currencies[0] ?? null;
const labels: ConcentrationLabels = {
missingIssuer: t("portfolio.concentration.missingIssuer"),
@@ -173,16 +166,14 @@ function useAccountPageVm(): AccountPageViewModel {
const concentration = accountId !== "all"
&& current.tab === "concentration"
? toConcentration(portfolio.data, current.slice, currency, labels)
? toConcentration(portfolio.data, current.slice, labels)
: null;
return {
account,
accountId,
concentration,
currency,
incomeSummary,
onCurrencyChange: value => updateSelection({ currency: value }),
onSliceChange: slice => updateSelection({ slice }),
onTabChange: tab => updateSelection({ tab: tab ?? "positions" }),
partial: isPartial,
@@ -55,7 +55,12 @@ const AccountPageEmpty: FC<AccountPageEmptyProps> = (props) => {
<StateView text={text} title={t("portfolio.emptyTitle")} />
<PortfolioStructure
structure={{ currencies: [], unvaluedCategories: [] }}
structure={{
categories: [],
hasNegativeValues: false,
totalValue: "0",
unvaluedCategories: [],
}}
/>
<RecentOperations
@@ -28,7 +28,6 @@ import type {
import classes from "../AccountPage.module.css";
import { AccountHeading } from "./AccountHeading.view";
import { Concentration } from "./Concentration/Concentration.view";
import { CurrencyCards } from "./CurrencyCards/CurrencyCards.view";
import { IncomeSummary } from "./IncomeSummary.view";
import { PerformanceTab } from "./Performance/PerformanceTab";
import { PortfolioStructure } from "./PortfolioStructure/PortfolioStructure";
@@ -39,9 +38,7 @@ type AccountPageLoadedProps = {
account?: BrokerageAccount;
accountId?: string;
concentration: ConcentrationModel | null;
currency: null | string;
incomeSummary?: AccountPageIncomeSummary;
onCurrencyChange: (currency: null | string) => void;
onSliceChange: (slice: Slice) => void;
onTabChange: (tab: null | string) => void;
partial?: boolean;
@@ -53,7 +50,9 @@ type AccountPageLoadedProps = {
slice: Slice;
source?: InvestmentResourceMeta;
tab: string;
unrealizedReturns: Portfolio["totalsByCurrency"];
unrealizedReturns:
| null
| { currency: string; value: string };
};
const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
@@ -94,9 +93,23 @@ const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
? tab !== "concentration" && (
<Alert role="status">{t("investment.partial")}</Alert>
)
: <CurrencyCards amounts={props.portfolio.totalsByCurrency} />}
: (
<Stack component="dl" gap={4} m={0}>
<dt>
<Text fw={600}>{t("portfolio.total")}</Text>
</dt>
{!props.partial && props.unrealizedReturns.length > 0 && (
<dd style={{ margin: 0 }}>
<Text className={classes.totalAmount}>
{formatMoney(props.portfolio.totals, {
withRoundedCents: true,
})}
</Text>
</dd>
</Stack>
)}
{!props.partial && props.unrealizedReturns && (
<Stack
aria-label={t("portfolio.unrealizedResult")}
component="section"
@@ -105,9 +118,7 @@ const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
<Text fw={600}>{t("portfolio.unrealizedResult")}</Text>
<Group gap="md">
{props.unrealizedReturns.map(total => (
<Text key={total.currency}>{formatMoney(total)}</Text>
))}
<Text>{formatMoney(props.unrealizedReturns)}</Text>
</Group>
<Text c="dimmed" size="xs">
@@ -174,10 +185,8 @@ const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
<Tabs.Panel value="concentration">
{props.concentration && (
<Concentration
currency={props.currency}
key={`${props.slice}-${props.currency}`}
key={props.slice}
model={props.concentration}
onCurrencyChange={props.onCurrencyChange}
onSliceChange={props.onSliceChange}
partial={!!props.partial}
slice={props.slice}
@@ -187,7 +196,17 @@ const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
)}
<Tabs.Panel value="cash">
<CurrencyCards amounts={props.portfolio.cashBalances} />
<Stack component="dl" gap={4} m={0}>
<dt>
<Text fw={600}>{t("portfolio.cashTitle")}</Text>
</dt>
<dd style={{ margin: 0 }}>
<Text>
{formatMoney(props.portfolio.cash, { withRoundedCents: true })}
</Text>
</dd>
</Stack>
</Tabs.Panel>
<Tabs.Panel value="operations">
@@ -1,6 +1,6 @@
import { DonutChart } from "@mantine/charts";
import {
Alert, Box, Group, Paper, SegmentedControl, Select, Stack,
Alert, Box, Group, Paper, SegmentedControl, Stack,
Text, Title,
} from "@mantine/core";
import { type FC, useId, useState } from "react";
@@ -18,9 +18,7 @@ import { PositionLogo } from "../PositionLogo.view";
import classes from "./Concentration.module.css";
type Props = {
currency: null | string;
model: ConcentrationModel;
onCurrencyChange: (currency: null | string) => void;
onSliceChange: (slice: Slice) => void;
partial: boolean;
slice: Slice;
@@ -35,7 +33,6 @@ const sliceLabels = {
type RowProps = {
color: string;
currency: string;
index: number;
item: ConcentrationItem;
logo?: ConcentrationItem["logo"];
@@ -50,8 +47,8 @@ const colors = [
const PERCENT = 100;
const OTHER_START = 6;
function amountFor(item: ConcentrationItem, currency: string): string {
return formatMoney({ currency, value: item.amount });
function amountFor(item: ConcentrationItem): string {
return formatMoney({ currency: "RUB", value: item.amount });
}
const ConcentrationRow: FC<RowProps> = props => (
@@ -83,7 +80,7 @@ const ConcentrationRow: FC<RowProps> = props => (
</span>
<span className={classes.value}>
<strong>{amountFor(props.item, props.currency)}</strong>
<strong>{amountFor(props.item)}</strong>
<Text c="dimmed" size="sm">{props.item.share}</Text>
</span>
@@ -131,7 +128,6 @@ const Concentration: FC<Props> = (props) => {
const [expanded, setExpanded] = useState(false);
const otherId = useId();
const chartId = useId();
const currency = props.currency ?? "";
const rows = props.model.other
? [...props.model.items, props.model.other]
@@ -147,10 +143,8 @@ const Concentration: FC<Props> = (props) => {
props.model.top5Share && t("portfolio.concentration.top5", {
share: props.model.top5Share,
}),
props.model.total && formatMoney({
currency, value: props.model.total,
}),
...rows.map(item => `${item.label}: ${amountFor(item, currency)}, ${item.share}`),
props.model.total && formatMoney({ currency: "RUB", value: props.model.total }),
...rows.map(item => `${item.label}: ${amountFor(item)}, ${item.share}`),
].filter(Boolean).join("; ");
const slices = [
@@ -170,7 +164,7 @@ const Concentration: FC<Props> = (props) => {
const pieProps = { isAnimationActive: false, label: rankLabel };
const tooltipRows = rows.map(item => ({
amount: amountFor(item, currency),
amount: amountFor(item),
label: item.label,
share: item.share,
}));
@@ -178,7 +172,7 @@ const Concentration: FC<Props> = (props) => {
const tooltipProps = { content: <ChartTooltip rows={tooltipRows} /> };
const totalText = props.model.total
? formatMoney({ currency, value: props.model.total })
? formatMoney({ currency: "RUB", value: props.model.total })
: "";
return (
@@ -192,16 +186,6 @@ const Concentration: FC<Props> = (props) => {
value={props.slice}
/>
{props.model.currencies.length > 1 && (
<Select
allowDeselect={false}
aria-label={t("portfolio.concentration.currency")}
data={props.model.currencies}
onChange={props.onCurrencyChange}
value={props.currency}
w={130}
/>
)}
</Group>
{props.partial && (
@@ -211,9 +195,7 @@ const Concentration: FC<Props> = (props) => {
{props.model.empty
? (
<Stack gap="xs">
<Text fw={600}>{t(sliceLabels[props.slice])}
{props.currency && ` · ${props.currency}`}
</Text>
<Text fw={600}>{t(sliceLabels[props.slice])}</Text>
<Text>{t("portfolio.concentration.empty")}</Text>
</Stack>
@@ -260,7 +242,6 @@ const Concentration: FC<Props> = (props) => {
{props.model.items.map((item, index) => (
<ConcentrationRow
color={colors[index % colors.length] ?? "blue"}
currency={currency}
index={index + 1}
item={item}
key={item.key}
@@ -285,7 +266,7 @@ const Concentration: FC<Props> = (props) => {
)}
</span>
<span>{amountFor(props.model.other, currency)} · {
<span>{amountFor(props.model.other)} · {
props.model.other.share
}
</span>
@@ -301,7 +282,6 @@ const Concentration: FC<Props> = (props) => {
<ConcentrationRow
color={colors[(index + OTHER_START) % colors.length]
?? "blue"}
currency={currency}
index={index + OTHER_START}
item={item}
key={item.key}
@@ -1,77 +0,0 @@
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, 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),
);
// eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
expect(container.querySelectorAll("dl")).toHaveLength(count);
expect(
// eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
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);
// eslint-disable-next-line testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
expect(term.querySelector("[aria-hidden=\"true\"]")).toHaveTextContent(
symbol,
);
expect(screen.getByRole("definition")).toHaveTextContent(expected);
// eslint-disable-next-line testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
expect(term.parentElement).toBe(
// eslint-disable-next-line testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
screen.getByRole("definition").parentElement,
);
},
);
});
@@ -1,74 +0,0 @@
import type { FC } from "react";
import { Paper, SimpleGrid, Text, VisuallyHidden } from "@mantine/core";
import { useTranslation } from "react-i18next";
import type { Portfolio } from "@/entities/portfolio";
import { formatDecimal } from "@/shared/lib";
import classes from "../../AccountPage.module.css";
const SIGN_PREFIX_LENGTH = 2;
type CurrencyCardsProps = {
amounts: Portfolio["totalsByCurrency"];
};
const CurrencyCards: FC<CurrencyCardsProps> = (props) => {
const { t } = useTranslation();
const { amounts } = props;
const currencies: Record<string, { name: string; symbol: string }> = {
EUR: { name: t("portfolio.currencies.EUR"), symbol: "€" },
RUB: { name: t("portfolio.currencies.RUB"), symbol: "₽" },
USD: { name: t("portfolio.currencies.USD"), symbol: "$" },
};
return (
<SimpleGrid cols={{ base: 1, md: 3, sm: 2 }} spacing={10}>
{amounts.map((money) => {
const amount = formatDecimal(money.value);
return (
<Paper
className={classes.total}
component="dl"
key={money.currency}
m={0}
withBorder
>
<Text className={classes.totalBadge} component="dt">
<span aria-hidden="true">
{currencies[money.currency]?.symbol ?? money.currency}
</span>
<VisuallyHidden>
{currencies[money.currency]?.name ?? money.currency}
</VisuallyHidden>
</Text>
<Text className={classes.totalAmount} component="dd" m={0}>
{amount.startsWith("-")
? (
<>
<span className={classes.totalLeadingDigits}>
{amount.slice(0, SIGN_PREFIX_LENGTH)}
</span>
{amount.slice(SIGN_PREFIX_LENGTH)}
</>
)
: (
amount
)}{" "}
{currencies[money.currency]?.symbol ?? money.currency}
</Text>
</Paper>
);
})}
</SimpleGrid>
);
};
export { CurrencyCards };
@@ -64,16 +64,14 @@ const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
return (
<Stack gap="xs">
{props.summary.totalsByCurrency.map(total => (
<Paper key={total.currency} p="sm" withBorder>
<Text fw={700}>{formatMoney(total.total)}</Text>
<Paper p="sm" withBorder>
<Text fw={700}>{formatMoney(props.summary.total.total)}</Text>
<Text c="dimmed" size="sm">
{t("income.coupon")}: {formatMoney(total.coupon)} ·{" "}
{t("income.dividend")}: {formatMoney(total.dividend)}
</Text>
</Paper>
))}
<Text c="dimmed" size="sm">
{t("income.coupon")}: {formatMoney(props.summary.total.coupon)} ·{" "}
{t("income.dividend")}: {formatMoney(props.summary.total.dividend)}
</Text>
</Paper>
<Button component={Link} to={props.to} variant="subtle">
{props.moreLabel ?? t("income.open")}
@@ -99,7 +99,7 @@ export const Incomplete: Story = {
...data,
completeness: "incomplete",
excludedAccounts: [
{ accountId: "usd", name: "Валютный", reason: "NON_RUB_ACTIVITY" },
{ accountId: "usd", name: "Валютный", reason: "PORTFOLIO_VALUATION_INCOMPLETE" },
],
},
},
@@ -114,13 +114,13 @@ describe("PerformanceTab", () => {
renderTab({
data: performance({
completeness: "incomplete",
excludedAccounts: [{ accountId: "usd", name: "Валютный", reason: "NON_RUB_ACTIVITY" }],
excludedAccounts: [{ accountId: "usd", name: "Валютный", reason: "PORTFOLIO_VALUATION_INCOMPLETE" }],
}),
meta,
});
expect(await screen.findByText("Результат неполный")).toBeInTheDocument();
expect(screen.getByText("Валютный: Есть операции или позиции не в рублях")).toBeInTheDocument();
expect(screen.getByText("Валютный: Нет полной оценки портфеля")).toBeInTheDocument();
});
it("explains unavailability instead of showing zeros, including unknown reasons", async () => {
@@ -4,20 +4,20 @@ import type { Portfolio } from "@/entities/portfolio";
import { PortfolioStructure } from "./PortfolioStructure";
const rub: Portfolio["structure"]["currencies"][number] = {
const rub: Portfolio["structure"] = {
categories: [
{ sharePercent: "52", type: "STOCK", value: "650000" },
{ sharePercent: "30", type: "BOND", value: "375000" },
{ sharePercent: "10", type: "OTHER", value: "125000" },
{ sharePercent: "8", type: "CASH", value: "100000" },
],
currency: "RUB",
hasNegativeValues: false,
totalValue: "1250000",
unvaluedCategories: [],
};
const meta = {
args: { structure: { currencies: [rub], unvaluedCategories: [] } },
args: { structure: rub },
component: PortfolioStructure,
parameters: {
docs: {
@@ -36,60 +36,34 @@ export default meta;
type Story = StoryObj<typeof meta>;
export const Regular: Story = {};
export const MultipleCurrencies: Story = {
args: {
structure: {
currencies: [
rub,
{
categories: [{ sharePercent: "100", type: "CASH", value: "500" }],
currency: "USD",
hasNegativeValues: false,
totalValue: "500",
},
],
unvaluedCategories: [],
},
},
};
export const CashOnly: Story = {
args: {
structure: {
currencies: [
{
categories: rub.categories.map(row => ({
...row,
sharePercent: row.type === "CASH" ? "100" : "0",
value: row.type === "CASH" ? "100000" : "0",
})),
currency: "RUB",
hasNegativeValues: false,
totalValue: "100000",
},
],
unvaluedCategories: [],
...rub,
categories: rub.categories.map(row => ({
...row,
sharePercent: row.type === "CASH" ? "100" : "0",
value: row.type === "CASH" ? "100000" : "0",
})),
totalValue: "100000",
},
},
};
export const Empty: Story = {
args: { structure: { currencies: [], unvaluedCategories: [] } },
args: {
structure: {
categories: [],
hasNegativeValues: false,
totalValue: "0",
unvaluedCategories: [],
},
},
};
export const Incomplete: Story = {
args: {
structure: {
currencies: [
{
...rub,
categories: rub.categories.map(
row =>
({
...row,
sharePercent: null,
}),
),
},
],
...rub,
categories: rub.categories.map(row => ({ ...row, sharePercent: null })),
unvaluedCategories: [{ count: 2, type: "STOCK" }],
},
},
@@ -97,7 +71,9 @@ export const Incomplete: Story = {
export const UnknownOnly: Story = {
args: {
structure: {
currencies: [],
categories: [],
hasNegativeValues: false,
totalValue: "0",
unvaluedCategories: [{ count: 1, type: "BOND" }],
},
},
@@ -105,23 +81,14 @@ export const UnknownOnly: Story = {
export const Negative: Story = {
args: {
structure: {
currencies: [
{
...rub,
categories: rub.categories.map(
row =>
({
...row,
sharePercent: null,
value: row.type === "OTHER" ? "25000" : row.value,
}),
),
hasNegativeValues: true,
totalValue: "1150000",
},
],
unvaluedCategories: [],
...rub,
categories: rub.categories.map(row => ({
...row,
sharePercent: null,
value: row.type === "OTHER" ? "25000" : row.value,
})),
hasNegativeValues: true,
totalValue: "1150000",
},
},
};
@@ -1,21 +1,21 @@
import { MantineProvider } from "@mantine/core";
import { fireEvent, render, screen, within } from "@testing-library/react";
import { 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] = {
const rub: Portfolio["structure"] = {
categories: [
{ sharePercent: "60", type: "STOCK", value: "60" },
{ sharePercent: "20", type: "BOND", value: "20" },
{ sharePercent: "0", type: "OTHER", value: "0" },
{ sharePercent: "20", type: "CASH", value: "20" },
],
currency: "RUB",
hasNegativeValues: false,
totalValue: "100",
unvaluedCategories: [],
};
const ui = (structure: null | Portfolio["structure"] | undefined) => (
@@ -39,7 +39,7 @@ describe("portfolio structure", () => {
screen.queryByText(/Нет положительной стоимости/),
).not.toBeInTheDocument();
expect(screen.queryByRole("list")).not.toBeInTheDocument();
view.rerender(ui({ currencies: [rub], unvaluedCategories: [] }));
view.rerender(ui(rub));
expect(screen.getByRole("list")).toHaveTextContent("Акции60 ₽60 %");
expect(
screen.queryByText("Данные о структуре портфеля пока недоступны."),
@@ -47,41 +47,23 @@ describe("portfolio structure", () => {
},
);
it("shows exact server amounts and cash-inclusive shares without hovering", () => {
render(ui({ currencies: [rub], unvaluedCategories: [] }));
render(ui(rub));
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 $");
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,
}),
),
},
],
...rub,
categories: rub.categories.map(
row =>
({
...row,
sharePercent: null,
}),
),
unvaluedCategories: [
{ count: 2, type: "OTHER" },
{ count: 1, type: "STOCK" },
@@ -89,10 +71,8 @@ describe("portfolio structure", () => {
}),
);
expect(screen.getByText(/Оценка неполная/)).toBeInTheDocument();
expect(screen.getByRole("list")).toHaveTextContent("Известно: 60 ₽");
expect(screen.getByRole("list")).toHaveTextContent(
"Другие активыНет оценки",
);
expect(screen.getByRole("list")).toHaveTextContent("АкцииИзвестно: 60 ₽");
expect(screen.getByRole("list")).toHaveTextContent("Другие активы");
expect(
screen.queryByLabelText(/Структура по типам/),
).not.toBeInTheDocument();
@@ -100,22 +80,16 @@ describe("portfolio structure", () => {
it("keeps negative amounts visible without a donut or invented positive shares", () => {
render(
ui({
currencies: [
{
...rub,
categories: rub.categories.map(
row =>
({
...row,
sharePercent: null,
value: row.type === "STOCK" ? "-60" : row.value,
}),
),
hasNegativeValues: true,
},
],
unvaluedCategories: [],
...rub,
categories: rub.categories.map(
row =>
({
...row,
sharePercent: null,
value: row.type === "STOCK" ? "-60" : row.value,
}),
),
hasNegativeValues: true,
}),
);
expect(screen.getByText(/Есть отрицательные/)).toBeInTheDocument();
@@ -128,31 +102,30 @@ describe("portfolio structure", () => {
).not.toBeInTheDocument();
});
it("handles unknown-only and empty compositions", () => {
const view = render(
ui({ currencies: [], unvaluedCategories: [{ count: 1, type: "BOND" }] }),
render(
ui({
categories: [],
hasNegativeValues: false,
totalValue: "0",
unvaluedCategories: [{ count: 1, type: "BOND" }],
}),
);
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: [
{
...rub,
categories: [
{
sharePercent: "0.000001",
type: "CASH",
value: "9007199254740993.000000001",
},
],
sharePercent: "0.000001",
type: "CASH",
value: "9007199254740993.000000001",
},
],
unvaluedCategories: [],
totalValue: "9007199254740993.000000001",
}),
);
expect(screen.getByRole("list")).toHaveTextContent(
@@ -1,5 +1,5 @@
import { DonutChart } from "@mantine/charts";
import { Box, Group, Paper, Select, Stack, Text, Title } from "@mantine/core";
import { Box, Group, Paper, Stack, Text, Title } from "@mantine/core";
import { type FC, useId } from "react";
import { useTranslation } from "react-i18next";
@@ -7,11 +7,8 @@ import classes from "./PortfolioStructure.module.css";
type PortfolioStructureViewProps = {
chartData: StructureRow[];
currencies: string[];
currency: null | string;
incomplete: boolean;
negative: boolean;
onCurrencyChange: (currency: null | string) => void;
rows: StructureRow[];
unavailable: boolean;
unvalued: string[];
@@ -64,17 +61,6 @@ const PortfolioStructureView: FC<PortfolioStructureViewProps> = (props) => {
<Title id={titleId} order={2} size="h4">
{t("portfolio.structure.title")}
</Title>
{props.currencies.length > 1 && (
<Select
allowDeselect={false}
aria-label={t("portfolio.structure.currency")}
data={props.currencies}
onChange={props.onCurrencyChange}
value={props.currency}
w={112}
/>
)}
</Group>
<Text c="dimmed" size="sm">
@@ -110,11 +96,11 @@ const PortfolioStructureView: FC<PortfolioStructureViewProps> = (props) => {
</Text>
)}
<div className={appearanceClass} key={props.currency}>
<div className={appearanceClass}>
{props.chartData.length > 0 && (
<DonutChart
aria-label={t("portfolio.structure.chartLabel")}
chartLabel={props.currency ?? undefined}
chartLabel="₽"
data={props.chartData}
endAngle={-270}
pieChartProps={{ title: t("portfolio.structure.chartLabel") }}
@@ -1,6 +1,5 @@
import type { TFunction } from "i18next";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import type { Portfolio } from "@/entities/portfolio";
@@ -15,24 +14,15 @@ type PortfolioStructureProps = { structure?: null | Portfolio["structure"] };
const usePortfolioStructureVm = (props: PortfolioStructureProps) => {
const { structure } = props;
const { t } = useTranslation();
const [currency, setCurrency] = useState<null | string>(null);
const selected
= structure?.currencies.find(item => item.currency === currency)
?? structure?.currencies[0];
const isIncomplete = (structure?.unvaluedCategories.length ?? 0) > 0;
const rows = portfolioRows(selected, structure, t);
const rows = portfolioRows(structure, t);
const chartData = rows.filter(row => row.value > 0);
return {
chartData,
currencies: structure?.currencies.map(item => item.currency) ?? [],
currency: selected?.currency ?? null,
incomplete: isIncomplete,
negative: selected?.hasNegativeValues ?? false,
onCurrencyChange: setCurrency,
negative: structure?.hasNegativeValues ?? false,
rows,
unavailable: !structure,
unvalued:
@@ -46,14 +36,12 @@ const usePortfolioStructureVm = (props: PortfolioStructureProps) => {
};
function portfolioRows(
selected:
NonNullable<Portfolio["structure"]>["currencies"][number] | undefined,
structure: PortfolioStructureProps["structure"],
t: TFunction,
) {
if (!selected) return [];
if (!structure) return [];
return selected.categories.map((category) => {
return structure.categories.map((category) => {
const presentation = portfolioCategoryPresentation[category.type];
const percentage
@@ -61,16 +49,13 @@ function portfolioRows(
? undefined
: Number(category.sharePercent);
const unknown = structure?.unvaluedCategories.some(
const isUnknown = structure.unvaluedCategories.some(
item => item.type === category.type,
);
let amount = formatMoney({
currency: selected.currency,
value: category.value,
});
let amount = formatMoney({ currency: "RUB", value: category.value });
if (unknown) {
if (isUnknown) {
amount
= category.value === "0"
? t("portfolio.structure.unvalued")