Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2b94a16ae5 | ||
|
|
e2062ce837 |
@@ -55,12 +55,12 @@ const position: Portfolio["positions"][number]
|
||||
};
|
||||
|
||||
const portfolio: Portfolio = {
|
||||
cashBalances: [],
|
||||
cash: { currency: "RUB", value: "0" },
|
||||
isStale: false,
|
||||
lastSuccessfulAt: "2026-08-15T12:00:00Z",
|
||||
positions: accounts.map(account => ({ ...position, account })),
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
totalsByCurrency: [{ currency: "RUB", value: "1200" }],
|
||||
structure: { categories: [], hasNegativeValues: false, totalValue: "0", unvaluedCategories: [] },
|
||||
totals: { currency: "RUB", value: "1200" },
|
||||
};
|
||||
|
||||
const receipt: BrokerageOperation
|
||||
@@ -106,14 +106,11 @@ const analytics: IncomeAnalytics
|
||||
},
|
||||
],
|
||||
period: { from: "2026-08-01", to: "2026-08-31" },
|
||||
totalsByCurrency: [
|
||||
{
|
||||
total: {
|
||||
coupon: { currency: "RUB", value: "2" },
|
||||
currency: "RUB",
|
||||
dividend: { currency: "RUB", value: "0" },
|
||||
total: { currency: "RUB", value: "2" },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const CurrentLocation: FC = () => {
|
||||
@@ -216,7 +213,7 @@ beforeEach(() => {
|
||||
type: "coupon",
|
||||
}),
|
||||
),
|
||||
incomeTotalsByCurrency: [],
|
||||
incomeTotal: { currency: "RUB", value: "0" },
|
||||
window: { from: "2026-09-01", to: "2026-10-01" },
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -66,7 +66,7 @@ const OperationGroup: FC<OperationGroupProps> = (props) => {
|
||||
|
||||
const totalsText = totalText(totals, true);
|
||||
|
||||
const totalTone = isCoupon && totals?.length && totals.every(total => !isZeroDecimal(total.value) && !total.value.startsWith("-"))
|
||||
const totalTone = isCoupon && totals && !isZeroDecimal(totals.value) && !totals.value.startsWith("-")
|
||||
? "positive"
|
||||
: "neutral";
|
||||
|
||||
|
||||
@@ -4,8 +4,6 @@ import type {
|
||||
BrokerageAccount,
|
||||
} from "../api/useBrokerageAccounts";
|
||||
|
||||
const VISIBLE_CURRENCY_LIMIT = 2;
|
||||
|
||||
type BrokerageAccountCard = {
|
||||
account: BrokerageAccount;
|
||||
positionCounts: null | PositionCounts;
|
||||
@@ -13,18 +11,13 @@ type BrokerageAccountCard = {
|
||||
summary:
|
||||
| {
|
||||
portfolio: NonNullable<BrokerageAccount["portfolioSummary"]>;
|
||||
remainingCurrencyCount: number;
|
||||
state: "available";
|
||||
totals: Money[];
|
||||
totals: NonNullable<BrokerageAccount["portfolioSummary"]>["totals"];
|
||||
}
|
||||
| { state: "empty" }
|
||||
| { state: "unavailable" };
|
||||
};
|
||||
|
||||
type Money = NonNullable<
|
||||
BrokerageAccount["portfolioSummary"]
|
||||
>["totalsByCurrency"][number];
|
||||
|
||||
type PositionCounts = { bonds: number; stocks: number; total: number };
|
||||
|
||||
function accountTypeKey(type: BrokerageAccount["type"]) {
|
||||
@@ -57,7 +50,7 @@ function brokerageAccountCards(
|
||||
total: summary.totalPositionCount,
|
||||
};
|
||||
|
||||
if (summary.totalsByCurrency.length === 0)
|
||||
if (Number(summary.totals.value) === 0)
|
||||
return { account, positionCounts, source, summary: { state: "empty" } };
|
||||
|
||||
return {
|
||||
@@ -66,12 +59,8 @@ function brokerageAccountCards(
|
||||
source,
|
||||
summary: {
|
||||
portfolio: summary,
|
||||
remainingCurrencyCount: Math.max(
|
||||
summary.totalsByCurrency.length - VISIBLE_CURRENCY_LIMIT,
|
||||
0,
|
||||
),
|
||||
state: "available",
|
||||
totals: summary.totalsByCurrency.slice(0, VISIBLE_CURRENCY_LIMIT),
|
||||
totals: summary.totals,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
+17
-53
@@ -14,36 +14,29 @@ type PortfolioSummary = NonNullable<BrokerageAccount["portfolioSummary"]>;
|
||||
const rubReturn = {
|
||||
absolute: "136900",
|
||||
costBasis: "1103600.50",
|
||||
currency: "RUB",
|
||||
partial: false,
|
||||
percent: "12.40",
|
||||
};
|
||||
|
||||
const portfolioSummary = {
|
||||
bondPositionCount: 12,
|
||||
cashBalances: [
|
||||
{ currency: "RUB", value: "82500.50" },
|
||||
{ currency: "USD", value: "1500" },
|
||||
],
|
||||
cash: { currency: "RUB", value: "82500.50" },
|
||||
fundPositionCount: 2,
|
||||
stockPositionCount: 5,
|
||||
structure: {
|
||||
currencies: [{
|
||||
categories: [
|
||||
{ sharePercent: "55.000000", type: "STOCK", value: "682500" },
|
||||
{ sharePercent: "25.000000", type: "BOND", value: "310500" },
|
||||
{ sharePercent: "10.000000", type: "OTHER", value: "124200" },
|
||||
{ sharePercent: "10.000000", type: "CASH", value: "124200" },
|
||||
],
|
||||
currency: "RUB",
|
||||
hasNegativeValues: false,
|
||||
totalValue: "1241400",
|
||||
}],
|
||||
unvaluedCategories: [],
|
||||
},
|
||||
totalPositionCount: 19,
|
||||
totalsByCurrency: [{ currency: "RUB", value: "1240500.50" }],
|
||||
unrealizedReturnByCurrency: [rubReturn],
|
||||
totals: { currency: "RUB", value: "1240500.50" },
|
||||
unrealizedReturn: rubReturn,
|
||||
} satisfies PortfolioSummary;
|
||||
|
||||
function account(
|
||||
@@ -63,20 +56,25 @@ function account(
|
||||
|
||||
const negativeSummary: PortfolioSummary = {
|
||||
...portfolioSummary,
|
||||
unrealizedReturnByCurrency: [{
|
||||
unrealizedReturn: {
|
||||
...rubReturn,
|
||||
absolute: "-4200",
|
||||
percent: "-3.05",
|
||||
}],
|
||||
},
|
||||
};
|
||||
|
||||
const emptySummary: PortfolioSummary = {
|
||||
...portfolioSummary,
|
||||
cashBalances: [],
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
cash: { currency: "RUB", value: "0" },
|
||||
structure: {
|
||||
categories: [],
|
||||
hasNegativeValues: false,
|
||||
totalValue: "0",
|
||||
unvaluedCategories: [],
|
||||
},
|
||||
totalPositionCount: 0,
|
||||
totalsByCurrency: [],
|
||||
unrealizedReturnByCurrency: [],
|
||||
totals: { currency: "RUB", value: "0" },
|
||||
unrealizedReturn: rubReturn,
|
||||
};
|
||||
|
||||
const meta = {
|
||||
@@ -94,7 +92,7 @@ const meta = {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
"Карточки счетов: стоимость и доходность по валютам, деньги, структура и свежесть источника. Денежные и процентные значения остаются строками. Все примеры содержат вымышленные данные; ссылки работают только внутри MemoryRouter.",
|
||||
"Карточки счетов: стоимость и доходность, деньги, структура и свежесть источника. Денежные и процентные значения остаются строками. Все примеры содержат вымышленные данные; ссылки работают только внутри MemoryRouter.",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -108,40 +106,6 @@ type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Normal: Story = {};
|
||||
|
||||
export const MultiCurrency: Story = {
|
||||
args: {
|
||||
accounts: brokerageAccountCards([account("multi", "Мультивалютный", {
|
||||
...portfolioSummary,
|
||||
cashBalances: [
|
||||
{ currency: "RUB", value: "82500.50" },
|
||||
{ currency: "USD", value: "1500" },
|
||||
],
|
||||
totalsByCurrency: [
|
||||
{ currency: "RUB", value: "1240500.50" },
|
||||
{ currency: "USD", value: "3200" },
|
||||
{ currency: "EUR", value: "900" },
|
||||
],
|
||||
unrealizedReturnByCurrency: [
|
||||
...portfolioSummary.unrealizedReturnByCurrency,
|
||||
{
|
||||
absolute: "20",
|
||||
costBasis: "3180",
|
||||
currency: "USD",
|
||||
partial: false,
|
||||
percent: "2.10",
|
||||
},
|
||||
{
|
||||
absolute: "0",
|
||||
costBasis: "900",
|
||||
currency: "EUR",
|
||||
partial: false,
|
||||
percent: null,
|
||||
},
|
||||
],
|
||||
})]),
|
||||
},
|
||||
};
|
||||
|
||||
export const Negative: Story = {
|
||||
args: {
|
||||
accounts: brokerageAccountCards([
|
||||
@@ -154,10 +118,10 @@ export const Partial: Story = {
|
||||
args: {
|
||||
accounts: brokerageAccountCards([account("partial", "Частичные данные", {
|
||||
...portfolioSummary,
|
||||
unrealizedReturnByCurrency: [{
|
||||
unrealizedReturn: {
|
||||
...rubReturn,
|
||||
partial: true,
|
||||
}],
|
||||
},
|
||||
})]),
|
||||
},
|
||||
};
|
||||
|
||||
+21
-46
@@ -14,55 +14,28 @@ type PortfolioSummary = NonNullable<BrokerageAccount["portfolioSummary"]>;
|
||||
|
||||
const portfolioSummary = {
|
||||
bondPositionCount: 12,
|
||||
cashBalances: [
|
||||
{ currency: "RUB", value: "82500.5" },
|
||||
{ currency: "USD", value: "20" },
|
||||
],
|
||||
cash: { currency: "RUB", value: "82500.5" },
|
||||
fundPositionCount: 0,
|
||||
stockPositionCount: 5,
|
||||
structure: {
|
||||
currencies: [{
|
||||
categories: [
|
||||
{ sharePercent: "50.000000", type: "STOCK", value: "100" },
|
||||
{ sharePercent: "30.000000", type: "BOND", value: "60" },
|
||||
{ sharePercent: "0.000000", type: "OTHER", value: "0" },
|
||||
{ sharePercent: "20.000000", type: "CASH", value: "40" },
|
||||
],
|
||||
currency: "RUB",
|
||||
hasNegativeValues: false,
|
||||
totalValue: "200",
|
||||
}],
|
||||
unvaluedCategories: [],
|
||||
},
|
||||
totalPositionCount: 17,
|
||||
totalsByCurrency: [
|
||||
{ currency: "RUB", value: "123456789012345678901.995" },
|
||||
{ currency: "USD", value: "20" },
|
||||
{ currency: "EUR", value: "5" },
|
||||
],
|
||||
unrealizedReturnByCurrency: [
|
||||
{
|
||||
totals: { currency: "RUB", value: "123456789012345678901.995" },
|
||||
unrealizedReturn: {
|
||||
absolute: "136900",
|
||||
costBasis: "1000000",
|
||||
currency: "RUB",
|
||||
partial: true,
|
||||
percent: "12.40",
|
||||
},
|
||||
{
|
||||
absolute: "-4.2",
|
||||
costBasis: "24.2",
|
||||
currency: "USD",
|
||||
partial: false,
|
||||
percent: "-3.05",
|
||||
},
|
||||
{
|
||||
absolute: "0",
|
||||
costBasis: "5",
|
||||
currency: "EUR",
|
||||
partial: false,
|
||||
percent: null,
|
||||
},
|
||||
],
|
||||
} satisfies PortfolioSummary;
|
||||
|
||||
type BrokerageAccountCardInput = Parameters<typeof BrokerageAccountList>[0][
|
||||
@@ -97,16 +70,19 @@ describe("BrokerageAccountList", () => {
|
||||
it("renders returns, cash and structure with precise totals", () => {
|
||||
const nullReturnSummary: PortfolioSummary = {
|
||||
...portfolioSummary,
|
||||
cashBalances: [],
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
totalsByCurrency: [{ currency: "EUR", value: "5" }],
|
||||
unrealizedReturnByCurrency: [{
|
||||
structure: {
|
||||
categories: [],
|
||||
hasNegativeValues: false,
|
||||
totalValue: "0",
|
||||
unvaluedCategories: [],
|
||||
},
|
||||
totals: { currency: "RUB", value: "5" },
|
||||
unrealizedReturn: {
|
||||
absolute: "0",
|
||||
costBasis: "5",
|
||||
currency: "EUR",
|
||||
partial: false,
|
||||
percent: null,
|
||||
}],
|
||||
},
|
||||
};
|
||||
|
||||
renderList(brokerageAccountCards([
|
||||
@@ -118,19 +94,15 @@ describe("BrokerageAccountList", () => {
|
||||
expect(link).toHaveAttribute("href", "/accounts/account-1");
|
||||
expect(within(link).getByText("123 456 789 012 345 678 902,00 ₽"))
|
||||
.toBeInTheDocument();
|
||||
expect(within(link).getByText("Еще 1 валюта")).toBeInTheDocument();
|
||||
expect(within(link).getByText("+12,4 %")).toBeInTheDocument();
|
||||
expect(within(link).getByText("+136 900 ₽")).toBeInTheDocument();
|
||||
expect(within(link).getByText("−3,1 %")).toBeInTheDocument();
|
||||
expect(within(link).getByText("−4,2 $")).toBeInTheDocument();
|
||||
const nullReturnLink = screen.getByRole("link", { name: /Без доходности/ });
|
||||
expect(within(nullReturnLink).getByText("—")).toBeInTheDocument();
|
||||
expect(within(link).getByText("частично")).toBeInTheDocument();
|
||||
expect(within(link).getByText("82 500,50 ₽")).toBeInTheDocument();
|
||||
expect(within(link).getAllByText("20,00 $")).not.toHaveLength(0);
|
||||
expect(within(link).getByText("17 позиций")).toBeInTheDocument();
|
||||
expect(screen.getByRole("img", {
|
||||
name: "Структура в RUB: Акции 50,0 %; Облигации 30,0 %; "
|
||||
name: "Структура: Акции 50,0 %; Облигации 30,0 %; "
|
||||
+ "Другие активы 0,0 %; Свободные деньги 20,0 %",
|
||||
})).toBeInTheDocument();
|
||||
const stockLegend = within(link).getByText(/Акции 50,0 %/);
|
||||
@@ -140,17 +112,20 @@ describe("BrokerageAccountList", () => {
|
||||
expect(within(link).queryByText(/Другие активы 0,0 %/))
|
||||
.not.toBeInTheDocument();
|
||||
expect(link).toHaveTextContent("По данным брокера");
|
||||
expect(link).toHaveTextContent("Структура RUB: Акции 100");
|
||||
expect(link).toHaveTextContent("Структура: Акции 100");
|
||||
});
|
||||
|
||||
it("preserves empty, unavailable and stale states", () => {
|
||||
const emptySummary: PortfolioSummary = {
|
||||
...portfolioSummary,
|
||||
cashBalances: [],
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
structure: {
|
||||
categories: [],
|
||||
hasNegativeValues: false,
|
||||
totalValue: "0",
|
||||
unvaluedCategories: [],
|
||||
},
|
||||
totalPositionCount: 0,
|
||||
totalsByCurrency: [],
|
||||
unrealizedReturnByCurrency: [],
|
||||
totals: { currency: "RUB", value: "0" },
|
||||
};
|
||||
|
||||
const cards = brokerageAccountCards([
|
||||
|
||||
@@ -34,10 +34,10 @@ type BrokerageAccountSummaryProps = {
|
||||
type PortfolioSummary = AvailableSummary["portfolio"];
|
||||
|
||||
type ReturnValueProps = {
|
||||
item: PortfolioSummary["unrealizedReturnByCurrency"][number];
|
||||
item: PortfolioSummary["unrealizedReturn"];
|
||||
};
|
||||
|
||||
type StructureCurrency = PortfolioSummary["structure"]["currencies"][number];
|
||||
type StructureCurrency = PortfolioSummary["structure"];
|
||||
|
||||
function formatPercent(value: null | string) {
|
||||
if (value === null) return "—";
|
||||
@@ -81,7 +81,7 @@ const ReturnValue: FC<ReturnValueProps> = (props) => {
|
||||
|
||||
<Text className={toneClass} size="sm">
|
||||
{formatMoney(
|
||||
{ currency: item.currency, value: item.absolute },
|
||||
{ currency: "RUB", value: item.absolute },
|
||||
{ withSign: true },
|
||||
)}
|
||||
</Text>
|
||||
@@ -119,7 +119,6 @@ const StructureBar: FC<StructureBarProps> = (props) => {
|
||||
}).join("; ");
|
||||
|
||||
const label = t("accounts.structure.label", {
|
||||
currency: props.item.currency,
|
||||
value: description,
|
||||
});
|
||||
|
||||
@@ -197,50 +196,24 @@ const BrokerageAccountSummary: FC<BrokerageAccountSummaryProps> = (props) => {
|
||||
return (
|
||||
<Stack className={classes.balance} gap="xs">
|
||||
<Stack className={classes.summary} gap="sm">
|
||||
{summary.totals.map((total) => {
|
||||
const item = summary.portfolio.unrealizedReturnByCurrency.find(
|
||||
returnItem => returnItem.currency === total.currency,
|
||||
);
|
||||
|
||||
return (
|
||||
<Stack
|
||||
className={classes.currencySummary}
|
||||
gap={2}
|
||||
key={total.currency}
|
||||
>
|
||||
<Stack className={classes.currencySummary} gap={2}>
|
||||
<Text className={classes.total} fw={700}>
|
||||
{formatMoney(total, { withRoundedCents: true })}
|
||||
{formatMoney(summary.totals, { withRoundedCents: true })}
|
||||
</Text>
|
||||
|
||||
{item && <ReturnValue item={item} />}
|
||||
<ReturnValue item={summary.portfolio.unrealizedReturn} />
|
||||
</Stack>
|
||||
);
|
||||
})}
|
||||
|
||||
{!!summary.remainingCurrencyCount && (
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("accounts.remainingCurrencies", {
|
||||
count: summary.remainingCurrencyCount,
|
||||
})}
|
||||
</Text>
|
||||
)}
|
||||
</Stack>
|
||||
|
||||
{summary.portfolio.cashBalances.length > 0 && (
|
||||
<Group className={classes.cash} gap="xs" justify="flex-end">
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("accounts.cash")}
|
||||
</Text>
|
||||
|
||||
<Stack gap={0}>
|
||||
{summary.portfolio.cashBalances.map(cash => (
|
||||
<Text className={classes.cashValue} key={cash.currency} size="sm">
|
||||
{formatMoney(cash, { withRoundedCents: true })}
|
||||
<Text className={classes.cashValue} size="sm">
|
||||
{formatMoney(summary.portfolio.cash, { withRoundedCents: true })}
|
||||
</Text>
|
||||
))}
|
||||
</Stack>
|
||||
</Group>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
@@ -287,39 +260,31 @@ const AccountDescription: FC<AccountDescriptionProps> = (props) => {
|
||||
const { account, summary } = props.account;
|
||||
if (summary.state !== "available") return null;
|
||||
|
||||
const returns = summary.portfolio.unrealizedReturnByCurrency.map(item =>
|
||||
t("accounts.description.return", {
|
||||
const returns = [t("accounts.description.return", {
|
||||
absolute: formatMoney(
|
||||
{ currency: item.currency, value: item.absolute },
|
||||
{ currency: "RUB", value: summary.portfolio.unrealizedReturn.absolute },
|
||||
{ withSign: true },
|
||||
),
|
||||
currency: item.currency,
|
||||
percent: formatPercent(item.percent),
|
||||
}),
|
||||
);
|
||||
percent: formatPercent(summary.portfolio.unrealizedReturn.percent),
|
||||
})];
|
||||
|
||||
const structures = summary.portfolio.structure.currencies.map((item) => {
|
||||
const categories = item.categories.map(category =>
|
||||
const structures = (() => {
|
||||
const categories = summary.portfolio.structure.categories.map(category =>
|
||||
t("accounts.description.structureCategory", {
|
||||
category: t(portfolioCategoryPresentation[category.type].label),
|
||||
value: formatMoney(
|
||||
{ currency: item.currency, value: category.value },
|
||||
{ currency: "RUB", value: category.value },
|
||||
{ withRoundedCents: true },
|
||||
),
|
||||
}),
|
||||
).join(", ");
|
||||
|
||||
return t("accounts.description.structure", {
|
||||
currency: item.currency,
|
||||
value: categories,
|
||||
});
|
||||
});
|
||||
return t("accounts.description.structure", { value: categories });
|
||||
})();
|
||||
|
||||
const hasPartialReturn = summary.portfolio.unrealizedReturnByCurrency.some(
|
||||
item => item.partial,
|
||||
);
|
||||
const hasPartialReturn = summary.portfolio.unrealizedReturn.partial;
|
||||
|
||||
const details = [...returns, ...structures].join(". ");
|
||||
const details = [returns, structures].join(". ");
|
||||
|
||||
return (
|
||||
<VisuallyHidden>
|
||||
@@ -328,8 +293,7 @@ const AccountDescription: FC<AccountDescriptionProps> = (props) => {
|
||||
type: t(accountTypeKey(account.type)),
|
||||
})}
|
||||
{t("accounts.description.currentValue", {
|
||||
value: summary.portfolio.totalsByCurrency
|
||||
.map(total => formatMoney(total)).join(", "),
|
||||
value: formatMoney(summary.portfolio.totals),
|
||||
})}
|
||||
{details ? `${details}. ` : ""}
|
||||
{hasPartialReturn ? t("accounts.brokerDescription") : ""}
|
||||
@@ -369,9 +333,7 @@ const BrokerageAccountList: FC<BrokerageAccountListProps> = (props) => {
|
||||
|
||||
{summary.state === "available" && (
|
||||
<Stack className={classes.structure} gap={4}>
|
||||
{summary.portfolio.structure.currencies.map(item => (
|
||||
<StructureBar item={item} key={item.currency} />
|
||||
))}
|
||||
<StructureBar item={summary.portfolio.structure} />
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
|
||||
@@ -97,13 +97,13 @@ describe("BrokerageEventGroup", () => {
|
||||
expect(screen.getByText("0,00 ₽")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows separate forecast totals per currency without conversion", () => {
|
||||
it("sums forecast totals exactly", () => {
|
||||
renderGroup([
|
||||
event({ id: "broker", name: "Брокерский" }, "10", "USD"),
|
||||
event({ id: "broker", name: "Брокерский" }, "10"),
|
||||
event({ id: "iis", name: "ИИС" }, "200"),
|
||||
]);
|
||||
|
||||
expect(screen.getByRole("list", { name: /10 \$.*200 ₽/ }))
|
||||
expect(screen.getByRole("list", { name: /210 ₽/ }))
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { apiQueryClient, type paths, useAuthenticatedQuery } from "@/shared/api";
|
||||
|
||||
type Performance = NonNullable<
|
||||
paths["/api/v1/brokerage-accounts/{accountId}/performance"]["get"]["responses"][200]["content"]["application/json"]["data"]
|
||||
>;
|
||||
|
||||
function usePerformance(accountId: string) {
|
||||
return useAuthenticatedQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/brokerage-accounts/{accountId}/performance",
|
||||
{ params: { path: { accountId } } },
|
||||
),
|
||||
enabled: Boolean(accountId),
|
||||
staleTime: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
export { type Performance, usePerformance };
|
||||
@@ -0,0 +1 @@
|
||||
export { type Performance, usePerformance } from "./api/usePerformance";
|
||||
@@ -2,7 +2,7 @@ import type { Portfolio } from "../api/usePortfolio";
|
||||
|
||||
const PERCENT_SCALE = 100;
|
||||
|
||||
type Money = Portfolio["totalsByCurrency"][number];
|
||||
type Money = Portfolio["totals"];
|
||||
|
||||
function formatShare(
|
||||
numerator: Money | null,
|
||||
|
||||
@@ -19,7 +19,6 @@ function useInstrumentChartVm(props: InstrumentChartProps) {
|
||||
const average = vm.position?.averagePurchasePrice;
|
||||
|
||||
const averageLine = average && props.priceUnit !== "percent"
|
||||
&& average.currency === vm.candles?.currency
|
||||
? Number(average.value)
|
||||
: null;
|
||||
|
||||
@@ -47,7 +46,7 @@ function useInstrumentChartVm(props: InstrumentChartProps) {
|
||||
currency:
|
||||
props.priceUnit === "percent"
|
||||
? t("bond.percentOfNominal")
|
||||
: (vm.candles?.currency ?? ""),
|
||||
: "₽",
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ const meta = {
|
||||
},
|
||||
render: arguments_ => (
|
||||
<Stack>
|
||||
<Text>125 000,50 ₽ · 320 USD</Text>
|
||||
<Text>125 000,50 ₽</Text>
|
||||
|
||||
<InvestmentRefreshState {...arguments_} />
|
||||
</Stack>
|
||||
|
||||
@@ -263,7 +263,7 @@ describe("Upcoming event date filters", () => {
|
||||
accountId,
|
||||
calculatedAt: "2099-01-01T00:00:00Z",
|
||||
events: [],
|
||||
incomeTotalsByCurrency: [],
|
||||
incomeTotal: { currency: "RUB", value: "0" },
|
||||
window: { from: "2099-01-01", to: "2099-01-31" },
|
||||
}),
|
||||
);
|
||||
@@ -353,7 +353,7 @@ it("retains the previous complete forecast when its source refresh fails", async
|
||||
];
|
||||
|
||||
const snapshot = resource(
|
||||
{ events, incomeTotalsByCurrency: [{ currency: "RUB", value: "123.45" }] },
|
||||
{ events, incomeTotal: { currency: "RUB", value: "123.45" } },
|
||||
{
|
||||
lastAttempt: {
|
||||
finishedAt: "2026-08-14T00:01:00Z",
|
||||
|
||||
@@ -33,7 +33,7 @@ const snapshot = resource({
|
||||
type: "coupon",
|
||||
},
|
||||
],
|
||||
incomeTotalsByCurrency: [{ currency: "RUB", value: "123.45" }],
|
||||
incomeTotal: { currency: "RUB", value: "123.45" },
|
||||
window: { from: "2026-08-14", to: "2026-09-13" },
|
||||
});
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ const analytics
|
||||
buckets: [
|
||||
{
|
||||
period: { from: "2026-08-01", to: "2026-08-01" },
|
||||
totalsByCurrency: [summary("RUB", "10", "2")],
|
||||
total: summary("10", "2"),
|
||||
},
|
||||
],
|
||||
calculatedAt: "2026-08-27T00:00:00Z",
|
||||
@@ -77,7 +77,7 @@ const analytics
|
||||
},
|
||||
],
|
||||
period: { from: "2026-08-01", to: "2026-08-27" },
|
||||
totalsByCurrency: [summary("RUB", "10", "2")],
|
||||
total: summary("10", "2"),
|
||||
} satisfies IncomeAnalytics & { instruments: [unknown] };
|
||||
|
||||
function entry(): IncomeAnalytics["entries"][number] {
|
||||
@@ -145,12 +145,11 @@ function renderPage(
|
||||
return { ...view, queryClient };
|
||||
}
|
||||
|
||||
function summary(currency: string, coupon: string, dividend: string) {
|
||||
function summary(coupon: string, dividend: string) {
|
||||
return {
|
||||
coupon: money(currency, coupon),
|
||||
currency,
|
||||
dividend: money(currency, dividend),
|
||||
total: money(currency, String(Number(coupon) + Number(dividend))),
|
||||
coupon: money("RUB", coupon),
|
||||
dividend: money("RUB", dividend),
|
||||
total: money("RUB", String(Number(coupon) + Number(dividend))),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -308,7 +307,7 @@ describe("AccountIncomePage", () => {
|
||||
buckets: [],
|
||||
entries: [],
|
||||
instruments: [],
|
||||
totalsByCurrency: [],
|
||||
total: summary("0", "0"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -410,7 +409,7 @@ describe("AccountIncomePage", () => {
|
||||
|
||||
it.each([
|
||||
["full", analytics],
|
||||
["empty", { ...analytics, buckets: [], entries: [], instruments: [], totalsByCurrency: [] }],
|
||||
["empty", { ...analytics, buckets: [], entries: [], instruments: [], total: summary("0", "0") }],
|
||||
])("shows the server source time and last attempt for a %s result", async (_name, data) => {
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
|
||||
@@ -737,11 +736,11 @@ describe("income period and snapshot boundary", () => {
|
||||
const instruments = [
|
||||
{
|
||||
...analytics.instruments[0],
|
||||
coupon: money("USD", "10"),
|
||||
dividend: money("USD", "0"),
|
||||
key: "usd",
|
||||
coupon: money("RUB", "10"),
|
||||
dividend: money("RUB", "0"),
|
||||
key: "rub-positive",
|
||||
receiptCount: 1,
|
||||
total: money("USD", "10"),
|
||||
total: money("RUB", "10"),
|
||||
},
|
||||
{
|
||||
...analytics.instruments[0],
|
||||
@@ -770,7 +769,7 @@ describe("income period and snapshot boundary", () => {
|
||||
payment: instrument.total,
|
||||
})),
|
||||
instruments,
|
||||
totalsByCurrency: [summary("RUB", "-5", "0"), summary("USD", "10", "0")],
|
||||
total: summary("-5", "0"),
|
||||
});
|
||||
|
||||
render(
|
||||
@@ -782,10 +781,9 @@ describe("income period and snapshot boundary", () => {
|
||||
screen.getByRole("heading", { name: "Выплаты" }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByText("RUB")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("USD")).not.toBeInTheDocument();
|
||||
const cards = screen.getAllByRole("listitem");
|
||||
expect(cards).toHaveLength(3);
|
||||
expect(cards[0]).toHaveTextContent("+10 $");
|
||||
expect(cards[0]).toHaveTextContent("+10 ₽");
|
||||
expect(cards[1]).toHaveTextContent("−2 ₽");
|
||||
expect(cards[2]).toHaveTextContent("−3 ₽");
|
||||
expect(screen.queryByText(/Итого:|Выплат:/)).not.toBeInTheDocument();
|
||||
|
||||
+3
-8
@@ -5,7 +5,6 @@ import {
|
||||
Stack,
|
||||
Title,
|
||||
} from "@mantine/core";
|
||||
import { StateView } from "@wealthledger/ui";
|
||||
import { FormProvider } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@@ -25,13 +24,9 @@ const AccountIncomePageLoadedSummary: FC<LoadedProps> = (props) => {
|
||||
|
||||
const { analytics } = props;
|
||||
|
||||
if (props.partial) {
|
||||
return <Alert role="status">{t("investment.partial")}</Alert>;
|
||||
}
|
||||
|
||||
return analytics.totalsByCurrency.length > 0
|
||||
? <IncomeSummary totals={analytics.totalsByCurrency} />
|
||||
: <StateView text={t("income.emptyText")} title={t("income.emptyTitle")} />;
|
||||
return props.partial
|
||||
? <Alert role="status">{t("investment.partial")}</Alert>
|
||||
: <IncomeSummary totals={analytics.total} />;
|
||||
};
|
||||
|
||||
const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
|
||||
|
||||
@@ -7,7 +7,7 @@ import type { IncomeAnalytics } from "@/entities/income";
|
||||
|
||||
import { formatMoney } from "@/shared/lib";
|
||||
|
||||
type IncomeSummaryProps = { totals: IncomeAnalytics["totalsByCurrency"] };
|
||||
type IncomeSummaryProps = { totals: IncomeAnalytics["total"] };
|
||||
|
||||
const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
@@ -16,16 +16,14 @@ const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
|
||||
<Stack>
|
||||
<Title order={2}>{t("income.summaryTitle")}</Title>
|
||||
|
||||
{props.totals.map(total => (
|
||||
<Paper key={total.currency} p="md" radius="md" withBorder>
|
||||
<Text fw={700}>{formatMoney(total.total)}</Text>
|
||||
<Paper p="md" radius="md" withBorder>
|
||||
<Text fw={700}>{formatMoney(props.totals.total)}</Text>
|
||||
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("income.coupon")}: {formatMoney(total.coupon)} ·{" "}
|
||||
{t("income.dividend")}: {formatMoney(total.dividend)}
|
||||
{t("income.coupon")}: {formatMoney(props.totals.coupon)} ·{" "}
|
||||
{t("income.dividend")}: {formatMoney(props.totals.dividend)}
|
||||
</Text>
|
||||
</Paper>
|
||||
))}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -35,15 +35,13 @@ describe("account concentration", () => {
|
||||
const model = toConcentration(snapshot([
|
||||
stock("A", "1"), stock("B", "15"),
|
||||
stock("C", "0"), stock("D", "-50"), stock("E", null),
|
||||
stock("F", null, "USD"), stock("G", "-3", "USD"),
|
||||
]), "stocks", "RUB", labels);
|
||||
]), "stocks", labels);
|
||||
|
||||
expect(model.currencies).toEqual(["RUB", "USD"]);
|
||||
expect(model.total).toBe("16");
|
||||
expect(model.items.map(item => item.share)).toEqual(["93,8 %", "6,3 %"]);
|
||||
expect(model.unaccounted).toBe(3);
|
||||
const negative = snapshot([stock("A", "-3", "USD")]);
|
||||
expect(toConcentration(negative, "stocks", "USD", labels))
|
||||
expect(model.unaccounted).toBe(2);
|
||||
const negative = snapshot([stock("A", "-3")]);
|
||||
expect(toConcentration(negative, "stocks", labels))
|
||||
.toMatchObject({ empty: true, unaccounted: 1 });
|
||||
});
|
||||
|
||||
@@ -52,7 +50,7 @@ describe("account concentration", () => {
|
||||
stock("A", "400"), stock("B", "250"), stock("C", "150"),
|
||||
stock("D", "100"), stock("E", "50"), stock("F", "30"),
|
||||
stock("G", "20"),
|
||||
]), "stocks", "RUB", labels);
|
||||
]), "stocks", labels);
|
||||
|
||||
expect(model.items.map(item => item.amount)).toEqual([
|
||||
"400", "250", "150", "100", "50",
|
||||
@@ -71,7 +69,7 @@ describe("account concentration", () => {
|
||||
stock("Сбер", "100"), stock("X5", "100"),
|
||||
stock("VK", "100"), stock("D", "100"),
|
||||
stock("E", "100"), stock("F", "100"),
|
||||
]), "stocks", "RUB", labels);
|
||||
]), "stocks", labels);
|
||||
|
||||
expect(model.items).toHaveLength(6);
|
||||
expect(model.other).toBeNull();
|
||||
@@ -83,7 +81,7 @@ describe("account concentration", () => {
|
||||
stock("Large", "100000000"), stock("Small", "1"),
|
||||
]);
|
||||
|
||||
expect(toConcentration(tiny, "stocks", "RUB", labels).items[1]?.share)
|
||||
expect(toConcentration(tiny, "stocks", labels).items[1]?.share)
|
||||
.toBe("< 0,1 %");
|
||||
});
|
||||
|
||||
@@ -103,9 +101,9 @@ describe("account concentration", () => {
|
||||
stock("D", "50", "RUB", { issuer: null, sector: null }),
|
||||
];
|
||||
|
||||
expect(toConcentration(snapshot(positions), "sectors", "RUB", labels)
|
||||
expect(toConcentration(snapshot(positions), "sectors", labels)
|
||||
.items.map(item => item.amount)).toEqual(["500", "100", "50"]);
|
||||
expect(toConcentration(snapshot(positions), "issuers", "RUB", labels)
|
||||
expect(toConcentration(snapshot(positions), "issuers", labels)
|
||||
.items.map(item => [item.name, item.amount])).toEqual([
|
||||
["Сбербанк", "500"], ["", "50"],
|
||||
]);
|
||||
@@ -123,7 +121,7 @@ describe("account concentration", () => {
|
||||
stock("D", "100", "RUB", { issuer: null, sector: "energy" }),
|
||||
]);
|
||||
|
||||
expect(toConcentration(issuers, "issuers", "RUB", labels)
|
||||
expect(toConcentration(issuers, "issuers", labels)
|
||||
.items.map(item => [item.label, item.amount])).toEqual([
|
||||
["Газпром", "300"], ["Сбер", "300"], ["Эмитент не указан", "300"],
|
||||
]);
|
||||
@@ -140,7 +138,7 @@ describe("account concentration", () => {
|
||||
: "Энергетика",
|
||||
};
|
||||
|
||||
expect(toConcentration(sectors, "sectors", "RUB", sectorLabels)
|
||||
expect(toConcentration(sectors, "sectors", sectorLabels)
|
||||
.items.map(item => item.label))
|
||||
.toEqual(["Информационные технологии", "Энергетика"]);
|
||||
});
|
||||
@@ -158,7 +156,7 @@ describe("account concentration", () => {
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(toConcentration(data, "issuers", "RUB", labels).items
|
||||
expect(toConcentration(data, "issuers", labels).items
|
||||
.map(item => [item.name, item.label, item.amount])).toEqual([
|
||||
["Альфа", "Альфа", "400"], ["Бета", "Бета", "400"],
|
||||
]);
|
||||
@@ -169,7 +167,7 @@ describe("account concentration", () => {
|
||||
isin: "RU000A0JX0J2", ticker: "BOND", type: "BOND",
|
||||
})]);
|
||||
|
||||
expect(toConcentration(data, "bonds", "RUB", labels)
|
||||
expect(toConcentration(data, "bonds", labels)
|
||||
.items[0]?.logo?.subtitle).toBe("RU000A0JX0J2");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
} from "@/shared/lib";
|
||||
|
||||
type Concentration = {
|
||||
currencies: string[];
|
||||
empty: boolean;
|
||||
items: ConcentrationItem[];
|
||||
other: ConcentrationOther | null;
|
||||
@@ -83,11 +82,9 @@ function addPosition(
|
||||
index: number,
|
||||
slice: Slice,
|
||||
labels: ConcentrationLabels,
|
||||
selected: null | string,
|
||||
): number {
|
||||
if (!isIncluded(slice, position.type)) return 0;
|
||||
if (!position.currentValue) return 1;
|
||||
if (position.currentValue.currency !== selected) return 0;
|
||||
const value = decimalFromString(position.currentValue.value);
|
||||
if (value.value < 0n) return 1;
|
||||
if (value.value === 0n) return 0;
|
||||
@@ -135,16 +132,6 @@ function compareDecimal(a: Decimal, b: Decimal): number {
|
||||
return left < right ? -1 : 0;
|
||||
}
|
||||
|
||||
function concentrationCurrencies(portfolio: Portfolio): string[] {
|
||||
return [...new Set(portfolio.positions
|
||||
.filter(position => eligibleTypes.has(position.type))
|
||||
.filter(position => position.currentValue
|
||||
&& decimalFromString(position.currentValue.value).value !== 0n)
|
||||
.map(position => position.currentValue?.currency)
|
||||
.filter((value): value is string => !!value))]
|
||||
.toSorted((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
function groupIdentity(
|
||||
position: Position,
|
||||
slice: Slice,
|
||||
@@ -214,22 +201,13 @@ function share(part: Decimal, total: Decimal): string {
|
||||
function toConcentration(
|
||||
portfolio: Portfolio,
|
||||
slice: Slice,
|
||||
currency: null | string,
|
||||
labels: ConcentrationLabels,
|
||||
): Concentration {
|
||||
const currencies = concentrationCurrencies(portfolio);
|
||||
|
||||
const selected = currency && currencies.includes(currency)
|
||||
? currency
|
||||
: currencies[0] ?? null;
|
||||
|
||||
const groups = new Map<string, Group>();
|
||||
let unaccounted = 0;
|
||||
|
||||
for (const [index, position] of portfolio.positions.entries()) {
|
||||
unaccounted += addPosition(
|
||||
groups, position, index, slice, labels, selected,
|
||||
);
|
||||
unaccounted += addPosition(groups, position, index, slice, labels);
|
||||
}
|
||||
|
||||
const ranked = Array.from(groups.values(), group => ({
|
||||
@@ -278,7 +256,6 @@ function toConcentration(
|
||||
: null;
|
||||
|
||||
return {
|
||||
currencies,
|
||||
empty: !total,
|
||||
items: other ? entries.slice(0, TOP) : entries,
|
||||
other,
|
||||
@@ -289,7 +266,6 @@ function toConcentration(
|
||||
}
|
||||
|
||||
export {
|
||||
concentrationCurrencies,
|
||||
toConcentration,
|
||||
};
|
||||
export type {
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import type { Performance } from "@/entities/performance";
|
||||
|
||||
import { formatDate, formatMoney, formatPercentagePoints, formatSignedPercent } from "@/shared/lib";
|
||||
|
||||
type TextValue = { tone: Tone; value: string };
|
||||
|
||||
type Tone
|
||||
= | "negative"
|
||||
| "neutral"
|
||||
| "positive";
|
||||
|
||||
const reasonLabels: Record<string, string> = {
|
||||
ACCOUNT_VALUATION_DATES_DIFFER: "Оценки счетов сделаны в разные дни",
|
||||
AMBIGUOUS_RETURN: "У расчёта доходности несколько возможных решений",
|
||||
HISTORY_START_UNKNOWN: "Начало истории счёта неизвестно",
|
||||
INDEX_HISTORY_UNAVAILABLE: "История индекса временно недоступна",
|
||||
NO_SOLUTION: "Расчёт доходности не сходится",
|
||||
OPERATIONS_HISTORY_INCOMPLETE: "История операций ещё не получена полностью",
|
||||
PORTFOLIO_VALUATION_INCOMPLETE: "Нет полной оценки портфеля",
|
||||
UNCONFIRMED_TRANSFER: "Перевод между счетами не удалось подтвердить",
|
||||
UNVALUED_SECURITIES_TRANSFER: "Бумаги переведены без денежной оценки",
|
||||
};
|
||||
|
||||
const unknownReason = "Причину недоступности не удалось определить";
|
||||
|
||||
function performanceVm(data: Performance) {
|
||||
return {
|
||||
basis: data.return.basis,
|
||||
comparison: data.outperformance
|
||||
? {
|
||||
money: signedMoney(data.outperformance.money),
|
||||
points: valueText(
|
||||
data.outperformance.percentagePoints,
|
||||
formatPercentagePoints,
|
||||
),
|
||||
}
|
||||
: null,
|
||||
current: formatMoney(data.currentValue),
|
||||
currentPoint: data.series.length > 0
|
||||
? { date: formatDate(`${data.series.at(-1)?.date ?? data.period.to}T00:00:00Z`) }
|
||||
: null,
|
||||
days: data.period.days,
|
||||
excluded: data.excludedAccounts.map(item => ({
|
||||
id: item.accountId,
|
||||
name: item.name,
|
||||
reason: reasonText(item.reason),
|
||||
})),
|
||||
from: data.period.from,
|
||||
indexReason: data.benchmark.unavailableReason
|
||||
? reasonText(data.benchmark.unavailableReason)
|
||||
: null,
|
||||
indexReturn: valueText(data.benchmark.return.value, formatSignedPercent),
|
||||
indexValue: data.benchmark.value ? formatMoney(data.benchmark.value) : "—",
|
||||
invested: formatMoney(data.netInvested),
|
||||
profit: signedMoney(data.profit),
|
||||
returnReason: data.return.unavailableReason
|
||||
? reasonText(data.return.unavailableReason)
|
||||
: null,
|
||||
returnValue: valueText(data.return.value, formatSignedPercent),
|
||||
series: data.series.map(item => ({
|
||||
benchmarkValue: Number(item.benchmarkValue),
|
||||
date: item.date,
|
||||
label: formatDate(`${item.date}T00:00:00Z`),
|
||||
netInvested: Number(item.netInvested),
|
||||
referenceValue: item.referenceValue === null
|
||||
? null
|
||||
: Number(item.referenceValue),
|
||||
})),
|
||||
to: data.period.to,
|
||||
};
|
||||
}
|
||||
|
||||
function reasonText(reason: string): string {
|
||||
// eslint-disable-next-line security/detect-object-injection -- Lookup accepts only an API reason, with a safe fallback.
|
||||
return reasonLabels[reason] ?? unknownReason;
|
||||
}
|
||||
|
||||
function signedMoney(value: Performance["profit"]): TextValue {
|
||||
return {
|
||||
tone: tone(value.value),
|
||||
value: formatMoney(value, { withSign: true }),
|
||||
};
|
||||
}
|
||||
|
||||
function tone(value: string): Tone {
|
||||
const number = Number(value);
|
||||
if (number > 0) return "positive";
|
||||
|
||||
return number < 0 ? "negative" : "neutral";
|
||||
}
|
||||
|
||||
// Tone follows the displayed text, so "0,0 %" is never coloured.
|
||||
function valueText(
|
||||
value: null | string,
|
||||
format: (value: string) => string,
|
||||
): TextValue {
|
||||
if (value === null) return { tone: "neutral", value: "—" };
|
||||
const text = format(value);
|
||||
if (text.startsWith("+")) return { tone: "positive", value: text };
|
||||
|
||||
return { tone: text.startsWith("−") ? "negative" : "neutral", value: text };
|
||||
}
|
||||
|
||||
export { performanceVm, reasonText };
|
||||
@@ -2,7 +2,7 @@ import type { Portfolio } from "@/entities/portfolio";
|
||||
|
||||
const portfolio
|
||||
= {
|
||||
cashBalances: [{ currency: "USD", value: "1" }],
|
||||
cash: { currency: "RUB", value: "1" },
|
||||
isStale: true,
|
||||
lastSuccessfulAt: "2026-08-13T10:00:00Z",
|
||||
positions: [
|
||||
@@ -49,8 +49,13 @@ const portfolio
|
||||
type: "FUND",
|
||||
},
|
||||
] satisfies [Portfolio["positions"][number], ...Portfolio["positions"]],
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
totalsByCurrency: [{ currency: "RUB", value: "150" }],
|
||||
structure: {
|
||||
categories: [],
|
||||
hasNegativeValues: false,
|
||||
totalValue: "0",
|
||||
unvaluedCategories: [],
|
||||
},
|
||||
totals: { currency: "RUB", value: "150" },
|
||||
} satisfies Portfolio;
|
||||
|
||||
const position: Portfolio["positions"][number] = {
|
||||
|
||||
@@ -35,7 +35,7 @@ describe("account position sections", () => {
|
||||
|
||||
const snapshot: Portfolio = {
|
||||
...portfolio,
|
||||
cashBalances: [{ currency: "RUB", value: "1000" }],
|
||||
cash: { currency: "RUB", value: "1000" },
|
||||
positions: [
|
||||
...portfolio.positions,
|
||||
{
|
||||
@@ -56,8 +56,8 @@ describe("account position sections", () => {
|
||||
}),
|
||||
),
|
||||
],
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
totalsByCurrency: [{ currency: "RUB", value: "1250" }],
|
||||
structure: { categories: [], hasNegativeValues: false, totalValue: "0", unvaluedCategories: [] },
|
||||
totals: { currency: "RUB", value: "1250" },
|
||||
};
|
||||
|
||||
const original = structuredClone(snapshot);
|
||||
@@ -193,13 +193,13 @@ describe("account position sections", () => {
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("keeps currencies and purchase prices attached to their source positions", () => {
|
||||
it("keeps values and purchase prices attached to their source positions", () => {
|
||||
const source = [
|
||||
position,
|
||||
{
|
||||
...second,
|
||||
averagePurchasePrice: { currency: "USD", value: "0.99" },
|
||||
currentValue: { currency: "USD", value: "1.01" },
|
||||
averagePurchasePrice: { currency: "RUB", value: "0.99" },
|
||||
currentValue: { currency: "RUB", value: "1.01" },
|
||||
},
|
||||
];
|
||||
|
||||
@@ -264,10 +264,6 @@ describe("account position returns", () => {
|
||||
{ name: "zero quantity", overrides: { quantity: "0" } },
|
||||
{ name: "negative quantity", overrides: { quantity: "-1" } },
|
||||
{ name: "missing average price", overrides: { averagePurchasePrice: null } },
|
||||
{
|
||||
name: "currency mismatch",
|
||||
overrides: { averagePurchasePrice: { currency: "USD", value: "280" } },
|
||||
},
|
||||
{ name: "zero cost", overrides: { averagePurchasePrice: { currency: "RUB", value: "0" } } },
|
||||
])("returns null for $name", ({ overrides }) => {
|
||||
const result = sections([makePosition({
|
||||
@@ -301,29 +297,24 @@ describe("account position returns", () => {
|
||||
expect(formatPositionReturnPercent(testCase.value)).toBe(testCase.expected);
|
||||
});
|
||||
|
||||
it("sums complete unrealized returns by currency", () => {
|
||||
it("sums complete unrealized returns", () => {
|
||||
const result = toUnrealizedReturns([
|
||||
makePosition({ absoluteReturn: { currency: "RUB", value: "0.1" } }),
|
||||
makePosition({ absoluteReturn: { currency: "RUB", value: "0.2" } }),
|
||||
makePosition({ absoluteReturn: { currency: "USD", value: "-2.5" } }),
|
||||
]);
|
||||
|
||||
expect(result).toEqual([
|
||||
{ currency: "RUB", value: "0.3" },
|
||||
{ currency: "USD", value: "-2.5" },
|
||||
]);
|
||||
expect(result).toEqual({ currency: "RUB", value: "0.3" });
|
||||
});
|
||||
|
||||
it("omits only currencies with incomplete returns", () => {
|
||||
it("returns null when any return is incomplete", () => {
|
||||
const result = toUnrealizedReturns([
|
||||
makePosition({ absoluteReturn: { currency: "RUB", value: "10" } }),
|
||||
makePosition({
|
||||
absoluteReturn: null,
|
||||
currentValue: { currency: "RUB", value: "100" },
|
||||
}),
|
||||
makePosition({ absoluteReturn: { currency: "USD", value: "2" } }),
|
||||
]);
|
||||
|
||||
expect(result).toEqual([{ currency: "USD", value: "2" }]);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -249,37 +249,23 @@ function toSection(
|
||||
|
||||
function toUnrealizedReturns(
|
||||
positions: Portfolio["positions"],
|
||||
): Money[] {
|
||||
const totals = new Map<string, {
|
||||
complete: boolean;
|
||||
values: Decimal[];
|
||||
}>();
|
||||
): Money | null {
|
||||
const values: Decimal[] = [];
|
||||
|
||||
for (const position of positions) {
|
||||
const currencies = position.absoluteReturn
|
||||
? [position.absoluteReturn.currency]
|
||||
: [...new Set([
|
||||
position.averagePurchasePrice?.currency,
|
||||
position.currentValue?.currency,
|
||||
].filter((currency): currency is string => !!currency))];
|
||||
if (!position.absoluteReturn) {
|
||||
// A position without any valuation has nothing to contribute.
|
||||
|
||||
for (const currency of currencies) {
|
||||
const total = totals.get(currency) ?? { complete: true, values: [] };
|
||||
if (!position.averagePurchasePrice && !position.currentValue)
|
||||
continue;
|
||||
|
||||
if (position.absoluteReturn) {
|
||||
total.values.push(decimalFromString(position.absoluteReturn.value));
|
||||
}
|
||||
else {
|
||||
total.complete = false;
|
||||
return null;
|
||||
}
|
||||
|
||||
totals.set(currency, total);
|
||||
}
|
||||
values.push(decimalFromString(position.absoluteReturn.value));
|
||||
}
|
||||
|
||||
return [...totals].flatMap(([currency, total]) => total.complete
|
||||
? [{ currency, value: decimalToString(sumDecimals(total.values)) }]
|
||||
: []);
|
||||
return { currency: "RUB", value: decimalToString(sumDecimals(values)) };
|
||||
}
|
||||
|
||||
export {
|
||||
|
||||
@@ -64,7 +64,7 @@ function toIncomeSummary(
|
||||
if (income.meta?.completeness === "incomplete") return { state: "partial", to };
|
||||
if (!income.data && (income.isError || income.meta?.lastAttempt.state === "failed"))
|
||||
return { state: "error", to };
|
||||
if (!income.data?.totalsByCurrency.length) return { state: "empty", to };
|
||||
if (!income.data) return { state: "empty", to };
|
||||
|
||||
return {
|
||||
state: "loaded",
|
||||
|
||||
@@ -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}`,
|
||||
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",
|
||||
},
|
||||
],
|
||||
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,8 +28,8 @@ 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";
|
||||
import { PositionSection } from "./PositionSection.view";
|
||||
import { RecentOperations } from "./RecentOperations.view";
|
||||
@@ -38,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;
|
||||
@@ -52,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) => {
|
||||
@@ -93,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"
|
||||
@@ -104,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">
|
||||
@@ -148,6 +160,8 @@ const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
|
||||
<Tabs.Tab value="events">{t("portfolio.tabs.events")}</Tabs.Tab>
|
||||
|
||||
<Tabs.Tab value="income">{t("portfolio.tabs.income")}</Tabs.Tab>
|
||||
|
||||
<Tabs.Tab value="performance">{t("portfolio.tabs.performance")}</Tabs.Tab>
|
||||
</Tabs.List>
|
||||
|
||||
<Tabs.Panel value="positions">
|
||||
@@ -171,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}
|
||||
@@ -184,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">
|
||||
@@ -211,6 +233,10 @@ const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
|
||||
/>
|
||||
)}
|
||||
</Tabs.Panel>
|
||||
|
||||
<Tabs.Panel value="performance">
|
||||
{props.accountId && <PerformanceTab accountId={props.accountId} />}
|
||||
</Tabs.Panel>
|
||||
</Tabs>
|
||||
</Stack>
|
||||
);
|
||||
|
||||
@@ -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)}
|
||||
{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")}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
.positive { color: var(--wl-color-positive); }
|
||||
.negative { color: var(--wl-color-negative); }
|
||||
.neutral { color: var(--mantine-color-dark-7); }
|
||||
@@ -0,0 +1,106 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
|
||||
import type { Performance } from "@/entities/performance";
|
||||
|
||||
import { PerformanceView } from "./Performance.view";
|
||||
|
||||
const rub = (value: string) => ({ currency: "RUB", value });
|
||||
|
||||
const series = Array.from({ length: 24 }, (_, month) => {
|
||||
const date = new Date(Date.UTC(2024, month, 1)).toISOString().slice(0, 10);
|
||||
const invested = 300_000 + Math.floor(month / 6) * 150_000;
|
||||
|
||||
return {
|
||||
benchmarkValue: String(Math.round(invested * (1 + month * 0.009))),
|
||||
date,
|
||||
netInvested: String(invested),
|
||||
referenceValue: String(Math.round(invested * (1 + month * 0.004))),
|
||||
};
|
||||
});
|
||||
|
||||
const data: Performance = {
|
||||
accountId: "account-1",
|
||||
benchmark: {
|
||||
asOf: "2025-12-01",
|
||||
code: "MCFTRR",
|
||||
return: { basis: "annual", unavailableReason: null, value: "0.108" },
|
||||
unavailableReason: null,
|
||||
value: rub("1387973"),
|
||||
},
|
||||
calculatedAt: "2025-12-01T00:00:00Z",
|
||||
completeness: "complete",
|
||||
currentValue: rub("1536400"),
|
||||
excludedAccounts: [],
|
||||
netInvested: rub("1060000"),
|
||||
outperformance: { money: rub("148427"), percentagePoints: "0.043" },
|
||||
period: { days: 700, from: "2024-01-01", to: "2025-12-01" },
|
||||
profit: rub("476400"),
|
||||
reference: {
|
||||
asOf: "2025-12-01",
|
||||
code: "IMOEX",
|
||||
return: { basis: "annual", unavailableReason: null, value: "0.047" },
|
||||
unavailableReason: null,
|
||||
value: rub("1150000"),
|
||||
},
|
||||
return: { basis: "annual", unavailableReason: null, value: "0.151" },
|
||||
series,
|
||||
};
|
||||
|
||||
const meta = {
|
||||
args: { data },
|
||||
component: PerformanceView,
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
"Вкладка «Результат»: доходность, прибыль, те же деньги в индексе Мосбиржи и опережение. Синтетический серверный ответ без расчётов на клиенте.",
|
||||
},
|
||||
},
|
||||
},
|
||||
tags: ["autodocs"],
|
||||
title: "Product/Performance",
|
||||
} satisfies Meta<typeof PerformanceView>;
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Ahead: Story = {};
|
||||
|
||||
export const Behind: Story = {
|
||||
args: {
|
||||
data: {
|
||||
...data,
|
||||
currentValue: rub("1172400"),
|
||||
outperformance: { money: rub("-215573"), percentagePoints: "-0.068" },
|
||||
profit: rub("112400"),
|
||||
return: { basis: "annual", unavailableReason: null, value: "0.04" },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const ShortHistory: Story = {
|
||||
args: {
|
||||
data: {
|
||||
...data,
|
||||
benchmark: {
|
||||
...data.benchmark,
|
||||
return: { basis: "period", unavailableReason: null, value: "0.112" },
|
||||
},
|
||||
period: { days: 277, from: "2025-02-27", to: "2025-12-01" },
|
||||
return: { basis: "period", unavailableReason: null, value: "0.074" },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const Incomplete: Story = {
|
||||
args: {
|
||||
data: {
|
||||
...data,
|
||||
completeness: "incomplete",
|
||||
excludedAccounts: [
|
||||
{ accountId: "usd", name: "Валютный", reason: "PORTFOLIO_VALUATION_INCOMPLETE" },
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,185 @@
|
||||
import { LineChart } from "@mantine/charts";
|
||||
import {
|
||||
Accordion,
|
||||
ActionIcon,
|
||||
Alert,
|
||||
Group,
|
||||
Paper,
|
||||
SimpleGrid,
|
||||
Stack,
|
||||
Text,
|
||||
Title,
|
||||
Tooltip,
|
||||
} from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import type { Performance } from "@/entities/performance";
|
||||
|
||||
import { formatChartValue, formatDate } from "@/shared/lib";
|
||||
|
||||
import { performanceVm } from "../../../../model/performance";
|
||||
import classes from "./Performance.module.css";
|
||||
|
||||
const formatRub = (value: number) => `${formatChartValue(Math.round(value))} ₽`;
|
||||
|
||||
function PerformanceView({ data }: Readonly<{ data: Performance }>) {
|
||||
const { t } = useTranslation();
|
||||
const vm = performanceVm(data);
|
||||
|
||||
const basis = vm.basis === "annual"
|
||||
? t("portfolio.performance.yearly")
|
||||
: t("portfolio.performance.periodLabel", { days: vm.days });
|
||||
|
||||
const comparisonTone = vm.comparison?.points.tone ?? "neutral";
|
||||
let comparisonTitle = t("portfolio.performance.marketEqual");
|
||||
if (comparisonTone === "positive") comparisonTitle = t("portfolio.performance.marketAhead");
|
||||
else if (comparisonTone === "negative") comparisonTitle = t("portfolio.performance.marketBehind");
|
||||
const percentText = vm.returnValue.value;
|
||||
const indexText = vm.indexReturn.value;
|
||||
|
||||
const currentLines = vm.currentPoint
|
||||
? [{ color: "blue.6", label: t("portfolio.performance.current"), x: vm.currentPoint.date }]
|
||||
: [];
|
||||
|
||||
const profitCaption = t("portfolio.performance.profitCaption", { current: vm.current, invested: vm.invested });
|
||||
|
||||
const chartLabel = [
|
||||
`${t("portfolio.performance.invested")}: ${vm.invested}`,
|
||||
`${t("portfolio.performance.benchmark")}: ${vm.indexValue}`,
|
||||
`${t("portfolio.performance.current")}: ${vm.current}`,
|
||||
`${t("portfolio.performance.returnLabel")}: ${percentText}`,
|
||||
].join("; ");
|
||||
|
||||
return (
|
||||
<Stack gap="md">
|
||||
{vm.excluded.length > 0 && (
|
||||
<Alert role="status" title={t("portfolio.performance.incomplete")}>
|
||||
{vm.excluded.map(item => (
|
||||
<Text key={item.id} size="sm">
|
||||
{t("portfolio.performance.unavailableReason", item)}
|
||||
</Text>
|
||||
))}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{vm.basis === "period" && (
|
||||
<Alert role="status">
|
||||
{t("portfolio.performance.periodNote", { days: vm.days })}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<SimpleGrid cols={{ base: 1, lg: 4, sm: 2 }}>
|
||||
<Paper component="dl" m={0} p="md" withBorder>
|
||||
<Text component="dt" size="sm">{t("portfolio.performance.returnLabel")}</Text>
|
||||
|
||||
<Text className={classes[vm.returnValue.tone]} component="dd" fw={700} m={0} size="xl">
|
||||
{percentText}
|
||||
</Text>
|
||||
|
||||
<Text c="dimmed" size="xs">{vm.returnReason ?? basis}</Text>
|
||||
</Paper>
|
||||
|
||||
<Paper component="dl" m={0} p="md" withBorder>
|
||||
<Text component="dt" size="sm">{t("portfolio.performance.profit")}</Text>
|
||||
|
||||
<Text className={classes[vm.profit.tone]} component="dd" fw={700} m={0} size="xl">
|
||||
{vm.profit.value}
|
||||
</Text>
|
||||
|
||||
<Text c="dimmed" size="xs">{profitCaption}</Text>
|
||||
</Paper>
|
||||
|
||||
<Paper component="dl" m={0} p="md" withBorder>
|
||||
<Group gap="xs">
|
||||
<Text component="dt" size="sm">{t("portfolio.performance.benchmark")}</Text>
|
||||
|
||||
<Tooltip
|
||||
events={{ focus: true, hover: true, touch: true }}
|
||||
label={t("portfolio.performance.benchmarkHint")}
|
||||
multiline
|
||||
w={280}
|
||||
>
|
||||
<ActionIcon
|
||||
aria-label={t("portfolio.performance.benchmarkHint")}
|
||||
size="xs"
|
||||
variant="subtle"
|
||||
>?
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
|
||||
<Text component="dd" fw={700} m={0} size="xl">{indexText}</Text>
|
||||
|
||||
<Text c="dimmed" size="xs">
|
||||
{vm.indexReason ?? `${basis} · ${vm.indexValue}`}
|
||||
</Text>
|
||||
</Paper>
|
||||
|
||||
<Paper component="dl" m={0} p="md" withBorder>
|
||||
<Text component="dt" size="sm">
|
||||
{comparisonTitle}
|
||||
</Text>
|
||||
|
||||
<Text
|
||||
className={classes[vm.comparison?.points.tone ?? "neutral"]}
|
||||
component="dd"
|
||||
fw={700}
|
||||
m={0}
|
||||
size="xl"
|
||||
>
|
||||
{vm.comparison?.points.value ?? "—"}
|
||||
</Text>
|
||||
|
||||
<Text c="dimmed" size="xs">{vm.comparison?.money.value ?? vm.indexReason ?? vm.returnReason}</Text>
|
||||
</Paper>
|
||||
</SimpleGrid>
|
||||
|
||||
<Paper component="section" p="md" withBorder>
|
||||
<Title mb="sm" order={2} size="h4">{t("portfolio.performance.chartTitle")}</Title>
|
||||
|
||||
{vm.series.length > 0
|
||||
? (
|
||||
<LineChart
|
||||
aria-label={chartLabel}
|
||||
curveType="linear"
|
||||
data={vm.series}
|
||||
dataKey="label"
|
||||
gridAxis="y"
|
||||
h={{ base: 220, sm: 300 }}
|
||||
lineProps={{ isAnimationActive: false }}
|
||||
referenceLines={currentLines}
|
||||
series={[
|
||||
{ color: "dark.4", label: t("portfolio.performance.invested"), name: "netInvested" },
|
||||
{ color: "orange.6", label: t("portfolio.performance.benchmark"), name: "benchmarkValue" },
|
||||
{ color: "gray.5", label: t("portfolio.performance.reference"), name: "referenceValue", strokeDasharray: "4 3" },
|
||||
]}
|
||||
tooltipAnimationDuration={0}
|
||||
valueFormatter={formatRub}
|
||||
yAxisProps={{ domain: [0, "auto"], width: 70 }}
|
||||
/>
|
||||
)
|
||||
: <Text c="dimmed">{t("portfolio.performance.benchmarkUnavailable")}</Text>}
|
||||
|
||||
<Text c="dimmed" mt="sm" size="sm">
|
||||
{t("portfolio.performance.missingHistory")}
|
||||
</Text>
|
||||
</Paper>
|
||||
|
||||
<Accordion variant="contained">
|
||||
<Accordion.Item value="method">
|
||||
<Accordion.Control>{t("portfolio.performance.calculation")}</Accordion.Control>
|
||||
|
||||
<Accordion.Panel>
|
||||
<Text size="sm">
|
||||
{t("portfolio.performance.datePeriod", { from: formatDate(`${vm.from}T00:00:00Z`), to: formatDate(`${vm.to}T00:00:00Z`) })}
|
||||
</Text>
|
||||
|
||||
<Text mt="sm" size="sm">{t("portfolio.performance.method")}</Text>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
export { PerformanceView };
|
||||
@@ -0,0 +1,193 @@
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { http, HttpResponse, type JsonBodyType } from "msw";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { Performance } from "@/entities/performance";
|
||||
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createTestQueryClient } from "@/test/query";
|
||||
import { server } from "@/test/server";
|
||||
|
||||
import { PerformanceTab } from "./PerformanceTab";
|
||||
|
||||
const url = "*/api/v1/brokerage-accounts/:accountId/performance";
|
||||
|
||||
const rub = (value: string) => ({ currency: "RUB", value });
|
||||
|
||||
function performance(overrides: Partial<Performance> = {}): Performance {
|
||||
return {
|
||||
accountId: "account-1",
|
||||
benchmark: {
|
||||
asOf: "2025-12-31",
|
||||
code: "MCFTRR",
|
||||
return: { basis: "annual", unavailableReason: null, value: "0.048809" },
|
||||
unavailableReason: null,
|
||||
value: rub("110000"),
|
||||
},
|
||||
calculatedAt: "2026-01-01T00:00:00Z",
|
||||
completeness: "complete",
|
||||
currentValue: rub("121000"),
|
||||
excludedAccounts: [],
|
||||
netInvested: rub("100000"),
|
||||
outperformance: { money: rub("11000"), percentagePoints: "0.051191" },
|
||||
period: { days: 730, from: "2024-01-01", to: "2025-12-31" },
|
||||
profit: rub("21000"),
|
||||
reference: {
|
||||
asOf: "2025-12-31",
|
||||
code: "IMOEX",
|
||||
return: { basis: "annual", unavailableReason: null, value: "0.02" },
|
||||
unavailableReason: null,
|
||||
value: rub("105000"),
|
||||
},
|
||||
return: { basis: "annual", unavailableReason: null, value: "0.1" },
|
||||
series: [
|
||||
{ benchmarkValue: "100000", date: "2024-01-01", netInvested: "100000", referenceValue: "100000" },
|
||||
{ benchmarkValue: "110000", date: "2025-12-31", netInvested: "100000", referenceValue: "105000" },
|
||||
],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function renderTab(body: JsonBodyType, status = 200) {
|
||||
configureAuthClient({
|
||||
accessToken: () => "test-token",
|
||||
clear: vi.fn(),
|
||||
refresh: () => Promise.resolve(true),
|
||||
});
|
||||
server.use(http.get(url, () => HttpResponse.json(body, { status })));
|
||||
|
||||
return render(
|
||||
<QueryClientProvider client={createTestQueryClient()}>
|
||||
<MantineProvider>
|
||||
<PerformanceTab accountId="account-1" />
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
const meta = { dependencies: [], unavailable: [] };
|
||||
|
||||
describe("PerformanceTab", () => {
|
||||
it("shows return, profit, the same money in the index and outperformance with signs", async () => {
|
||||
renderTab({ data: performance(), meta });
|
||||
|
||||
expect(await screen.findByText("+10,0 %")).toBeInTheDocument();
|
||||
expect(screen.getByText("+21 000 ₽")).toBeInTheDocument();
|
||||
expect(screen.getByText("+4,9 %")).toBeInTheDocument();
|
||||
expect(screen.getByText("Опережение рынка")).toBeInTheDocument();
|
||||
expect(screen.getByText("+5,1 п.п.")).toBeInTheDocument();
|
||||
expect(screen.getByText("+11 000 ₽")).toBeInTheDocument();
|
||||
// Index codes are allowed only inside "Как считали", not as captions.
|
||||
expect(screen.getByText("Те же деньги в индексе Мосбиржи")).toBeInTheDocument();
|
||||
expect(screen.queryByText("MCFTRR")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("labels lagging the market without colour-only meaning", async () => {
|
||||
renderTab({
|
||||
data: performance({
|
||||
outperformance: { money: rub("-5000"), percentagePoints: "-0.02" },
|
||||
}),
|
||||
meta,
|
||||
});
|
||||
|
||||
expect(await screen.findByText("Отставание от рынка")).toBeInTheDocument();
|
||||
expect(screen.getByText("−2,0 п.п.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("never says annual when history is shorter than a year", async () => {
|
||||
renderTab({
|
||||
data: performance({
|
||||
benchmark: { ...performance().benchmark, return: { basis: "period", unavailableReason: null, value: "0.05" } },
|
||||
period: { days: 200, from: "2025-06-14", to: "2025-12-31" },
|
||||
return: { basis: "period", unavailableReason: null, value: "0.07" },
|
||||
}),
|
||||
meta,
|
||||
});
|
||||
|
||||
expect(await screen.findByText(/проценты показаны за 200 дн\./)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/годовых/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("lists excluded accounts when the all-accounts result is incomplete", async () => {
|
||||
renderTab({
|
||||
data: performance({
|
||||
completeness: "incomplete",
|
||||
excludedAccounts: [{ accountId: "usd", name: "Валютный", reason: "PORTFOLIO_VALUATION_INCOMPLETE" }],
|
||||
}),
|
||||
meta,
|
||||
});
|
||||
|
||||
expect(await screen.findByText("Результат неполный")).toBeInTheDocument();
|
||||
expect(screen.getByText("Валютный: Нет полной оценки портфеля")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("explains unavailability instead of showing zeros, including unknown reasons", async () => {
|
||||
renderTab({
|
||||
data: null,
|
||||
meta: {
|
||||
dependencies: [],
|
||||
unavailable: [
|
||||
{ accountId: "iis", name: "ИИС", reason: "HISTORY_START_UNKNOWN" },
|
||||
{ accountId: "x", name: "Новый", reason: "SOMETHING_NEW" },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(await screen.findByText("Доходность недоступна")).toBeInTheDocument();
|
||||
expect(screen.getByText("ИИС: Начало истории счёта неизвестно")).toBeInTheDocument();
|
||||
expect(screen.getByText("Новый: Причину недоступности не удалось определить")).toBeInTheDocument();
|
||||
expect(screen.queryByText(/0,0 %/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps profit and hides the comparison when the index is unavailable", async () => {
|
||||
renderTab({
|
||||
data: performance({
|
||||
benchmark: {
|
||||
asOf: null,
|
||||
code: "MCFTRR",
|
||||
return: { basis: "annual", unavailableReason: "INDEX_HISTORY_UNAVAILABLE", value: null },
|
||||
unavailableReason: "INDEX_HISTORY_UNAVAILABLE",
|
||||
value: null,
|
||||
},
|
||||
outperformance: null,
|
||||
series: [],
|
||||
}),
|
||||
meta,
|
||||
});
|
||||
|
||||
expect(await screen.findByText("+21 000 ₽")).toBeInTheDocument();
|
||||
expect(screen.getByText("Сравнение с индексом сейчас недоступно")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not colour or call a rounded-to-zero difference outperformance", async () => {
|
||||
renderTab({
|
||||
data: performance({
|
||||
outperformance: { money: rub("0"), percentagePoints: "-0.0004" },
|
||||
}),
|
||||
meta,
|
||||
});
|
||||
|
||||
expect(await screen.findByText("Сравнение с рынком")).toBeInTheDocument();
|
||||
expect(screen.getByText("0,0 п.п.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("explains a pending sync when no account reasons are available", async () => {
|
||||
renderTab({ data: null, meta });
|
||||
|
||||
expect(await screen.findByText(/ещё синхронизируются/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows a local error with retry", async () => {
|
||||
renderTab({ code: "INTERNAL_SERVER_ERROR", status: 500 }, 500);
|
||||
|
||||
expect(await screen.findByText("Не удалось загрузить результат инвестирования", {}, { timeout: 8000 })).toBeInTheDocument();
|
||||
server.use(http.get(
|
||||
url,
|
||||
() => HttpResponse.json({ data: performance(), meta }),
|
||||
));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Повторить" }));
|
||||
expect(await screen.findByText("+10,0 %")).toBeInTheDocument();
|
||||
}, 10_000);
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Button, Paper, SimpleGrid, Skeleton, Stack, Text, Title } from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { usePerformance } from "@/entities/performance";
|
||||
|
||||
import { reasonText } from "../../../../model/performance";
|
||||
import { PerformanceView } from "./Performance.view";
|
||||
|
||||
function PerformanceTab({ accountId }: Readonly<{ accountId: string }>) {
|
||||
const { t } = useTranslation();
|
||||
const query = usePerformance(accountId);
|
||||
|
||||
if (query.isPending) return (
|
||||
<Stack aria-label={t("portfolio.performance.returnLabel")} gap="md">
|
||||
<SimpleGrid cols={{ base: 1, lg: 4, sm: 2 }}>
|
||||
{["rate", "profit", "benchmark", "difference"].map(key => (
|
||||
<Paper key={key} p="md" withBorder>
|
||||
<Skeleton h={14} mb="sm" w="60%" />
|
||||
|
||||
<Skeleton h={28} w="80%" />
|
||||
</Paper>
|
||||
))}
|
||||
</SimpleGrid>
|
||||
|
||||
<Skeleton h={220} />
|
||||
</Stack>
|
||||
);
|
||||
|
||||
const onRetry = () => {
|
||||
void query.refetch();
|
||||
};
|
||||
|
||||
if (query.isError) return (
|
||||
<Paper p="lg" withBorder>
|
||||
<Stack align="flex-start" gap="sm">
|
||||
<Text>{t("portfolio.performance.error")}</Text>
|
||||
|
||||
<Button onClick={onRetry} variant="light">
|
||||
{t("portfolio.performance.retry")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Paper>
|
||||
);
|
||||
if (!query.data.data) return (
|
||||
<Paper p="xl" withBorder>
|
||||
<Title order={2} size="h4">{t("portfolio.performance.unavailable")}</Title>
|
||||
|
||||
{query.data.meta.unavailable.length === 0 && (
|
||||
<Text c="dimmed" mt="sm">{t("portfolio.performance.syncing")}</Text>
|
||||
)}
|
||||
|
||||
{query.data.meta.unavailable.map(item => (
|
||||
<Text c="dimmed" key={item.accountId} mt="sm">
|
||||
{t("portfolio.performance.unavailableReason", {
|
||||
name: item.name,
|
||||
reason: reasonText(item.reason),
|
||||
})}
|
||||
</Text>
|
||||
))}
|
||||
</Paper>
|
||||
);
|
||||
|
||||
return <PerformanceView data={query.data.data} />;
|
||||
}
|
||||
|
||||
export { PerformanceTab };
|
||||
+18
-51
@@ -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: [
|
||||
{
|
||||
...rub,
|
||||
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: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
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,
|
||||
}),
|
||||
),
|
||||
},
|
||||
],
|
||||
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 =>
|
||||
({
|
||||
categories: rub.categories.map(row => ({
|
||||
...row,
|
||||
sharePercent: null,
|
||||
value: row.type === "OTHER" ? "25000" : row.value,
|
||||
}),
|
||||
),
|
||||
})),
|
||||
hasNegativeValues: true,
|
||||
totalValue: "1150000",
|
||||
},
|
||||
],
|
||||
unvaluedCategories: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
+15
-42
@@ -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,
|
||||
}),
|
||||
),
|
||||
},
|
||||
],
|
||||
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,11 +80,8 @@ 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,
|
||||
@@ -113,9 +90,6 @@ describe("portfolio structure", () => {
|
||||
}),
|
||||
),
|
||||
hasNegativeValues: true,
|
||||
},
|
||||
],
|
||||
unvaluedCategories: [],
|
||||
}),
|
||||
);
|
||||
expect(screen.getByText(/Есть отрицательные/)).toBeInTheDocument();
|
||||
@@ -128,20 +102,21 @@ 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: [
|
||||
{
|
||||
@@ -150,9 +125,7 @@ describe("portfolio structure", () => {
|
||||
value: "9007199254740993.000000001",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
unvaluedCategories: [],
|
||||
totalValue: "9007199254740993.000000001",
|
||||
}),
|
||||
);
|
||||
expect(screen.getByRole("list")).toHaveTextContent(
|
||||
|
||||
+3
-17
@@ -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") }}
|
||||
|
||||
+7
-22
@@ -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")
|
||||
|
||||
@@ -31,16 +31,26 @@ function configureTestAuth() {
|
||||
});
|
||||
}
|
||||
|
||||
function portfolioSummary(totals: { currency: string; value: string }[]) {
|
||||
function portfolioSummary(totals: { currency: string; value: string }) {
|
||||
return {
|
||||
bondPositionCount: 1,
|
||||
cashBalances: [],
|
||||
cash: { currency: "RUB", value: "0" },
|
||||
fundPositionCount: 0,
|
||||
stockPositionCount: 0,
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
structure: {
|
||||
categories: [],
|
||||
hasNegativeValues: false,
|
||||
totalValue: "0",
|
||||
unvaluedCategories: [],
|
||||
},
|
||||
totalPositionCount: 1,
|
||||
totalsByCurrency: totals,
|
||||
unrealizedReturnByCurrency: [],
|
||||
totals,
|
||||
unrealizedReturn: {
|
||||
absolute: "0",
|
||||
costBasis: "0",
|
||||
partial: false,
|
||||
percent: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -59,23 +69,18 @@ function renderPage(queryClient: QueryClient) {
|
||||
}
|
||||
|
||||
describe("AccountsPage", () => {
|
||||
it("summarizes currencies separately and reports excluded accounts", async () => {
|
||||
it("summarizes account totals and reports excluded accounts", async () => {
|
||||
server.use(http.get("*/api/v1/brokerage-accounts", () =>
|
||||
HttpResponse.json(resource([
|
||||
{
|
||||
...account,
|
||||
portfolioSummary: portfolioSummary([
|
||||
{ currency: "RUB", value: "100.10" },
|
||||
{ currency: "USD", value: "20" },
|
||||
]),
|
||||
portfolioSummary: portfolioSummary({ currency: "RUB", value: "100.10" }),
|
||||
},
|
||||
{
|
||||
...account,
|
||||
id: "account-2",
|
||||
name: "Второй",
|
||||
portfolioSummary: portfolioSummary([
|
||||
{ currency: "RUB", value: "50.20" },
|
||||
]),
|
||||
portfolioSummary: portfolioSummary({ currency: "RUB", value: "50.20" }),
|
||||
},
|
||||
{
|
||||
...account,
|
||||
@@ -88,9 +93,9 @@ describe("AccountsPage", () => {
|
||||
id: "account-4",
|
||||
name: "Только деньги",
|
||||
portfolioSummary: {
|
||||
...portfolioSummary([{ currency: "RUB", value: "25" }]),
|
||||
...portfolioSummary({ currency: "RUB", value: "25" }),
|
||||
bondPositionCount: 0,
|
||||
cashBalances: [{ currency: "RUB", value: "25" }],
|
||||
cash: { currency: "RUB", value: "25" },
|
||||
totalPositionCount: 0,
|
||||
},
|
||||
},
|
||||
@@ -99,7 +104,7 @@ describe("AccountsPage", () => {
|
||||
id: "account-5",
|
||||
name: "Без сумм",
|
||||
portfolioSummary: {
|
||||
...portfolioSummary([]),
|
||||
...portfolioSummary({ currency: "RUB", value: "0" }),
|
||||
totalPositionCount: 0,
|
||||
},
|
||||
},
|
||||
@@ -110,7 +115,6 @@ describe("AccountsPage", () => {
|
||||
renderPage(client);
|
||||
|
||||
expect(await screen.findByText("175,30 ₽")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("20,00 $")).not.toHaveLength(0);
|
||||
expect(screen.queryByText("Ваши инвестиции по счетам"))
|
||||
.not.toBeInTheDocument();
|
||||
expect(screen.getByText("5 счетов")).toBeInTheDocument();
|
||||
|
||||
@@ -25,34 +25,16 @@ type AccountsPageLoadedProps = {
|
||||
readRetry?: ReadRetryProps;
|
||||
};
|
||||
|
||||
type Money = { currency: string; value: string };
|
||||
|
||||
function accountTotals(accounts: BrokerageAccountCard[]) {
|
||||
const values = new Map<string, string[]>();
|
||||
let excludedCount = 0;
|
||||
function accountTotals(accounts: BrokerageAccountCard[]): null | string {
|
||||
const values: string[] = [];
|
||||
|
||||
for (const { summary } of accounts) {
|
||||
if (summary.state === "empty") continue;
|
||||
if (summary.state !== "available") continue;
|
||||
|
||||
if (summary.state === "unavailable") {
|
||||
excludedCount += 1;
|
||||
continue;
|
||||
values.push(summary.portfolio.totals.value);
|
||||
}
|
||||
|
||||
for (const total of summary.portfolio.totalsByCurrency) {
|
||||
values.set(total.currency, [
|
||||
...values.get(total.currency) ?? [],
|
||||
total.value,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
const totals: Money[] = Array.from(values, ([currency, amounts]) => ({
|
||||
currency,
|
||||
value: sumDecimals(amounts),
|
||||
}));
|
||||
|
||||
return { excludedCount, totals };
|
||||
return values.length > 0 ? sumDecimals(values) : null;
|
||||
}
|
||||
|
||||
function sumDecimals(values: string[]) {
|
||||
@@ -88,9 +70,11 @@ function sumDecimals(values: string[]) {
|
||||
|
||||
const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
const { excludedCount, totals } = accountTotals(props.accounts);
|
||||
const primaryTotal = totals.find(total => total.currency === "RUB") ?? totals[0];
|
||||
const otherTotals = totals.filter(total => total !== primaryTotal);
|
||||
const total = accountTotals(props.accounts);
|
||||
|
||||
const excludedCount = props.accounts.filter(
|
||||
account => account.summary.state === "unavailable",
|
||||
).length;
|
||||
|
||||
return (
|
||||
<Stack gap="lg">
|
||||
@@ -101,24 +85,14 @@ const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
|
||||
{t("accounts.currentValue")}
|
||||
</Text>
|
||||
|
||||
{primaryTotal
|
||||
{total === null
|
||||
? (
|
||||
<Text className={classes.primaryTotal} fw={700}>
|
||||
{formatMoney(primaryTotal, { withRoundedCents: true })}
|
||||
</Text>
|
||||
<Text c="dimmed">{t("accounts.summaryNoTotals")}</Text>
|
||||
)
|
||||
: (
|
||||
<Text c="dimmed">{t("accounts.summaryNoTotals")}</Text>
|
||||
)}
|
||||
|
||||
{otherTotals.length > 0 && (
|
||||
<Group gap="md" wrap="wrap">
|
||||
{otherTotals.map(total => (
|
||||
<Text className={classes.otherTotal} key={total.currency}>
|
||||
{formatMoney(total, { withRoundedCents: true })}
|
||||
<Text className={classes.primaryTotal} fw={700}>
|
||||
{formatMoney({ currency: "RUB", value: total }, { withRoundedCents: true })}
|
||||
</Text>
|
||||
))}
|
||||
</Group>
|
||||
)}
|
||||
|
||||
<Group className={classes.meta} gap="xs" wrap="wrap">
|
||||
|
||||
@@ -258,17 +258,10 @@ function setup(
|
||||
}
|
||||
|
||||
describe("stock page", () => {
|
||||
it("preserves unknown and unambiguous currencies with compact, ratio and percent formatting", async () => {
|
||||
it("formats RUB money, ratio and percent metrics", async () => {
|
||||
setup(
|
||||
{
|
||||
metrics: [
|
||||
{
|
||||
currency: null,
|
||||
key: "marketCapitalization",
|
||||
period: null,
|
||||
unit: "money",
|
||||
value: 1_234_567.89,
|
||||
},
|
||||
{
|
||||
currency: "RUB",
|
||||
key: "revenueTtm",
|
||||
@@ -276,20 +269,6 @@ describe("stock page", () => {
|
||||
unit: "money",
|
||||
value: 1_234_567.89,
|
||||
},
|
||||
{
|
||||
currency: "USD",
|
||||
key: "ebitdaTtm",
|
||||
period: "TTM",
|
||||
unit: "money",
|
||||
value: 1_234_567.89,
|
||||
},
|
||||
{
|
||||
currency: "CAD",
|
||||
key: "netIncomeTtm",
|
||||
period: "TTM",
|
||||
unit: "money",
|
||||
value: 1_234_567.89,
|
||||
},
|
||||
{
|
||||
currency: null,
|
||||
key: "peRatioTtm",
|
||||
@@ -307,14 +286,8 @@ describe("stock page", () => {
|
||||
],
|
||||
},
|
||||
);
|
||||
expect(await screen.findByText("1,23 млн валюта неизвестна")).toBeVisible();
|
||||
for (const value of [
|
||||
"1,23 млн ₽",
|
||||
"1,23 млн USD",
|
||||
"1,23 млн CAD",
|
||||
"5,68 ×",
|
||||
"12,35 %",
|
||||
])
|
||||
expect(await screen.findByText("1,23 млн ₽")).toBeVisible();
|
||||
for (const value of ["5,68 ×", "12,35 %"])
|
||||
expect(screen.getByText(value)).toBeVisible();
|
||||
});
|
||||
it("opens a direct ticker URL and uses its resolved UID for market and personal requests", async () => {
|
||||
|
||||
@@ -37,7 +37,7 @@ const StockCompany: FC<StockCompanyProps> = (props) => {
|
||||
{props.company.metrics.map((metric) => {
|
||||
const label = [t(`stock.metrics.${metric.key}`), metric.period].filter(Boolean).join(" · ");
|
||||
const formatter = metric.unit === "money" ? compactMetricFormatter : metricFormatter;
|
||||
const value = `${formatter.format(metric.value)} ${metricUnit(metric, t("stock.currencyUnknown"))}`;
|
||||
const value = `${formatter.format(metric.value)} ${metricUnit(metric)}`;
|
||||
|
||||
return (
|
||||
<InstrumentMetric key={metric.key} label={label} value={value} />
|
||||
@@ -89,14 +89,9 @@ const StockCompany: FC<StockCompanyProps> = (props) => {
|
||||
);
|
||||
};
|
||||
|
||||
function metricUnit(
|
||||
metric: NonNullable<StockPageVm["company"]>["metrics"][number],
|
||||
unknownCurrency: string,
|
||||
) {
|
||||
function metricUnit(metric: NonNullable<StockPageVm["company"]>["metrics"][number]) {
|
||||
if (metric.unit === "money")
|
||||
return metric.currency === "RUB"
|
||||
? "₽"
|
||||
: (metric.currency ?? unknownCurrency);
|
||||
return "₽";
|
||||
|
||||
return metric.unit === "percent" ? "%" : "×";
|
||||
}
|
||||
|
||||
@@ -69,7 +69,6 @@ const criteriaFields: CriteriaField[] = [
|
||||
"SHARE_TYPE_PREFERRED",
|
||||
],
|
||||
},
|
||||
{ label: "currency", options: ["RUB", "USD", "EUR", "CNY", "HKD", "TRY"] },
|
||||
{
|
||||
label: "realExchange",
|
||||
options: [
|
||||
@@ -184,10 +183,6 @@ const StockCard: FC<StockCardProps> = (props) => {
|
||||
<Group gap="xs">
|
||||
{exchange && <Badge color="gray" variant="light">{exchange}</Badge>}
|
||||
|
||||
{item.currency && (
|
||||
<Badge color="gray" variant="light">{item.currency}</Badge>
|
||||
)}
|
||||
|
||||
{lot && <Text c="dimmed" size="xs">{lot}</Text>}
|
||||
</Group>
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ import { apiClient } from "@/shared/api";
|
||||
|
||||
type Criteria = {
|
||||
countryOfRisk: string;
|
||||
currency: string;
|
||||
maxLot: string;
|
||||
query: string;
|
||||
realExchange: string;
|
||||
@@ -18,7 +17,6 @@ type StocksPageVm = ReturnType<typeof useStocksPageVm>;
|
||||
|
||||
const emptyCriteria: Criteria = {
|
||||
countryOfRisk: "",
|
||||
currency: "",
|
||||
maxLot: "",
|
||||
query: "",
|
||||
realExchange: "",
|
||||
@@ -30,7 +28,6 @@ async function createSearch(criteria: Criteria) {
|
||||
const { data } = await apiClient.POST("/api/v1/stocks/screener/search", {
|
||||
body: {
|
||||
...(criteria.countryOfRisk && { countryOfRisk: criteria.countryOfRisk }),
|
||||
...(criteria.currency && { currency: criteria.currency }),
|
||||
...(criteria.maxLot && { maxLot: Number(criteria.maxLot) }),
|
||||
...(criteria.query && { query: criteria.query }),
|
||||
...(criteria.realExchange && { realExchange: criteria.realExchange }),
|
||||
|
||||
Vendored
+257
-226
@@ -276,6 +276,38 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/brokerage-accounts/all/performance": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get: operations["PerformanceController_all"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/brokerage-accounts/{accountId}/performance": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get: operations["PerformanceController_account"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/brokerage-accounts/all/operations": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -708,22 +740,6 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/tbank-sync/{id}": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get: operations["TbankSyncController_status"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
}
|
||||
export type webhooks = Record<string, never>;
|
||||
export interface components {
|
||||
@@ -968,25 +984,21 @@ export interface components {
|
||||
/** @description Percentage including cash, rounded to six decimal places. Null for incomplete, negative or zero-total compositions. */
|
||||
sharePercent: string | null;
|
||||
};
|
||||
PortfolioStructureCurrencyDto: {
|
||||
currency: string;
|
||||
totalValue: string;
|
||||
/** @description Any negative constituent, even if netted positive. */
|
||||
hasNegativeValues: boolean;
|
||||
categories: components["schemas"]["PortfolioStructureCategoryDto"][];
|
||||
};
|
||||
PortfolioUnvaluedCategoryDto: {
|
||||
/** @enum {string} */
|
||||
type: "STOCK" | "BOND" | "OTHER";
|
||||
count: number;
|
||||
};
|
||||
PortfolioStructureDto: {
|
||||
currencies: components["schemas"]["PortfolioStructureCurrencyDto"][];
|
||||
/** @description Positions without current value and known valuation currency. Shares are unavailable across all currencies when nonempty. */
|
||||
/** @description Exact known total as a decimal string. */
|
||||
totalValue: string;
|
||||
/** @description Any negative constituent, even if netted positive. */
|
||||
hasNegativeValues: boolean;
|
||||
categories: components["schemas"]["PortfolioStructureCategoryDto"][];
|
||||
/** @description Positions without current value. Shares are unavailable when nonempty. */
|
||||
unvaluedCategories: components["schemas"]["PortfolioUnvaluedCategoryDto"][];
|
||||
};
|
||||
UnrealizedReturnDto: {
|
||||
currency: string;
|
||||
/** @example 12.345678901 */
|
||||
absolute: string;
|
||||
/** @example 100.00 */
|
||||
@@ -996,10 +1008,10 @@ export interface components {
|
||||
partial: boolean;
|
||||
};
|
||||
PortfolioSummaryDto: {
|
||||
totalsByCurrency: components["schemas"]["MoneyDto"][];
|
||||
cashBalances: components["schemas"]["MoneyDto"][];
|
||||
totals: components["schemas"]["MoneyDto"];
|
||||
cash: components["schemas"]["MoneyDto"];
|
||||
structure: components["schemas"]["PortfolioStructureDto"];
|
||||
unrealizedReturnByCurrency: components["schemas"]["UnrealizedReturnDto"][];
|
||||
unrealizedReturn: components["schemas"]["UnrealizedReturnDto"];
|
||||
/** @description Number of non-zero stock positions, not the number of units. */
|
||||
stockPositionCount: number;
|
||||
/** @description Number of non-zero bond positions, not the number of units. */
|
||||
@@ -1129,15 +1141,82 @@ export interface components {
|
||||
/** Format: date-time */
|
||||
lastSuccessfulAt: string;
|
||||
isStale: boolean;
|
||||
totalsByCurrency: components["schemas"]["MoneyDto"][];
|
||||
totals: components["schemas"]["MoneyDto"];
|
||||
positions: components["schemas"]["PortfolioPositionDto"][];
|
||||
cashBalances: components["schemas"]["MoneyDto"][];
|
||||
cash: components["schemas"]["MoneyDto"];
|
||||
structure: components["schemas"]["PortfolioStructureDto"];
|
||||
};
|
||||
PortfolioResourceDto: {
|
||||
data: components["schemas"]["PortfolioDto"] | null;
|
||||
meta: components["schemas"]["InvestmentResourceMetaDto"];
|
||||
};
|
||||
PerformancePeriodDto: {
|
||||
/** Format: date */
|
||||
from: string;
|
||||
/** Format: date */
|
||||
to: string;
|
||||
days: number;
|
||||
};
|
||||
/** @enum {string} */
|
||||
PerformanceUnavailableReason: "ACCOUNT_VALUATION_DATES_DIFFER" | "AMBIGUOUS_RETURN" | "HISTORY_START_UNKNOWN" | "INDEX_HISTORY_UNAVAILABLE" | "NO_SOLUTION" | "OPERATIONS_HISTORY_INCOMPLETE" | "PORTFOLIO_VALUATION_INCOMPLETE" | "UNCONFIRMED_TRANSFER" | "UNVALUED_SECURITIES_TRANSFER";
|
||||
PerformanceReturnDto: {
|
||||
/** @description Decimal fraction: 0.151 = 15.1% */
|
||||
value: string | null;
|
||||
/** @enum {string} */
|
||||
basis: "annual" | "period";
|
||||
unavailableReason: components["schemas"]["PerformanceUnavailableReason"] | null;
|
||||
};
|
||||
PerformanceIndexDto: {
|
||||
/** @enum {string} */
|
||||
code: "MCFTRR" | "IMOEX";
|
||||
value: components["schemas"]["MoneyDto"] | null;
|
||||
return: components["schemas"]["PerformanceReturnDto"];
|
||||
/** Format: date */
|
||||
asOf: string | null;
|
||||
unavailableReason: components["schemas"]["PerformanceUnavailableReason"] | null;
|
||||
};
|
||||
PerformanceOutperformanceDto: {
|
||||
/** @description Difference between rates as decimal fractions */
|
||||
percentagePoints: string;
|
||||
money: components["schemas"]["MoneyDto"];
|
||||
};
|
||||
PerformanceSeriesPointDto: {
|
||||
/** Format: date */
|
||||
date: string;
|
||||
netInvested: string;
|
||||
benchmarkValue: string;
|
||||
referenceValue: string | null;
|
||||
};
|
||||
PerformanceExcludedAccountDto: {
|
||||
accountId: string;
|
||||
name: string;
|
||||
reason: components["schemas"]["PerformanceUnavailableReason"];
|
||||
};
|
||||
PerformanceDto: {
|
||||
accountId: string;
|
||||
period: components["schemas"]["PerformancePeriodDto"];
|
||||
netInvested: components["schemas"]["MoneyDto"];
|
||||
currentValue: components["schemas"]["MoneyDto"];
|
||||
profit: components["schemas"]["MoneyDto"];
|
||||
return: components["schemas"]["PerformanceReturnDto"];
|
||||
benchmark: components["schemas"]["PerformanceIndexDto"];
|
||||
reference: components["schemas"]["PerformanceIndexDto"];
|
||||
outperformance: components["schemas"]["PerformanceOutperformanceDto"] | null;
|
||||
series: components["schemas"]["PerformanceSeriesPointDto"][];
|
||||
/** @enum {string} */
|
||||
completeness: "complete" | "incomplete";
|
||||
excludedAccounts: components["schemas"]["PerformanceExcludedAccountDto"][];
|
||||
/** Format: date-time */
|
||||
calculatedAt: string;
|
||||
};
|
||||
PerformanceMetaDto: {
|
||||
dependencies: components["schemas"]["InvestmentDependencyDto"][];
|
||||
unavailable: components["schemas"]["PerformanceExcludedAccountDto"][];
|
||||
};
|
||||
PerformanceResourceDto: {
|
||||
data: components["schemas"]["PerformanceDto"] | null;
|
||||
meta: components["schemas"]["PerformanceMetaDto"];
|
||||
};
|
||||
BrokerageOperationDto: {
|
||||
account?: components["schemas"]["AccountReferenceDto"];
|
||||
id: string;
|
||||
@@ -1176,8 +1255,7 @@ export interface components {
|
||||
/** Format: date */
|
||||
to: string;
|
||||
};
|
||||
IncomeCurrencySummaryDto: {
|
||||
currency: string;
|
||||
IncomeTotalDto: {
|
||||
coupon: components["schemas"]["MoneyDto"];
|
||||
dividend: components["schemas"]["MoneyDto"];
|
||||
total: components["schemas"]["MoneyDto"];
|
||||
@@ -1185,7 +1263,7 @@ export interface components {
|
||||
IncomeSummaryDto: {
|
||||
accountId: string;
|
||||
period: components["schemas"]["IncomePeriodDto"];
|
||||
totalsByCurrency: components["schemas"]["IncomeCurrencySummaryDto"][];
|
||||
total: components["schemas"]["IncomeTotalDto"];
|
||||
/** Format: date-time */
|
||||
calculatedAt: string;
|
||||
};
|
||||
@@ -1195,7 +1273,7 @@ export interface components {
|
||||
};
|
||||
IncomeBucketDto: {
|
||||
period: components["schemas"]["IncomePeriodDto"];
|
||||
totalsByCurrency: components["schemas"]["IncomeCurrencySummaryDto"][];
|
||||
total: components["schemas"]["IncomeTotalDto"];
|
||||
};
|
||||
IncomeInstrumentDto: {
|
||||
key: string;
|
||||
@@ -1233,7 +1311,7 @@ export interface components {
|
||||
IncomeAnalyticsDto: {
|
||||
accountId: string;
|
||||
period: components["schemas"]["IncomePeriodDto"];
|
||||
totalsByCurrency: components["schemas"]["IncomeCurrencySummaryDto"][];
|
||||
total: components["schemas"]["IncomeTotalDto"];
|
||||
/** Format: date-time */
|
||||
calculatedAt: string;
|
||||
/** @enum {string} */
|
||||
@@ -1309,7 +1387,7 @@ export interface components {
|
||||
/** @description Inclusive UTC window the saved forecast was calculated for. Unchanged by the requested from/to filter. */
|
||||
window: components["schemas"]["UpcomingEventsWindowDto"];
|
||||
events: components["schemas"]["UpcomingEventDto"][];
|
||||
incomeTotalsByCurrency: components["schemas"]["MoneyDto"][];
|
||||
incomeTotal: components["schemas"]["MoneyDto"];
|
||||
};
|
||||
UpcomingEventsResourceDto: {
|
||||
data: components["schemas"]["UpcomingEventsDto"] | null;
|
||||
@@ -1368,7 +1446,6 @@ export interface components {
|
||||
query?: string;
|
||||
sector?: string;
|
||||
shareType?: string;
|
||||
currency?: string;
|
||||
realExchange?: string;
|
||||
countryOfRisk?: string;
|
||||
maxLot?: number;
|
||||
@@ -1708,84 +1785,6 @@ export interface components {
|
||||
PutTbankConnectionDto: {
|
||||
token: string;
|
||||
};
|
||||
EventsInvestmentScreenDto: {
|
||||
accountId: string;
|
||||
/**
|
||||
* @description discriminator enum property added by openapi-typescript
|
||||
* @enum {string}
|
||||
*/
|
||||
screen: "events";
|
||||
/**
|
||||
* Format: date
|
||||
* @description Inclusive UTC calendar start date (YYYY-MM-DD). May be supplied independently; defaults to today in UTC.
|
||||
*/
|
||||
from?: string;
|
||||
/**
|
||||
* Format: date
|
||||
* @description Inclusive UTC calendar end date (YYYY-MM-DD). May be supplied independently; defaults to 30 days after from. Timestamp queries use the start of the following UTC day as the exclusive end.
|
||||
*/
|
||||
to?: string;
|
||||
};
|
||||
IncomeInvestmentScreenDto: {
|
||||
accountId: string;
|
||||
/**
|
||||
* @description discriminator enum property added by openapi-typescript
|
||||
* @enum {string}
|
||||
*/
|
||||
screen: "income";
|
||||
/**
|
||||
* Format: date
|
||||
* @description Inclusive start calendar date in Europe/Moscow (YYYY-MM-DD). Supply both from and to, or neither for the current Moscow month.
|
||||
*/
|
||||
from?: string;
|
||||
/**
|
||||
* Format: date
|
||||
* @description Inclusive end calendar date in Europe/Moscow (YYYY-MM-DD). Supply both from and to, or neither. Timestamp queries use the start of the following Moscow day as the exclusive end, capped at now.
|
||||
*/
|
||||
to?: string;
|
||||
};
|
||||
SyncCandleRangeDto: {
|
||||
/** Format: date-time */
|
||||
from: string;
|
||||
/** Format: date-time */
|
||||
to: string;
|
||||
};
|
||||
TimestampInvestmentScreenDto: {
|
||||
accountId?: string;
|
||||
/** Format: uuid */
|
||||
instrumentUid?: string;
|
||||
query?: string;
|
||||
/** @enum {string} */
|
||||
candlePeriod?: "month" | "halfYear" | "year" | "all";
|
||||
candleRange?: components["schemas"]["SyncCandleRangeDto"];
|
||||
categories?: ("trade" | "income" | "tax" | "fee" | "transfer" | "other")[];
|
||||
limit?: number;
|
||||
/**
|
||||
* @description discriminator enum property added by openapi-typescript
|
||||
* @enum {string}
|
||||
*/
|
||||
screen: "accounts" | "account" | "operations" | "stocks" | "bonds" | "stock" | "bond";
|
||||
/**
|
||||
* Format: date-time
|
||||
* @description Start instant for operations.
|
||||
*/
|
||||
from?: string;
|
||||
/**
|
||||
* Format: date-time
|
||||
* @description End instant for operations.
|
||||
*/
|
||||
to?: string;
|
||||
};
|
||||
TbankSyncStatusDto: {
|
||||
/** Format: uuid */
|
||||
id: string;
|
||||
scope: (components["schemas"]["IncomeInvestmentScreenDto"] | components["schemas"]["EventsInvestmentScreenDto"] | components["schemas"]["TimestampInvestmentScreenDto"]) | null;
|
||||
/** Format: date-time */
|
||||
now: string;
|
||||
/** @enum {string} */
|
||||
state: "running" | "succeeded" | "failed" | "cancelled";
|
||||
errorCode: string | null;
|
||||
};
|
||||
};
|
||||
responses: never;
|
||||
parameters: never;
|
||||
@@ -3525,6 +3524,136 @@ export interface operations {
|
||||
};
|
||||
};
|
||||
};
|
||||
PerformanceController_all: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["PerformanceResourceDto"];
|
||||
};
|
||||
};
|
||||
/** @description Invalid request */
|
||||
400: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
/** @description Authentication required */
|
||||
401: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
/** @description Resource not found */
|
||||
404: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
/** @description Internal server error */
|
||||
500: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
/** @description Upstream service unavailable */
|
||||
503: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
PerformanceController_account: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
accountId: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["PerformanceResourceDto"];
|
||||
};
|
||||
};
|
||||
/** @description Invalid request */
|
||||
400: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
/** @description Authentication required */
|
||||
401: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
/** @description Resource not found */
|
||||
404: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
/** @description Internal server error */
|
||||
500: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
/** @description Upstream service unavailable */
|
||||
503: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
BrokerageOperationsController_all: {
|
||||
parameters: {
|
||||
query?: {
|
||||
@@ -3673,9 +3802,7 @@ export interface operations {
|
||||
};
|
||||
IncomeAnalyticsController_allSummary: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
};
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
@@ -3740,7 +3867,6 @@ export interface operations {
|
||||
IncomeAnalyticsController_allAnalytics: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
/** @description Inclusive calendar date in Europe/Moscow. Supply both from/to or neither. */
|
||||
from?: string;
|
||||
/** @description Inclusive calendar date in Europe/Moscow, no later than today. Supply both from/to or neither. */
|
||||
@@ -3809,9 +3935,7 @@ export interface operations {
|
||||
};
|
||||
IncomeAnalyticsController_summary: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
};
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
accountId: string;
|
||||
@@ -3878,7 +4002,6 @@ export interface operations {
|
||||
IncomeAnalyticsController_analytics: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
/** @description Inclusive calendar date in Europe/Moscow. Supply both from/to or neither. */
|
||||
from?: string;
|
||||
/** @description Inclusive calendar date in Europe/Moscow, no later than today. Supply both from/to or neither. */
|
||||
@@ -3950,7 +4073,6 @@ export interface operations {
|
||||
UpcomingEventsController_all: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
/** @description Inclusive UTC calendar start date (YYYY-MM-DD). May be supplied independently; defaults to today in UTC. */
|
||||
from?: string;
|
||||
/** @description Inclusive UTC calendar end date (YYYY-MM-DD). May be supplied independently; defaults to 30 days after from. Timestamp queries use the start of the following UTC day as the exclusive end. */
|
||||
@@ -4020,7 +4142,6 @@ export interface operations {
|
||||
UpcomingEventsController_get: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
/** @description Inclusive UTC calendar start date (YYYY-MM-DD). May be supplied independently; defaults to today in UTC. */
|
||||
from?: string;
|
||||
/** @description Inclusive UTC calendar end date (YYYY-MM-DD). May be supplied independently; defaults to 30 days after from. Timestamp queries use the start of the following UTC day as the exclusive end. */
|
||||
@@ -4092,7 +4213,6 @@ export interface operations {
|
||||
StockController_search: {
|
||||
parameters: {
|
||||
query: {
|
||||
sync?: "observe";
|
||||
query: string;
|
||||
};
|
||||
header?: never;
|
||||
@@ -4158,9 +4278,7 @@ export interface operations {
|
||||
};
|
||||
StockController_getByTicker: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
};
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
ticker: string;
|
||||
@@ -4362,9 +4480,7 @@ export interface operations {
|
||||
};
|
||||
StockController_get: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
};
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
uid: string;
|
||||
@@ -4430,9 +4546,7 @@ export interface operations {
|
||||
};
|
||||
StockController_quote: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
};
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
uid: string;
|
||||
@@ -4499,7 +4613,6 @@ export interface operations {
|
||||
StockController_candles: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
period?: "month" | "halfYear" | "year" | "all";
|
||||
};
|
||||
header?: never;
|
||||
@@ -4633,9 +4746,7 @@ export interface operations {
|
||||
};
|
||||
StockController_company: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
};
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
uid: string;
|
||||
@@ -4701,9 +4812,7 @@ export interface operations {
|
||||
};
|
||||
StockController_dividends: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
};
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
uid: string;
|
||||
@@ -4769,9 +4878,7 @@ export interface operations {
|
||||
};
|
||||
BondController_metrics: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
};
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
uid: string;
|
||||
@@ -4838,7 +4945,6 @@ export interface operations {
|
||||
BondController_search: {
|
||||
parameters: {
|
||||
query: {
|
||||
sync?: "observe";
|
||||
query: string;
|
||||
};
|
||||
header?: never;
|
||||
@@ -4904,9 +5010,7 @@ export interface operations {
|
||||
};
|
||||
BondController_getByTicker: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
};
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
ticker: string;
|
||||
@@ -4972,9 +5076,7 @@ export interface operations {
|
||||
};
|
||||
BondController_get: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
};
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
uid: string;
|
||||
@@ -5040,9 +5142,7 @@ export interface operations {
|
||||
};
|
||||
BondController_quote: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
};
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
uid: string;
|
||||
@@ -5109,7 +5209,6 @@ export interface operations {
|
||||
BondController_candles: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
period?: "month" | "halfYear" | "year" | "all";
|
||||
};
|
||||
header?: never;
|
||||
@@ -5243,9 +5342,7 @@ export interface operations {
|
||||
};
|
||||
BondController_coupons: {
|
||||
parameters: {
|
||||
query?: {
|
||||
sync?: "observe";
|
||||
};
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
uid: string;
|
||||
@@ -5503,70 +5600,4 @@ export interface operations {
|
||||
};
|
||||
};
|
||||
};
|
||||
TbankSyncController_status: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["TbankSyncStatusDto"];
|
||||
};
|
||||
};
|
||||
/** @description Invalid request */
|
||||
400: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
/** @description Authentication required */
|
||||
401: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
/** @description Resource not found */
|
||||
404: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
/** @description Internal server error */
|
||||
500: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
/** @description Upstream service unavailable */
|
||||
503: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/problem+json": components["schemas"]["ProblemDetailsDto"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -20,12 +20,12 @@ function usePrivateResource(accountId: string) {
|
||||
}
|
||||
|
||||
const snapshot: Portfolio = {
|
||||
cashBalances: [],
|
||||
cash: { currency: "RUB", value: "0" },
|
||||
isStale: false,
|
||||
lastSuccessfulAt: "2026-08-14T00:00:00Z",
|
||||
positions: [],
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
totalsByCurrency: [{ currency: "RUB", value: "123.000000001" }],
|
||||
structure: { categories: [], hasNegativeValues: false, totalValue: "0", unvaluedCategories: [] },
|
||||
totals: { currency: "RUB", value: "123.000000001" },
|
||||
};
|
||||
|
||||
function auth() {
|
||||
@@ -94,8 +94,8 @@ describe("persistent resource query lifecycle", () => {
|
||||
isReady = true;
|
||||
const loaded = await result.current.refetch();
|
||||
expect(loaded.data).toEqual(refreshed);
|
||||
expect(loaded.data?.data?.totalsByCurrency).toEqual(
|
||||
snapshot.totalsByCurrency,
|
||||
expect(loaded.data?.data?.totals).toEqual(
|
||||
snapshot.totals,
|
||||
);
|
||||
});
|
||||
await waitFor(() => expect(result.current.data).toEqual(snapshot));
|
||||
|
||||
+489
-604
File diff suppressed because it is too large
Load Diff
@@ -14,9 +14,9 @@ const ru = {
|
||||
currentValue: "Текущая стоимость",
|
||||
description: {
|
||||
currentValue: "Текущая стоимость: {{value}}. ",
|
||||
return: "Доходность {{currency}}: {{percent}}, {{absolute}}",
|
||||
return: "Доходность: {{percent}}, {{absolute}}",
|
||||
start: "Счёт {{name}}, {{type}}. ",
|
||||
structure: "Структура {{currency}}: {{value}}",
|
||||
structure: "Структура: {{value}}",
|
||||
structureCategory: "{{category}} {{value}}",
|
||||
},
|
||||
emptyText:
|
||||
@@ -39,17 +39,13 @@ const ru = {
|
||||
refreshError:
|
||||
"Не удалось обновить данные. Показаны последние полученные.",
|
||||
refreshing: "Обновляем данные",
|
||||
remainingCurrencies_few: "Еще {{count}} валюты",
|
||||
remainingCurrencies_many: "Еще {{count}} валют",
|
||||
remainingCurrencies_one: "Еще {{count}} валюта",
|
||||
remainingCurrencies_other: "Еще {{count}} валюты",
|
||||
retry: "Повторить",
|
||||
scope: "Счёт",
|
||||
stocks: "Акции",
|
||||
structure: {
|
||||
category: "{{category}} {{percent}} %",
|
||||
incomplete: "{{category}}: доля неизвестна",
|
||||
label: "Структура в {{currency}}: {{value}}",
|
||||
label: "Структура: {{value}}",
|
||||
},
|
||||
summaryEmpty: "Нет текущих сумм",
|
||||
summaryExcluded_few:
|
||||
@@ -512,9 +508,9 @@ const ru = {
|
||||
bonds: "Облигации",
|
||||
byAccount: "Позиции по счетам",
|
||||
cashBalances: "Денежные остатки",
|
||||
cashTitle: "Деньги",
|
||||
concentration: {
|
||||
chart: "Распределение позиций",
|
||||
currency: "Валюта концентрации",
|
||||
empty: "В этом разрезе нет позиций с положительной оценкой.",
|
||||
incomplete: "Данные неполные",
|
||||
issuers: "Эмитенты",
|
||||
@@ -534,15 +530,42 @@ const ru = {
|
||||
},
|
||||
connectionErrorText: "Настройте подключение, чтобы посмотреть портфель.",
|
||||
connectionErrorTitle: "Проверьте подключение T-Bank",
|
||||
currencies: {
|
||||
EUR: "Евро",
|
||||
RUB: "Российский рубль",
|
||||
USD: "Доллар США",
|
||||
},
|
||||
emptyText: "На счете нет позиций и доступных денежных остатков.",
|
||||
emptyTitle: "Портфель пока пуст",
|
||||
more: "Подробнее",
|
||||
otherPositions: "Другие позиции",
|
||||
performance: {
|
||||
benchmark: "Те же деньги в индексе Мосбиржи",
|
||||
benchmarkHint:
|
||||
"Если бы каждое пополнение вкладывалось в индекс Мосбиржи с учётом дивидендов после налогов",
|
||||
benchmarkUnavailable: "Сравнение с индексом сейчас недоступно",
|
||||
calculation: "Как считали",
|
||||
chartTitle: "Ваш портфель против индекса",
|
||||
current: "Ваш портфель сейчас",
|
||||
datePeriod: "С {{from}} по {{to}}",
|
||||
error: "Не удалось загрузить результат инвестирования",
|
||||
incomplete: "Результат неполный",
|
||||
invested: "Вложено (нетто)",
|
||||
marketAhead: "Опережение рынка",
|
||||
marketBehind: "Отставание от рынка",
|
||||
marketEqual: "Сравнение с рынком",
|
||||
method:
|
||||
"Доходность учитывает суммы и даты пополнений и выводов. Купоны, дивиденды, налоги и комиссии уже входят в текущую стоимость. Для сравнения те же потоки вложены в индекс полной доходности Мосбиржи с дивидендами после налогов (MCFTRR). Ценовой индекс IMOEX дивиденды не учитывает и показан только для справки. Источник: MOEX ISS. Это не налоговый расчёт.",
|
||||
missingHistory:
|
||||
"Линии прошлой стоимости вашего портфеля нет: такая история ещё не накоплена. Точка справа — текущая оценка.",
|
||||
periodLabel: "за {{days}} дн.",
|
||||
periodNote:
|
||||
"История меньше года: проценты показаны за {{days}} дн. без пересчёта в годовые.",
|
||||
profit: "Прибыль",
|
||||
profitCaption: "{{current}} сейчас · вложено {{invested}}",
|
||||
reference: "Индекс Мосбиржи без дивидендов",
|
||||
retry: "Повторить",
|
||||
returnLabel: "Доходность",
|
||||
syncing: "Данные счетов ещё синхронизируются. Результат появится после загрузки.",
|
||||
unavailable: "Доходность недоступна",
|
||||
unavailableReason: "{{name}}: {{reason}}",
|
||||
yearly: "годовых",
|
||||
},
|
||||
positionFilter: "Тип позиции",
|
||||
positionKinds: {
|
||||
bonds: "Облигации",
|
||||
@@ -566,7 +589,6 @@ const ru = {
|
||||
categories: "Категории активов",
|
||||
chartLabel:
|
||||
"Структура по типам активов. Суммы и доли — в списке рядом.",
|
||||
currency: "Валюта структуры портфеля",
|
||||
empty: "Нет положительной стоимости для кольцевой диаграммы.",
|
||||
incomplete:
|
||||
"Оценка неполная: ниже показаны только известные суммы. Валюта оценки части позиций неизвестна, поэтому доли и диаграмма недоступны.",
|
||||
@@ -586,9 +608,11 @@ const ru = {
|
||||
events: "Предстоящие события",
|
||||
income: "Доход",
|
||||
operations: "История операций",
|
||||
performance: "Результат",
|
||||
positions: "Позиции",
|
||||
},
|
||||
title: "Портфель",
|
||||
total: "Текущая стоимость",
|
||||
unrealizedResult: "Нереализованный результат",
|
||||
unrealizedResultCaption: "по цене, без НКД и купонов",
|
||||
updatedAt: "Данные получены {{date}}",
|
||||
@@ -631,7 +655,6 @@ const ru = {
|
||||
complete: "Завершена",
|
||||
connect:
|
||||
"Для просмотра акций подключите T-Банк в настройках или обновите подключение.",
|
||||
currencyUnknown: "валюта неизвестна",
|
||||
date: "Дата",
|
||||
dateUnknown: "Дата не указана",
|
||||
dividendHistory: "История дивидендов компании",
|
||||
@@ -719,7 +742,6 @@ const ru = {
|
||||
screener: {
|
||||
asOf: "Список получен {{date}}",
|
||||
countryOfRisk: "Страна риска",
|
||||
currency: "Валюта расчётов",
|
||||
empty: "Подходящие акции не найдены.",
|
||||
error: "Не удалось получить результат скринера. Попробуйте найти снова.",
|
||||
maxLot: "Максимальный размер лота",
|
||||
|
||||
@@ -3,18 +3,13 @@ import { describe, expect, it } from "vitest";
|
||||
import { sumMoney } from "./decimal";
|
||||
|
||||
describe("sumMoney", () => {
|
||||
it("adds exact signed decimals independently per currency", () => {
|
||||
it("adds exact signed decimals", () => {
|
||||
expect(sumMoney([
|
||||
{ currency: "RUB", value: "0.1" },
|
||||
{ currency: "USD", value: "0.01" },
|
||||
{ currency: "RUB", value: "0.2" },
|
||||
{ currency: "RUB", value: "-1500000.45" },
|
||||
{ currency: "USD", value: "-0.02" },
|
||||
{ currency: "RUB", value: "200" },
|
||||
])).toEqual([
|
||||
{ currency: "RUB", value: "-1499800.15" },
|
||||
{ currency: "USD", value: "-0.01" },
|
||||
]);
|
||||
])).toEqual({ currency: "RUB", value: "-1499800.15" });
|
||||
});
|
||||
|
||||
it("preserves significant fractional digits and a compensated zero", () => {
|
||||
@@ -22,11 +17,11 @@ describe("sumMoney", () => {
|
||||
{ currency: "RUB", value: "100.5" },
|
||||
{ currency: "RUB", value: "49.50" },
|
||||
{ currency: "RUB", value: "0.005" },
|
||||
])).toEqual([{ currency: "RUB", value: "150.005" }]);
|
||||
])).toEqual({ currency: "RUB", value: "150.005" });
|
||||
expect(sumMoney([
|
||||
{ currency: "RUB", value: "100" },
|
||||
{ currency: "RUB", value: "-100" },
|
||||
])).toEqual([{ currency: "RUB", value: "0" }]);
|
||||
])).toEqual({ currency: "RUB", value: "0" });
|
||||
});
|
||||
|
||||
it.each(["", ".", "1.2.3", "not-a-number"])(
|
||||
|
||||
@@ -46,26 +46,22 @@ function sumDecimals(decimals: readonly Decimal[]): Decimal {
|
||||
return { scale, value };
|
||||
}
|
||||
|
||||
function sumMoney(amounts: readonly Money[]): Money[] | null {
|
||||
const decimals = new Map<string, Decimal[]>();
|
||||
|
||||
for (const amount of amounts) {
|
||||
function sumMoney(amounts: readonly Money[]): Money | null {
|
||||
try {
|
||||
const values = decimals.get(amount.currency) ?? [];
|
||||
values.push(decimalFromString(amount.value));
|
||||
decimals.set(amount.currency, values);
|
||||
const currency = amounts[0]?.currency ?? "RUB";
|
||||
|
||||
return {
|
||||
currency,
|
||||
value: decimalToString(sumDecimals(
|
||||
amounts.map(amount => decimalFromString(amount.value)),
|
||||
)),
|
||||
};
|
||||
}
|
||||
catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(decimals, ([currency, values]) => ({
|
||||
currency,
|
||||
value: decimalToString(sumDecimals(values)),
|
||||
}));
|
||||
}
|
||||
|
||||
export {
|
||||
type Decimal,
|
||||
decimalFromString,
|
||||
|
||||
@@ -3,12 +3,22 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
formatDate,
|
||||
formatMoney,
|
||||
formatPercentagePoints,
|
||||
formatSignedPercent,
|
||||
formatSnapshotDay,
|
||||
formatSnapshotTime,
|
||||
instrumentLogoUrl,
|
||||
} from "./display";
|
||||
|
||||
describe("shared display helpers", () => {
|
||||
it("formats signed rates as percentages and percentage points without negative zero", () => {
|
||||
expect(formatSignedPercent("0.151")).toBe("+15,1 %");
|
||||
expect(formatSignedPercent("-0.15149")).toBe("−15,1 %");
|
||||
expect(formatSignedPercent("0")).toBe("0,0 %");
|
||||
expect(formatSignedPercent("-0.00049")).toBe("0,0 %");
|
||||
expect(formatPercentagePoints("0.043")).toBe("+4,3 п.п.");
|
||||
expect(formatPercentagePoints("-0.0435")).toBe("−4,4 п.п.");
|
||||
});
|
||||
it("uses padded Russian dates and preserves the UTC date of timestamps", () => {
|
||||
expect(formatDate("2027-09-10")).toBe("10.09.2027");
|
||||
expect(formatDate("2024-02-29")).toBe("29.02.2024");
|
||||
@@ -33,7 +43,6 @@ describe("shared display helpers", () => {
|
||||
"-1 234 567,89 ₽",
|
||||
);
|
||||
expect(formatMoney({ currency: "RUB", value: "10" })).toBe("10 ₽");
|
||||
expect(formatMoney({ currency: "USD", value: "0.5" })).toBe("0,5 $");
|
||||
expect(formatMoney({ currency: "RUB", value: "0001234.50" })).toBe(
|
||||
"0 001 234,50 ₽",
|
||||
);
|
||||
@@ -61,14 +70,11 @@ describe("shared display helpers", () => {
|
||||
)).toBe("0,00 ₽");
|
||||
});
|
||||
|
||||
it("rounds to the currency's minor units and drops the sign of a rounded zero", () => {
|
||||
it("rounds to minor units and drops the sign of a rounded zero", () => {
|
||||
const rounded = { withRoundedCents: true };
|
||||
expect(formatMoney({ currency: "RUB", value: "-0.004" }, rounded)).toBe("0,00 ₽");
|
||||
expect(formatMoney({ currency: "RUB", value: "-0.005" }, rounded)).toBe("-0,01 ₽");
|
||||
expect(formatMoney({ currency: "RUB", value: "999.995" }, rounded)).toBe("1 000,00 ₽");
|
||||
expect(formatMoney({ currency: "JPY", value: "1500.5" }, rounded)).toBe("1 501 JPY");
|
||||
expect(formatMoney({ currency: "KWD", value: "1.2345" }, rounded)).toBe("1,235 KWD");
|
||||
expect(formatMoney({ currency: "ZZZ", value: "1.234" }, rounded)).toBe("1,23 ZZZ");
|
||||
});
|
||||
|
||||
it("builds the brand logo url from an upstream file name", () => {
|
||||
|
||||
+31
-21
@@ -1,5 +1,7 @@
|
||||
import { decimalFromString } from "./decimal";
|
||||
|
||||
const DECIMAL_PART_COUNT = 2;
|
||||
const DEFAULT_MINOR_UNITS = 2;
|
||||
const MINOR_UNITS = 2;
|
||||
|
||||
type FormatMoneyOptions = {
|
||||
withRoundedCents?: boolean;
|
||||
@@ -23,17 +25,6 @@ const dateFormatter = new Intl.DateTimeFormat("ru-RU", {
|
||||
year: "numeric",
|
||||
});
|
||||
|
||||
// ISO 4217 minor units (JPY 0, KWD 3); unknown codes fall back to 2.
|
||||
function currencyMinorUnits(currency: string): number {
|
||||
try {
|
||||
return new Intl.NumberFormat("en", { currency, style: "currency" })
|
||||
.resolvedOptions().maximumFractionDigits ?? DEFAULT_MINOR_UNITS;
|
||||
}
|
||||
catch {
|
||||
return DEFAULT_MINOR_UNITS;
|
||||
}
|
||||
}
|
||||
|
||||
function formatDate(value: string): string {
|
||||
return dateFormatter.format(new Date(value));
|
||||
}
|
||||
@@ -67,10 +58,8 @@ function formatMoney(
|
||||
): string {
|
||||
if (!money) return "—";
|
||||
|
||||
const minorUnits = currencyMinorUnits(money.currency);
|
||||
|
||||
const value = withRoundedCents
|
||||
? roundDecimal(money.value, minorUnits)
|
||||
? roundDecimal(money.value, MINOR_UNITS)
|
||||
: money.value;
|
||||
|
||||
const [integerPart = "", fractionPart = ""] = value.split(
|
||||
@@ -79,18 +68,14 @@ function formatMoney(
|
||||
);
|
||||
|
||||
const normalizedFraction = withRoundedCents || withZeroCents
|
||||
? fractionPart.padEnd(minorUnits, "0")
|
||||
? fractionPart.padEnd(MINOR_UNITS, "0")
|
||||
: fractionPart;
|
||||
|
||||
const decimal = normalizedFraction
|
||||
? `${integerPart}.${normalizedFraction}`
|
||||
: integerPart;
|
||||
|
||||
let currency = money.currency;
|
||||
if (currency === "RUB") currency = "₽";
|
||||
else if (currency === "USD") currency = "$";
|
||||
|
||||
const formatted = `${formatDecimal(decimal)} ${currency}`;
|
||||
const formatted = `${formatDecimal(decimal)} ₽`;
|
||||
|
||||
if (!withSign) return formatted;
|
||||
if (isZeroDecimal(value))
|
||||
@@ -99,6 +84,29 @@ function formatMoney(
|
||||
return value.startsWith("-") ? `−${formatted.slice(1)}` : `+${formatted}`;
|
||||
}
|
||||
|
||||
function formatPercentagePoints(rate: string): string {
|
||||
return formatRate(rate, "п.п.");
|
||||
}
|
||||
|
||||
function formatRate(rate: string, suffix: string): string {
|
||||
const { scale, value } = decimalFromString(rate);
|
||||
const abs = value < 0n ? -value : value;
|
||||
const radix = 10n;
|
||||
const half = 2n;
|
||||
const tenthsPerUnit = 1000n;
|
||||
const denominator = radix ** BigInt(scale);
|
||||
const tenths = (abs * tenthsPerUnit + denominator / half) / denominator;
|
||||
let sign = "";
|
||||
if (tenths !== 0n) sign = value < 0n ? "−" : "+";
|
||||
const formatted = `${formatDecimal(String(tenths / radix))},${tenths % radix}`;
|
||||
|
||||
return `${sign}${formatted} ${suffix}`;
|
||||
}
|
||||
|
||||
function formatSignedPercent(rate: string): string {
|
||||
return formatRate(rate, "%");
|
||||
}
|
||||
|
||||
function isZeroDecimal(value: string) {
|
||||
const unsigned = value.startsWith("-") ? value.slice(1) : value;
|
||||
|
||||
@@ -171,6 +179,8 @@ export {
|
||||
formatDate,
|
||||
formatDecimal,
|
||||
formatMoney,
|
||||
formatPercentagePoints,
|
||||
formatSignedPercent,
|
||||
formatSnapshotDay,
|
||||
formatSnapshotTime,
|
||||
instrumentLogoUrl,
|
||||
|
||||
@@ -12,6 +12,8 @@ export {
|
||||
formatDate,
|
||||
formatDecimal,
|
||||
formatMoney,
|
||||
formatPercentagePoints,
|
||||
formatSignedPercent,
|
||||
formatSnapshotDay,
|
||||
formatSnapshotTime,
|
||||
instrumentLogoUrl,
|
||||
|
||||
@@ -2,12 +2,8 @@ import { formatMoney } from "./display";
|
||||
|
||||
type Money = { currency: string; value: string };
|
||||
|
||||
function totalText(totals: Money[] | null, isSigned: boolean): string {
|
||||
return totals
|
||||
? totals.map(total =>
|
||||
formatMoney(total, { withSign: isSigned || undefined }),
|
||||
).join(", ")
|
||||
: "";
|
||||
function totalText(total: Money | null, isSigned: boolean): string {
|
||||
return total ? formatMoney(total, { withSign: isSigned || undefined }) : "";
|
||||
}
|
||||
|
||||
export { totalText };
|
||||
|
||||
@@ -24,7 +24,9 @@ type EntryGroupProps = PropsWithChildren<{
|
||||
|
||||
type EntryGroupTotalProps = {
|
||||
isSigned?: boolean;
|
||||
totals: null | { currency: string; value: string }[];
|
||||
totals:
|
||||
| null
|
||||
| { currency: string; value: string };
|
||||
};
|
||||
|
||||
const AccountRow: FC<AccountRowProps> = (props) => {
|
||||
@@ -88,11 +90,9 @@ const EntryGroupTotal: FC<EntryGroupTotalProps> = (props) => {
|
||||
|
||||
return (
|
||||
<Stack gap={2}>
|
||||
{props.totals.map(total => (
|
||||
<span key={`${total.currency}-${total.value}`}>
|
||||
{formatMoney(total, { withSign: isSigned || undefined })}
|
||||
<span>
|
||||
{formatMoney(props.totals, { withSign: isSigned || undefined })}
|
||||
</span>
|
||||
))}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
+13
-4
@@ -37,12 +37,17 @@ const handlers = [
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
|
||||
HttpResponse.json(
|
||||
resource({
|
||||
cashBalances: [],
|
||||
cash: { currency: "RUB", value: "0" },
|
||||
isStale: false,
|
||||
lastSuccessfulAt: "2026-08-14T00:00:00Z",
|
||||
positions: [],
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
totalsByCurrency: [],
|
||||
structure: {
|
||||
categories: [],
|
||||
hasNegativeValues: false,
|
||||
totalValue: "0",
|
||||
unvaluedCategories: [],
|
||||
},
|
||||
totals: { currency: "RUB", value: "0" },
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -76,7 +81,11 @@ const handlers = [
|
||||
accountId: "account-1",
|
||||
calculatedAt: "2026-08-14T00:00:00Z",
|
||||
period: { from: "2026-01-01", to: "2026-08-14" },
|
||||
totalsByCurrency: [],
|
||||
total: {
|
||||
coupon: { currency: "RUB", value: "0" },
|
||||
dividend: { currency: "RUB", value: "0" },
|
||||
total: { currency: "RUB", value: "0" },
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
Reference in New Issue
Block a user