Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2abbb3e329 | ||
|
|
21383852d9 | ||
|
|
010e3ab8af |
@@ -55,12 +55,12 @@ const position: Portfolio["positions"][number]
|
|||||||
};
|
};
|
||||||
|
|
||||||
const portfolio: Portfolio = {
|
const portfolio: Portfolio = {
|
||||||
cash: { currency: "RUB", value: "0" },
|
cashBalances: [],
|
||||||
isStale: false,
|
isStale: false,
|
||||||
lastSuccessfulAt: "2026-08-15T12:00:00Z",
|
lastSuccessfulAt: "2026-08-15T12:00:00Z",
|
||||||
positions: accounts.map(account => ({ ...position, account })),
|
positions: accounts.map(account => ({ ...position, account })),
|
||||||
structure: { categories: [], hasNegativeValues: false, totalValue: "0", unvaluedCategories: [] },
|
structure: { currencies: [], unvaluedCategories: [] },
|
||||||
totals: { currency: "RUB", value: "1200" },
|
totalsByCurrency: [{ currency: "RUB", value: "1200" }],
|
||||||
};
|
};
|
||||||
|
|
||||||
const receipt: BrokerageOperation
|
const receipt: BrokerageOperation
|
||||||
@@ -106,11 +106,14 @@ const analytics: IncomeAnalytics
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
period: { from: "2026-08-01", to: "2026-08-31" },
|
period: { from: "2026-08-01", to: "2026-08-31" },
|
||||||
total: {
|
totalsByCurrency: [
|
||||||
|
{
|
||||||
coupon: { currency: "RUB", value: "2" },
|
coupon: { currency: "RUB", value: "2" },
|
||||||
|
currency: "RUB",
|
||||||
dividend: { currency: "RUB", value: "0" },
|
dividend: { currency: "RUB", value: "0" },
|
||||||
total: { currency: "RUB", value: "2" },
|
total: { currency: "RUB", value: "2" },
|
||||||
},
|
},
|
||||||
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
const CurrentLocation: FC = () => {
|
const CurrentLocation: FC = () => {
|
||||||
@@ -213,7 +216,7 @@ beforeEach(() => {
|
|||||||
type: "coupon",
|
type: "coupon",
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
incomeTotal: { currency: "RUB", value: "0" },
|
incomeTotalsByCurrency: [],
|
||||||
window: { from: "2026-09-01", to: "2026-10-01" },
|
window: { from: "2026-09-01", to: "2026-10-01" },
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ const OperationGroup: FC<OperationGroupProps> = (props) => {
|
|||||||
|
|
||||||
const totalsText = totalText(totals, true);
|
const totalsText = totalText(totals, true);
|
||||||
|
|
||||||
const totalTone = isCoupon && totals && !isZeroDecimal(totals.value) && !totals.value.startsWith("-")
|
const totalTone = isCoupon && totals?.length && totals.every(total => !isZeroDecimal(total.value) && !total.value.startsWith("-"))
|
||||||
? "positive"
|
? "positive"
|
||||||
: "neutral";
|
: "neutral";
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import type {
|
|||||||
BrokerageAccount,
|
BrokerageAccount,
|
||||||
} from "../api/useBrokerageAccounts";
|
} from "../api/useBrokerageAccounts";
|
||||||
|
|
||||||
|
const VISIBLE_CURRENCY_LIMIT = 2;
|
||||||
|
|
||||||
type BrokerageAccountCard = {
|
type BrokerageAccountCard = {
|
||||||
account: BrokerageAccount;
|
account: BrokerageAccount;
|
||||||
positionCounts: null | PositionCounts;
|
positionCounts: null | PositionCounts;
|
||||||
@@ -11,13 +13,18 @@ type BrokerageAccountCard = {
|
|||||||
summary:
|
summary:
|
||||||
| {
|
| {
|
||||||
portfolio: NonNullable<BrokerageAccount["portfolioSummary"]>;
|
portfolio: NonNullable<BrokerageAccount["portfolioSummary"]>;
|
||||||
|
remainingCurrencyCount: number;
|
||||||
state: "available";
|
state: "available";
|
||||||
totals: NonNullable<BrokerageAccount["portfolioSummary"]>["totals"];
|
totals: Money[];
|
||||||
}
|
}
|
||||||
| { state: "empty" }
|
| { state: "empty" }
|
||||||
| { state: "unavailable" };
|
| { state: "unavailable" };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type Money = NonNullable<
|
||||||
|
BrokerageAccount["portfolioSummary"]
|
||||||
|
>["totalsByCurrency"][number];
|
||||||
|
|
||||||
type PositionCounts = { bonds: number; stocks: number; total: number };
|
type PositionCounts = { bonds: number; stocks: number; total: number };
|
||||||
|
|
||||||
function accountTypeKey(type: BrokerageAccount["type"]) {
|
function accountTypeKey(type: BrokerageAccount["type"]) {
|
||||||
@@ -50,7 +57,7 @@ function brokerageAccountCards(
|
|||||||
total: summary.totalPositionCount,
|
total: summary.totalPositionCount,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (Number(summary.totals.value) === 0)
|
if (summary.totalsByCurrency.length === 0)
|
||||||
return { account, positionCounts, source, summary: { state: "empty" } };
|
return { account, positionCounts, source, summary: { state: "empty" } };
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -59,8 +66,12 @@ function brokerageAccountCards(
|
|||||||
source,
|
source,
|
||||||
summary: {
|
summary: {
|
||||||
portfolio: summary,
|
portfolio: summary,
|
||||||
|
remainingCurrencyCount: Math.max(
|
||||||
|
summary.totalsByCurrency.length - VISIBLE_CURRENCY_LIMIT,
|
||||||
|
0,
|
||||||
|
),
|
||||||
state: "available",
|
state: "available",
|
||||||
totals: summary.totals,
|
totals: summary.totalsByCurrency.slice(0, VISIBLE_CURRENCY_LIMIT),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|||||||
+53
-17
@@ -14,29 +14,36 @@ type PortfolioSummary = NonNullable<BrokerageAccount["portfolioSummary"]>;
|
|||||||
const rubReturn = {
|
const rubReturn = {
|
||||||
absolute: "136900",
|
absolute: "136900",
|
||||||
costBasis: "1103600.50",
|
costBasis: "1103600.50",
|
||||||
|
currency: "RUB",
|
||||||
partial: false,
|
partial: false,
|
||||||
percent: "12.40",
|
percent: "12.40",
|
||||||
};
|
};
|
||||||
|
|
||||||
const portfolioSummary = {
|
const portfolioSummary = {
|
||||||
bondPositionCount: 12,
|
bondPositionCount: 12,
|
||||||
cash: { currency: "RUB", value: "82500.50" },
|
cashBalances: [
|
||||||
|
{ currency: "RUB", value: "82500.50" },
|
||||||
|
{ currency: "USD", value: "1500" },
|
||||||
|
],
|
||||||
fundPositionCount: 2,
|
fundPositionCount: 2,
|
||||||
stockPositionCount: 5,
|
stockPositionCount: 5,
|
||||||
structure: {
|
structure: {
|
||||||
|
currencies: [{
|
||||||
categories: [
|
categories: [
|
||||||
{ sharePercent: "55.000000", type: "STOCK", value: "682500" },
|
{ sharePercent: "55.000000", type: "STOCK", value: "682500" },
|
||||||
{ sharePercent: "25.000000", type: "BOND", value: "310500" },
|
{ sharePercent: "25.000000", type: "BOND", value: "310500" },
|
||||||
{ sharePercent: "10.000000", type: "OTHER", value: "124200" },
|
{ sharePercent: "10.000000", type: "OTHER", value: "124200" },
|
||||||
{ sharePercent: "10.000000", type: "CASH", value: "124200" },
|
{ sharePercent: "10.000000", type: "CASH", value: "124200" },
|
||||||
],
|
],
|
||||||
|
currency: "RUB",
|
||||||
hasNegativeValues: false,
|
hasNegativeValues: false,
|
||||||
totalValue: "1241400",
|
totalValue: "1241400",
|
||||||
|
}],
|
||||||
unvaluedCategories: [],
|
unvaluedCategories: [],
|
||||||
},
|
},
|
||||||
totalPositionCount: 19,
|
totalPositionCount: 19,
|
||||||
totals: { currency: "RUB", value: "1240500.50" },
|
totalsByCurrency: [{ currency: "RUB", value: "1240500.50" }],
|
||||||
unrealizedReturn: rubReturn,
|
unrealizedReturnByCurrency: [rubReturn],
|
||||||
} satisfies PortfolioSummary;
|
} satisfies PortfolioSummary;
|
||||||
|
|
||||||
function account(
|
function account(
|
||||||
@@ -56,25 +63,20 @@ function account(
|
|||||||
|
|
||||||
const negativeSummary: PortfolioSummary = {
|
const negativeSummary: PortfolioSummary = {
|
||||||
...portfolioSummary,
|
...portfolioSummary,
|
||||||
unrealizedReturn: {
|
unrealizedReturnByCurrency: [{
|
||||||
...rubReturn,
|
...rubReturn,
|
||||||
absolute: "-4200",
|
absolute: "-4200",
|
||||||
percent: "-3.05",
|
percent: "-3.05",
|
||||||
},
|
}],
|
||||||
};
|
};
|
||||||
|
|
||||||
const emptySummary: PortfolioSummary = {
|
const emptySummary: PortfolioSummary = {
|
||||||
...portfolioSummary,
|
...portfolioSummary,
|
||||||
cash: { currency: "RUB", value: "0" },
|
cashBalances: [],
|
||||||
structure: {
|
structure: { currencies: [], unvaluedCategories: [] },
|
||||||
categories: [],
|
|
||||||
hasNegativeValues: false,
|
|
||||||
totalValue: "0",
|
|
||||||
unvaluedCategories: [],
|
|
||||||
},
|
|
||||||
totalPositionCount: 0,
|
totalPositionCount: 0,
|
||||||
totals: { currency: "RUB", value: "0" },
|
totalsByCurrency: [],
|
||||||
unrealizedReturn: rubReturn,
|
unrealizedReturnByCurrency: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
const meta = {
|
const meta = {
|
||||||
@@ -92,7 +94,7 @@ const meta = {
|
|||||||
docs: {
|
docs: {
|
||||||
description: {
|
description: {
|
||||||
component:
|
component:
|
||||||
"Карточки счетов: стоимость и доходность, деньги, структура и свежесть источника. Денежные и процентные значения остаются строками. Все примеры содержат вымышленные данные; ссылки работают только внутри MemoryRouter.",
|
"Карточки счетов: стоимость и доходность по валютам, деньги, структура и свежесть источника. Денежные и процентные значения остаются строками. Все примеры содержат вымышленные данные; ссылки работают только внутри MemoryRouter.",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -106,6 +108,40 @@ type Story = StoryObj<typeof meta>;
|
|||||||
|
|
||||||
export const Normal: Story = {};
|
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 = {
|
export const Negative: Story = {
|
||||||
args: {
|
args: {
|
||||||
accounts: brokerageAccountCards([
|
accounts: brokerageAccountCards([
|
||||||
@@ -118,10 +154,10 @@ export const Partial: Story = {
|
|||||||
args: {
|
args: {
|
||||||
accounts: brokerageAccountCards([account("partial", "Частичные данные", {
|
accounts: brokerageAccountCards([account("partial", "Частичные данные", {
|
||||||
...portfolioSummary,
|
...portfolioSummary,
|
||||||
unrealizedReturn: {
|
unrealizedReturnByCurrency: [{
|
||||||
...rubReturn,
|
...rubReturn,
|
||||||
partial: true,
|
partial: true,
|
||||||
},
|
}],
|
||||||
})]),
|
})]),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
+46
-21
@@ -14,28 +14,55 @@ type PortfolioSummary = NonNullable<BrokerageAccount["portfolioSummary"]>;
|
|||||||
|
|
||||||
const portfolioSummary = {
|
const portfolioSummary = {
|
||||||
bondPositionCount: 12,
|
bondPositionCount: 12,
|
||||||
cash: { currency: "RUB", value: "82500.5" },
|
cashBalances: [
|
||||||
|
{ currency: "RUB", value: "82500.5" },
|
||||||
|
{ currency: "USD", value: "20" },
|
||||||
|
],
|
||||||
fundPositionCount: 0,
|
fundPositionCount: 0,
|
||||||
stockPositionCount: 5,
|
stockPositionCount: 5,
|
||||||
structure: {
|
structure: {
|
||||||
|
currencies: [{
|
||||||
categories: [
|
categories: [
|
||||||
{ sharePercent: "50.000000", type: "STOCK", value: "100" },
|
{ sharePercent: "50.000000", type: "STOCK", value: "100" },
|
||||||
{ sharePercent: "30.000000", type: "BOND", value: "60" },
|
{ sharePercent: "30.000000", type: "BOND", value: "60" },
|
||||||
{ sharePercent: "0.000000", type: "OTHER", value: "0" },
|
{ sharePercent: "0.000000", type: "OTHER", value: "0" },
|
||||||
{ sharePercent: "20.000000", type: "CASH", value: "40" },
|
{ sharePercent: "20.000000", type: "CASH", value: "40" },
|
||||||
],
|
],
|
||||||
|
currency: "RUB",
|
||||||
hasNegativeValues: false,
|
hasNegativeValues: false,
|
||||||
totalValue: "200",
|
totalValue: "200",
|
||||||
|
}],
|
||||||
unvaluedCategories: [],
|
unvaluedCategories: [],
|
||||||
},
|
},
|
||||||
totalPositionCount: 17,
|
totalPositionCount: 17,
|
||||||
totals: { currency: "RUB", value: "123456789012345678901.995" },
|
totalsByCurrency: [
|
||||||
unrealizedReturn: {
|
{ currency: "RUB", value: "123456789012345678901.995" },
|
||||||
|
{ currency: "USD", value: "20" },
|
||||||
|
{ currency: "EUR", value: "5" },
|
||||||
|
],
|
||||||
|
unrealizedReturnByCurrency: [
|
||||||
|
{
|
||||||
absolute: "136900",
|
absolute: "136900",
|
||||||
costBasis: "1000000",
|
costBasis: "1000000",
|
||||||
|
currency: "RUB",
|
||||||
partial: true,
|
partial: true,
|
||||||
percent: "12.40",
|
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;
|
} satisfies PortfolioSummary;
|
||||||
|
|
||||||
type BrokerageAccountCardInput = Parameters<typeof BrokerageAccountList>[0][
|
type BrokerageAccountCardInput = Parameters<typeof BrokerageAccountList>[0][
|
||||||
@@ -70,19 +97,16 @@ describe("BrokerageAccountList", () => {
|
|||||||
it("renders returns, cash and structure with precise totals", () => {
|
it("renders returns, cash and structure with precise totals", () => {
|
||||||
const nullReturnSummary: PortfolioSummary = {
|
const nullReturnSummary: PortfolioSummary = {
|
||||||
...portfolioSummary,
|
...portfolioSummary,
|
||||||
structure: {
|
cashBalances: [],
|
||||||
categories: [],
|
structure: { currencies: [], unvaluedCategories: [] },
|
||||||
hasNegativeValues: false,
|
totalsByCurrency: [{ currency: "EUR", value: "5" }],
|
||||||
totalValue: "0",
|
unrealizedReturnByCurrency: [{
|
||||||
unvaluedCategories: [],
|
|
||||||
},
|
|
||||||
totals: { currency: "RUB", value: "5" },
|
|
||||||
unrealizedReturn: {
|
|
||||||
absolute: "0",
|
absolute: "0",
|
||||||
costBasis: "5",
|
costBasis: "5",
|
||||||
|
currency: "EUR",
|
||||||
partial: false,
|
partial: false,
|
||||||
percent: null,
|
percent: null,
|
||||||
},
|
}],
|
||||||
};
|
};
|
||||||
|
|
||||||
renderList(brokerageAccountCards([
|
renderList(brokerageAccountCards([
|
||||||
@@ -94,15 +118,19 @@ describe("BrokerageAccountList", () => {
|
|||||||
expect(link).toHaveAttribute("href", "/accounts/account-1");
|
expect(link).toHaveAttribute("href", "/accounts/account-1");
|
||||||
expect(within(link).getByText("123 456 789 012 345 678 902,00 ₽"))
|
expect(within(link).getByText("123 456 789 012 345 678 902,00 ₽"))
|
||||||
.toBeInTheDocument();
|
.toBeInTheDocument();
|
||||||
|
expect(within(link).getByText("Еще 1 валюта")).toBeInTheDocument();
|
||||||
expect(within(link).getByText("+12,4 %")).toBeInTheDocument();
|
expect(within(link).getByText("+12,4 %")).toBeInTheDocument();
|
||||||
expect(within(link).getByText("+136 900 ₽")).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: /Без доходности/ });
|
const nullReturnLink = screen.getByRole("link", { name: /Без доходности/ });
|
||||||
expect(within(nullReturnLink).getByText("—")).toBeInTheDocument();
|
expect(within(nullReturnLink).getByText("—")).toBeInTheDocument();
|
||||||
expect(within(link).getByText("частично")).toBeInTheDocument();
|
expect(within(link).getByText("частично")).toBeInTheDocument();
|
||||||
expect(within(link).getByText("82 500,50 ₽")).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(within(link).getByText("17 позиций")).toBeInTheDocument();
|
||||||
expect(screen.getByRole("img", {
|
expect(screen.getByRole("img", {
|
||||||
name: "Структура: Акции 50,0 %; Облигации 30,0 %; "
|
name: "Структура в RUB: Акции 50,0 %; Облигации 30,0 %; "
|
||||||
+ "Другие активы 0,0 %; Свободные деньги 20,0 %",
|
+ "Другие активы 0,0 %; Свободные деньги 20,0 %",
|
||||||
})).toBeInTheDocument();
|
})).toBeInTheDocument();
|
||||||
const stockLegend = within(link).getByText(/Акции 50,0 %/);
|
const stockLegend = within(link).getByText(/Акции 50,0 %/);
|
||||||
@@ -112,20 +140,17 @@ describe("BrokerageAccountList", () => {
|
|||||||
expect(within(link).queryByText(/Другие активы 0,0 %/))
|
expect(within(link).queryByText(/Другие активы 0,0 %/))
|
||||||
.not.toBeInTheDocument();
|
.not.toBeInTheDocument();
|
||||||
expect(link).toHaveTextContent("По данным брокера");
|
expect(link).toHaveTextContent("По данным брокера");
|
||||||
expect(link).toHaveTextContent("Структура: Акции 100");
|
expect(link).toHaveTextContent("Структура RUB: Акции 100");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("preserves empty, unavailable and stale states", () => {
|
it("preserves empty, unavailable and stale states", () => {
|
||||||
const emptySummary: PortfolioSummary = {
|
const emptySummary: PortfolioSummary = {
|
||||||
...portfolioSummary,
|
...portfolioSummary,
|
||||||
structure: {
|
cashBalances: [],
|
||||||
categories: [],
|
structure: { currencies: [], unvaluedCategories: [] },
|
||||||
hasNegativeValues: false,
|
|
||||||
totalValue: "0",
|
|
||||||
unvaluedCategories: [],
|
|
||||||
},
|
|
||||||
totalPositionCount: 0,
|
totalPositionCount: 0,
|
||||||
totals: { currency: "RUB", value: "0" },
|
totalsByCurrency: [],
|
||||||
|
unrealizedReturnByCurrency: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
const cards = brokerageAccountCards([
|
const cards = brokerageAccountCards([
|
||||||
|
|||||||
@@ -34,10 +34,10 @@ type BrokerageAccountSummaryProps = {
|
|||||||
type PortfolioSummary = AvailableSummary["portfolio"];
|
type PortfolioSummary = AvailableSummary["portfolio"];
|
||||||
|
|
||||||
type ReturnValueProps = {
|
type ReturnValueProps = {
|
||||||
item: PortfolioSummary["unrealizedReturn"];
|
item: PortfolioSummary["unrealizedReturnByCurrency"][number];
|
||||||
};
|
};
|
||||||
|
|
||||||
type StructureCurrency = PortfolioSummary["structure"];
|
type StructureCurrency = PortfolioSummary["structure"]["currencies"][number];
|
||||||
|
|
||||||
function formatPercent(value: null | string) {
|
function formatPercent(value: null | string) {
|
||||||
if (value === null) return "—";
|
if (value === null) return "—";
|
||||||
@@ -81,7 +81,7 @@ const ReturnValue: FC<ReturnValueProps> = (props) => {
|
|||||||
|
|
||||||
<Text className={toneClass} size="sm">
|
<Text className={toneClass} size="sm">
|
||||||
{formatMoney(
|
{formatMoney(
|
||||||
{ currency: "RUB", value: item.absolute },
|
{ currency: item.currency, value: item.absolute },
|
||||||
{ withSign: true },
|
{ withSign: true },
|
||||||
)}
|
)}
|
||||||
</Text>
|
</Text>
|
||||||
@@ -119,6 +119,7 @@ const StructureBar: FC<StructureBarProps> = (props) => {
|
|||||||
}).join("; ");
|
}).join("; ");
|
||||||
|
|
||||||
const label = t("accounts.structure.label", {
|
const label = t("accounts.structure.label", {
|
||||||
|
currency: props.item.currency,
|
||||||
value: description,
|
value: description,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -196,24 +197,50 @@ const BrokerageAccountSummary: FC<BrokerageAccountSummaryProps> = (props) => {
|
|||||||
return (
|
return (
|
||||||
<Stack className={classes.balance} gap="xs">
|
<Stack className={classes.balance} gap="xs">
|
||||||
<Stack className={classes.summary} gap="sm">
|
<Stack className={classes.summary} gap="sm">
|
||||||
<Stack className={classes.currencySummary} gap={2}>
|
{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}
|
||||||
|
>
|
||||||
<Text className={classes.total} fw={700}>
|
<Text className={classes.total} fw={700}>
|
||||||
{formatMoney(summary.totals, { withRoundedCents: true })}
|
{formatMoney(total, { withRoundedCents: true })}
|
||||||
</Text>
|
</Text>
|
||||||
|
|
||||||
<ReturnValue item={summary.portfolio.unrealizedReturn} />
|
{item && <ReturnValue item={item} />}
|
||||||
</Stack>
|
</Stack>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
{!!summary.remainingCurrencyCount && (
|
||||||
|
<Text c="dimmed" size="sm">
|
||||||
|
{t("accounts.remainingCurrencies", {
|
||||||
|
count: summary.remainingCurrencyCount,
|
||||||
|
})}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
|
{summary.portfolio.cashBalances.length > 0 && (
|
||||||
<Group className={classes.cash} gap="xs" justify="flex-end">
|
<Group className={classes.cash} gap="xs" justify="flex-end">
|
||||||
<Text c="dimmed" size="xs">
|
<Text c="dimmed" size="xs">
|
||||||
{t("accounts.cash")}
|
{t("accounts.cash")}
|
||||||
</Text>
|
</Text>
|
||||||
|
|
||||||
<Text className={classes.cashValue} size="sm">
|
<Stack gap={0}>
|
||||||
{formatMoney(summary.portfolio.cash, { withRoundedCents: true })}
|
{summary.portfolio.cashBalances.map(cash => (
|
||||||
|
<Text className={classes.cashValue} key={cash.currency} size="sm">
|
||||||
|
{formatMoney(cash, { withRoundedCents: true })}
|
||||||
</Text>
|
</Text>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
</Group>
|
</Group>
|
||||||
|
)}
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -260,31 +287,39 @@ const AccountDescription: FC<AccountDescriptionProps> = (props) => {
|
|||||||
const { account, summary } = props.account;
|
const { account, summary } = props.account;
|
||||||
if (summary.state !== "available") return null;
|
if (summary.state !== "available") return null;
|
||||||
|
|
||||||
const returns = [t("accounts.description.return", {
|
const returns = summary.portfolio.unrealizedReturnByCurrency.map(item =>
|
||||||
|
t("accounts.description.return", {
|
||||||
absolute: formatMoney(
|
absolute: formatMoney(
|
||||||
{ currency: "RUB", value: summary.portfolio.unrealizedReturn.absolute },
|
{ currency: item.currency, value: item.absolute },
|
||||||
{ withSign: true },
|
{ withSign: true },
|
||||||
),
|
),
|
||||||
percent: formatPercent(summary.portfolio.unrealizedReturn.percent),
|
currency: item.currency,
|
||||||
})];
|
percent: formatPercent(item.percent),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
const structures = (() => {
|
const structures = summary.portfolio.structure.currencies.map((item) => {
|
||||||
const categories = summary.portfolio.structure.categories.map(category =>
|
const categories = item.categories.map(category =>
|
||||||
t("accounts.description.structureCategory", {
|
t("accounts.description.structureCategory", {
|
||||||
category: t(portfolioCategoryPresentation[category.type].label),
|
category: t(portfolioCategoryPresentation[category.type].label),
|
||||||
value: formatMoney(
|
value: formatMoney(
|
||||||
{ currency: "RUB", value: category.value },
|
{ currency: item.currency, value: category.value },
|
||||||
{ withRoundedCents: true },
|
{ withRoundedCents: true },
|
||||||
),
|
),
|
||||||
}),
|
}),
|
||||||
).join(", ");
|
).join(", ");
|
||||||
|
|
||||||
return t("accounts.description.structure", { value: categories });
|
return t("accounts.description.structure", {
|
||||||
})();
|
currency: item.currency,
|
||||||
|
value: categories,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
const hasPartialReturn = summary.portfolio.unrealizedReturn.partial;
|
const hasPartialReturn = summary.portfolio.unrealizedReturnByCurrency.some(
|
||||||
|
item => item.partial,
|
||||||
|
);
|
||||||
|
|
||||||
const details = [returns, structures].join(". ");
|
const details = [...returns, ...structures].join(". ");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<VisuallyHidden>
|
<VisuallyHidden>
|
||||||
@@ -293,7 +328,8 @@ const AccountDescription: FC<AccountDescriptionProps> = (props) => {
|
|||||||
type: t(accountTypeKey(account.type)),
|
type: t(accountTypeKey(account.type)),
|
||||||
})}
|
})}
|
||||||
{t("accounts.description.currentValue", {
|
{t("accounts.description.currentValue", {
|
||||||
value: formatMoney(summary.portfolio.totals),
|
value: summary.portfolio.totalsByCurrency
|
||||||
|
.map(total => formatMoney(total)).join(", "),
|
||||||
})}
|
})}
|
||||||
{details ? `${details}. ` : ""}
|
{details ? `${details}. ` : ""}
|
||||||
{hasPartialReturn ? t("accounts.brokerDescription") : ""}
|
{hasPartialReturn ? t("accounts.brokerDescription") : ""}
|
||||||
@@ -333,7 +369,9 @@ const BrokerageAccountList: FC<BrokerageAccountListProps> = (props) => {
|
|||||||
|
|
||||||
{summary.state === "available" && (
|
{summary.state === "available" && (
|
||||||
<Stack className={classes.structure} gap={4}>
|
<Stack className={classes.structure} gap={4}>
|
||||||
<StructureBar item={summary.portfolio.structure} />
|
{summary.portfolio.structure.currencies.map(item => (
|
||||||
|
<StructureBar item={item} key={item.currency} />
|
||||||
|
))}
|
||||||
</Stack>
|
</Stack>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -97,13 +97,13 @@ describe("BrokerageEventGroup", () => {
|
|||||||
expect(screen.getByText("0,00 ₽")).toBeInTheDocument();
|
expect(screen.getByText("0,00 ₽")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("sums forecast totals exactly", () => {
|
it("shows separate forecast totals per currency without conversion", () => {
|
||||||
renderGroup([
|
renderGroup([
|
||||||
event({ id: "broker", name: "Брокерский" }, "10"),
|
event({ id: "broker", name: "Брокерский" }, "10", "USD"),
|
||||||
event({ id: "iis", name: "ИИС" }, "200"),
|
event({ id: "iis", name: "ИИС" }, "200"),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
expect(screen.getByRole("list", { name: /210 ₽/ }))
|
expect(screen.getByRole("list", { name: /10 \$.*200 ₽/ }))
|
||||||
.toBeInTheDocument();
|
.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import type { Portfolio } from "../api/usePortfolio";
|
|||||||
|
|
||||||
const PERCENT_SCALE = 100;
|
const PERCENT_SCALE = 100;
|
||||||
|
|
||||||
type Money = Portfolio["totals"];
|
type Money = Portfolio["totalsByCurrency"][number];
|
||||||
|
|
||||||
function formatShare(
|
function formatShare(
|
||||||
numerator: Money | null,
|
numerator: Money | null,
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ function useInstrumentChartVm(props: InstrumentChartProps) {
|
|||||||
const average = vm.position?.averagePurchasePrice;
|
const average = vm.position?.averagePurchasePrice;
|
||||||
|
|
||||||
const averageLine = average && props.priceUnit !== "percent"
|
const averageLine = average && props.priceUnit !== "percent"
|
||||||
|
&& average.currency === vm.candles?.currency
|
||||||
? Number(average.value)
|
? Number(average.value)
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
@@ -46,7 +47,7 @@ function useInstrumentChartVm(props: InstrumentChartProps) {
|
|||||||
currency:
|
currency:
|
||||||
props.priceUnit === "percent"
|
props.priceUnit === "percent"
|
||||||
? t("bond.percentOfNominal")
|
? t("bond.percentOfNominal")
|
||||||
: "₽",
|
: (vm.candles?.currency ?? ""),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -23,7 +23,7 @@ const meta = {
|
|||||||
},
|
},
|
||||||
render: arguments_ => (
|
render: arguments_ => (
|
||||||
<Stack>
|
<Stack>
|
||||||
<Text>125 000,50 ₽</Text>
|
<Text>125 000,50 ₽ · 320 USD</Text>
|
||||||
|
|
||||||
<InvestmentRefreshState {...arguments_} />
|
<InvestmentRefreshState {...arguments_} />
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|||||||
@@ -263,7 +263,7 @@ describe("Upcoming event date filters", () => {
|
|||||||
accountId,
|
accountId,
|
||||||
calculatedAt: "2099-01-01T00:00:00Z",
|
calculatedAt: "2099-01-01T00:00:00Z",
|
||||||
events: [],
|
events: [],
|
||||||
incomeTotal: { currency: "RUB", value: "0" },
|
incomeTotalsByCurrency: [],
|
||||||
window: { from: "2099-01-01", to: "2099-01-31" },
|
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(
|
const snapshot = resource(
|
||||||
{ events, incomeTotal: { currency: "RUB", value: "123.45" } },
|
{ events, incomeTotalsByCurrency: [{ currency: "RUB", value: "123.45" }] },
|
||||||
{
|
{
|
||||||
lastAttempt: {
|
lastAttempt: {
|
||||||
finishedAt: "2026-08-14T00:01:00Z",
|
finishedAt: "2026-08-14T00:01:00Z",
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ const snapshot = resource({
|
|||||||
type: "coupon",
|
type: "coupon",
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
incomeTotal: { currency: "RUB", value: "123.45" },
|
incomeTotalsByCurrency: [{ currency: "RUB", value: "123.45" }],
|
||||||
window: { from: "2026-08-14", to: "2026-09-13" },
|
window: { from: "2026-08-14", to: "2026-09-13" },
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ const analytics
|
|||||||
buckets: [
|
buckets: [
|
||||||
{
|
{
|
||||||
period: { from: "2026-08-01", to: "2026-08-01" },
|
period: { from: "2026-08-01", to: "2026-08-01" },
|
||||||
total: summary("10", "2"),
|
totalsByCurrency: [summary("RUB", "10", "2")],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
calculatedAt: "2026-08-27T00:00:00Z",
|
calculatedAt: "2026-08-27T00:00:00Z",
|
||||||
@@ -77,7 +77,7 @@ const analytics
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
period: { from: "2026-08-01", to: "2026-08-27" },
|
period: { from: "2026-08-01", to: "2026-08-27" },
|
||||||
total: summary("10", "2"),
|
totalsByCurrency: [summary("RUB", "10", "2")],
|
||||||
} satisfies IncomeAnalytics & { instruments: [unknown] };
|
} satisfies IncomeAnalytics & { instruments: [unknown] };
|
||||||
|
|
||||||
function entry(): IncomeAnalytics["entries"][number] {
|
function entry(): IncomeAnalytics["entries"][number] {
|
||||||
@@ -145,11 +145,12 @@ function renderPage(
|
|||||||
return { ...view, queryClient };
|
return { ...view, queryClient };
|
||||||
}
|
}
|
||||||
|
|
||||||
function summary(coupon: string, dividend: string) {
|
function summary(currency: string, coupon: string, dividend: string) {
|
||||||
return {
|
return {
|
||||||
coupon: money("RUB", coupon),
|
coupon: money(currency, coupon),
|
||||||
dividend: money("RUB", dividend),
|
currency,
|
||||||
total: money("RUB", String(Number(coupon) + Number(dividend))),
|
dividend: money(currency, dividend),
|
||||||
|
total: money(currency, String(Number(coupon) + Number(dividend))),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -307,7 +308,7 @@ describe("AccountIncomePage", () => {
|
|||||||
buckets: [],
|
buckets: [],
|
||||||
entries: [],
|
entries: [],
|
||||||
instruments: [],
|
instruments: [],
|
||||||
total: summary("0", "0"),
|
totalsByCurrency: [],
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -409,7 +410,7 @@ describe("AccountIncomePage", () => {
|
|||||||
|
|
||||||
it.each([
|
it.each([
|
||||||
["full", analytics],
|
["full", analytics],
|
||||||
["empty", { ...analytics, buckets: [], entries: [], instruments: [], total: summary("0", "0") }],
|
["empty", { ...analytics, buckets: [], entries: [], instruments: [], totalsByCurrency: [] }],
|
||||||
])("shows the server source time and last attempt for a %s result", async (_name, data) => {
|
])("shows the server source time and last attempt for a %s result", async (_name, data) => {
|
||||||
server.use(
|
server.use(
|
||||||
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
|
http.get("*/api/v1/brokerage-accounts/account-1/income-analytics", () =>
|
||||||
@@ -736,11 +737,11 @@ describe("income period and snapshot boundary", () => {
|
|||||||
const instruments = [
|
const instruments = [
|
||||||
{
|
{
|
||||||
...analytics.instruments[0],
|
...analytics.instruments[0],
|
||||||
coupon: money("RUB", "10"),
|
coupon: money("USD", "10"),
|
||||||
dividend: money("RUB", "0"),
|
dividend: money("USD", "0"),
|
||||||
key: "rub-positive",
|
key: "usd",
|
||||||
receiptCount: 1,
|
receiptCount: 1,
|
||||||
total: money("RUB", "10"),
|
total: money("USD", "10"),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
...analytics.instruments[0],
|
...analytics.instruments[0],
|
||||||
@@ -769,7 +770,7 @@ describe("income period and snapshot boundary", () => {
|
|||||||
payment: instrument.total,
|
payment: instrument.total,
|
||||||
})),
|
})),
|
||||||
instruments,
|
instruments,
|
||||||
total: summary("-5", "0"),
|
totalsByCurrency: [summary("RUB", "-5", "0"), summary("USD", "10", "0")],
|
||||||
});
|
});
|
||||||
|
|
||||||
render(
|
render(
|
||||||
@@ -781,9 +782,10 @@ describe("income period and snapshot boundary", () => {
|
|||||||
screen.getByRole("heading", { name: "Выплаты" }),
|
screen.getByRole("heading", { name: "Выплаты" }),
|
||||||
).toBeInTheDocument();
|
).toBeInTheDocument();
|
||||||
expect(screen.queryByText("RUB")).not.toBeInTheDocument();
|
expect(screen.queryByText("RUB")).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByText("USD")).not.toBeInTheDocument();
|
||||||
const cards = screen.getAllByRole("listitem");
|
const cards = screen.getAllByRole("listitem");
|
||||||
expect(cards).toHaveLength(3);
|
expect(cards).toHaveLength(3);
|
||||||
expect(cards[0]).toHaveTextContent("+10 ₽");
|
expect(cards[0]).toHaveTextContent("+10 $");
|
||||||
expect(cards[1]).toHaveTextContent("−2 ₽");
|
expect(cards[1]).toHaveTextContent("−2 ₽");
|
||||||
expect(cards[2]).toHaveTextContent("−3 ₽");
|
expect(cards[2]).toHaveTextContent("−3 ₽");
|
||||||
expect(screen.queryByText(/Итого:|Выплат:/)).not.toBeInTheDocument();
|
expect(screen.queryByText(/Итого:|Выплат:/)).not.toBeInTheDocument();
|
||||||
|
|||||||
+8
-3
@@ -5,6 +5,7 @@ import {
|
|||||||
Stack,
|
Stack,
|
||||||
Title,
|
Title,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
|
import { StateView } from "@wealthledger/ui";
|
||||||
import { FormProvider } from "react-hook-form";
|
import { FormProvider } from "react-hook-form";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
@@ -24,9 +25,13 @@ const AccountIncomePageLoadedSummary: FC<LoadedProps> = (props) => {
|
|||||||
|
|
||||||
const { analytics } = props;
|
const { analytics } = props;
|
||||||
|
|
||||||
return props.partial
|
if (props.partial) {
|
||||||
? <Alert role="status">{t("investment.partial")}</Alert>
|
return <Alert role="status">{t("investment.partial")}</Alert>;
|
||||||
: <IncomeSummary totals={analytics.total} />;
|
}
|
||||||
|
|
||||||
|
return analytics.totalsByCurrency.length > 0
|
||||||
|
? <IncomeSummary totals={analytics.totalsByCurrency} />
|
||||||
|
: <StateView text={t("income.emptyText")} title={t("income.emptyTitle")} />;
|
||||||
};
|
};
|
||||||
|
|
||||||
const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
|
const AccountIncomePageLoaded: FC<LoadedProps> = (props) => {
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import type { IncomeAnalytics } from "@/entities/income";
|
|||||||
|
|
||||||
import { formatMoney } from "@/shared/lib";
|
import { formatMoney } from "@/shared/lib";
|
||||||
|
|
||||||
type IncomeSummaryProps = { totals: IncomeAnalytics["total"] };
|
type IncomeSummaryProps = { totals: IncomeAnalytics["totalsByCurrency"] };
|
||||||
|
|
||||||
const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
|
const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -16,14 +16,16 @@ const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
|
|||||||
<Stack>
|
<Stack>
|
||||||
<Title order={2}>{t("income.summaryTitle")}</Title>
|
<Title order={2}>{t("income.summaryTitle")}</Title>
|
||||||
|
|
||||||
<Paper p="md" radius="md" withBorder>
|
{props.totals.map(total => (
|
||||||
<Text fw={700}>{formatMoney(props.totals.total)}</Text>
|
<Paper key={total.currency} p="md" radius="md" withBorder>
|
||||||
|
<Text fw={700}>{formatMoney(total.total)}</Text>
|
||||||
|
|
||||||
<Text c="dimmed" size="sm">
|
<Text c="dimmed" size="sm">
|
||||||
{t("income.coupon")}: {formatMoney(props.totals.coupon)} ·{" "}
|
{t("income.coupon")}: {formatMoney(total.coupon)} ·{" "}
|
||||||
{t("income.dividend")}: {formatMoney(props.totals.dividend)}
|
{t("income.dividend")}: {formatMoney(total.dividend)}
|
||||||
</Text>
|
</Text>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
))}
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -35,13 +35,15 @@ describe("account concentration", () => {
|
|||||||
const model = toConcentration(snapshot([
|
const model = toConcentration(snapshot([
|
||||||
stock("A", "1"), stock("B", "15"),
|
stock("A", "1"), stock("B", "15"),
|
||||||
stock("C", "0"), stock("D", "-50"), stock("E", null),
|
stock("C", "0"), stock("D", "-50"), stock("E", null),
|
||||||
]), "stocks", labels);
|
stock("F", null, "USD"), stock("G", "-3", "USD"),
|
||||||
|
]), "stocks", "RUB", labels);
|
||||||
|
|
||||||
|
expect(model.currencies).toEqual(["RUB", "USD"]);
|
||||||
expect(model.total).toBe("16");
|
expect(model.total).toBe("16");
|
||||||
expect(model.items.map(item => item.share)).toEqual(["93,8 %", "6,3 %"]);
|
expect(model.items.map(item => item.share)).toEqual(["93,8 %", "6,3 %"]);
|
||||||
expect(model.unaccounted).toBe(2);
|
expect(model.unaccounted).toBe(3);
|
||||||
const negative = snapshot([stock("A", "-3")]);
|
const negative = snapshot([stock("A", "-3", "USD")]);
|
||||||
expect(toConcentration(negative, "stocks", labels))
|
expect(toConcentration(negative, "stocks", "USD", labels))
|
||||||
.toMatchObject({ empty: true, unaccounted: 1 });
|
.toMatchObject({ empty: true, unaccounted: 1 });
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -50,7 +52,7 @@ describe("account concentration", () => {
|
|||||||
stock("A", "400"), stock("B", "250"), stock("C", "150"),
|
stock("A", "400"), stock("B", "250"), stock("C", "150"),
|
||||||
stock("D", "100"), stock("E", "50"), stock("F", "30"),
|
stock("D", "100"), stock("E", "50"), stock("F", "30"),
|
||||||
stock("G", "20"),
|
stock("G", "20"),
|
||||||
]), "stocks", labels);
|
]), "stocks", "RUB", labels);
|
||||||
|
|
||||||
expect(model.items.map(item => item.amount)).toEqual([
|
expect(model.items.map(item => item.amount)).toEqual([
|
||||||
"400", "250", "150", "100", "50",
|
"400", "250", "150", "100", "50",
|
||||||
@@ -69,7 +71,7 @@ describe("account concentration", () => {
|
|||||||
stock("Сбер", "100"), stock("X5", "100"),
|
stock("Сбер", "100"), stock("X5", "100"),
|
||||||
stock("VK", "100"), stock("D", "100"),
|
stock("VK", "100"), stock("D", "100"),
|
||||||
stock("E", "100"), stock("F", "100"),
|
stock("E", "100"), stock("F", "100"),
|
||||||
]), "stocks", labels);
|
]), "stocks", "RUB", labels);
|
||||||
|
|
||||||
expect(model.items).toHaveLength(6);
|
expect(model.items).toHaveLength(6);
|
||||||
expect(model.other).toBeNull();
|
expect(model.other).toBeNull();
|
||||||
@@ -81,7 +83,7 @@ describe("account concentration", () => {
|
|||||||
stock("Large", "100000000"), stock("Small", "1"),
|
stock("Large", "100000000"), stock("Small", "1"),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
expect(toConcentration(tiny, "stocks", labels).items[1]?.share)
|
expect(toConcentration(tiny, "stocks", "RUB", labels).items[1]?.share)
|
||||||
.toBe("< 0,1 %");
|
.toBe("< 0,1 %");
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -101,9 +103,9 @@ describe("account concentration", () => {
|
|||||||
stock("D", "50", "RUB", { issuer: null, sector: null }),
|
stock("D", "50", "RUB", { issuer: null, sector: null }),
|
||||||
];
|
];
|
||||||
|
|
||||||
expect(toConcentration(snapshot(positions), "sectors", labels)
|
expect(toConcentration(snapshot(positions), "sectors", "RUB", labels)
|
||||||
.items.map(item => item.amount)).toEqual(["500", "100", "50"]);
|
.items.map(item => item.amount)).toEqual(["500", "100", "50"]);
|
||||||
expect(toConcentration(snapshot(positions), "issuers", labels)
|
expect(toConcentration(snapshot(positions), "issuers", "RUB", labels)
|
||||||
.items.map(item => [item.name, item.amount])).toEqual([
|
.items.map(item => [item.name, item.amount])).toEqual([
|
||||||
["Сбербанк", "500"], ["", "50"],
|
["Сбербанк", "500"], ["", "50"],
|
||||||
]);
|
]);
|
||||||
@@ -121,7 +123,7 @@ describe("account concentration", () => {
|
|||||||
stock("D", "100", "RUB", { issuer: null, sector: "energy" }),
|
stock("D", "100", "RUB", { issuer: null, sector: "energy" }),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
expect(toConcentration(issuers, "issuers", labels)
|
expect(toConcentration(issuers, "issuers", "RUB", labels)
|
||||||
.items.map(item => [item.label, item.amount])).toEqual([
|
.items.map(item => [item.label, item.amount])).toEqual([
|
||||||
["Газпром", "300"], ["Сбер", "300"], ["Эмитент не указан", "300"],
|
["Газпром", "300"], ["Сбер", "300"], ["Эмитент не указан", "300"],
|
||||||
]);
|
]);
|
||||||
@@ -138,7 +140,7 @@ describe("account concentration", () => {
|
|||||||
: "Энергетика",
|
: "Энергетика",
|
||||||
};
|
};
|
||||||
|
|
||||||
expect(toConcentration(sectors, "sectors", sectorLabels)
|
expect(toConcentration(sectors, "sectors", "RUB", sectorLabels)
|
||||||
.items.map(item => item.label))
|
.items.map(item => item.label))
|
||||||
.toEqual(["Информационные технологии", "Энергетика"]);
|
.toEqual(["Информационные технологии", "Энергетика"]);
|
||||||
});
|
});
|
||||||
@@ -156,7 +158,7 @@ describe("account concentration", () => {
|
|||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
expect(toConcentration(data, "issuers", labels).items
|
expect(toConcentration(data, "issuers", "RUB", labels).items
|
||||||
.map(item => [item.name, item.label, item.amount])).toEqual([
|
.map(item => [item.name, item.label, item.amount])).toEqual([
|
||||||
["Альфа", "Альфа", "400"], ["Бета", "Бета", "400"],
|
["Альфа", "Альфа", "400"], ["Бета", "Бета", "400"],
|
||||||
]);
|
]);
|
||||||
@@ -167,7 +169,7 @@ describe("account concentration", () => {
|
|||||||
isin: "RU000A0JX0J2", ticker: "BOND", type: "BOND",
|
isin: "RU000A0JX0J2", ticker: "BOND", type: "BOND",
|
||||||
})]);
|
})]);
|
||||||
|
|
||||||
expect(toConcentration(data, "bonds", labels)
|
expect(toConcentration(data, "bonds", "RUB", labels)
|
||||||
.items[0]?.logo?.subtitle).toBe("RU000A0JX0J2");
|
.items[0]?.logo?.subtitle).toBe("RU000A0JX0J2");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
} from "@/shared/lib";
|
} from "@/shared/lib";
|
||||||
|
|
||||||
type Concentration = {
|
type Concentration = {
|
||||||
|
currencies: string[];
|
||||||
empty: boolean;
|
empty: boolean;
|
||||||
items: ConcentrationItem[];
|
items: ConcentrationItem[];
|
||||||
other: ConcentrationOther | null;
|
other: ConcentrationOther | null;
|
||||||
@@ -82,9 +83,11 @@ function addPosition(
|
|||||||
index: number,
|
index: number,
|
||||||
slice: Slice,
|
slice: Slice,
|
||||||
labels: ConcentrationLabels,
|
labels: ConcentrationLabels,
|
||||||
|
selected: null | string,
|
||||||
): number {
|
): number {
|
||||||
if (!isIncluded(slice, position.type)) return 0;
|
if (!isIncluded(slice, position.type)) return 0;
|
||||||
if (!position.currentValue) return 1;
|
if (!position.currentValue) return 1;
|
||||||
|
if (position.currentValue.currency !== selected) return 0;
|
||||||
const value = decimalFromString(position.currentValue.value);
|
const value = decimalFromString(position.currentValue.value);
|
||||||
if (value.value < 0n) return 1;
|
if (value.value < 0n) return 1;
|
||||||
if (value.value === 0n) return 0;
|
if (value.value === 0n) return 0;
|
||||||
@@ -132,6 +135,16 @@ function compareDecimal(a: Decimal, b: Decimal): number {
|
|||||||
return left < right ? -1 : 0;
|
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(
|
function groupIdentity(
|
||||||
position: Position,
|
position: Position,
|
||||||
slice: Slice,
|
slice: Slice,
|
||||||
@@ -201,13 +214,22 @@ function share(part: Decimal, total: Decimal): string {
|
|||||||
function toConcentration(
|
function toConcentration(
|
||||||
portfolio: Portfolio,
|
portfolio: Portfolio,
|
||||||
slice: Slice,
|
slice: Slice,
|
||||||
|
currency: null | string,
|
||||||
labels: ConcentrationLabels,
|
labels: ConcentrationLabels,
|
||||||
): Concentration {
|
): Concentration {
|
||||||
|
const currencies = concentrationCurrencies(portfolio);
|
||||||
|
|
||||||
|
const selected = currency && currencies.includes(currency)
|
||||||
|
? currency
|
||||||
|
: currencies[0] ?? null;
|
||||||
|
|
||||||
const groups = new Map<string, Group>();
|
const groups = new Map<string, Group>();
|
||||||
let unaccounted = 0;
|
let unaccounted = 0;
|
||||||
|
|
||||||
for (const [index, position] of portfolio.positions.entries()) {
|
for (const [index, position] of portfolio.positions.entries()) {
|
||||||
unaccounted += addPosition(groups, position, index, slice, labels);
|
unaccounted += addPosition(
|
||||||
|
groups, position, index, slice, labels, selected,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const ranked = Array.from(groups.values(), group => ({
|
const ranked = Array.from(groups.values(), group => ({
|
||||||
@@ -256,6 +278,7 @@ function toConcentration(
|
|||||||
: null;
|
: null;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
currencies,
|
||||||
empty: !total,
|
empty: !total,
|
||||||
items: other ? entries.slice(0, TOP) : entries,
|
items: other ? entries.slice(0, TOP) : entries,
|
||||||
other,
|
other,
|
||||||
@@ -266,6 +289,7 @@ function toConcentration(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
|
concentrationCurrencies,
|
||||||
toConcentration,
|
toConcentration,
|
||||||
};
|
};
|
||||||
export type {
|
export type {
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ const reasonLabels: Record<string, string> = {
|
|||||||
HISTORY_START_UNKNOWN: "Начало истории счёта неизвестно",
|
HISTORY_START_UNKNOWN: "Начало истории счёта неизвестно",
|
||||||
INDEX_HISTORY_UNAVAILABLE: "История индекса временно недоступна",
|
INDEX_HISTORY_UNAVAILABLE: "История индекса временно недоступна",
|
||||||
NO_SOLUTION: "Расчёт доходности не сходится",
|
NO_SOLUTION: "Расчёт доходности не сходится",
|
||||||
|
NON_RUB_ACTIVITY: "Есть операции или позиции не в рублях",
|
||||||
OPERATIONS_HISTORY_INCOMPLETE: "История операций ещё не получена полностью",
|
OPERATIONS_HISTORY_INCOMPLETE: "История операций ещё не получена полностью",
|
||||||
PORTFOLIO_VALUATION_INCOMPLETE: "Нет полной оценки портфеля",
|
PORTFOLIO_VALUATION_INCOMPLETE: "Нет полной оценки портфеля",
|
||||||
UNCONFIRMED_TRANSFER: "Перевод между счетами не удалось подтвердить",
|
UNCONFIRMED_TRANSFER: "Перевод между счетами не удалось подтвердить",
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import type { Portfolio } from "@/entities/portfolio";
|
|||||||
|
|
||||||
const portfolio
|
const portfolio
|
||||||
= {
|
= {
|
||||||
cash: { currency: "RUB", value: "1" },
|
cashBalances: [{ currency: "USD", value: "1" }],
|
||||||
isStale: true,
|
isStale: true,
|
||||||
lastSuccessfulAt: "2026-08-13T10:00:00Z",
|
lastSuccessfulAt: "2026-08-13T10:00:00Z",
|
||||||
positions: [
|
positions: [
|
||||||
@@ -49,13 +49,8 @@ const portfolio
|
|||||||
type: "FUND",
|
type: "FUND",
|
||||||
},
|
},
|
||||||
] satisfies [Portfolio["positions"][number], ...Portfolio["positions"]],
|
] satisfies [Portfolio["positions"][number], ...Portfolio["positions"]],
|
||||||
structure: {
|
structure: { currencies: [], unvaluedCategories: [] },
|
||||||
categories: [],
|
totalsByCurrency: [{ currency: "RUB", value: "150" }],
|
||||||
hasNegativeValues: false,
|
|
||||||
totalValue: "0",
|
|
||||||
unvaluedCategories: [],
|
|
||||||
},
|
|
||||||
totals: { currency: "RUB", value: "150" },
|
|
||||||
} satisfies Portfolio;
|
} satisfies Portfolio;
|
||||||
|
|
||||||
const position: Portfolio["positions"][number] = {
|
const position: Portfolio["positions"][number] = {
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ describe("account position sections", () => {
|
|||||||
|
|
||||||
const snapshot: Portfolio = {
|
const snapshot: Portfolio = {
|
||||||
...portfolio,
|
...portfolio,
|
||||||
cash: { currency: "RUB", value: "1000" },
|
cashBalances: [{ currency: "RUB", value: "1000" }],
|
||||||
positions: [
|
positions: [
|
||||||
...portfolio.positions,
|
...portfolio.positions,
|
||||||
{
|
{
|
||||||
@@ -56,8 +56,8 @@ describe("account position sections", () => {
|
|||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
structure: { categories: [], hasNegativeValues: false, totalValue: "0", unvaluedCategories: [] },
|
structure: { currencies: [], unvaluedCategories: [] },
|
||||||
totals: { currency: "RUB", value: "1250" },
|
totalsByCurrency: [{ currency: "RUB", value: "1250" }],
|
||||||
};
|
};
|
||||||
|
|
||||||
const original = structuredClone(snapshot);
|
const original = structuredClone(snapshot);
|
||||||
@@ -193,13 +193,13 @@ describe("account position sections", () => {
|
|||||||
).toHaveLength(2);
|
).toHaveLength(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("keeps values and purchase prices attached to their source positions", () => {
|
it("keeps currencies and purchase prices attached to their source positions", () => {
|
||||||
const source = [
|
const source = [
|
||||||
position,
|
position,
|
||||||
{
|
{
|
||||||
...second,
|
...second,
|
||||||
averagePurchasePrice: { currency: "RUB", value: "0.99" },
|
averagePurchasePrice: { currency: "USD", value: "0.99" },
|
||||||
currentValue: { currency: "RUB", value: "1.01" },
|
currentValue: { currency: "USD", value: "1.01" },
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -264,6 +264,10 @@ describe("account position returns", () => {
|
|||||||
{ name: "zero quantity", overrides: { quantity: "0" } },
|
{ name: "zero quantity", overrides: { quantity: "0" } },
|
||||||
{ name: "negative quantity", overrides: { quantity: "-1" } },
|
{ name: "negative quantity", overrides: { quantity: "-1" } },
|
||||||
{ name: "missing average price", overrides: { averagePurchasePrice: null } },
|
{ 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" } } },
|
{ name: "zero cost", overrides: { averagePurchasePrice: { currency: "RUB", value: "0" } } },
|
||||||
])("returns null for $name", ({ overrides }) => {
|
])("returns null for $name", ({ overrides }) => {
|
||||||
const result = sections([makePosition({
|
const result = sections([makePosition({
|
||||||
@@ -297,24 +301,29 @@ describe("account position returns", () => {
|
|||||||
expect(formatPositionReturnPercent(testCase.value)).toBe(testCase.expected);
|
expect(formatPositionReturnPercent(testCase.value)).toBe(testCase.expected);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("sums complete unrealized returns", () => {
|
it("sums complete unrealized returns by currency", () => {
|
||||||
const result = toUnrealizedReturns([
|
const result = toUnrealizedReturns([
|
||||||
makePosition({ absoluteReturn: { currency: "RUB", value: "0.1" } }),
|
makePosition({ absoluteReturn: { currency: "RUB", value: "0.1" } }),
|
||||||
makePosition({ absoluteReturn: { currency: "RUB", value: "0.2" } }),
|
makePosition({ absoluteReturn: { currency: "RUB", value: "0.2" } }),
|
||||||
|
makePosition({ absoluteReturn: { currency: "USD", value: "-2.5" } }),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
expect(result).toEqual({ currency: "RUB", value: "0.3" });
|
expect(result).toEqual([
|
||||||
|
{ currency: "RUB", value: "0.3" },
|
||||||
|
{ currency: "USD", value: "-2.5" },
|
||||||
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns null when any return is incomplete", () => {
|
it("omits only currencies with incomplete returns", () => {
|
||||||
const result = toUnrealizedReturns([
|
const result = toUnrealizedReturns([
|
||||||
makePosition({ absoluteReturn: { currency: "RUB", value: "10" } }),
|
makePosition({ absoluteReturn: { currency: "RUB", value: "10" } }),
|
||||||
makePosition({
|
makePosition({
|
||||||
absoluteReturn: null,
|
absoluteReturn: null,
|
||||||
currentValue: { currency: "RUB", value: "100" },
|
currentValue: { currency: "RUB", value: "100" },
|
||||||
}),
|
}),
|
||||||
|
makePosition({ absoluteReturn: { currency: "USD", value: "2" } }),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
expect(result).toBeNull();
|
expect(result).toEqual([{ currency: "USD", value: "2" }]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -249,23 +249,37 @@ function toSection(
|
|||||||
|
|
||||||
function toUnrealizedReturns(
|
function toUnrealizedReturns(
|
||||||
positions: Portfolio["positions"],
|
positions: Portfolio["positions"],
|
||||||
): Money | null {
|
): Money[] {
|
||||||
const values: Decimal[] = [];
|
const totals = new Map<string, {
|
||||||
|
complete: boolean;
|
||||||
|
values: Decimal[];
|
||||||
|
}>();
|
||||||
|
|
||||||
for (const position of positions) {
|
for (const position of positions) {
|
||||||
if (!position.absoluteReturn) {
|
const currencies = position.absoluteReturn
|
||||||
// A position without any valuation has nothing to contribute.
|
? [position.absoluteReturn.currency]
|
||||||
|
: [...new Set([
|
||||||
|
position.averagePurchasePrice?.currency,
|
||||||
|
position.currentValue?.currency,
|
||||||
|
].filter((currency): currency is string => !!currency))];
|
||||||
|
|
||||||
if (!position.averagePurchasePrice && !position.currentValue)
|
for (const currency of currencies) {
|
||||||
continue;
|
const total = totals.get(currency) ?? { complete: true, values: [] };
|
||||||
|
|
||||||
return null;
|
if (position.absoluteReturn) {
|
||||||
|
total.values.push(decimalFromString(position.absoluteReturn.value));
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
total.complete = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
values.push(decimalFromString(position.absoluteReturn.value));
|
totals.set(currency, total);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return { currency: "RUB", value: decimalToString(sumDecimals(values)) };
|
return [...totals].flatMap(([currency, total]) => total.complete
|
||||||
|
? [{ currency, value: decimalToString(sumDecimals(total.values)) }]
|
||||||
|
: []);
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ function toIncomeSummary(
|
|||||||
if (income.meta?.completeness === "incomplete") return { state: "partial", to };
|
if (income.meta?.completeness === "incomplete") return { state: "partial", to };
|
||||||
if (!income.data && (income.isError || income.meta?.lastAttempt.state === "failed"))
|
if (!income.data && (income.isError || income.meta?.lastAttempt.state === "failed"))
|
||||||
return { state: "error", to };
|
return { state: "error", to };
|
||||||
if (!income.data) return { state: "empty", to };
|
if (!income.data?.totalsByCurrency.length) return { state: "empty", to };
|
||||||
|
|
||||||
return {
|
return {
|
||||||
state: "loaded",
|
state: "loaded",
|
||||||
|
|||||||
@@ -96,7 +96,7 @@ function renderPage(ui: React.ReactNode) {
|
|||||||
|
|
||||||
const portfolio
|
const portfolio
|
||||||
= {
|
= {
|
||||||
cash: { currency: "RUB", value: "0.5" },
|
cashBalances: [{ currency: "USD", value: "0.5" }],
|
||||||
isStale: true,
|
isStale: true,
|
||||||
lastSuccessfulAt: "2026-08-13T10:00:00Z",
|
lastSuccessfulAt: "2026-08-13T10:00:00Z",
|
||||||
positions: [
|
positions: [
|
||||||
@@ -129,8 +129,8 @@ const portfolio
|
|||||||
type: "BOND",
|
type: "BOND",
|
||||||
},
|
},
|
||||||
] satisfies [Portfolio["positions"][number], ...Portfolio["positions"]],
|
] satisfies [Portfolio["positions"][number], ...Portfolio["positions"]],
|
||||||
structure: { categories: [], hasNegativeValues: false, totalValue: "0", unvaluedCategories: [] },
|
structure: { currencies: [], unvaluedCategories: [] },
|
||||||
totals: { currency: "RUB", value: "1234.5" },
|
totalsByCurrency: [{ currency: "RUB", value: "1234.5" }],
|
||||||
} satisfies Portfolio;
|
} satisfies Portfolio;
|
||||||
|
|
||||||
function position(
|
function position(
|
||||||
@@ -201,6 +201,8 @@ const LoadedHarness = (
|
|||||||
function loadedProps(nextPortfolio: Portfolio = portfolio) {
|
function loadedProps(nextPortfolio: Portfolio = portfolio) {
|
||||||
return {
|
return {
|
||||||
concentration: null,
|
concentration: null,
|
||||||
|
currency: null,
|
||||||
|
onCurrencyChange: vi.fn(),
|
||||||
onSliceChange: vi.fn(),
|
onSliceChange: vi.fn(),
|
||||||
portfolio: nextPortfolio,
|
portfolio: nextPortfolio,
|
||||||
positionSections: toAccountPagePositionSections(nextPortfolio),
|
positionSections: toAccountPagePositionSections(nextPortfolio),
|
||||||
@@ -240,10 +242,10 @@ describe("AccountPage states", () => {
|
|||||||
HttpResponse.json(resource(
|
HttpResponse.json(resource(
|
||||||
{
|
{
|
||||||
...portfolio,
|
...portfolio,
|
||||||
cash: { currency: "RUB", value: "0" },
|
cashBalances: [],
|
||||||
isStale: false,
|
isStale: false,
|
||||||
positions: [],
|
positions: [],
|
||||||
totals: { currency: "RUB", value: "0" },
|
totalsByCurrency: [],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
lastAttempt: {
|
lastAttempt: {
|
||||||
@@ -276,7 +278,7 @@ describe("AccountPage states", () => {
|
|||||||
const data = { ...portfolio, positions };
|
const data = { ...portfolio, positions };
|
||||||
|
|
||||||
const model = toConcentration(
|
const model = toConcentration(
|
||||||
data, "stocks", concentrationLabels(),
|
data, "stocks", "RUB", concentrationLabels(),
|
||||||
);
|
);
|
||||||
|
|
||||||
const props = loadedProps(data);
|
const props = loadedProps(data);
|
||||||
@@ -285,6 +287,7 @@ describe("AccountPage states", () => {
|
|||||||
{...props}
|
{...props}
|
||||||
accountId="a"
|
accountId="a"
|
||||||
concentration={model}
|
concentration={model}
|
||||||
|
currency="RUB"
|
||||||
tab="concentration"
|
tab="concentration"
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
@@ -323,8 +326,10 @@ describe("AccountPage states", () => {
|
|||||||
concentration={toConcentration(
|
concentration={toConcentration(
|
||||||
{ ...portfolio, positions },
|
{ ...portfolio, positions },
|
||||||
"stocks",
|
"stocks",
|
||||||
|
"RUB",
|
||||||
concentrationLabels(),
|
concentrationLabels(),
|
||||||
)}
|
)}
|
||||||
|
currency="RUB"
|
||||||
tab="concentration"
|
tab="concentration"
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
@@ -349,8 +354,9 @@ describe("AccountPage states", () => {
|
|||||||
{...loadedProps(data)}
|
{...loadedProps(data)}
|
||||||
accountId="a"
|
accountId="a"
|
||||||
concentration={toConcentration(
|
concentration={toConcentration(
|
||||||
data, "stocks", concentrationLabels(),
|
data, "stocks", "RUB", concentrationLabels(),
|
||||||
)}
|
)}
|
||||||
|
currency="RUB"
|
||||||
tab="concentration"
|
tab="concentration"
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
@@ -364,8 +370,9 @@ describe("AccountPage states", () => {
|
|||||||
{...loadedProps(data)}
|
{...loadedProps(data)}
|
||||||
accountId="a"
|
accountId="a"
|
||||||
concentration={toConcentration(
|
concentration={toConcentration(
|
||||||
data, "issuers", concentrationLabels(),
|
data, "issuers", "RUB", concentrationLabels(),
|
||||||
)}
|
)}
|
||||||
|
currency="RUB"
|
||||||
slice="issuers"
|
slice="issuers"
|
||||||
tab="concentration"
|
tab="concentration"
|
||||||
/>,
|
/>,
|
||||||
@@ -385,8 +392,9 @@ describe("AccountPage states", () => {
|
|||||||
{...loadedProps(data)}
|
{...loadedProps(data)}
|
||||||
accountId="a"
|
accountId="a"
|
||||||
concentration={toConcentration(
|
concentration={toConcentration(
|
||||||
data, "stocks", concentrationLabels(),
|
data, "stocks", "RUB", concentrationLabels(),
|
||||||
)}
|
)}
|
||||||
|
currency="RUB"
|
||||||
tab="concentration"
|
tab="concentration"
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
@@ -416,8 +424,9 @@ describe("AccountPage states", () => {
|
|||||||
{...loadedProps(data)}
|
{...loadedProps(data)}
|
||||||
accountId="a"
|
accountId="a"
|
||||||
concentration={toConcentration(
|
concentration={toConcentration(
|
||||||
data, "sectors", concentrationLabels(),
|
data, "sectors", "RUB", concentrationLabels(),
|
||||||
)}
|
)}
|
||||||
|
currency="RUB"
|
||||||
slice="sectors"
|
slice="sectors"
|
||||||
tab="concentration"
|
tab="concentration"
|
||||||
/>,
|
/>,
|
||||||
@@ -448,8 +457,9 @@ describe("AccountPage states", () => {
|
|||||||
{...loadedProps(data)}
|
{...loadedProps(data)}
|
||||||
accountId="a"
|
accountId="a"
|
||||||
concentration={toConcentration(
|
concentration={toConcentration(
|
||||||
data, "stocks", concentrationLabels(),
|
data, "stocks", "RUB", concentrationLabels(),
|
||||||
)}
|
)}
|
||||||
|
currency="RUB"
|
||||||
tab="concentration"
|
tab="concentration"
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
@@ -474,8 +484,9 @@ describe("AccountPage states", () => {
|
|||||||
{...loadedProps(data)}
|
{...loadedProps(data)}
|
||||||
accountId="a"
|
accountId="a"
|
||||||
concentration={toConcentration(
|
concentration={toConcentration(
|
||||||
data, "stocks", concentrationLabels(),
|
data, "stocks", "RUB", concentrationLabels(),
|
||||||
)}
|
)}
|
||||||
|
currency="RUB"
|
||||||
partial
|
partial
|
||||||
tab="concentration"
|
tab="concentration"
|
||||||
/>,
|
/>,
|
||||||
@@ -485,14 +496,16 @@ describe("AccountPage states", () => {
|
|||||||
.toHaveLength(1);
|
.toHaveLength(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("keeps the slice while switching page tabs and resets on account change", async () => {
|
it("keeps slice and currency while switching page tabs and resets on account change", async () => {
|
||||||
const multiCurrency = { ...portfolio, positions:
|
const multiCurrency = { ...portfolio, positions:
|
||||||
|
["RUB", "USD"].flatMap(currency =>
|
||||||
[400, 250, 150, 100, 50, 30, 20].map((value, index) =>
|
[400, 250, 150, 100, 50, 30, 20].map((value, index) =>
|
||||||
position({
|
position({
|
||||||
currentValue: { currency: "RUB", value: String(value) },
|
currentValue: { currency, value: String(value) },
|
||||||
displayName: `Акция ${index + 1}`,
|
displayName: `${currency} акция ${index + 1}`,
|
||||||
sector: "energy", type: "STOCK",
|
sector: "energy", type: "STOCK",
|
||||||
}),
|
}),
|
||||||
|
),
|
||||||
) };
|
) };
|
||||||
|
|
||||||
server.use(
|
server.use(
|
||||||
@@ -507,27 +520,37 @@ describe("AccountPage states", () => {
|
|||||||
fireEvent.click(screen.getByRole("button", { name: /Прочее/ }));
|
fireEvent.click(screen.getByRole("button", { name: /Прочее/ }));
|
||||||
expect(screen.getByRole("button", { name: /Прочее/ }))
|
expect(screen.getByRole("button", { name: /Прочее/ }))
|
||||||
.toHaveAttribute("aria-expanded", "true");
|
.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("button", { name: /Прочее/ }));
|
||||||
fireEvent.click(screen.getByRole("radio", { name: "Секторы" }));
|
fireEvent.click(screen.getByRole("radio", { name: "Секторы" }));
|
||||||
fireEvent.click(screen.getByRole("radio", { name: "Акции" }));
|
fireEvent.click(screen.getByRole("radio", { name: "Акции" }));
|
||||||
expect(screen.getByRole("button", { name: /Прочее/ }))
|
expect(screen.getByRole("button", { name: /Прочее/ }))
|
||||||
.toHaveAttribute("aria-expanded", "false");
|
.toHaveAttribute("aria-expanded", "false");
|
||||||
fireEvent.click(screen.getByRole("radio", { name: "Секторы" }));
|
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: "Позиции" }));
|
||||||
fireEvent.click(screen.getByRole("tab", { name: "Концентрация" }));
|
fireEvent.click(screen.getByRole("tab", { name: "Концентрация" }));
|
||||||
|
|
||||||
expect(screen.getByRole("radio", { name: "Секторы" }))
|
expect(screen.getByRole("radio", { name: "Секторы" }))
|
||||||
.toBeChecked();
|
.toBeChecked();
|
||||||
|
expect(screen.getByRole("combobox", { name: "Валюта концентрации" }))
|
||||||
|
.toHaveValue("USD");
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Другой счёт" }));
|
fireEvent.click(screen.getByRole("button", { name: "Другой счёт" }));
|
||||||
fireEvent.click(await screen.findByRole("tab", { name: "Концентрация" }));
|
fireEvent.click(await screen.findByRole("tab", { name: "Концентрация" }));
|
||||||
expect(screen.getByRole("radio", { name: "Акции" })).toBeChecked();
|
expect(screen.getByRole("radio", { name: "Акции" })).toBeChecked();
|
||||||
|
expect(screen.getByRole("combobox", { name: "Валюта концентрации" }))
|
||||||
|
.toHaveValue("RUB");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("includes all ruble positions in concentration", () => {
|
it("falls back to the first currency when the selected one disappears", () => {
|
||||||
const data = { ...portfolio, positions: [
|
const data = { ...portfolio, positions: [
|
||||||
position({
|
position({
|
||||||
currentValue: { currency: "RUB", value: "200" },
|
currentValue: { currency: "USD", value: "200" },
|
||||||
}),
|
}),
|
||||||
position({
|
position({
|
||||||
currentValue: { currency: "RUB", value: "100" },
|
currentValue: { currency: "RUB", value: "100" },
|
||||||
@@ -535,11 +558,12 @@ describe("AccountPage states", () => {
|
|||||||
] };
|
] };
|
||||||
|
|
||||||
const model = toConcentration(
|
const model = toConcentration(
|
||||||
data, "stocks", concentrationLabels(),
|
data, "stocks", "EUR", concentrationLabels(),
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(model.total).toBe("300");
|
expect(model.currencies).toEqual(["RUB", "USD"]);
|
||||||
expect(model.items.map(item => item.amount)).toEqual(["200", "100"]);
|
expect(model.total).toBe("100");
|
||||||
|
expect(model.items.map(item => item.amount)).toEqual(["100"]);
|
||||||
});
|
});
|
||||||
it("shows the loaded portfolio source sync status", async () => {
|
it("shows the loaded portfolio source sync status", async () => {
|
||||||
server.use(
|
server.use(
|
||||||
@@ -655,7 +679,7 @@ describe("AccountPage states", () => {
|
|||||||
).toHaveTextContent("Данные о структуре портфеля пока недоступны.");
|
).toHaveTextContent("Данные о структуре портфеля пока недоступны.");
|
||||||
expect(
|
expect(
|
||||||
screen.getAllByRole("definition").map(node => node.textContent),
|
screen.getAllByRole("definition").map(node => node.textContent),
|
||||||
).toEqual(["1 234,50 ₽"]);
|
).toEqual(["1 234,5 ₽"]);
|
||||||
});
|
});
|
||||||
it("keeps initial placeholders decorative without amounts or focus targets", () => {
|
it("keeps initial placeholders decorative without amounts or focus targets", () => {
|
||||||
const { container } = renderPage(<AccountPageLoading />);
|
const { container } = renderPage(<AccountPageLoading />);
|
||||||
@@ -698,7 +722,11 @@ describe("AccountPage states", () => {
|
|||||||
<LoadedHarness
|
<LoadedHarness
|
||||||
{...loadedProps({
|
{...loadedProps({
|
||||||
...portfolio,
|
...portfolio,
|
||||||
cash: { currency: "RUB", value: "234.500000000000000001" },
|
cashBalances: [
|
||||||
|
{ currency: "RUB", value: "234.500000000000000001" },
|
||||||
|
{ currency: "USD", value: "-0.5" },
|
||||||
|
{ currency: "XYZ", value: "3.00" },
|
||||||
|
],
|
||||||
positions: [
|
positions: [
|
||||||
...portfolio.positions,
|
...portfolio.positions,
|
||||||
{
|
{
|
||||||
@@ -709,7 +737,7 @@ describe("AccountPage states", () => {
|
|||||||
type: "CURRENCY",
|
type: "CURRENCY",
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
structure: { categories: [], hasNegativeValues: false, totalValue: "0", unvaluedCategories: [] },
|
structure: { currencies: [], unvaluedCategories: [] },
|
||||||
})}
|
})}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
@@ -722,12 +750,14 @@ describe("AccountPage states", () => {
|
|||||||
|
|
||||||
expect(
|
expect(
|
||||||
balances.getAllByRole("definition").map(node => node.textContent),
|
balances.getAllByRole("definition").map(node => node.textContent),
|
||||||
).toEqual(["234,50 ₽"]);
|
).toEqual(["234,500000000000000001 ₽", "-0,5 $", "3,00 XYZ"]);
|
||||||
expect(
|
expect(
|
||||||
screen.getAllByRole("definition").map(node => node.textContent),
|
screen.getAllByRole("definition").map(node => node.textContent),
|
||||||
).toEqual([
|
).toEqual([
|
||||||
"1 234,50 ₽",
|
"1 234,5 ₽",
|
||||||
"234,50 ₽",
|
"234,500000000000000001 ₽",
|
||||||
|
"-0,5 $",
|
||||||
|
"3,00 XYZ",
|
||||||
]);
|
]);
|
||||||
expect(screen.queryByText("Торгуемая валюта")).not.toBeInTheDocument();
|
expect(screen.queryByText("Торгуемая валюта")).not.toBeInTheDocument();
|
||||||
expect(
|
expect(
|
||||||
@@ -744,7 +774,7 @@ describe("AccountPage states", () => {
|
|||||||
resource({
|
resource({
|
||||||
...portfolio,
|
...portfolio,
|
||||||
positions: hasPositions ? portfolio.positions : [],
|
positions: hasPositions ? portfolio.positions : [],
|
||||||
totals: { currency: "RUB", value: "0" },
|
totalsByCurrency: [],
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -752,20 +782,20 @@ describe("AccountPage states", () => {
|
|||||||
renderAccountRoute(createTestQueryClient());
|
renderAccountRoute(createTestQueryClient());
|
||||||
await screen.findByRole("heading", { level: 1, name: "Портфель" });
|
await screen.findByRole("heading", { level: 1, name: "Портфель" });
|
||||||
fireEvent.click(screen.getByRole("tab", { name: "Деньги" }));
|
fireEvent.click(screen.getByRole("tab", { name: "Деньги" }));
|
||||||
expect(screen.getByText("0,50 ₽")).toBeInTheDocument();
|
expect(screen.getByRole("definition")).toHaveTextContent("0,5 $");
|
||||||
expect(screen.queryByText("Портфель пока пуст")).not.toBeInTheDocument();
|
expect(screen.queryByText("Портфель пока пуст")).not.toBeInTheDocument();
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
it.each([
|
it.each([
|
||||||
{ empty: true, totals: { currency: "RUB", value: "0" } },
|
{ totalsByCurrency: [] },
|
||||||
{ empty: false, totals: { currency: "RUB", value: "100" } },
|
{ totalsByCurrency: [{ currency: "RUB", value: "100" }] },
|
||||||
])(
|
])(
|
||||||
"hides the empty other section without emptying a currency-only portfolio (totals: $totals.value)",
|
"hides the empty other section without emptying a currency-only portfolio (totals: $totalsByCurrency)",
|
||||||
async ({ empty, totals }) => {
|
async ({ totalsByCurrency }) => {
|
||||||
const snapshot: Portfolio = {
|
const snapshot: Portfolio = {
|
||||||
...portfolio,
|
...portfolio,
|
||||||
cash: { currency: "RUB", value: "0" },
|
cashBalances: [],
|
||||||
positions: [
|
positions: [
|
||||||
{
|
{
|
||||||
...portfolio.positions[0],
|
...portfolio.positions[0],
|
||||||
@@ -774,8 +804,8 @@ describe("AccountPage states", () => {
|
|||||||
type: "CURRENCY",
|
type: "CURRENCY",
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
structure: { categories: [], hasNegativeValues: false, totalValue: "0", unvaluedCategories: [] },
|
structure: { currencies: [], unvaluedCategories: [] },
|
||||||
totals,
|
totalsByCurrency,
|
||||||
};
|
};
|
||||||
|
|
||||||
server.use(
|
server.use(
|
||||||
@@ -796,11 +826,11 @@ describe("AccountPage states", () => {
|
|||||||
expect(
|
expect(
|
||||||
within(
|
within(
|
||||||
screen.getByRole("tabpanel", { name: "Деньги" }),
|
screen.getByRole("tabpanel", { name: "Деньги" }),
|
||||||
).getByRole("definition"),
|
).queryByRole("definition"),
|
||||||
).toHaveTextContent("0,00 ₽");
|
).not.toBeInTheDocument();
|
||||||
expect(
|
expect(
|
||||||
screen.queryAllByRole("definition").map(node => node.textContent),
|
screen.queryAllByRole("definition").map(node => node.textContent),
|
||||||
).toEqual([empty ? "0,00 ₽" : "100,00 ₽", "0,00 ₽"]);
|
).toEqual(totalsByCurrency.length > 0 ? ["100 ₽"] : []);
|
||||||
expect(
|
expect(
|
||||||
queryClient.getQueryData(portfolioQueryOptions("account-1").queryKey),
|
queryClient.getQueryData(portfolioQueryOptions("account-1").queryKey),
|
||||||
).toEqual(resource(snapshot));
|
).toEqual(resource(snapshot));
|
||||||
@@ -1117,7 +1147,7 @@ describe("AccountPage states", () => {
|
|||||||
date: "2026-09-11",
|
date: "2026-09-11",
|
||||||
dateKind: "registry",
|
dateKind: "registry",
|
||||||
displayName: "Акция",
|
displayName: "Акция",
|
||||||
projectedAmount: { currency: "RUB", value: "0" },
|
projectedAmount: { currency: "USD", value: "0" },
|
||||||
type: "dividend",
|
type: "dividend",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1161,7 +1191,7 @@ describe("AccountPage states", () => {
|
|||||||
expect(
|
expect(
|
||||||
content.getByText("11.09.2026 · Дата реестра · RU000A0JX0J2"),
|
content.getByText("11.09.2026 · Дата реестра · RU000A0JX0J2"),
|
||||||
).toBeVisible();
|
).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.getByText(amount)).toBeVisible();
|
||||||
expect(content.getAllByText("Прогноз")).toHaveLength(4);
|
expect(content.getAllByText("Прогноз")).toHaveLength(4);
|
||||||
expect(content.queryByText("Без движения денег")).not.toBeInTheDocument();
|
expect(content.queryByText("Без движения денег")).not.toBeInTheDocument();
|
||||||
@@ -1247,7 +1277,7 @@ describe("AccountPage states", () => {
|
|||||||
return HttpResponse.json(resource(
|
return HttpResponse.json(resource(
|
||||||
requests === 1
|
requests === 1
|
||||||
? portfolio
|
? portfolio
|
||||||
: { ...portfolio, totals: { currency: "RUB", value: "999" } },
|
: { ...portfolio, totalsByCurrency: [{ currency: "RUB", value: "999" }] },
|
||||||
{ resourceKey: "portfolio" },
|
{ resourceKey: "portfolio" },
|
||||||
));
|
));
|
||||||
}),
|
}),
|
||||||
@@ -1271,14 +1301,14 @@ describe("AccountPage states", () => {
|
|||||||
|
|
||||||
expect(screen.getByText("Не удалось обновить данные")).toBeInTheDocument();
|
expect(screen.getByText("Не удалось обновить данные")).toBeInTheDocument();
|
||||||
expect(screen.getByText("Вторая")).toBeInTheDocument();
|
expect(screen.getByText("Вторая")).toBeInTheDocument();
|
||||||
expect(screen.getByText("1 234,50 ₽")).toBeInTheDocument();
|
expect(screen.getByText("1 234,5 ₽")).toBeInTheDocument();
|
||||||
// One cached read plus the three automatic attempts.
|
// One cached read plus the three automatic attempts.
|
||||||
expect(requests).toBe(4);
|
expect(requests).toBe(4);
|
||||||
|
|
||||||
isFailing = false;
|
isFailing = false;
|
||||||
fireEvent.click(retry);
|
fireEvent.click(retry);
|
||||||
|
|
||||||
expect(await screen.findByText("999,00 ₽")).toBeInTheDocument();
|
expect(await screen.findByText("999 ₽")).toBeInTheDocument();
|
||||||
expect(requests).toBe(5);
|
expect(requests).toBe(5);
|
||||||
expect(screen.queryByText("Не удалось обновить данные"))
|
expect(screen.queryByText("Не удалось обновить данные"))
|
||||||
.not.toBeInTheDocument();
|
.not.toBeInTheDocument();
|
||||||
@@ -1340,9 +1370,14 @@ describe("AccountPage states", () => {
|
|||||||
= {
|
= {
|
||||||
...portfolio,
|
...portfolio,
|
||||||
structure: {
|
structure: {
|
||||||
|
currencies: [
|
||||||
|
{
|
||||||
categories: [{ sharePercent: null, type: "BOND", value: "10" }],
|
categories: [{ sharePercent: null, type: "BOND", value: "10" }],
|
||||||
|
currency: "RUB",
|
||||||
hasNegativeValues: false,
|
hasNegativeValues: false,
|
||||||
totalValue: "10",
|
totalValue: "10",
|
||||||
|
},
|
||||||
|
],
|
||||||
unvaluedCategories: [{ count: 1, type: "STOCK" }],
|
unvaluedCategories: [{ count: 1, type: "STOCK" }],
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -1393,7 +1428,7 @@ describe("AccountPage states", () => {
|
|||||||
expect(screen.getByText("Вторая")).toBeInTheDocument();
|
expect(screen.getByText("Вторая")).toBeInTheDocument();
|
||||||
expect(
|
expect(
|
||||||
screen.getAllByRole("definition").map(node => node.textContent),
|
screen.getAllByRole("definition").map(node => node.textContent),
|
||||||
).toEqual(["1 234,50 ₽"]);
|
).toEqual(["1 234,5 ₽"]);
|
||||||
expect(screen.queryByRole("button", { name: "Повторить" }))
|
expect(screen.queryByRole("button", { name: "Повторить" }))
|
||||||
.not.toBeInTheDocument();
|
.not.toBeInTheDocument();
|
||||||
void queryClient.invalidateQueries({
|
void queryClient.invalidateQueries({
|
||||||
@@ -1403,17 +1438,17 @@ describe("AccountPage states", () => {
|
|||||||
expect(structure).toHaveTextContent("10 ₽");
|
expect(structure).toHaveTextContent("10 ₽");
|
||||||
expect(
|
expect(
|
||||||
screen.getAllByRole("definition").map(node => node.textContent),
|
screen.getAllByRole("definition").map(node => node.textContent),
|
||||||
).toEqual(["1 234,50 ₽"]);
|
).toEqual(["1 234,5 ₽"]);
|
||||||
resolveRetry?.(
|
resolveRetry?.(
|
||||||
HttpResponse.json(
|
HttpResponse.json(
|
||||||
resource(
|
resource(
|
||||||
{
|
{
|
||||||
...portfolio,
|
...portfolio,
|
||||||
cash: { currency: "RUB", value: "2.50" },
|
cashBalances: [{ currency: "EUR", value: "2.50" }],
|
||||||
isStale: false,
|
isStale: false,
|
||||||
lastSuccessfulAt: "2026-08-14T11:30:00Z",
|
lastSuccessfulAt: "2026-08-14T11:30:00Z",
|
||||||
structure: { categories: [], hasNegativeValues: false, totalValue: "0", unvaluedCategories: [] },
|
structure: { currencies: [], unvaluedCategories: [] },
|
||||||
totals: { currency: "RUB", value: "-0.5" },
|
totalsByCurrency: [{ currency: "USD", value: "-0.5" }],
|
||||||
},
|
},
|
||||||
{ dataRevision: "2", resourceKey: "portfolio" },
|
{ dataRevision: "2", resourceKey: "portfolio" },
|
||||||
),
|
),
|
||||||
@@ -1422,7 +1457,7 @@ describe("AccountPage states", () => {
|
|||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(
|
expect(
|
||||||
screen.getAllByRole("definition").map(node => node.textContent),
|
screen.getAllByRole("definition").map(node => node.textContent),
|
||||||
).toEqual(["-0,50 ₽"]),
|
).toEqual(["-0,5 $"]),
|
||||||
);
|
);
|
||||||
expect(screen.getByText(/^Данные на /)).toHaveTextContent("Данные на");
|
expect(screen.getByText(/^Данные на /)).toHaveTextContent("Данные на");
|
||||||
expect(structure).not.toHaveTextContent("10 ₽");
|
expect(structure).not.toHaveTextContent("10 ₽");
|
||||||
@@ -1464,7 +1499,7 @@ describe("AccountPage states", () => {
|
|||||||
expect(screen.getByText("Вторая")).toBeInTheDocument();
|
expect(screen.getByText("Вторая")).toBeInTheDocument();
|
||||||
expect(
|
expect(
|
||||||
screen.getAllByRole("definition").map(node => node.textContent),
|
screen.getAllByRole("definition").map(node => node.textContent),
|
||||||
).toEqual(["1 234,50 ₽"]);
|
).toEqual(["1 234,5 ₽"]);
|
||||||
expect(screen.getByText(/^Данные на /)).toBeInTheDocument();
|
expect(screen.getByText(/^Данные на /)).toBeInTheDocument();
|
||||||
expect(
|
expect(
|
||||||
screen.queryByRole("status", { name: "Загрузка" }),
|
screen.queryByRole("status", { name: "Загрузка" }),
|
||||||
|
|||||||
@@ -28,7 +28,9 @@ const AccountPage: FC = () => {
|
|||||||
account={vm.account}
|
account={vm.account}
|
||||||
accountId={vm.accountId}
|
accountId={vm.accountId}
|
||||||
concentration={vm.concentration}
|
concentration={vm.concentration}
|
||||||
|
currency={vm.currency}
|
||||||
incomeSummary={vm.incomeSummary}
|
incomeSummary={vm.incomeSummary}
|
||||||
|
onCurrencyChange={vm.onCurrencyChange}
|
||||||
onSliceChange={vm.onSliceChange}
|
onSliceChange={vm.onSliceChange}
|
||||||
onTabChange={vm.onTabChange}
|
onTabChange={vm.onTabChange}
|
||||||
partial={vm.partial}
|
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", () =>
|
http.get("*/api/v1/brokerage-accounts/:accountId/events", () =>
|
||||||
HttpResponse.json(
|
HttpResponse.json(
|
||||||
resource(
|
resource(
|
||||||
{ events: [], incomeTotal: { currency: "RUB", value: "0" } },
|
{ events: [], incomeTotalsByCurrency: [] },
|
||||||
{ completeness: "incomplete" },
|
{ completeness: "incomplete" },
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -213,8 +213,8 @@ it("keeps overview sections loaded without exposing technical retry", async () =
|
|||||||
|
|
||||||
const sections: Record<string, unknown>
|
const sections: Record<string, unknown>
|
||||||
= {
|
= {
|
||||||
"events": { events: [], incomeTotal: { currency: "RUB", value: "0" } },
|
"events": { events: [], incomeTotalsByCurrency: [] },
|
||||||
"income-summary": { total: { coupon: { currency: "RUB", value: "0" }, dividend: { currency: "RUB", value: "0" }, total: { currency: "RUB", value: "0" } } },
|
"income-summary": { totalsByCurrency: [] },
|
||||||
"operations": { hasNext: false, items: [], nextCursor: null },
|
"operations": { hasNext: false, items: [], nextCursor: null },
|
||||||
portfolio,
|
portfolio,
|
||||||
};
|
};
|
||||||
@@ -238,7 +238,7 @@ it("keeps overview sections loaded without exposing technical retry", async () =
|
|||||||
|
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(result.current).toMatchObject({
|
expect(result.current).toMatchObject({
|
||||||
incomeSummary: { state: "loaded" },
|
incomeSummary: { state: "empty" },
|
||||||
recentEvents: { state: "empty" },
|
recentEvents: { state: "empty" },
|
||||||
recentOperations: { state: "empty" },
|
recentOperations: { state: "empty" },
|
||||||
state: "loaded",
|
state: "loaded",
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import { useInitialAvailability } from "@/shared/lib";
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
type Concentration,
|
type Concentration,
|
||||||
|
concentrationCurrencies,
|
||||||
type ConcentrationLabels,
|
type ConcentrationLabels,
|
||||||
type Slice,
|
type Slice,
|
||||||
toConcentration,
|
toConcentration,
|
||||||
@@ -56,6 +57,8 @@ type AccountPageEmptyViewModel = AccountPageContent & {
|
|||||||
|
|
||||||
type AccountPageLoadedViewModel = AccountPageContent & {
|
type AccountPageLoadedViewModel = AccountPageContent & {
|
||||||
concentration: Concentration | null;
|
concentration: Concentration | null;
|
||||||
|
currency: null | string;
|
||||||
|
onCurrencyChange: (currency: null | string) => void;
|
||||||
onSliceChange: (slice: Slice) => void;
|
onSliceChange: (slice: Slice) => void;
|
||||||
onTabChange: (tab: null | string) => void;
|
onTabChange: (tab: null | string) => void;
|
||||||
portfolio: Portfolio;
|
portfolio: Portfolio;
|
||||||
@@ -63,9 +66,7 @@ type AccountPageLoadedViewModel = AccountPageContent & {
|
|||||||
slice: Slice;
|
slice: Slice;
|
||||||
state: "loaded";
|
state: "loaded";
|
||||||
tab: string;
|
tab: string;
|
||||||
unrealizedReturns:
|
unrealizedReturns: Portfolio["totalsByCurrency"];
|
||||||
| null
|
|
||||||
| { currency: string; value: string };
|
|
||||||
};
|
};
|
||||||
|
|
||||||
type AccountPageReadRetry = ReturnType<typeof readRetry>;
|
type AccountPageReadRetry = ReturnType<typeof readRetry>;
|
||||||
@@ -82,14 +83,15 @@ function useAccountPageVm(): AccountPageViewModel {
|
|||||||
|
|
||||||
const [selection, setSelection] = useState<{
|
const [selection, setSelection] = useState<{
|
||||||
accountId?: string;
|
accountId?: string;
|
||||||
|
currency: null | string;
|
||||||
slice: Slice;
|
slice: Slice;
|
||||||
tab: string;
|
tab: string;
|
||||||
}>({ accountId, slice: "stocks", tab: "positions" });
|
}>({ accountId, currency: null, slice: "stocks", tab: "positions" });
|
||||||
|
|
||||||
const current = selection.accountId === accountId
|
const current = selection.accountId === accountId
|
||||||
? selection
|
? selection
|
||||||
: {
|
: {
|
||||||
accountId, slice: "stocks" as const, tab: "positions",
|
accountId, currency: null, slice: "stocks" as const, tab: "positions",
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateSelection = (change: Partial<typeof selection>) =>
|
const updateSelection = (change: Partial<typeof selection>) =>
|
||||||
@@ -142,7 +144,7 @@ function useAccountPageVm(): AccountPageViewModel {
|
|||||||
if (
|
if (
|
||||||
portfolio.meta?.availability === "available"
|
portfolio.meta?.availability === "available"
|
||||||
&& portfolio.data.positions.length === 0
|
&& portfolio.data.positions.length === 0
|
||||||
&& Number(portfolio.data.cash.value) === 0
|
&& portfolio.data.cashBalances.length === 0
|
||||||
)
|
)
|
||||||
return {
|
return {
|
||||||
account,
|
account,
|
||||||
@@ -156,6 +158,11 @@ function useAccountPageVm(): AccountPageViewModel {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const isPartial = portfolio.meta?.completeness === "incomplete";
|
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 = {
|
const labels: ConcentrationLabels = {
|
||||||
missingIssuer: t("portfolio.concentration.missingIssuer"),
|
missingIssuer: t("portfolio.concentration.missingIssuer"),
|
||||||
@@ -166,14 +173,16 @@ function useAccountPageVm(): AccountPageViewModel {
|
|||||||
|
|
||||||
const concentration = accountId !== "all"
|
const concentration = accountId !== "all"
|
||||||
&& current.tab === "concentration"
|
&& current.tab === "concentration"
|
||||||
? toConcentration(portfolio.data, current.slice, labels)
|
? toConcentration(portfolio.data, current.slice, currency, labels)
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
account,
|
account,
|
||||||
accountId,
|
accountId,
|
||||||
concentration,
|
concentration,
|
||||||
|
currency,
|
||||||
incomeSummary,
|
incomeSummary,
|
||||||
|
onCurrencyChange: value => updateSelection({ currency: value }),
|
||||||
onSliceChange: slice => updateSelection({ slice }),
|
onSliceChange: slice => updateSelection({ slice }),
|
||||||
onTabChange: tab => updateSelection({ tab: tab ?? "positions" }),
|
onTabChange: tab => updateSelection({ tab: tab ?? "positions" }),
|
||||||
partial: isPartial,
|
partial: isPartial,
|
||||||
|
|||||||
@@ -55,12 +55,7 @@ const AccountPageEmpty: FC<AccountPageEmptyProps> = (props) => {
|
|||||||
<StateView text={text} title={t("portfolio.emptyTitle")} />
|
<StateView text={text} title={t("portfolio.emptyTitle")} />
|
||||||
|
|
||||||
<PortfolioStructure
|
<PortfolioStructure
|
||||||
structure={{
|
structure={{ currencies: [], unvaluedCategories: [] }}
|
||||||
categories: [],
|
|
||||||
hasNegativeValues: false,
|
|
||||||
totalValue: "0",
|
|
||||||
unvaluedCategories: [],
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<RecentOperations
|
<RecentOperations
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import type {
|
|||||||
import classes from "../AccountPage.module.css";
|
import classes from "../AccountPage.module.css";
|
||||||
import { AccountHeading } from "./AccountHeading.view";
|
import { AccountHeading } from "./AccountHeading.view";
|
||||||
import { Concentration } from "./Concentration/Concentration.view";
|
import { Concentration } from "./Concentration/Concentration.view";
|
||||||
|
import { CurrencyCards } from "./CurrencyCards/CurrencyCards.view";
|
||||||
import { IncomeSummary } from "./IncomeSummary.view";
|
import { IncomeSummary } from "./IncomeSummary.view";
|
||||||
import { PerformanceTab } from "./Performance/PerformanceTab";
|
import { PerformanceTab } from "./Performance/PerformanceTab";
|
||||||
import { PortfolioStructure } from "./PortfolioStructure/PortfolioStructure";
|
import { PortfolioStructure } from "./PortfolioStructure/PortfolioStructure";
|
||||||
@@ -38,7 +39,9 @@ type AccountPageLoadedProps = {
|
|||||||
account?: BrokerageAccount;
|
account?: BrokerageAccount;
|
||||||
accountId?: string;
|
accountId?: string;
|
||||||
concentration: ConcentrationModel | null;
|
concentration: ConcentrationModel | null;
|
||||||
|
currency: null | string;
|
||||||
incomeSummary?: AccountPageIncomeSummary;
|
incomeSummary?: AccountPageIncomeSummary;
|
||||||
|
onCurrencyChange: (currency: null | string) => void;
|
||||||
onSliceChange: (slice: Slice) => void;
|
onSliceChange: (slice: Slice) => void;
|
||||||
onTabChange: (tab: null | string) => void;
|
onTabChange: (tab: null | string) => void;
|
||||||
partial?: boolean;
|
partial?: boolean;
|
||||||
@@ -50,9 +53,7 @@ type AccountPageLoadedProps = {
|
|||||||
slice: Slice;
|
slice: Slice;
|
||||||
source?: InvestmentResourceMeta;
|
source?: InvestmentResourceMeta;
|
||||||
tab: string;
|
tab: string;
|
||||||
unrealizedReturns:
|
unrealizedReturns: Portfolio["totalsByCurrency"];
|
||||||
| null
|
|
||||||
| { currency: string; value: string };
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
|
const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
|
||||||
@@ -93,23 +94,9 @@ const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
|
|||||||
? tab !== "concentration" && (
|
? tab !== "concentration" && (
|
||||||
<Alert role="status">{t("investment.partial")}</Alert>
|
<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>
|
|
||||||
|
|
||||||
<dd style={{ margin: 0 }}>
|
{!props.partial && props.unrealizedReturns.length > 0 && (
|
||||||
<Text className={classes.totalAmount}>
|
|
||||||
{formatMoney(props.portfolio.totals, {
|
|
||||||
withRoundedCents: true,
|
|
||||||
})}
|
|
||||||
</Text>
|
|
||||||
</dd>
|
|
||||||
</Stack>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!props.partial && props.unrealizedReturns && (
|
|
||||||
<Stack
|
<Stack
|
||||||
aria-label={t("portfolio.unrealizedResult")}
|
aria-label={t("portfolio.unrealizedResult")}
|
||||||
component="section"
|
component="section"
|
||||||
@@ -118,7 +105,9 @@ const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
|
|||||||
<Text fw={600}>{t("portfolio.unrealizedResult")}</Text>
|
<Text fw={600}>{t("portfolio.unrealizedResult")}</Text>
|
||||||
|
|
||||||
<Group gap="md">
|
<Group gap="md">
|
||||||
<Text>{formatMoney(props.unrealizedReturns)}</Text>
|
{props.unrealizedReturns.map(total => (
|
||||||
|
<Text key={total.currency}>{formatMoney(total)}</Text>
|
||||||
|
))}
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
<Text c="dimmed" size="xs">
|
<Text c="dimmed" size="xs">
|
||||||
@@ -185,8 +174,10 @@ const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
|
|||||||
<Tabs.Panel value="concentration">
|
<Tabs.Panel value="concentration">
|
||||||
{props.concentration && (
|
{props.concentration && (
|
||||||
<Concentration
|
<Concentration
|
||||||
key={props.slice}
|
currency={props.currency}
|
||||||
|
key={`${props.slice}-${props.currency}`}
|
||||||
model={props.concentration}
|
model={props.concentration}
|
||||||
|
onCurrencyChange={props.onCurrencyChange}
|
||||||
onSliceChange={props.onSliceChange}
|
onSliceChange={props.onSliceChange}
|
||||||
partial={!!props.partial}
|
partial={!!props.partial}
|
||||||
slice={props.slice}
|
slice={props.slice}
|
||||||
@@ -196,17 +187,7 @@ const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<Tabs.Panel value="cash">
|
<Tabs.Panel value="cash">
|
||||||
<Stack component="dl" gap={4} m={0}>
|
<CurrencyCards amounts={props.portfolio.cashBalances} />
|
||||||
<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>
|
||||||
|
|
||||||
<Tabs.Panel value="operations">
|
<Tabs.Panel value="operations">
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { DonutChart } from "@mantine/charts";
|
import { DonutChart } from "@mantine/charts";
|
||||||
import {
|
import {
|
||||||
Alert, Box, Group, Paper, SegmentedControl, Stack,
|
Alert, Box, Group, Paper, SegmentedControl, Select, Stack,
|
||||||
Text, Title,
|
Text, Title,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
import { type FC, useId, useState } from "react";
|
import { type FC, useId, useState } from "react";
|
||||||
@@ -18,7 +18,9 @@ import { PositionLogo } from "../PositionLogo.view";
|
|||||||
import classes from "./Concentration.module.css";
|
import classes from "./Concentration.module.css";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
|
currency: null | string;
|
||||||
model: ConcentrationModel;
|
model: ConcentrationModel;
|
||||||
|
onCurrencyChange: (currency: null | string) => void;
|
||||||
onSliceChange: (slice: Slice) => void;
|
onSliceChange: (slice: Slice) => void;
|
||||||
partial: boolean;
|
partial: boolean;
|
||||||
slice: Slice;
|
slice: Slice;
|
||||||
@@ -33,6 +35,7 @@ const sliceLabels = {
|
|||||||
|
|
||||||
type RowProps = {
|
type RowProps = {
|
||||||
color: string;
|
color: string;
|
||||||
|
currency: string;
|
||||||
index: number;
|
index: number;
|
||||||
item: ConcentrationItem;
|
item: ConcentrationItem;
|
||||||
logo?: ConcentrationItem["logo"];
|
logo?: ConcentrationItem["logo"];
|
||||||
@@ -47,8 +50,8 @@ const colors = [
|
|||||||
const PERCENT = 100;
|
const PERCENT = 100;
|
||||||
const OTHER_START = 6;
|
const OTHER_START = 6;
|
||||||
|
|
||||||
function amountFor(item: ConcentrationItem): string {
|
function amountFor(item: ConcentrationItem, currency: string): string {
|
||||||
return formatMoney({ currency: "RUB", value: item.amount });
|
return formatMoney({ currency, value: item.amount });
|
||||||
}
|
}
|
||||||
|
|
||||||
const ConcentrationRow: FC<RowProps> = props => (
|
const ConcentrationRow: FC<RowProps> = props => (
|
||||||
@@ -80,7 +83,7 @@ const ConcentrationRow: FC<RowProps> = props => (
|
|||||||
</span>
|
</span>
|
||||||
|
|
||||||
<span className={classes.value}>
|
<span className={classes.value}>
|
||||||
<strong>{amountFor(props.item)}</strong>
|
<strong>{amountFor(props.item, props.currency)}</strong>
|
||||||
|
|
||||||
<Text c="dimmed" size="sm">{props.item.share}</Text>
|
<Text c="dimmed" size="sm">{props.item.share}</Text>
|
||||||
</span>
|
</span>
|
||||||
@@ -128,6 +131,7 @@ const Concentration: FC<Props> = (props) => {
|
|||||||
const [expanded, setExpanded] = useState(false);
|
const [expanded, setExpanded] = useState(false);
|
||||||
const otherId = useId();
|
const otherId = useId();
|
||||||
const chartId = useId();
|
const chartId = useId();
|
||||||
|
const currency = props.currency ?? "";
|
||||||
|
|
||||||
const rows = props.model.other
|
const rows = props.model.other
|
||||||
? [...props.model.items, props.model.other]
|
? [...props.model.items, props.model.other]
|
||||||
@@ -143,8 +147,10 @@ const Concentration: FC<Props> = (props) => {
|
|||||||
props.model.top5Share && t("portfolio.concentration.top5", {
|
props.model.top5Share && t("portfolio.concentration.top5", {
|
||||||
share: props.model.top5Share,
|
share: props.model.top5Share,
|
||||||
}),
|
}),
|
||||||
props.model.total && formatMoney({ currency: "RUB", value: props.model.total }),
|
props.model.total && formatMoney({
|
||||||
...rows.map(item => `${item.label}: ${amountFor(item)}, ${item.share}`),
|
currency, value: props.model.total,
|
||||||
|
}),
|
||||||
|
...rows.map(item => `${item.label}: ${amountFor(item, currency)}, ${item.share}`),
|
||||||
].filter(Boolean).join("; ");
|
].filter(Boolean).join("; ");
|
||||||
|
|
||||||
const slices = [
|
const slices = [
|
||||||
@@ -164,7 +170,7 @@ const Concentration: FC<Props> = (props) => {
|
|||||||
const pieProps = { isAnimationActive: false, label: rankLabel };
|
const pieProps = { isAnimationActive: false, label: rankLabel };
|
||||||
|
|
||||||
const tooltipRows = rows.map(item => ({
|
const tooltipRows = rows.map(item => ({
|
||||||
amount: amountFor(item),
|
amount: amountFor(item, currency),
|
||||||
label: item.label,
|
label: item.label,
|
||||||
share: item.share,
|
share: item.share,
|
||||||
}));
|
}));
|
||||||
@@ -172,7 +178,7 @@ const Concentration: FC<Props> = (props) => {
|
|||||||
const tooltipProps = { content: <ChartTooltip rows={tooltipRows} /> };
|
const tooltipProps = { content: <ChartTooltip rows={tooltipRows} /> };
|
||||||
|
|
||||||
const totalText = props.model.total
|
const totalText = props.model.total
|
||||||
? formatMoney({ currency: "RUB", value: props.model.total })
|
? formatMoney({ currency, value: props.model.total })
|
||||||
: "";
|
: "";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -186,6 +192,16 @@ const Concentration: FC<Props> = (props) => {
|
|||||||
value={props.slice}
|
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>
|
</Group>
|
||||||
|
|
||||||
{props.partial && (
|
{props.partial && (
|
||||||
@@ -195,7 +211,9 @@ const Concentration: FC<Props> = (props) => {
|
|||||||
{props.model.empty
|
{props.model.empty
|
||||||
? (
|
? (
|
||||||
<Stack gap="xs">
|
<Stack gap="xs">
|
||||||
<Text fw={600}>{t(sliceLabels[props.slice])}</Text>
|
<Text fw={600}>{t(sliceLabels[props.slice])}
|
||||||
|
{props.currency && ` · ${props.currency}`}
|
||||||
|
</Text>
|
||||||
|
|
||||||
<Text>{t("portfolio.concentration.empty")}</Text>
|
<Text>{t("portfolio.concentration.empty")}</Text>
|
||||||
</Stack>
|
</Stack>
|
||||||
@@ -242,6 +260,7 @@ const Concentration: FC<Props> = (props) => {
|
|||||||
{props.model.items.map((item, index) => (
|
{props.model.items.map((item, index) => (
|
||||||
<ConcentrationRow
|
<ConcentrationRow
|
||||||
color={colors[index % colors.length] ?? "blue"}
|
color={colors[index % colors.length] ?? "blue"}
|
||||||
|
currency={currency}
|
||||||
index={index + 1}
|
index={index + 1}
|
||||||
item={item}
|
item={item}
|
||||||
key={item.key}
|
key={item.key}
|
||||||
@@ -266,7 +285,7 @@ const Concentration: FC<Props> = (props) => {
|
|||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
|
|
||||||
<span>{amountFor(props.model.other)} · {
|
<span>{amountFor(props.model.other, currency)} · {
|
||||||
props.model.other.share
|
props.model.other.share
|
||||||
}
|
}
|
||||||
</span>
|
</span>
|
||||||
@@ -282,6 +301,7 @@ const Concentration: FC<Props> = (props) => {
|
|||||||
<ConcentrationRow
|
<ConcentrationRow
|
||||||
color={colors[(index + OTHER_START) % colors.length]
|
color={colors[(index + OTHER_START) % colors.length]
|
||||||
?? "blue"}
|
?? "blue"}
|
||||||
|
currency={currency}
|
||||||
index={index + OTHER_START}
|
index={index + OTHER_START}
|
||||||
item={item}
|
item={item}
|
||||||
key={item.key}
|
key={item.key}
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
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,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
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,14 +64,16 @@ const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap="xs">
|
<Stack gap="xs">
|
||||||
<Paper p="sm" withBorder>
|
{props.summary.totalsByCurrency.map(total => (
|
||||||
<Text fw={700}>{formatMoney(props.summary.total.total)}</Text>
|
<Paper key={total.currency} p="sm" withBorder>
|
||||||
|
<Text fw={700}>{formatMoney(total.total)}</Text>
|
||||||
|
|
||||||
<Text c="dimmed" size="sm">
|
<Text c="dimmed" size="sm">
|
||||||
{t("income.coupon")}: {formatMoney(props.summary.total.coupon)} ·{" "}
|
{t("income.coupon")}: {formatMoney(total.coupon)} ·{" "}
|
||||||
{t("income.dividend")}: {formatMoney(props.summary.total.dividend)}
|
{t("income.dividend")}: {formatMoney(total.dividend)}
|
||||||
</Text>
|
</Text>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
))}
|
||||||
|
|
||||||
<Button component={Link} to={props.to} variant="subtle">
|
<Button component={Link} to={props.to} variant="subtle">
|
||||||
{props.moreLabel ?? t("income.open")}
|
{props.moreLabel ?? t("income.open")}
|
||||||
|
|||||||
@@ -99,7 +99,7 @@ export const Incomplete: Story = {
|
|||||||
...data,
|
...data,
|
||||||
completeness: "incomplete",
|
completeness: "incomplete",
|
||||||
excludedAccounts: [
|
excludedAccounts: [
|
||||||
{ accountId: "usd", name: "Валютный", reason: "PORTFOLIO_VALUATION_INCOMPLETE" },
|
{ accountId: "usd", name: "Валютный", reason: "NON_RUB_ACTIVITY" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -114,13 +114,13 @@ describe("PerformanceTab", () => {
|
|||||||
renderTab({
|
renderTab({
|
||||||
data: performance({
|
data: performance({
|
||||||
completeness: "incomplete",
|
completeness: "incomplete",
|
||||||
excludedAccounts: [{ accountId: "usd", name: "Валютный", reason: "PORTFOLIO_VALUATION_INCOMPLETE" }],
|
excludedAccounts: [{ accountId: "usd", name: "Валютный", reason: "NON_RUB_ACTIVITY" }],
|
||||||
}),
|
}),
|
||||||
meta,
|
meta,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(await screen.findByText("Результат неполный")).toBeInTheDocument();
|
expect(await screen.findByText("Результат неполный")).toBeInTheDocument();
|
||||||
expect(screen.getByText("Валютный: Нет полной оценки портфеля")).toBeInTheDocument();
|
expect(screen.getByText("Валютный: Есть операции или позиции не в рублях")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("explains unavailability instead of showing zeros, including unknown reasons", async () => {
|
it("explains unavailability instead of showing zeros, including unknown reasons", async () => {
|
||||||
|
|||||||
+51
-18
@@ -4,20 +4,20 @@ import type { Portfolio } from "@/entities/portfolio";
|
|||||||
|
|
||||||
import { PortfolioStructure } from "./PortfolioStructure";
|
import { PortfolioStructure } from "./PortfolioStructure";
|
||||||
|
|
||||||
const rub: Portfolio["structure"] = {
|
const rub: Portfolio["structure"]["currencies"][number] = {
|
||||||
categories: [
|
categories: [
|
||||||
{ sharePercent: "52", type: "STOCK", value: "650000" },
|
{ sharePercent: "52", type: "STOCK", value: "650000" },
|
||||||
{ sharePercent: "30", type: "BOND", value: "375000" },
|
{ sharePercent: "30", type: "BOND", value: "375000" },
|
||||||
{ sharePercent: "10", type: "OTHER", value: "125000" },
|
{ sharePercent: "10", type: "OTHER", value: "125000" },
|
||||||
{ sharePercent: "8", type: "CASH", value: "100000" },
|
{ sharePercent: "8", type: "CASH", value: "100000" },
|
||||||
],
|
],
|
||||||
|
currency: "RUB",
|
||||||
hasNegativeValues: false,
|
hasNegativeValues: false,
|
||||||
totalValue: "1250000",
|
totalValue: "1250000",
|
||||||
unvaluedCategories: [],
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const meta = {
|
const meta = {
|
||||||
args: { structure: rub },
|
args: { structure: { currencies: [rub], unvaluedCategories: [] } },
|
||||||
component: PortfolioStructure,
|
component: PortfolioStructure,
|
||||||
parameters: {
|
parameters: {
|
||||||
docs: {
|
docs: {
|
||||||
@@ -36,34 +36,60 @@ export default meta;
|
|||||||
type Story = StoryObj<typeof meta>;
|
type Story = StoryObj<typeof meta>;
|
||||||
|
|
||||||
export const Regular: Story = {};
|
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 = {
|
export const CashOnly: Story = {
|
||||||
args: {
|
args: {
|
||||||
structure: {
|
structure: {
|
||||||
...rub,
|
currencies: [
|
||||||
|
{
|
||||||
categories: rub.categories.map(row => ({
|
categories: rub.categories.map(row => ({
|
||||||
...row,
|
...row,
|
||||||
sharePercent: row.type === "CASH" ? "100" : "0",
|
sharePercent: row.type === "CASH" ? "100" : "0",
|
||||||
value: row.type === "CASH" ? "100000" : "0",
|
value: row.type === "CASH" ? "100000" : "0",
|
||||||
})),
|
})),
|
||||||
|
currency: "RUB",
|
||||||
|
hasNegativeValues: false,
|
||||||
totalValue: "100000",
|
totalValue: "100000",
|
||||||
},
|
},
|
||||||
},
|
],
|
||||||
};
|
|
||||||
export const Empty: Story = {
|
|
||||||
args: {
|
|
||||||
structure: {
|
|
||||||
categories: [],
|
|
||||||
hasNegativeValues: false,
|
|
||||||
totalValue: "0",
|
|
||||||
unvaluedCategories: [],
|
unvaluedCategories: [],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
export const Empty: Story = {
|
||||||
|
args: { structure: { currencies: [], unvaluedCategories: [] } },
|
||||||
|
};
|
||||||
export const Incomplete: Story = {
|
export const Incomplete: Story = {
|
||||||
args: {
|
args: {
|
||||||
structure: {
|
structure: {
|
||||||
|
currencies: [
|
||||||
|
{
|
||||||
...rub,
|
...rub,
|
||||||
categories: rub.categories.map(row => ({ ...row, sharePercent: null })),
|
categories: rub.categories.map(
|
||||||
|
|
||||||
|
row =>
|
||||||
|
({
|
||||||
|
...row,
|
||||||
|
sharePercent: null,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
],
|
||||||
unvaluedCategories: [{ count: 2, type: "STOCK" }],
|
unvaluedCategories: [{ count: 2, type: "STOCK" }],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -71,9 +97,7 @@ export const Incomplete: Story = {
|
|||||||
export const UnknownOnly: Story = {
|
export const UnknownOnly: Story = {
|
||||||
args: {
|
args: {
|
||||||
structure: {
|
structure: {
|
||||||
categories: [],
|
currencies: [],
|
||||||
hasNegativeValues: false,
|
|
||||||
totalValue: "0",
|
|
||||||
unvaluedCategories: [{ count: 1, type: "BOND" }],
|
unvaluedCategories: [{ count: 1, type: "BOND" }],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -81,14 +105,23 @@ export const UnknownOnly: Story = {
|
|||||||
export const Negative: Story = {
|
export const Negative: Story = {
|
||||||
args: {
|
args: {
|
||||||
structure: {
|
structure: {
|
||||||
|
currencies: [
|
||||||
|
{
|
||||||
...rub,
|
...rub,
|
||||||
categories: rub.categories.map(row => ({
|
categories: rub.categories.map(
|
||||||
|
|
||||||
|
row =>
|
||||||
|
({
|
||||||
...row,
|
...row,
|
||||||
sharePercent: null,
|
sharePercent: null,
|
||||||
value: row.type === "OTHER" ? "25000" : row.value,
|
value: row.type === "OTHER" ? "25000" : row.value,
|
||||||
})),
|
}),
|
||||||
|
),
|
||||||
hasNegativeValues: true,
|
hasNegativeValues: true,
|
||||||
totalValue: "1150000",
|
totalValue: "1150000",
|
||||||
},
|
},
|
||||||
|
],
|
||||||
|
unvaluedCategories: [],
|
||||||
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
+42
-15
@@ -1,21 +1,21 @@
|
|||||||
import { MantineProvider } from "@mantine/core";
|
import { MantineProvider } from "@mantine/core";
|
||||||
import { render, screen, within } from "@testing-library/react";
|
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import type { Portfolio } from "@/entities/portfolio";
|
import type { Portfolio } from "@/entities/portfolio";
|
||||||
|
|
||||||
import { PortfolioStructure } from "./PortfolioStructure";
|
import { PortfolioStructure } from "./PortfolioStructure";
|
||||||
|
|
||||||
const rub: Portfolio["structure"] = {
|
const rub: Portfolio["structure"]["currencies"][number] = {
|
||||||
categories: [
|
categories: [
|
||||||
{ sharePercent: "60", type: "STOCK", value: "60" },
|
{ sharePercent: "60", type: "STOCK", value: "60" },
|
||||||
{ sharePercent: "20", type: "BOND", value: "20" },
|
{ sharePercent: "20", type: "BOND", value: "20" },
|
||||||
{ sharePercent: "0", type: "OTHER", value: "0" },
|
{ sharePercent: "0", type: "OTHER", value: "0" },
|
||||||
{ sharePercent: "20", type: "CASH", value: "20" },
|
{ sharePercent: "20", type: "CASH", value: "20" },
|
||||||
],
|
],
|
||||||
|
currency: "RUB",
|
||||||
hasNegativeValues: false,
|
hasNegativeValues: false,
|
||||||
totalValue: "100",
|
totalValue: "100",
|
||||||
unvaluedCategories: [],
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const ui = (structure: null | Portfolio["structure"] | undefined) => (
|
const ui = (structure: null | Portfolio["structure"] | undefined) => (
|
||||||
@@ -39,7 +39,7 @@ describe("portfolio structure", () => {
|
|||||||
screen.queryByText(/Нет положительной стоимости/),
|
screen.queryByText(/Нет положительной стоимости/),
|
||||||
).not.toBeInTheDocument();
|
).not.toBeInTheDocument();
|
||||||
expect(screen.queryByRole("list")).not.toBeInTheDocument();
|
expect(screen.queryByRole("list")).not.toBeInTheDocument();
|
||||||
view.rerender(ui(rub));
|
view.rerender(ui({ currencies: [rub], unvaluedCategories: [] }));
|
||||||
expect(screen.getByRole("list")).toHaveTextContent("Акции60 ₽60 %");
|
expect(screen.getByRole("list")).toHaveTextContent("Акции60 ₽60 %");
|
||||||
expect(
|
expect(
|
||||||
screen.queryByText("Данные о структуре портфеля пока недоступны."),
|
screen.queryByText("Данные о структуре портфеля пока недоступны."),
|
||||||
@@ -47,23 +47,41 @@ describe("portfolio structure", () => {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
it("shows exact server amounts and cash-inclusive shares without hovering", () => {
|
it("shows exact server amounts and cash-inclusive shares without hovering", () => {
|
||||||
render(ui(rub));
|
render(ui({ currencies: [rub], unvaluedCategories: [] }));
|
||||||
const list = screen.getByRole("list", { name: "Категории активов" });
|
const list = screen.getByRole("list", { name: "Категории активов" });
|
||||||
expect(list).toHaveTextContent("Акции60 ₽60 %");
|
expect(list).toHaveTextContent("Акции60 ₽60 %");
|
||||||
expect(list).toHaveTextContent("Свободные деньги20 ₽20 %");
|
expect(list).toHaveTextContent("Свободные деньги20 ₽20 %");
|
||||||
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
|
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", () => {
|
it("retains known amounts and names unvalued categories without inventing a zero", () => {
|
||||||
render(
|
render(
|
||||||
ui({
|
ui({
|
||||||
|
currencies: [
|
||||||
|
{
|
||||||
...rub,
|
...rub,
|
||||||
categories: rub.categories.map(
|
categories: rub.categories.map(
|
||||||
|
|
||||||
row =>
|
row =>
|
||||||
({
|
({
|
||||||
...row,
|
...row,
|
||||||
sharePercent: null,
|
sharePercent: null,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
|
},
|
||||||
|
],
|
||||||
unvaluedCategories: [
|
unvaluedCategories: [
|
||||||
{ count: 2, type: "OTHER" },
|
{ count: 2, type: "OTHER" },
|
||||||
{ count: 1, type: "STOCK" },
|
{ count: 1, type: "STOCK" },
|
||||||
@@ -71,8 +89,10 @@ describe("portfolio structure", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
expect(screen.getByText(/Оценка неполная/)).toBeInTheDocument();
|
expect(screen.getByText(/Оценка неполная/)).toBeInTheDocument();
|
||||||
expect(screen.getByRole("list")).toHaveTextContent("АкцииИзвестно: 60 ₽");
|
expect(screen.getByRole("list")).toHaveTextContent("Известно: 60 ₽");
|
||||||
expect(screen.getByRole("list")).toHaveTextContent("Другие активы");
|
expect(screen.getByRole("list")).toHaveTextContent(
|
||||||
|
"Другие активыНет оценки",
|
||||||
|
);
|
||||||
expect(
|
expect(
|
||||||
screen.queryByLabelText(/Структура по типам/),
|
screen.queryByLabelText(/Структура по типам/),
|
||||||
).not.toBeInTheDocument();
|
).not.toBeInTheDocument();
|
||||||
@@ -80,8 +100,11 @@ describe("portfolio structure", () => {
|
|||||||
it("keeps negative amounts visible without a donut or invented positive shares", () => {
|
it("keeps negative amounts visible without a donut or invented positive shares", () => {
|
||||||
render(
|
render(
|
||||||
ui({
|
ui({
|
||||||
|
currencies: [
|
||||||
|
{
|
||||||
...rub,
|
...rub,
|
||||||
categories: rub.categories.map(
|
categories: rub.categories.map(
|
||||||
|
|
||||||
row =>
|
row =>
|
||||||
({
|
({
|
||||||
...row,
|
...row,
|
||||||
@@ -90,6 +113,9 @@ describe("portfolio structure", () => {
|
|||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
hasNegativeValues: true,
|
hasNegativeValues: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
unvaluedCategories: [],
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
expect(screen.getByText(/Есть отрицательные/)).toBeInTheDocument();
|
expect(screen.getByText(/Есть отрицательные/)).toBeInTheDocument();
|
||||||
@@ -102,21 +128,20 @@ describe("portfolio structure", () => {
|
|||||||
).not.toBeInTheDocument();
|
).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
it("handles unknown-only and empty compositions", () => {
|
it("handles unknown-only and empty compositions", () => {
|
||||||
render(
|
const view = render(
|
||||||
ui({
|
ui({ currencies: [], unvaluedCategories: [{ count: 1, type: "BOND" }] }),
|
||||||
categories: [],
|
|
||||||
hasNegativeValues: false,
|
|
||||||
totalValue: "0",
|
|
||||||
unvaluedCategories: [{ count: 1, type: "BOND" }],
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(screen.getByText("Облигации: без оценки — 1")).toBeInTheDocument();
|
expect(screen.getByText("Облигации: без оценки — 1")).toBeInTheDocument();
|
||||||
expect(screen.queryByRole("list")).not.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", () => {
|
it("keeps full decimal amounts and describes tiny shares", () => {
|
||||||
render(
|
render(
|
||||||
ui({
|
ui({
|
||||||
|
currencies: [
|
||||||
|
{
|
||||||
...rub,
|
...rub,
|
||||||
categories: [
|
categories: [
|
||||||
{
|
{
|
||||||
@@ -125,7 +150,9 @@ describe("portfolio structure", () => {
|
|||||||
value: "9007199254740993.000000001",
|
value: "9007199254740993.000000001",
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
totalValue: "9007199254740993.000000001",
|
},
|
||||||
|
],
|
||||||
|
unvaluedCategories: [],
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
expect(screen.getByRole("list")).toHaveTextContent(
|
expect(screen.getByRole("list")).toHaveTextContent(
|
||||||
|
|||||||
+17
-3
@@ -1,5 +1,5 @@
|
|||||||
import { DonutChart } from "@mantine/charts";
|
import { DonutChart } from "@mantine/charts";
|
||||||
import { Box, Group, Paper, Stack, Text, Title } from "@mantine/core";
|
import { Box, Group, Paper, Select, Stack, Text, Title } from "@mantine/core";
|
||||||
import { type FC, useId } from "react";
|
import { type FC, useId } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
@@ -7,8 +7,11 @@ import classes from "./PortfolioStructure.module.css";
|
|||||||
|
|
||||||
type PortfolioStructureViewProps = {
|
type PortfolioStructureViewProps = {
|
||||||
chartData: StructureRow[];
|
chartData: StructureRow[];
|
||||||
|
currencies: string[];
|
||||||
|
currency: null | string;
|
||||||
incomplete: boolean;
|
incomplete: boolean;
|
||||||
negative: boolean;
|
negative: boolean;
|
||||||
|
onCurrencyChange: (currency: null | string) => void;
|
||||||
rows: StructureRow[];
|
rows: StructureRow[];
|
||||||
unavailable: boolean;
|
unavailable: boolean;
|
||||||
unvalued: string[];
|
unvalued: string[];
|
||||||
@@ -61,6 +64,17 @@ const PortfolioStructureView: FC<PortfolioStructureViewProps> = (props) => {
|
|||||||
<Title id={titleId} order={2} size="h4">
|
<Title id={titleId} order={2} size="h4">
|
||||||
{t("portfolio.structure.title")}
|
{t("portfolio.structure.title")}
|
||||||
</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>
|
</Group>
|
||||||
|
|
||||||
<Text c="dimmed" size="sm">
|
<Text c="dimmed" size="sm">
|
||||||
@@ -96,11 +110,11 @@ const PortfolioStructureView: FC<PortfolioStructureViewProps> = (props) => {
|
|||||||
</Text>
|
</Text>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className={appearanceClass}>
|
<div className={appearanceClass} key={props.currency}>
|
||||||
{props.chartData.length > 0 && (
|
{props.chartData.length > 0 && (
|
||||||
<DonutChart
|
<DonutChart
|
||||||
aria-label={t("portfolio.structure.chartLabel")}
|
aria-label={t("portfolio.structure.chartLabel")}
|
||||||
chartLabel="₽"
|
chartLabel={props.currency ?? undefined}
|
||||||
data={props.chartData}
|
data={props.chartData}
|
||||||
endAngle={-270}
|
endAngle={-270}
|
||||||
pieChartProps={{ title: t("portfolio.structure.chartLabel") }}
|
pieChartProps={{ title: t("portfolio.structure.chartLabel") }}
|
||||||
|
|||||||
+22
-7
@@ -1,5 +1,6 @@
|
|||||||
import type { TFunction } from "i18next";
|
import type { TFunction } from "i18next";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import type { Portfolio } from "@/entities/portfolio";
|
import type { Portfolio } from "@/entities/portfolio";
|
||||||
@@ -14,15 +15,24 @@ type PortfolioStructureProps = { structure?: null | Portfolio["structure"] };
|
|||||||
const usePortfolioStructureVm = (props: PortfolioStructureProps) => {
|
const usePortfolioStructureVm = (props: PortfolioStructureProps) => {
|
||||||
const { structure } = props;
|
const { structure } = props;
|
||||||
const { t } = useTranslation();
|
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 isIncomplete = (structure?.unvaluedCategories.length ?? 0) > 0;
|
||||||
const rows = portfolioRows(structure, t);
|
const rows = portfolioRows(selected, structure, t);
|
||||||
const chartData = rows.filter(row => row.value > 0);
|
const chartData = rows.filter(row => row.value > 0);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
chartData,
|
chartData,
|
||||||
|
currencies: structure?.currencies.map(item => item.currency) ?? [],
|
||||||
|
|
||||||
|
currency: selected?.currency ?? null,
|
||||||
incomplete: isIncomplete,
|
incomplete: isIncomplete,
|
||||||
negative: structure?.hasNegativeValues ?? false,
|
negative: selected?.hasNegativeValues ?? false,
|
||||||
|
onCurrencyChange: setCurrency,
|
||||||
rows,
|
rows,
|
||||||
unavailable: !structure,
|
unavailable: !structure,
|
||||||
unvalued:
|
unvalued:
|
||||||
@@ -36,12 +46,14 @@ const usePortfolioStructureVm = (props: PortfolioStructureProps) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
function portfolioRows(
|
function portfolioRows(
|
||||||
|
selected:
|
||||||
|
NonNullable<Portfolio["structure"]>["currencies"][number] | undefined,
|
||||||
structure: PortfolioStructureProps["structure"],
|
structure: PortfolioStructureProps["structure"],
|
||||||
t: TFunction,
|
t: TFunction,
|
||||||
) {
|
) {
|
||||||
if (!structure) return [];
|
if (!selected) return [];
|
||||||
|
|
||||||
return structure.categories.map((category) => {
|
return selected.categories.map((category) => {
|
||||||
const presentation = portfolioCategoryPresentation[category.type];
|
const presentation = portfolioCategoryPresentation[category.type];
|
||||||
|
|
||||||
const percentage
|
const percentage
|
||||||
@@ -49,13 +61,16 @@ function portfolioRows(
|
|||||||
? undefined
|
? undefined
|
||||||
: Number(category.sharePercent);
|
: Number(category.sharePercent);
|
||||||
|
|
||||||
const isUnknown = structure.unvaluedCategories.some(
|
const unknown = structure?.unvaluedCategories.some(
|
||||||
item => item.type === category.type,
|
item => item.type === category.type,
|
||||||
);
|
);
|
||||||
|
|
||||||
let amount = formatMoney({ currency: "RUB", value: category.value });
|
let amount = formatMoney({
|
||||||
|
currency: selected.currency,
|
||||||
|
value: category.value,
|
||||||
|
});
|
||||||
|
|
||||||
if (isUnknown) {
|
if (unknown) {
|
||||||
amount
|
amount
|
||||||
= category.value === "0"
|
= category.value === "0"
|
||||||
? t("portfolio.structure.unvalued")
|
? t("portfolio.structure.unvalued")
|
||||||
|
|||||||
@@ -31,26 +31,16 @@ function configureTestAuth() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function portfolioSummary(totals: { currency: string; value: string }) {
|
function portfolioSummary(totals: { currency: string; value: string }[]) {
|
||||||
return {
|
return {
|
||||||
bondPositionCount: 1,
|
bondPositionCount: 1,
|
||||||
cash: { currency: "RUB", value: "0" },
|
cashBalances: [],
|
||||||
fundPositionCount: 0,
|
fundPositionCount: 0,
|
||||||
stockPositionCount: 0,
|
stockPositionCount: 0,
|
||||||
structure: {
|
structure: { currencies: [], unvaluedCategories: [] },
|
||||||
categories: [],
|
|
||||||
hasNegativeValues: false,
|
|
||||||
totalValue: "0",
|
|
||||||
unvaluedCategories: [],
|
|
||||||
},
|
|
||||||
totalPositionCount: 1,
|
totalPositionCount: 1,
|
||||||
totals,
|
totalsByCurrency: totals,
|
||||||
unrealizedReturn: {
|
unrealizedReturnByCurrency: [],
|
||||||
absolute: "0",
|
|
||||||
costBasis: "0",
|
|
||||||
partial: false,
|
|
||||||
percent: null,
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,18 +59,23 @@ function renderPage(queryClient: QueryClient) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("AccountsPage", () => {
|
describe("AccountsPage", () => {
|
||||||
it("summarizes account totals and reports excluded accounts", async () => {
|
it("summarizes currencies separately and reports excluded accounts", async () => {
|
||||||
server.use(http.get("*/api/v1/brokerage-accounts", () =>
|
server.use(http.get("*/api/v1/brokerage-accounts", () =>
|
||||||
HttpResponse.json(resource([
|
HttpResponse.json(resource([
|
||||||
{
|
{
|
||||||
...account,
|
...account,
|
||||||
portfolioSummary: portfolioSummary({ currency: "RUB", value: "100.10" }),
|
portfolioSummary: portfolioSummary([
|
||||||
|
{ currency: "RUB", value: "100.10" },
|
||||||
|
{ currency: "USD", value: "20" },
|
||||||
|
]),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
...account,
|
...account,
|
||||||
id: "account-2",
|
id: "account-2",
|
||||||
name: "Второй",
|
name: "Второй",
|
||||||
portfolioSummary: portfolioSummary({ currency: "RUB", value: "50.20" }),
|
portfolioSummary: portfolioSummary([
|
||||||
|
{ currency: "RUB", value: "50.20" },
|
||||||
|
]),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
...account,
|
...account,
|
||||||
@@ -93,9 +88,9 @@ describe("AccountsPage", () => {
|
|||||||
id: "account-4",
|
id: "account-4",
|
||||||
name: "Только деньги",
|
name: "Только деньги",
|
||||||
portfolioSummary: {
|
portfolioSummary: {
|
||||||
...portfolioSummary({ currency: "RUB", value: "25" }),
|
...portfolioSummary([{ currency: "RUB", value: "25" }]),
|
||||||
bondPositionCount: 0,
|
bondPositionCount: 0,
|
||||||
cash: { currency: "RUB", value: "25" },
|
cashBalances: [{ currency: "RUB", value: "25" }],
|
||||||
totalPositionCount: 0,
|
totalPositionCount: 0,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -104,7 +99,7 @@ describe("AccountsPage", () => {
|
|||||||
id: "account-5",
|
id: "account-5",
|
||||||
name: "Без сумм",
|
name: "Без сумм",
|
||||||
portfolioSummary: {
|
portfolioSummary: {
|
||||||
...portfolioSummary({ currency: "RUB", value: "0" }),
|
...portfolioSummary([]),
|
||||||
totalPositionCount: 0,
|
totalPositionCount: 0,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -115,6 +110,7 @@ describe("AccountsPage", () => {
|
|||||||
renderPage(client);
|
renderPage(client);
|
||||||
|
|
||||||
expect(await screen.findByText("175,30 ₽")).toBeInTheDocument();
|
expect(await screen.findByText("175,30 ₽")).toBeInTheDocument();
|
||||||
|
expect(screen.getAllByText("20,00 $")).not.toHaveLength(0);
|
||||||
expect(screen.queryByText("Ваши инвестиции по счетам"))
|
expect(screen.queryByText("Ваши инвестиции по счетам"))
|
||||||
.not.toBeInTheDocument();
|
.not.toBeInTheDocument();
|
||||||
expect(screen.getByText("5 счетов")).toBeInTheDocument();
|
expect(screen.getByText("5 счетов")).toBeInTheDocument();
|
||||||
|
|||||||
@@ -25,16 +25,34 @@ type AccountsPageLoadedProps = {
|
|||||||
readRetry?: ReadRetryProps;
|
readRetry?: ReadRetryProps;
|
||||||
};
|
};
|
||||||
|
|
||||||
function accountTotals(accounts: BrokerageAccountCard[]): null | string {
|
type Money = { currency: string; value: string };
|
||||||
const values: string[] = [];
|
|
||||||
|
function accountTotals(accounts: BrokerageAccountCard[]) {
|
||||||
|
const values = new Map<string, string[]>();
|
||||||
|
let excludedCount = 0;
|
||||||
|
|
||||||
for (const { summary } of accounts) {
|
for (const { summary } of accounts) {
|
||||||
if (summary.state !== "available") continue;
|
if (summary.state === "empty") continue;
|
||||||
|
|
||||||
values.push(summary.portfolio.totals.value);
|
if (summary.state === "unavailable") {
|
||||||
|
excludedCount += 1;
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
return values.length > 0 ? sumDecimals(values) : null;
|
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 };
|
||||||
}
|
}
|
||||||
|
|
||||||
function sumDecimals(values: string[]) {
|
function sumDecimals(values: string[]) {
|
||||||
@@ -70,11 +88,9 @@ function sumDecimals(values: string[]) {
|
|||||||
|
|
||||||
const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
|
const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const total = accountTotals(props.accounts);
|
const { excludedCount, totals } = accountTotals(props.accounts);
|
||||||
|
const primaryTotal = totals.find(total => total.currency === "RUB") ?? totals[0];
|
||||||
const excludedCount = props.accounts.filter(
|
const otherTotals = totals.filter(total => total !== primaryTotal);
|
||||||
account => account.summary.state === "unavailable",
|
|
||||||
).length;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap="lg">
|
<Stack gap="lg">
|
||||||
@@ -85,14 +101,24 @@ const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
|
|||||||
{t("accounts.currentValue")}
|
{t("accounts.currentValue")}
|
||||||
</Text>
|
</Text>
|
||||||
|
|
||||||
{total === null
|
{primaryTotal
|
||||||
? (
|
? (
|
||||||
<Text c="dimmed">{t("accounts.summaryNoTotals")}</Text>
|
<Text className={classes.primaryTotal} fw={700}>
|
||||||
|
{formatMoney(primaryTotal, { withRoundedCents: true })}
|
||||||
|
</Text>
|
||||||
)
|
)
|
||||||
: (
|
: (
|
||||||
<Text className={classes.primaryTotal} fw={700}>
|
<Text c="dimmed">{t("accounts.summaryNoTotals")}</Text>
|
||||||
{formatMoney({ currency: "RUB", value: total }, { withRoundedCents: true })}
|
)}
|
||||||
|
|
||||||
|
{otherTotals.length > 0 && (
|
||||||
|
<Group gap="md" wrap="wrap">
|
||||||
|
{otherTotals.map(total => (
|
||||||
|
<Text className={classes.otherTotal} key={total.currency}>
|
||||||
|
{formatMoney(total, { withRoundedCents: true })}
|
||||||
</Text>
|
</Text>
|
||||||
|
))}
|
||||||
|
</Group>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Group className={classes.meta} gap="xs" wrap="wrap">
|
<Group className={classes.meta} gap="xs" wrap="wrap">
|
||||||
|
|||||||
@@ -258,10 +258,17 @@ function setup(
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("stock page", () => {
|
describe("stock page", () => {
|
||||||
it("formats RUB money, ratio and percent metrics", async () => {
|
it("preserves unknown and unambiguous currencies with compact, ratio and percent formatting", async () => {
|
||||||
setup(
|
setup(
|
||||||
{
|
{
|
||||||
metrics: [
|
metrics: [
|
||||||
|
{
|
||||||
|
currency: null,
|
||||||
|
key: "marketCapitalization",
|
||||||
|
period: null,
|
||||||
|
unit: "money",
|
||||||
|
value: 1_234_567.89,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
currency: "RUB",
|
currency: "RUB",
|
||||||
key: "revenueTtm",
|
key: "revenueTtm",
|
||||||
@@ -269,6 +276,20 @@ describe("stock page", () => {
|
|||||||
unit: "money",
|
unit: "money",
|
||||||
value: 1_234_567.89,
|
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,
|
currency: null,
|
||||||
key: "peRatioTtm",
|
key: "peRatioTtm",
|
||||||
@@ -286,8 +307,14 @@ describe("stock page", () => {
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
expect(await screen.findByText("1,23 млн ₽")).toBeVisible();
|
expect(await screen.findByText("1,23 млн валюта неизвестна")).toBeVisible();
|
||||||
for (const value of ["5,68 ×", "12,35 %"])
|
for (const value of [
|
||||||
|
"1,23 млн ₽",
|
||||||
|
"1,23 млн USD",
|
||||||
|
"1,23 млн CAD",
|
||||||
|
"5,68 ×",
|
||||||
|
"12,35 %",
|
||||||
|
])
|
||||||
expect(screen.getByText(value)).toBeVisible();
|
expect(screen.getByText(value)).toBeVisible();
|
||||||
});
|
});
|
||||||
it("opens a direct ticker URL and uses its resolved UID for market and personal requests", async () => {
|
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) => {
|
{props.company.metrics.map((metric) => {
|
||||||
const label = [t(`stock.metrics.${metric.key}`), metric.period].filter(Boolean).join(" · ");
|
const label = [t(`stock.metrics.${metric.key}`), metric.period].filter(Boolean).join(" · ");
|
||||||
const formatter = metric.unit === "money" ? compactMetricFormatter : metricFormatter;
|
const formatter = metric.unit === "money" ? compactMetricFormatter : metricFormatter;
|
||||||
const value = `${formatter.format(metric.value)} ${metricUnit(metric)}`;
|
const value = `${formatter.format(metric.value)} ${metricUnit(metric, t("stock.currencyUnknown"))}`;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<InstrumentMetric key={metric.key} label={label} value={value} />
|
<InstrumentMetric key={metric.key} label={label} value={value} />
|
||||||
@@ -89,9 +89,14 @@ const StockCompany: FC<StockCompanyProps> = (props) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
function metricUnit(metric: NonNullable<StockPageVm["company"]>["metrics"][number]) {
|
function metricUnit(
|
||||||
|
metric: NonNullable<StockPageVm["company"]>["metrics"][number],
|
||||||
|
unknownCurrency: string,
|
||||||
|
) {
|
||||||
if (metric.unit === "money")
|
if (metric.unit === "money")
|
||||||
return "₽";
|
return metric.currency === "RUB"
|
||||||
|
? "₽"
|
||||||
|
: (metric.currency ?? unknownCurrency);
|
||||||
|
|
||||||
return metric.unit === "percent" ? "%" : "×";
|
return metric.unit === "percent" ? "%" : "×";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -69,6 +69,7 @@ const criteriaFields: CriteriaField[] = [
|
|||||||
"SHARE_TYPE_PREFERRED",
|
"SHARE_TYPE_PREFERRED",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
{ label: "currency", options: ["RUB", "USD", "EUR", "CNY", "HKD", "TRY"] },
|
||||||
{
|
{
|
||||||
label: "realExchange",
|
label: "realExchange",
|
||||||
options: [
|
options: [
|
||||||
@@ -183,6 +184,10 @@ const StockCard: FC<StockCardProps> = (props) => {
|
|||||||
<Group gap="xs">
|
<Group gap="xs">
|
||||||
{exchange && <Badge color="gray" variant="light">{exchange}</Badge>}
|
{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>}
|
{lot && <Text c="dimmed" size="xs">{lot}</Text>}
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { apiClient } from "@/shared/api";
|
|||||||
|
|
||||||
type Criteria = {
|
type Criteria = {
|
||||||
countryOfRisk: string;
|
countryOfRisk: string;
|
||||||
|
currency: string;
|
||||||
maxLot: string;
|
maxLot: string;
|
||||||
query: string;
|
query: string;
|
||||||
realExchange: string;
|
realExchange: string;
|
||||||
@@ -17,6 +18,7 @@ type StocksPageVm = ReturnType<typeof useStocksPageVm>;
|
|||||||
|
|
||||||
const emptyCriteria: Criteria = {
|
const emptyCriteria: Criteria = {
|
||||||
countryOfRisk: "",
|
countryOfRisk: "",
|
||||||
|
currency: "",
|
||||||
maxLot: "",
|
maxLot: "",
|
||||||
query: "",
|
query: "",
|
||||||
realExchange: "",
|
realExchange: "",
|
||||||
@@ -28,6 +30,7 @@ async function createSearch(criteria: Criteria) {
|
|||||||
const { data } = await apiClient.POST("/api/v1/stocks/screener/search", {
|
const { data } = await apiClient.POST("/api/v1/stocks/screener/search", {
|
||||||
body: {
|
body: {
|
||||||
...(criteria.countryOfRisk && { countryOfRisk: criteria.countryOfRisk }),
|
...(criteria.countryOfRisk && { countryOfRisk: criteria.countryOfRisk }),
|
||||||
|
...(criteria.currency && { currency: criteria.currency }),
|
||||||
...(criteria.maxLot && { maxLot: Number(criteria.maxLot) }),
|
...(criteria.maxLot && { maxLot: Number(criteria.maxLot) }),
|
||||||
...(criteria.query && { query: criteria.query }),
|
...(criteria.query && { query: criteria.query }),
|
||||||
...(criteria.realExchange && { realExchange: criteria.realExchange }),
|
...(criteria.realExchange && { realExchange: criteria.realExchange }),
|
||||||
|
|||||||
Vendored
+23
-17
@@ -984,21 +984,25 @@ export interface components {
|
|||||||
/** @description Percentage including cash, rounded to six decimal places. Null for incomplete, negative or zero-total compositions. */
|
/** @description Percentage including cash, rounded to six decimal places. Null for incomplete, negative or zero-total compositions. */
|
||||||
sharePercent: string | null;
|
sharePercent: string | null;
|
||||||
};
|
};
|
||||||
|
PortfolioStructureCurrencyDto: {
|
||||||
|
currency: string;
|
||||||
|
totalValue: string;
|
||||||
|
/** @description Any negative constituent, even if netted positive. */
|
||||||
|
hasNegativeValues: boolean;
|
||||||
|
categories: components["schemas"]["PortfolioStructureCategoryDto"][];
|
||||||
|
};
|
||||||
PortfolioUnvaluedCategoryDto: {
|
PortfolioUnvaluedCategoryDto: {
|
||||||
/** @enum {string} */
|
/** @enum {string} */
|
||||||
type: "STOCK" | "BOND" | "OTHER";
|
type: "STOCK" | "BOND" | "OTHER";
|
||||||
count: number;
|
count: number;
|
||||||
};
|
};
|
||||||
PortfolioStructureDto: {
|
PortfolioStructureDto: {
|
||||||
/** @description Exact known total as a decimal string. */
|
currencies: components["schemas"]["PortfolioStructureCurrencyDto"][];
|
||||||
totalValue: string;
|
/** @description Positions without current value and known valuation currency. Shares are unavailable across all currencies when nonempty. */
|
||||||
/** @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"][];
|
unvaluedCategories: components["schemas"]["PortfolioUnvaluedCategoryDto"][];
|
||||||
};
|
};
|
||||||
UnrealizedReturnDto: {
|
UnrealizedReturnDto: {
|
||||||
|
currency: string;
|
||||||
/** @example 12.345678901 */
|
/** @example 12.345678901 */
|
||||||
absolute: string;
|
absolute: string;
|
||||||
/** @example 100.00 */
|
/** @example 100.00 */
|
||||||
@@ -1008,10 +1012,10 @@ export interface components {
|
|||||||
partial: boolean;
|
partial: boolean;
|
||||||
};
|
};
|
||||||
PortfolioSummaryDto: {
|
PortfolioSummaryDto: {
|
||||||
totals: components["schemas"]["MoneyDto"];
|
totalsByCurrency: components["schemas"]["MoneyDto"][];
|
||||||
cash: components["schemas"]["MoneyDto"];
|
cashBalances: components["schemas"]["MoneyDto"][];
|
||||||
structure: components["schemas"]["PortfolioStructureDto"];
|
structure: components["schemas"]["PortfolioStructureDto"];
|
||||||
unrealizedReturn: components["schemas"]["UnrealizedReturnDto"];
|
unrealizedReturnByCurrency: components["schemas"]["UnrealizedReturnDto"][];
|
||||||
/** @description Number of non-zero stock positions, not the number of units. */
|
/** @description Number of non-zero stock positions, not the number of units. */
|
||||||
stockPositionCount: number;
|
stockPositionCount: number;
|
||||||
/** @description Number of non-zero bond positions, not the number of units. */
|
/** @description Number of non-zero bond positions, not the number of units. */
|
||||||
@@ -1141,9 +1145,9 @@ export interface components {
|
|||||||
/** Format: date-time */
|
/** Format: date-time */
|
||||||
lastSuccessfulAt: string;
|
lastSuccessfulAt: string;
|
||||||
isStale: boolean;
|
isStale: boolean;
|
||||||
totals: components["schemas"]["MoneyDto"];
|
totalsByCurrency: components["schemas"]["MoneyDto"][];
|
||||||
positions: components["schemas"]["PortfolioPositionDto"][];
|
positions: components["schemas"]["PortfolioPositionDto"][];
|
||||||
cash: components["schemas"]["MoneyDto"];
|
cashBalances: components["schemas"]["MoneyDto"][];
|
||||||
structure: components["schemas"]["PortfolioStructureDto"];
|
structure: components["schemas"]["PortfolioStructureDto"];
|
||||||
};
|
};
|
||||||
PortfolioResourceDto: {
|
PortfolioResourceDto: {
|
||||||
@@ -1158,7 +1162,7 @@ export interface components {
|
|||||||
days: number;
|
days: number;
|
||||||
};
|
};
|
||||||
/** @enum {string} */
|
/** @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";
|
PerformanceUnavailableReason: "ACCOUNT_VALUATION_DATES_DIFFER" | "AMBIGUOUS_RETURN" | "HISTORY_START_UNKNOWN" | "INDEX_HISTORY_UNAVAILABLE" | "NON_RUB_ACTIVITY" | "NO_SOLUTION" | "OPERATIONS_HISTORY_INCOMPLETE" | "PORTFOLIO_VALUATION_INCOMPLETE" | "UNCONFIRMED_TRANSFER" | "UNVALUED_SECURITIES_TRANSFER";
|
||||||
PerformanceReturnDto: {
|
PerformanceReturnDto: {
|
||||||
/** @description Decimal fraction: 0.151 = 15.1% */
|
/** @description Decimal fraction: 0.151 = 15.1% */
|
||||||
value: string | null;
|
value: string | null;
|
||||||
@@ -1255,7 +1259,8 @@ export interface components {
|
|||||||
/** Format: date */
|
/** Format: date */
|
||||||
to: string;
|
to: string;
|
||||||
};
|
};
|
||||||
IncomeTotalDto: {
|
IncomeCurrencySummaryDto: {
|
||||||
|
currency: string;
|
||||||
coupon: components["schemas"]["MoneyDto"];
|
coupon: components["schemas"]["MoneyDto"];
|
||||||
dividend: components["schemas"]["MoneyDto"];
|
dividend: components["schemas"]["MoneyDto"];
|
||||||
total: components["schemas"]["MoneyDto"];
|
total: components["schemas"]["MoneyDto"];
|
||||||
@@ -1263,7 +1268,7 @@ export interface components {
|
|||||||
IncomeSummaryDto: {
|
IncomeSummaryDto: {
|
||||||
accountId: string;
|
accountId: string;
|
||||||
period: components["schemas"]["IncomePeriodDto"];
|
period: components["schemas"]["IncomePeriodDto"];
|
||||||
total: components["schemas"]["IncomeTotalDto"];
|
totalsByCurrency: components["schemas"]["IncomeCurrencySummaryDto"][];
|
||||||
/** Format: date-time */
|
/** Format: date-time */
|
||||||
calculatedAt: string;
|
calculatedAt: string;
|
||||||
};
|
};
|
||||||
@@ -1273,7 +1278,7 @@ export interface components {
|
|||||||
};
|
};
|
||||||
IncomeBucketDto: {
|
IncomeBucketDto: {
|
||||||
period: components["schemas"]["IncomePeriodDto"];
|
period: components["schemas"]["IncomePeriodDto"];
|
||||||
total: components["schemas"]["IncomeTotalDto"];
|
totalsByCurrency: components["schemas"]["IncomeCurrencySummaryDto"][];
|
||||||
};
|
};
|
||||||
IncomeInstrumentDto: {
|
IncomeInstrumentDto: {
|
||||||
key: string;
|
key: string;
|
||||||
@@ -1311,7 +1316,7 @@ export interface components {
|
|||||||
IncomeAnalyticsDto: {
|
IncomeAnalyticsDto: {
|
||||||
accountId: string;
|
accountId: string;
|
||||||
period: components["schemas"]["IncomePeriodDto"];
|
period: components["schemas"]["IncomePeriodDto"];
|
||||||
total: components["schemas"]["IncomeTotalDto"];
|
totalsByCurrency: components["schemas"]["IncomeCurrencySummaryDto"][];
|
||||||
/** Format: date-time */
|
/** Format: date-time */
|
||||||
calculatedAt: string;
|
calculatedAt: string;
|
||||||
/** @enum {string} */
|
/** @enum {string} */
|
||||||
@@ -1387,7 +1392,7 @@ export interface components {
|
|||||||
/** @description Inclusive UTC window the saved forecast was calculated for. Unchanged by the requested from/to filter. */
|
/** @description Inclusive UTC window the saved forecast was calculated for. Unchanged by the requested from/to filter. */
|
||||||
window: components["schemas"]["UpcomingEventsWindowDto"];
|
window: components["schemas"]["UpcomingEventsWindowDto"];
|
||||||
events: components["schemas"]["UpcomingEventDto"][];
|
events: components["schemas"]["UpcomingEventDto"][];
|
||||||
incomeTotal: components["schemas"]["MoneyDto"];
|
incomeTotalsByCurrency: components["schemas"]["MoneyDto"][];
|
||||||
};
|
};
|
||||||
UpcomingEventsResourceDto: {
|
UpcomingEventsResourceDto: {
|
||||||
data: components["schemas"]["UpcomingEventsDto"] | null;
|
data: components["schemas"]["UpcomingEventsDto"] | null;
|
||||||
@@ -1446,6 +1451,7 @@ export interface components {
|
|||||||
query?: string;
|
query?: string;
|
||||||
sector?: string;
|
sector?: string;
|
||||||
shareType?: string;
|
shareType?: string;
|
||||||
|
currency?: string;
|
||||||
realExchange?: string;
|
realExchange?: string;
|
||||||
countryOfRisk?: string;
|
countryOfRisk?: string;
|
||||||
maxLot?: number;
|
maxLot?: number;
|
||||||
|
|||||||
@@ -20,12 +20,12 @@ function usePrivateResource(accountId: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const snapshot: Portfolio = {
|
const snapshot: Portfolio = {
|
||||||
cash: { currency: "RUB", value: "0" },
|
cashBalances: [],
|
||||||
isStale: false,
|
isStale: false,
|
||||||
lastSuccessfulAt: "2026-08-14T00:00:00Z",
|
lastSuccessfulAt: "2026-08-14T00:00:00Z",
|
||||||
positions: [],
|
positions: [],
|
||||||
structure: { categories: [], hasNegativeValues: false, totalValue: "0", unvaluedCategories: [] },
|
structure: { currencies: [], unvaluedCategories: [] },
|
||||||
totals: { currency: "RUB", value: "123.000000001" },
|
totalsByCurrency: [{ currency: "RUB", value: "123.000000001" }],
|
||||||
};
|
};
|
||||||
|
|
||||||
function auth() {
|
function auth() {
|
||||||
@@ -94,8 +94,8 @@ describe("persistent resource query lifecycle", () => {
|
|||||||
isReady = true;
|
isReady = true;
|
||||||
const loaded = await result.current.refetch();
|
const loaded = await result.current.refetch();
|
||||||
expect(loaded.data).toEqual(refreshed);
|
expect(loaded.data).toEqual(refreshed);
|
||||||
expect(loaded.data?.data?.totals).toEqual(
|
expect(loaded.data?.data?.totalsByCurrency).toEqual(
|
||||||
snapshot.totals,
|
snapshot.totalsByCurrency,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
await waitFor(() => expect(result.current.data).toEqual(snapshot));
|
await waitFor(() => expect(result.current.data).toEqual(snapshot));
|
||||||
|
|||||||
@@ -5871,6 +5871,33 @@
|
|||||||
"sharePercent"
|
"sharePercent"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
"PortfolioStructureCurrencyDto": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"currency": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"totalValue": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"hasNegativeValues": {
|
||||||
|
"type": "boolean",
|
||||||
|
"description": "Any negative constituent, even if netted positive."
|
||||||
|
},
|
||||||
|
"categories": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/PortfolioStructureCategoryDto"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"currency",
|
||||||
|
"totalValue",
|
||||||
|
"hasNegativeValues",
|
||||||
|
"categories"
|
||||||
|
]
|
||||||
|
},
|
||||||
"PortfolioUnvaluedCategoryDto": {
|
"PortfolioUnvaluedCategoryDto": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
@@ -5895,22 +5922,14 @@
|
|||||||
"PortfolioStructureDto": {
|
"PortfolioStructureDto": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"totalValue": {
|
"currencies": {
|
||||||
"type": "string",
|
|
||||||
"description": "Exact known total as a decimal string."
|
|
||||||
},
|
|
||||||
"hasNegativeValues": {
|
|
||||||
"type": "boolean",
|
|
||||||
"description": "Any negative constituent, even if netted positive."
|
|
||||||
},
|
|
||||||
"categories": {
|
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"$ref": "#/components/schemas/PortfolioStructureCategoryDto"
|
"$ref": "#/components/schemas/PortfolioStructureCurrencyDto"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"unvaluedCategories": {
|
"unvaluedCategories": {
|
||||||
"description": "Positions without current value. Shares are unavailable when nonempty.",
|
"description": "Positions without current value and known valuation currency. Shares are unavailable across all currencies when nonempty.",
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"$ref": "#/components/schemas/PortfolioUnvaluedCategoryDto"
|
"$ref": "#/components/schemas/PortfolioUnvaluedCategoryDto"
|
||||||
@@ -5918,15 +5937,16 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"totalValue",
|
"currencies",
|
||||||
"hasNegativeValues",
|
|
||||||
"categories",
|
|
||||||
"unvaluedCategories"
|
"unvaluedCategories"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"UnrealizedReturnDto": {
|
"UnrealizedReturnDto": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
|
"currency": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
"absolute": {
|
"absolute": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"example": "12.345678901"
|
"example": "12.345678901"
|
||||||
@@ -5945,6 +5965,7 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
|
"currency",
|
||||||
"absolute",
|
"absolute",
|
||||||
"costBasis",
|
"costBasis",
|
||||||
"percent",
|
"percent",
|
||||||
@@ -5954,17 +5975,26 @@
|
|||||||
"PortfolioSummaryDto": {
|
"PortfolioSummaryDto": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"totals": {
|
"totalsByCurrency": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
"$ref": "#/components/schemas/MoneyDto"
|
"$ref": "#/components/schemas/MoneyDto"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"cash": {
|
"cashBalances": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
"$ref": "#/components/schemas/MoneyDto"
|
"$ref": "#/components/schemas/MoneyDto"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"structure": {
|
"structure": {
|
||||||
"$ref": "#/components/schemas/PortfolioStructureDto"
|
"$ref": "#/components/schemas/PortfolioStructureDto"
|
||||||
},
|
},
|
||||||
"unrealizedReturn": {
|
"unrealizedReturnByCurrency": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
"$ref": "#/components/schemas/UnrealizedReturnDto"
|
"$ref": "#/components/schemas/UnrealizedReturnDto"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"stockPositionCount": {
|
"stockPositionCount": {
|
||||||
"type": "integer",
|
"type": "integer",
|
||||||
@@ -5988,10 +6018,10 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"totals",
|
"totalsByCurrency",
|
||||||
"cash",
|
"cashBalances",
|
||||||
"structure",
|
"structure",
|
||||||
"unrealizedReturn",
|
"unrealizedReturnByCurrency",
|
||||||
"stockPositionCount",
|
"stockPositionCount",
|
||||||
"bondPositionCount",
|
"bondPositionCount",
|
||||||
"fundPositionCount",
|
"fundPositionCount",
|
||||||
@@ -6507,8 +6537,11 @@
|
|||||||
"isStale": {
|
"isStale": {
|
||||||
"type": "boolean"
|
"type": "boolean"
|
||||||
},
|
},
|
||||||
"totals": {
|
"totalsByCurrency": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
"$ref": "#/components/schemas/MoneyDto"
|
"$ref": "#/components/schemas/MoneyDto"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"positions": {
|
"positions": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
@@ -6516,8 +6549,11 @@
|
|||||||
"$ref": "#/components/schemas/PortfolioPositionDto"
|
"$ref": "#/components/schemas/PortfolioPositionDto"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"cash": {
|
"cashBalances": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
"$ref": "#/components/schemas/MoneyDto"
|
"$ref": "#/components/schemas/MoneyDto"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"structure": {
|
"structure": {
|
||||||
"$ref": "#/components/schemas/PortfolioStructureDto"
|
"$ref": "#/components/schemas/PortfolioStructureDto"
|
||||||
@@ -6526,9 +6562,9 @@
|
|||||||
"required": [
|
"required": [
|
||||||
"lastSuccessfulAt",
|
"lastSuccessfulAt",
|
||||||
"isStale",
|
"isStale",
|
||||||
"totals",
|
"totalsByCurrency",
|
||||||
"positions",
|
"positions",
|
||||||
"cash",
|
"cashBalances",
|
||||||
"structure"
|
"structure"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -6581,6 +6617,7 @@
|
|||||||
"AMBIGUOUS_RETURN",
|
"AMBIGUOUS_RETURN",
|
||||||
"HISTORY_START_UNKNOWN",
|
"HISTORY_START_UNKNOWN",
|
||||||
"INDEX_HISTORY_UNAVAILABLE",
|
"INDEX_HISTORY_UNAVAILABLE",
|
||||||
|
"NON_RUB_ACTIVITY",
|
||||||
"NO_SOLUTION",
|
"NO_SOLUTION",
|
||||||
"OPERATIONS_HISTORY_INCOMPLETE",
|
"OPERATIONS_HISTORY_INCOMPLETE",
|
||||||
"PORTFOLIO_VALUATION_INCOMPLETE",
|
"PORTFOLIO_VALUATION_INCOMPLETE",
|
||||||
@@ -7023,9 +7060,12 @@
|
|||||||
"to"
|
"to"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"IncomeTotalDto": {
|
"IncomeCurrencySummaryDto": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
|
"currency": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
"coupon": {
|
"coupon": {
|
||||||
"$ref": "#/components/schemas/MoneyDto"
|
"$ref": "#/components/schemas/MoneyDto"
|
||||||
},
|
},
|
||||||
@@ -7037,6 +7077,7 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
|
"currency",
|
||||||
"coupon",
|
"coupon",
|
||||||
"dividend",
|
"dividend",
|
||||||
"total"
|
"total"
|
||||||
@@ -7051,8 +7092,11 @@
|
|||||||
"period": {
|
"period": {
|
||||||
"$ref": "#/components/schemas/IncomePeriodDto"
|
"$ref": "#/components/schemas/IncomePeriodDto"
|
||||||
},
|
},
|
||||||
"total": {
|
"totalsByCurrency": {
|
||||||
"$ref": "#/components/schemas/IncomeTotalDto"
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/IncomeCurrencySummaryDto"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"calculatedAt": {
|
"calculatedAt": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
@@ -7062,7 +7106,7 @@
|
|||||||
"required": [
|
"required": [
|
||||||
"accountId",
|
"accountId",
|
||||||
"period",
|
"period",
|
||||||
"total",
|
"totalsByCurrency",
|
||||||
"calculatedAt"
|
"calculatedAt"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -7093,13 +7137,16 @@
|
|||||||
"period": {
|
"period": {
|
||||||
"$ref": "#/components/schemas/IncomePeriodDto"
|
"$ref": "#/components/schemas/IncomePeriodDto"
|
||||||
},
|
},
|
||||||
"total": {
|
"totalsByCurrency": {
|
||||||
"$ref": "#/components/schemas/IncomeTotalDto"
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/IncomeCurrencySummaryDto"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"period",
|
"period",
|
||||||
"total"
|
"totalsByCurrency"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"IncomeInstrumentDto": {
|
"IncomeInstrumentDto": {
|
||||||
@@ -7275,8 +7322,11 @@
|
|||||||
"period": {
|
"period": {
|
||||||
"$ref": "#/components/schemas/IncomePeriodDto"
|
"$ref": "#/components/schemas/IncomePeriodDto"
|
||||||
},
|
},
|
||||||
"total": {
|
"totalsByCurrency": {
|
||||||
"$ref": "#/components/schemas/IncomeTotalDto"
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/IncomeCurrencySummaryDto"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"calculatedAt": {
|
"calculatedAt": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
@@ -7312,7 +7362,7 @@
|
|||||||
"required": [
|
"required": [
|
||||||
"accountId",
|
"accountId",
|
||||||
"period",
|
"period",
|
||||||
"total",
|
"totalsByCurrency",
|
||||||
"calculatedAt",
|
"calculatedAt",
|
||||||
"bucketGranularity",
|
"bucketGranularity",
|
||||||
"buckets",
|
"buckets",
|
||||||
@@ -7584,16 +7634,19 @@
|
|||||||
"$ref": "#/components/schemas/UpcomingEventDto"
|
"$ref": "#/components/schemas/UpcomingEventDto"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"incomeTotal": {
|
"incomeTotalsByCurrency": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
"$ref": "#/components/schemas/MoneyDto"
|
"$ref": "#/components/schemas/MoneyDto"
|
||||||
}
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"accountId",
|
"accountId",
|
||||||
"calculatedAt",
|
"calculatedAt",
|
||||||
"window",
|
"window",
|
||||||
"events",
|
"events",
|
||||||
"incomeTotal"
|
"incomeTotalsByCurrency"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"UpcomingEventsResourceDto": {
|
"UpcomingEventsResourceDto": {
|
||||||
@@ -7842,6 +7895,10 @@
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"minLength": 1
|
"minLength": 1
|
||||||
},
|
},
|
||||||
|
"currency": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1
|
||||||
|
},
|
||||||
"realExchange": {
|
"realExchange": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"minLength": 1
|
"minLength": 1
|
||||||
|
|||||||
@@ -14,9 +14,9 @@ const ru = {
|
|||||||
currentValue: "Текущая стоимость",
|
currentValue: "Текущая стоимость",
|
||||||
description: {
|
description: {
|
||||||
currentValue: "Текущая стоимость: {{value}}. ",
|
currentValue: "Текущая стоимость: {{value}}. ",
|
||||||
return: "Доходность: {{percent}}, {{absolute}}",
|
return: "Доходность {{currency}}: {{percent}}, {{absolute}}",
|
||||||
start: "Счёт {{name}}, {{type}}. ",
|
start: "Счёт {{name}}, {{type}}. ",
|
||||||
structure: "Структура: {{value}}",
|
structure: "Структура {{currency}}: {{value}}",
|
||||||
structureCategory: "{{category}} {{value}}",
|
structureCategory: "{{category}} {{value}}",
|
||||||
},
|
},
|
||||||
emptyText:
|
emptyText:
|
||||||
@@ -39,13 +39,17 @@ const ru = {
|
|||||||
refreshError:
|
refreshError:
|
||||||
"Не удалось обновить данные. Показаны последние полученные.",
|
"Не удалось обновить данные. Показаны последние полученные.",
|
||||||
refreshing: "Обновляем данные",
|
refreshing: "Обновляем данные",
|
||||||
|
remainingCurrencies_few: "Еще {{count}} валюты",
|
||||||
|
remainingCurrencies_many: "Еще {{count}} валют",
|
||||||
|
remainingCurrencies_one: "Еще {{count}} валюта",
|
||||||
|
remainingCurrencies_other: "Еще {{count}} валюты",
|
||||||
retry: "Повторить",
|
retry: "Повторить",
|
||||||
scope: "Счёт",
|
scope: "Счёт",
|
||||||
stocks: "Акции",
|
stocks: "Акции",
|
||||||
structure: {
|
structure: {
|
||||||
category: "{{category}} {{percent}} %",
|
category: "{{category}} {{percent}} %",
|
||||||
incomplete: "{{category}}: доля неизвестна",
|
incomplete: "{{category}}: доля неизвестна",
|
||||||
label: "Структура: {{value}}",
|
label: "Структура в {{currency}}: {{value}}",
|
||||||
},
|
},
|
||||||
summaryEmpty: "Нет текущих сумм",
|
summaryEmpty: "Нет текущих сумм",
|
||||||
summaryExcluded_few:
|
summaryExcluded_few:
|
||||||
@@ -508,9 +512,9 @@ const ru = {
|
|||||||
bonds: "Облигации",
|
bonds: "Облигации",
|
||||||
byAccount: "Позиции по счетам",
|
byAccount: "Позиции по счетам",
|
||||||
cashBalances: "Денежные остатки",
|
cashBalances: "Денежные остатки",
|
||||||
cashTitle: "Деньги",
|
|
||||||
concentration: {
|
concentration: {
|
||||||
chart: "Распределение позиций",
|
chart: "Распределение позиций",
|
||||||
|
currency: "Валюта концентрации",
|
||||||
empty: "В этом разрезе нет позиций с положительной оценкой.",
|
empty: "В этом разрезе нет позиций с положительной оценкой.",
|
||||||
incomplete: "Данные неполные",
|
incomplete: "Данные неполные",
|
||||||
issuers: "Эмитенты",
|
issuers: "Эмитенты",
|
||||||
@@ -530,6 +534,11 @@ const ru = {
|
|||||||
},
|
},
|
||||||
connectionErrorText: "Настройте подключение, чтобы посмотреть портфель.",
|
connectionErrorText: "Настройте подключение, чтобы посмотреть портфель.",
|
||||||
connectionErrorTitle: "Проверьте подключение T-Bank",
|
connectionErrorTitle: "Проверьте подключение T-Bank",
|
||||||
|
currencies: {
|
||||||
|
EUR: "Евро",
|
||||||
|
RUB: "Российский рубль",
|
||||||
|
USD: "Доллар США",
|
||||||
|
},
|
||||||
emptyText: "На счете нет позиций и доступных денежных остатков.",
|
emptyText: "На счете нет позиций и доступных денежных остатков.",
|
||||||
emptyTitle: "Портфель пока пуст",
|
emptyTitle: "Портфель пока пуст",
|
||||||
more: "Подробнее",
|
more: "Подробнее",
|
||||||
@@ -589,6 +598,7 @@ const ru = {
|
|||||||
categories: "Категории активов",
|
categories: "Категории активов",
|
||||||
chartLabel:
|
chartLabel:
|
||||||
"Структура по типам активов. Суммы и доли — в списке рядом.",
|
"Структура по типам активов. Суммы и доли — в списке рядом.",
|
||||||
|
currency: "Валюта структуры портфеля",
|
||||||
empty: "Нет положительной стоимости для кольцевой диаграммы.",
|
empty: "Нет положительной стоимости для кольцевой диаграммы.",
|
||||||
incomplete:
|
incomplete:
|
||||||
"Оценка неполная: ниже показаны только известные суммы. Валюта оценки части позиций неизвестна, поэтому доли и диаграмма недоступны.",
|
"Оценка неполная: ниже показаны только известные суммы. Валюта оценки части позиций неизвестна, поэтому доли и диаграмма недоступны.",
|
||||||
@@ -612,7 +622,6 @@ const ru = {
|
|||||||
positions: "Позиции",
|
positions: "Позиции",
|
||||||
},
|
},
|
||||||
title: "Портфель",
|
title: "Портфель",
|
||||||
total: "Текущая стоимость",
|
|
||||||
unrealizedResult: "Нереализованный результат",
|
unrealizedResult: "Нереализованный результат",
|
||||||
unrealizedResultCaption: "по цене, без НКД и купонов",
|
unrealizedResultCaption: "по цене, без НКД и купонов",
|
||||||
updatedAt: "Данные получены {{date}}",
|
updatedAt: "Данные получены {{date}}",
|
||||||
@@ -655,6 +664,7 @@ const ru = {
|
|||||||
complete: "Завершена",
|
complete: "Завершена",
|
||||||
connect:
|
connect:
|
||||||
"Для просмотра акций подключите T-Банк в настройках или обновите подключение.",
|
"Для просмотра акций подключите T-Банк в настройках или обновите подключение.",
|
||||||
|
currencyUnknown: "валюта неизвестна",
|
||||||
date: "Дата",
|
date: "Дата",
|
||||||
dateUnknown: "Дата не указана",
|
dateUnknown: "Дата не указана",
|
||||||
dividendHistory: "История дивидендов компании",
|
dividendHistory: "История дивидендов компании",
|
||||||
@@ -742,6 +752,7 @@ const ru = {
|
|||||||
screener: {
|
screener: {
|
||||||
asOf: "Список получен {{date}}",
|
asOf: "Список получен {{date}}",
|
||||||
countryOfRisk: "Страна риска",
|
countryOfRisk: "Страна риска",
|
||||||
|
currency: "Валюта расчётов",
|
||||||
empty: "Подходящие акции не найдены.",
|
empty: "Подходящие акции не найдены.",
|
||||||
error: "Не удалось получить результат скринера. Попробуйте найти снова.",
|
error: "Не удалось получить результат скринера. Попробуйте найти снова.",
|
||||||
maxLot: "Максимальный размер лота",
|
maxLot: "Максимальный размер лота",
|
||||||
|
|||||||
@@ -3,13 +3,18 @@ import { describe, expect, it } from "vitest";
|
|||||||
import { sumMoney } from "./decimal";
|
import { sumMoney } from "./decimal";
|
||||||
|
|
||||||
describe("sumMoney", () => {
|
describe("sumMoney", () => {
|
||||||
it("adds exact signed decimals", () => {
|
it("adds exact signed decimals independently per currency", () => {
|
||||||
expect(sumMoney([
|
expect(sumMoney([
|
||||||
{ currency: "RUB", value: "0.1" },
|
{ currency: "RUB", value: "0.1" },
|
||||||
|
{ currency: "USD", value: "0.01" },
|
||||||
{ currency: "RUB", value: "0.2" },
|
{ currency: "RUB", value: "0.2" },
|
||||||
{ currency: "RUB", value: "-1500000.45" },
|
{ currency: "RUB", value: "-1500000.45" },
|
||||||
|
{ currency: "USD", value: "-0.02" },
|
||||||
{ currency: "RUB", value: "200" },
|
{ currency: "RUB", value: "200" },
|
||||||
])).toEqual({ currency: "RUB", value: "-1499800.15" });
|
])).toEqual([
|
||||||
|
{ currency: "RUB", value: "-1499800.15" },
|
||||||
|
{ currency: "USD", value: "-0.01" },
|
||||||
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("preserves significant fractional digits and a compensated zero", () => {
|
it("preserves significant fractional digits and a compensated zero", () => {
|
||||||
@@ -17,11 +22,11 @@ describe("sumMoney", () => {
|
|||||||
{ currency: "RUB", value: "100.5" },
|
{ currency: "RUB", value: "100.5" },
|
||||||
{ currency: "RUB", value: "49.50" },
|
{ currency: "RUB", value: "49.50" },
|
||||||
{ currency: "RUB", value: "0.005" },
|
{ currency: "RUB", value: "0.005" },
|
||||||
])).toEqual({ currency: "RUB", value: "150.005" });
|
])).toEqual([{ currency: "RUB", value: "150.005" }]);
|
||||||
expect(sumMoney([
|
expect(sumMoney([
|
||||||
{ currency: "RUB", value: "100" },
|
{ currency: "RUB", value: "100" },
|
||||||
{ 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"])(
|
it.each(["", ".", "1.2.3", "not-a-number"])(
|
||||||
|
|||||||
@@ -46,20 +46,24 @@ function sumDecimals(decimals: readonly Decimal[]): Decimal {
|
|||||||
return { scale, value };
|
return { scale, value };
|
||||||
}
|
}
|
||||||
|
|
||||||
function sumMoney(amounts: readonly Money[]): Money | null {
|
function sumMoney(amounts: readonly Money[]): Money[] | null {
|
||||||
try {
|
const decimals = new Map<string, Decimal[]>();
|
||||||
const currency = amounts[0]?.currency ?? "RUB";
|
|
||||||
|
|
||||||
return {
|
for (const amount of amounts) {
|
||||||
currency,
|
try {
|
||||||
value: decimalToString(sumDecimals(
|
const values = decimals.get(amount.currency) ?? [];
|
||||||
amounts.map(amount => decimalFromString(amount.value)),
|
values.push(decimalFromString(amount.value));
|
||||||
)),
|
decimals.set(amount.currency, values);
|
||||||
};
|
|
||||||
}
|
}
|
||||||
catch {
|
catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Array.from(decimals, ([currency, values]) => ({
|
||||||
|
currency,
|
||||||
|
value: decimalToString(sumDecimals(values)),
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ describe("shared display helpers", () => {
|
|||||||
"-1 234 567,89 ₽",
|
"-1 234 567,89 ₽",
|
||||||
);
|
);
|
||||||
expect(formatMoney({ currency: "RUB", value: "10" })).toBe("10 ₽");
|
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(
|
expect(formatMoney({ currency: "RUB", value: "0001234.50" })).toBe(
|
||||||
"0 001 234,50 ₽",
|
"0 001 234,50 ₽",
|
||||||
);
|
);
|
||||||
@@ -70,11 +71,14 @@ describe("shared display helpers", () => {
|
|||||||
)).toBe("0,00 ₽");
|
)).toBe("0,00 ₽");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("rounds to minor units and drops the sign of a rounded zero", () => {
|
it("rounds to the currency's minor units and drops the sign of a rounded zero", () => {
|
||||||
const rounded = { withRoundedCents: true };
|
const rounded = { withRoundedCents: true };
|
||||||
expect(formatMoney({ currency: "RUB", value: "-0.004" }, rounded)).toBe("0,00 ₽");
|
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: "-0.005" }, rounded)).toBe("-0,01 ₽");
|
||||||
expect(formatMoney({ currency: "RUB", value: "999.995" }, rounded)).toBe("1 000,00 ₽");
|
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", () => {
|
it("builds the brand logo url from an upstream file name", () => {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { decimalFromString } from "./decimal";
|
import { decimalFromString } from "./decimal";
|
||||||
|
|
||||||
const DECIMAL_PART_COUNT = 2;
|
const DECIMAL_PART_COUNT = 2;
|
||||||
const MINOR_UNITS = 2;
|
const DEFAULT_MINOR_UNITS = 2;
|
||||||
|
|
||||||
type FormatMoneyOptions = {
|
type FormatMoneyOptions = {
|
||||||
withRoundedCents?: boolean;
|
withRoundedCents?: boolean;
|
||||||
@@ -25,6 +25,17 @@ const dateFormatter = new Intl.DateTimeFormat("ru-RU", {
|
|||||||
year: "numeric",
|
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 {
|
function formatDate(value: string): string {
|
||||||
return dateFormatter.format(new Date(value));
|
return dateFormatter.format(new Date(value));
|
||||||
}
|
}
|
||||||
@@ -58,8 +69,10 @@ function formatMoney(
|
|||||||
): string {
|
): string {
|
||||||
if (!money) return "—";
|
if (!money) return "—";
|
||||||
|
|
||||||
|
const minorUnits = currencyMinorUnits(money.currency);
|
||||||
|
|
||||||
const value = withRoundedCents
|
const value = withRoundedCents
|
||||||
? roundDecimal(money.value, MINOR_UNITS)
|
? roundDecimal(money.value, minorUnits)
|
||||||
: money.value;
|
: money.value;
|
||||||
|
|
||||||
const [integerPart = "", fractionPart = ""] = value.split(
|
const [integerPart = "", fractionPart = ""] = value.split(
|
||||||
@@ -68,14 +81,18 @@ function formatMoney(
|
|||||||
);
|
);
|
||||||
|
|
||||||
const normalizedFraction = withRoundedCents || withZeroCents
|
const normalizedFraction = withRoundedCents || withZeroCents
|
||||||
? fractionPart.padEnd(MINOR_UNITS, "0")
|
? fractionPart.padEnd(minorUnits, "0")
|
||||||
: fractionPart;
|
: fractionPart;
|
||||||
|
|
||||||
const decimal = normalizedFraction
|
const decimal = normalizedFraction
|
||||||
? `${integerPart}.${normalizedFraction}`
|
? `${integerPart}.${normalizedFraction}`
|
||||||
: integerPart;
|
: integerPart;
|
||||||
|
|
||||||
const formatted = `${formatDecimal(decimal)} ₽`;
|
let currency = money.currency;
|
||||||
|
if (currency === "RUB") currency = "₽";
|
||||||
|
else if (currency === "USD") currency = "$";
|
||||||
|
|
||||||
|
const formatted = `${formatDecimal(decimal)} ${currency}`;
|
||||||
|
|
||||||
if (!withSign) return formatted;
|
if (!withSign) return formatted;
|
||||||
if (isZeroDecimal(value))
|
if (isZeroDecimal(value))
|
||||||
|
|||||||
@@ -2,8 +2,12 @@ import { formatMoney } from "./display";
|
|||||||
|
|
||||||
type Money = { currency: string; value: string };
|
type Money = { currency: string; value: string };
|
||||||
|
|
||||||
function totalText(total: Money | null, isSigned: boolean): string {
|
function totalText(totals: Money[] | null, isSigned: boolean): string {
|
||||||
return total ? formatMoney(total, { withSign: isSigned || undefined }) : "";
|
return totals
|
||||||
|
? totals.map(total =>
|
||||||
|
formatMoney(total, { withSign: isSigned || undefined }),
|
||||||
|
).join(", ")
|
||||||
|
: "";
|
||||||
}
|
}
|
||||||
|
|
||||||
export { totalText };
|
export { totalText };
|
||||||
|
|||||||
@@ -24,9 +24,7 @@ type EntryGroupProps = PropsWithChildren<{
|
|||||||
|
|
||||||
type EntryGroupTotalProps = {
|
type EntryGroupTotalProps = {
|
||||||
isSigned?: boolean;
|
isSigned?: boolean;
|
||||||
totals:
|
totals: null | { currency: string; value: string }[];
|
||||||
| null
|
|
||||||
| { currency: string; value: string };
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const AccountRow: FC<AccountRowProps> = (props) => {
|
const AccountRow: FC<AccountRowProps> = (props) => {
|
||||||
@@ -90,9 +88,11 @@ const EntryGroupTotal: FC<EntryGroupTotalProps> = (props) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap={2}>
|
<Stack gap={2}>
|
||||||
<span>
|
{props.totals.map(total => (
|
||||||
{formatMoney(props.totals, { withSign: isSigned || undefined })}
|
<span key={`${total.currency}-${total.value}`}>
|
||||||
|
{formatMoney(total, { withSign: isSigned || undefined })}
|
||||||
</span>
|
</span>
|
||||||
|
))}
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
+4
-13
@@ -37,17 +37,12 @@ const handlers = [
|
|||||||
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
|
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
|
||||||
HttpResponse.json(
|
HttpResponse.json(
|
||||||
resource({
|
resource({
|
||||||
cash: { currency: "RUB", value: "0" },
|
cashBalances: [],
|
||||||
isStale: false,
|
isStale: false,
|
||||||
lastSuccessfulAt: "2026-08-14T00:00:00Z",
|
lastSuccessfulAt: "2026-08-14T00:00:00Z",
|
||||||
positions: [],
|
positions: [],
|
||||||
structure: {
|
structure: { currencies: [], unvaluedCategories: [] },
|
||||||
categories: [],
|
totalsByCurrency: [],
|
||||||
hasNegativeValues: false,
|
|
||||||
totalValue: "0",
|
|
||||||
unvaluedCategories: [],
|
|
||||||
},
|
|
||||||
totals: { currency: "RUB", value: "0" },
|
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -81,11 +76,7 @@ const handlers = [
|
|||||||
accountId: "account-1",
|
accountId: "account-1",
|
||||||
calculatedAt: "2026-08-14T00:00:00Z",
|
calculatedAt: "2026-08-14T00:00:00Z",
|
||||||
period: { from: "2026-01-01", to: "2026-08-14" },
|
period: { from: "2026-01-01", to: "2026-08-14" },
|
||||||
total: {
|
totalsByCurrency: [],
|
||||||
coupon: { currency: "RUB", value: "0" },
|
|
||||||
dividend: { currency: "RUB", value: "0" },
|
|
||||||
total: { currency: "RUB", value: "0" },
|
|
||||||
},
|
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
Reference in New Issue
Block a user