Compare commits
3
Commits
develop
...
c3c1528fd4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c3c1528fd4 | ||
|
|
b037fd9cab | ||
|
|
24e53c713e |
@@ -8,11 +8,15 @@ const VISIBLE_CURRENCY_LIMIT = 2;
|
|||||||
|
|
||||||
type BrokerageAccountCard = {
|
type BrokerageAccountCard = {
|
||||||
account: BrokerageAccount;
|
account: BrokerageAccount;
|
||||||
positionCounts: null
|
positionCounts: null | PositionCounts;
|
||||||
| { bonds: number; stocks: number };
|
|
||||||
source?: NonNullable<InvestmentResourceMeta["dependencies"]>[number];
|
source?: NonNullable<InvestmentResourceMeta["dependencies"]>[number];
|
||||||
summary:
|
summary:
|
||||||
| { remainingCurrencyCount: number; state: "available"; totals: Money[] }
|
| {
|
||||||
|
portfolio: NonNullable<BrokerageAccount["portfolioSummary"]>;
|
||||||
|
remainingCurrencyCount: number;
|
||||||
|
state: "available";
|
||||||
|
totals: Money[];
|
||||||
|
}
|
||||||
| { state: "empty" }
|
| { state: "empty" }
|
||||||
| { state: "unavailable" };
|
| { state: "unavailable" };
|
||||||
};
|
};
|
||||||
@@ -21,6 +25,8 @@ type Money = NonNullable<
|
|||||||
BrokerageAccount["portfolioSummary"]
|
BrokerageAccount["portfolioSummary"]
|
||||||
>["totalsByCurrency"][number];
|
>["totalsByCurrency"][number];
|
||||||
|
|
||||||
|
type PositionCounts = { bonds: number; stocks: number; total: number };
|
||||||
|
|
||||||
function accountTypeKey(type: BrokerageAccount["type"]) {
|
function accountTypeKey(type: BrokerageAccount["type"]) {
|
||||||
return `accounts.types.${type}` as const;
|
return `accounts.types.${type}` as const;
|
||||||
}
|
}
|
||||||
@@ -48,6 +54,7 @@ function brokerageAccountCards(
|
|||||||
const positionCounts = {
|
const positionCounts = {
|
||||||
bonds: summary.bondPositionCount,
|
bonds: summary.bondPositionCount,
|
||||||
stocks: summary.stockPositionCount,
|
stocks: summary.stockPositionCount,
|
||||||
|
total: summary.totalPositionCount,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (summary.totalsByCurrency.length === 0)
|
if (summary.totalsByCurrency.length === 0)
|
||||||
@@ -58,6 +65,7 @@ function brokerageAccountCards(
|
|||||||
positionCounts,
|
positionCounts,
|
||||||
source,
|
source,
|
||||||
summary: {
|
summary: {
|
||||||
|
portfolio: summary,
|
||||||
remainingCurrencyCount: Math.max(
|
remainingCurrencyCount: Math.max(
|
||||||
summary.totalsByCurrency.length - VISIBLE_CURRENCY_LIMIT,
|
summary.totalsByCurrency.length - VISIBLE_CURRENCY_LIMIT,
|
||||||
0,
|
0,
|
||||||
|
|||||||
+87
-109
@@ -1,166 +1,144 @@
|
|||||||
.list {
|
.list {
|
||||||
|
display: grid;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
gap: var(--mantine-spacing-sm);
|
||||||
|
list-style: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.card {
|
.row {
|
||||||
min-width: 0;
|
display: grid;
|
||||||
gap: var(--mantine-spacing-xl);
|
grid-template-areas:
|
||||||
background: var(--mantine-color-white);
|
"identity balance"
|
||||||
border-color: var(--mantine-color-gray-3);
|
"details balance"
|
||||||
box-shadow: 0 4px 16px rgb(15 23 42 / 3%);
|
"structure structure";
|
||||||
|
grid-template-columns: minmax(0, 1fr) minmax(0, auto);
|
||||||
|
gap: var(--mantine-spacing-sm) var(--mantine-spacing-xl);
|
||||||
|
align-items: center;
|
||||||
|
padding: var(--mantine-spacing-lg);
|
||||||
|
border: 1px solid var(--wl-color-border);
|
||||||
|
border-left: 3px solid var(--wl-color-primary);
|
||||||
|
border-radius: var(--mantine-radius-md);
|
||||||
|
background: var(--wl-color-surface);
|
||||||
color: inherit;
|
color: inherit;
|
||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
transition:
|
transition: background-color 160ms ease, border-color 160ms ease;
|
||||||
transform 160ms ease,
|
|
||||||
box-shadow 160ms ease,
|
|
||||||
border-color 160ms ease;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.card:hover,
|
.row:hover,
|
||||||
.card:focus-visible {
|
.row:focus-visible {
|
||||||
border-color: var(--mantine-color-blue-3);
|
border-color: var(--wl-color-primary);
|
||||||
box-shadow: 0 12px 28px rgb(15 23 42 / 8%);
|
background: var(--wl-color-subtle);
|
||||||
transform: translateY(-3px);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.card:focus-visible {
|
.row:focus-visible {
|
||||||
outline: 2px solid var(--mantine-color-blue-6);
|
outline: 2px solid var(--wl-color-primary);
|
||||||
outline-offset: 3px;
|
outline-offset: -2px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.identity {
|
.identity {
|
||||||
|
grid-area: identity;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.kicker {
|
|
||||||
padding: 5px 10px;
|
|
||||||
border-radius: var(--mantine-radius-sm);
|
|
||||||
background: var(--mantine-color-blue-0);
|
|
||||||
color: var(--mantine-color-blue-8);
|
|
||||||
letter-spacing: 0.02em;
|
|
||||||
}
|
|
||||||
|
|
||||||
.accountIcon {
|
|
||||||
width: 28px;
|
|
||||||
height: 28px;
|
|
||||||
flex-shrink: 0;
|
|
||||||
color: var(--mantine-color-blue-5);
|
|
||||||
}
|
|
||||||
|
|
||||||
.name {
|
.name {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
font-size: var(--mantine-h3-font-size);
|
color: var(--wl-color-text);
|
||||||
line-height: 1.3;
|
font-size: var(--mantine-font-size-md);
|
||||||
|
line-height: var(--mantine-line-height-md);
|
||||||
overflow-wrap: anywhere;
|
overflow-wrap: anywhere;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.accountType {
|
||||||
|
flex-shrink: 0;
|
||||||
|
align-self: flex-start;
|
||||||
|
padding: 2px var(--mantine-spacing-xs);
|
||||||
|
border-radius: var(--mantine-radius-sm);
|
||||||
|
}
|
||||||
|
|
||||||
.balance {
|
.balance {
|
||||||
flex: 1;
|
grid-area: balance;
|
||||||
|
min-width: 0;
|
||||||
|
text-align: right;
|
||||||
}
|
}
|
||||||
|
|
||||||
.summary {
|
.summary {
|
||||||
font-variant-numeric: tabular-nums;
|
font-variant-numeric: tabular-nums lining-nums;
|
||||||
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
.total {
|
.total {
|
||||||
font-size: clamp(1.5rem, 2.8vw, 2.25rem);
|
color: var(--wl-color-text);
|
||||||
letter-spacing: -0.035em;
|
|
||||||
line-height: 1.2;
|
|
||||||
overflow-wrap: anywhere;
|
|
||||||
}
|
|
||||||
|
|
||||||
.total + .total {
|
|
||||||
font-size: var(--mantine-font-size-lg);
|
font-size: var(--mantine-font-size-lg);
|
||||||
font-weight: 500;
|
line-height: var(--mantine-line-height-lg);
|
||||||
letter-spacing: 0;
|
|
||||||
color: var(--mantine-color-gray-7);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.positions {
|
.return,
|
||||||
display: grid;
|
.cashValue {
|
||||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
font-variant-numeric: tabular-nums lining-nums;
|
||||||
gap: var(--mantine-spacing-sm);
|
white-space: nowrap;
|
||||||
margin: 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.positions > div {
|
.positive {
|
||||||
display: flex;
|
color: var(--wl-color-positive);
|
||||||
flex-wrap: wrap;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: space-between;
|
|
||||||
gap: 4px var(--mantine-spacing-sm);
|
|
||||||
padding: var(--mantine-spacing-sm) var(--mantine-spacing-md);
|
|
||||||
border-radius: var(--mantine-radius-md);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.stocks {
|
.negative {
|
||||||
background: var(--mantine-color-blue-0);
|
color: var(--wl-color-negative);
|
||||||
color: var(--mantine-color-blue-8);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.bonds {
|
.neutral {
|
||||||
background: var(--mantine-color-grape-0);
|
color: var(--wl-color-muted);
|
||||||
color: var(--mantine-color-grape-8);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.positions dt {
|
.cash {
|
||||||
font-size: var(--mantine-font-size-sm);
|
font-variant-numeric: tabular-nums lining-nums;
|
||||||
font-weight: 500;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.positions dd {
|
.details {
|
||||||
margin: 0;
|
grid-area: details;
|
||||||
font-size: 1.75rem;
|
min-width: 0;
|
||||||
font-weight: 700;
|
font-variant-numeric: tabular-nums lining-nums;
|
||||||
font-variant-numeric: tabular-nums;
|
|
||||||
line-height: 1.25;
|
|
||||||
overflow-wrap: anywhere;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.footer {
|
.structure {
|
||||||
border-top: 1px solid var(--mantine-color-gray-2);
|
grid-area: structure;
|
||||||
padding-top: var(--mantine-spacing-md);
|
|
||||||
}
|
|
||||||
|
|
||||||
.open {
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: var(--mantine-spacing-xs);
|
gap: var(--mantine-spacing-xs);
|
||||||
margin-left: auto;
|
|
||||||
color: var(--mantine-color-blue-7);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.arrow {
|
.structureBar {
|
||||||
font-size: var(--mantine-font-size-lg);
|
display: flex;
|
||||||
transition: transform 160ms ease;
|
width: 100%;
|
||||||
|
height: 6px;
|
||||||
|
overflow: hidden;
|
||||||
|
border-radius: var(--mantine-radius-xs);
|
||||||
|
background: var(--wl-color-subtle);
|
||||||
}
|
}
|
||||||
|
|
||||||
.card:hover .arrow {
|
.structureSection {
|
||||||
transform: translateX(3px);
|
flex: none;
|
||||||
|
height: 100%;
|
||||||
|
background: var(--category-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 36em) {
|
@media (max-width: 47.9375em) {
|
||||||
.card {
|
.row {
|
||||||
|
grid-template-areas:
|
||||||
|
"identity"
|
||||||
|
"balance"
|
||||||
|
"structure"
|
||||||
|
"details";
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
gap: var(--mantine-spacing-sm);
|
||||||
padding: var(--mantine-spacing-md);
|
padding: var(--mantine-spacing-md);
|
||||||
gap: var(--mantine-spacing-lg);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.positions > div {
|
.balance {
|
||||||
flex-direction: column;
|
text-align: left;
|
||||||
align-items: flex-start;
|
|
||||||
padding: var(--mantine-spacing-sm);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
@media (prefers-reduced-motion: reduce) {
|
.balance > div {
|
||||||
.card,
|
justify-content: flex-start;
|
||||||
.arrow {
|
|
||||||
transition: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.card:hover,
|
|
||||||
.card:focus-visible,
|
|
||||||
.card:hover .arrow {
|
|
||||||
transform: none;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+154
-176
@@ -2,32 +2,86 @@ import type { Meta, StoryObj } from "@storybook/react-vite";
|
|||||||
|
|
||||||
import { MemoryRouter } from "react-router";
|
import { MemoryRouter } from "react-router";
|
||||||
|
|
||||||
|
import { resource } from "@/test/resource";
|
||||||
|
|
||||||
import type { BrokerageAccount } from "../../api/useBrokerageAccounts";
|
import type { BrokerageAccount } from "../../api/useBrokerageAccounts";
|
||||||
|
|
||||||
import { brokerageAccountCards } from "../../model/display";
|
import { brokerageAccountCards } from "../../model/display";
|
||||||
import { BrokerageAccountList } from "./BrokerageAccountList";
|
import { BrokerageAccountList } from "./BrokerageAccountList";
|
||||||
|
|
||||||
const syntheticAccount = {
|
type PortfolioSummary = NonNullable<BrokerageAccount["portfolioSummary"]>;
|
||||||
id: "storybook-account",
|
|
||||||
name: "Учебный брокерский счёт",
|
const rubReturn = {
|
||||||
openedOn: "2025-03-15",
|
absolute: "136900",
|
||||||
portfolioSummary: {
|
costBasis: "1103600.50",
|
||||||
|
currency: "RUB",
|
||||||
|
partial: false,
|
||||||
|
percent: "12.40",
|
||||||
|
};
|
||||||
|
|
||||||
|
const portfolioSummary = {
|
||||||
bondPositionCount: 12,
|
bondPositionCount: 12,
|
||||||
stockPositionCount: 5,
|
cashBalances: [
|
||||||
totalsByCurrency: [
|
{ currency: "RUB", value: "82500.50" },
|
||||||
{ currency: "RUB", value: "125000.50" },
|
{ currency: "USD", value: "1500" },
|
||||||
{ currency: "USD", value: "320" },
|
|
||||||
{ currency: "EUR", value: "210" },
|
|
||||||
],
|
],
|
||||||
|
fundPositionCount: 2,
|
||||||
|
stockPositionCount: 5,
|
||||||
|
structure: {
|
||||||
|
currencies: [{
|
||||||
|
categories: [
|
||||||
|
{ sharePercent: "55.000000", type: "STOCK", value: "682500" },
|
||||||
|
{ sharePercent: "25.000000", type: "BOND", value: "310500" },
|
||||||
|
{ sharePercent: "10.000000", type: "OTHER", value: "124200" },
|
||||||
|
{ sharePercent: "10.000000", type: "CASH", value: "124200" },
|
||||||
|
],
|
||||||
|
currency: "RUB",
|
||||||
|
hasNegativeValues: false,
|
||||||
|
totalValue: "1241400",
|
||||||
|
}],
|
||||||
|
unvaluedCategories: [],
|
||||||
},
|
},
|
||||||
type: "BROKERAGE",
|
totalPositionCount: 19,
|
||||||
} satisfies BrokerageAccount;
|
totalsByCurrency: [{ currency: "RUB", value: "1240500.50" }],
|
||||||
|
unrealizedReturnByCurrency: [rubReturn],
|
||||||
|
} satisfies PortfolioSummary;
|
||||||
|
|
||||||
|
function account(
|
||||||
|
id: string,
|
||||||
|
name: string,
|
||||||
|
summary: null | PortfolioSummary = portfolioSummary,
|
||||||
|
type: BrokerageAccount["type"] = "BROKERAGE",
|
||||||
|
): BrokerageAccount {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
openedOn: "2025-03-15",
|
||||||
|
portfolioSummary: summary,
|
||||||
|
type,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const negativeSummary: PortfolioSummary = {
|
||||||
|
...portfolioSummary,
|
||||||
|
unrealizedReturnByCurrency: [{
|
||||||
|
...rubReturn,
|
||||||
|
absolute: "-4200",
|
||||||
|
percent: "-3.05",
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
|
||||||
|
const emptySummary: PortfolioSummary = {
|
||||||
|
...portfolioSummary,
|
||||||
|
cashBalances: [],
|
||||||
|
structure: { currencies: [], unvaluedCategories: [] },
|
||||||
|
totalPositionCount: 0,
|
||||||
|
totalsByCurrency: [],
|
||||||
|
unrealizedReturnByCurrency: [],
|
||||||
|
};
|
||||||
|
|
||||||
const meta = {
|
const meta = {
|
||||||
args: { accounts: brokerageAccountCards([syntheticAccount]) },
|
args: { accounts: brokerageAccountCards([account("normal", "Основной ИИС")]) },
|
||||||
argTypes: {
|
argTypes: { accounts: { control: false } },
|
||||||
accounts: { control: false },
|
|
||||||
},
|
|
||||||
component: BrokerageAccountList,
|
component: BrokerageAccountList,
|
||||||
decorators: [
|
decorators: [
|
||||||
Story => (
|
Story => (
|
||||||
@@ -40,7 +94,7 @@ const meta = {
|
|||||||
docs: {
|
docs: {
|
||||||
description: {
|
description: {
|
||||||
component:
|
component:
|
||||||
"Карточки счетов WealthLedger со сводкой по валютам и числом наименований акций и облигаций. Используйте на экране выбора счёта; отсутствие сводки и отсутствие сумм имеют разные сообщения. Примеры содержат вымышленные данные. Ссылки меняют только локальный маршрут MemoryRouter; страница назначения в этой истории не отображается.",
|
"Карточки счетов: стоимость и доходность по валютам, деньги, структура и свежесть источника. Денежные и процентные значения остаются строками. Все примеры содержат вымышленные данные; ссылки работают только внутри MemoryRouter.",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -52,188 +106,112 @@ export default meta;
|
|||||||
|
|
||||||
type Story = StoryObj<typeof meta>;
|
type Story = StoryObj<typeof meta>;
|
||||||
|
|
||||||
export const Available: Story = {
|
export const Normal: Story = {};
|
||||||
name: "Сводка по нескольким валютам",
|
|
||||||
parameters: {
|
export const MultiCurrency: Story = {
|
||||||
docs: {
|
args: {
|
||||||
description: {
|
accounts: brokerageAccountCards([account("multi", "Мультивалютный", {
|
||||||
story:
|
...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 Unavailable: Story
|
export const Negative: Story = {
|
||||||
= {
|
|
||||||
args: {
|
args: {
|
||||||
accounts: brokerageAccountCards([
|
accounts: brokerageAccountCards([
|
||||||
{ ...syntheticAccount, openedOn: null, portfolioSummary: null },
|
account("negative", "Просевший портфель", negativeSummary),
|
||||||
]),
|
]),
|
||||||
},
|
},
|
||||||
name: "Сводка недоступна",
|
};
|
||||||
parameters: {
|
|
||||||
docs: {
|
export const Partial: Story = {
|
||||||
description: {
|
args: {
|
||||||
story:
|
accounts: brokerageAccountCards([account("partial", "Частичные данные", {
|
||||||
"Счёт остаётся доступен для открытия, даже если сводка временно недоступна. Неизвестные суммы не заменяются нулём; отсутствующая дата открытия не отображается.",
|
...portfolioSummary,
|
||||||
|
unrealizedReturnByCurrency: [{
|
||||||
|
...rubReturn,
|
||||||
|
partial: true,
|
||||||
|
}],
|
||||||
|
})]),
|
||||||
},
|
},
|
||||||
},
|
};
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
export const Empty: Story = {
|
export const Empty: Story = {
|
||||||
args: {
|
args: {
|
||||||
accounts: brokerageAccountCards([
|
accounts: brokerageAccountCards([
|
||||||
{
|
account("empty", "Новый пустой счёт", emptySummary),
|
||||||
...syntheticAccount,
|
|
||||||
portfolioSummary: {
|
|
||||||
bondPositionCount: 0,
|
|
||||||
stockPositionCount: 0,
|
|
||||||
totalsByCurrency: [],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]),
|
]),
|
||||||
},
|
},
|
||||||
name: "Нет текущих сумм",
|
};
|
||||||
parameters: {
|
|
||||||
docs: {
|
export const Unavailable: Story = {
|
||||||
description: {
|
args: {
|
||||||
story:
|
accounts: brokerageAccountCards([
|
||||||
"Успешно полученная пустая сводка отличается от ошибки получения данных. Карточка сохраняет название, тип счёта и переход.",
|
account("unavailable", "Счёт без сводки", null),
|
||||||
|
]),
|
||||||
},
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const Stale: Story = {
|
||||||
|
args: {
|
||||||
|
accounts: brokerageAccountCards([
|
||||||
|
account("stale", "Устаревший портфель"),
|
||||||
|
], resource([], {
|
||||||
|
dependencies: [{
|
||||||
|
availability: "available",
|
||||||
|
completeness: "complete",
|
||||||
|
dataRevision: "stale-revision",
|
||||||
|
freshness: "stale",
|
||||||
|
lastAttempt: {
|
||||||
|
finishedAt: null,
|
||||||
|
problems: [],
|
||||||
|
startedAt: null,
|
||||||
|
state: "none",
|
||||||
},
|
},
|
||||||
|
lastSuccessfulAt: "2026-08-13T00:00:00Z",
|
||||||
|
resourceKey: "portfolio/stale",
|
||||||
|
}],
|
||||||
|
freshness: "stale",
|
||||||
|
lastSuccessfulAt: "2026-08-14T00:00:00Z",
|
||||||
|
}).meta.dependencies),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export const LongName: Story = {
|
export const LongName: Story = {
|
||||||
args: {
|
args: {
|
||||||
accounts: brokerageAccountCards([
|
accounts: brokerageAccountCards([
|
||||||
{
|
account(
|
||||||
...syntheticAccount,
|
"long",
|
||||||
name: "Учебный индивидуальный инвестиционный счёт для долгосрочных накоплений",
|
"Очень длинное название индивидуального инвестиционного счёта, которое должно корректно переноситься на узком экране",
|
||||||
type: "INDIVIDUAL_INVESTMENT",
|
portfolioSummary,
|
||||||
},
|
"INDIVIDUAL_INVESTMENT",
|
||||||
]),
|
|
||||||
},
|
|
||||||
name: "Длинное название счёта",
|
|
||||||
parameters: {
|
|
||||||
docs: {
|
|
||||||
description: {
|
|
||||||
story:
|
|
||||||
"Проверьте перенос длинного названия на узком экране и доступность всей карточки с клавиатуры.",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
export const AccountGrid: Story = {
|
|
||||||
args: {
|
|
||||||
accounts: brokerageAccountCards([
|
|
||||||
{
|
|
||||||
...syntheticAccount,
|
|
||||||
name: "Основной",
|
|
||||||
portfolioSummary: {
|
|
||||||
bondPositionCount: 14,
|
|
||||||
stockPositionCount: 8,
|
|
||||||
totalsByCurrency: [{ currency: "RUB", value: "1256430.50" }],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
...syntheticAccount,
|
|
||||||
id: "storybook-iis",
|
|
||||||
name: "Долгосрочные инвестиции",
|
|
||||||
portfolioSummary: {
|
|
||||||
bondPositionCount: 6,
|
|
||||||
stockPositionCount: 0,
|
|
||||||
totalsByCurrency: [{ currency: "RUB", value: "480250" }],
|
|
||||||
},
|
|
||||||
type: "INDIVIDUAL_INVESTMENT",
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
},
|
|
||||||
name: "Несколько счетов",
|
|
||||||
};
|
|
||||||
|
|
||||||
export const UnvaluedPositions: Story = {
|
|
||||||
args: {
|
|
||||||
accounts: brokerageAccountCards([
|
|
||||||
{
|
|
||||||
...syntheticAccount,
|
|
||||||
portfolioSummary: {
|
|
||||||
bondPositionCount: 1,
|
|
||||||
stockPositionCount: 2,
|
|
||||||
totalsByCurrency: [],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
},
|
|
||||||
name: "Бумаги без текущей оценки",
|
|
||||||
};
|
|
||||||
|
|
||||||
export const LargeValues: Story = {
|
|
||||||
args: {
|
|
||||||
accounts: brokerageAccountCards([
|
|
||||||
{
|
|
||||||
...syntheticAccount,
|
|
||||||
portfolioSummary: {
|
|
||||||
bondPositionCount: 105,
|
|
||||||
stockPositionCount: 21,
|
|
||||||
totalsByCurrency: [
|
|
||||||
{ currency: "RUB", value: "1234567890123456789.50" },
|
|
||||||
{ currency: "USD", value: "-9876543210987654321.50" },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
},
|
|
||||||
name: "Длинные суммы",
|
|
||||||
};
|
|
||||||
|
|
||||||
export const IndependentFreshness: Story
|
|
||||||
= {
|
|
||||||
args: {
|
|
||||||
accounts: brokerageAccountCards(
|
|
||||||
[
|
|
||||||
syntheticAccount,
|
|
||||||
{
|
|
||||||
...syntheticAccount,
|
|
||||||
id: "waiting",
|
|
||||||
name: "Новый счёт",
|
|
||||||
portfolioSummary: null,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
[
|
|
||||||
{
|
|
||||||
availability: "available",
|
|
||||||
completeness: "complete",
|
|
||||||
dataRevision: "1",
|
|
||||||
freshness: "stale",
|
|
||||||
lastAttempt: {
|
|
||||||
finishedAt: "2026-09-24T10:31:00Z",
|
|
||||||
problems: [],
|
|
||||||
startedAt: "2026-09-24T10:30:00Z",
|
|
||||||
state: "failed",
|
|
||||||
},
|
|
||||||
lastSuccessfulAt: "2026-09-24T10:30:00Z",
|
|
||||||
resourceKey: "portfolio/storybook-account",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
availability: "initial-loading",
|
|
||||||
completeness: "incomplete",
|
|
||||||
dataRevision: "0",
|
|
||||||
freshness: "unknown",
|
|
||||||
lastAttempt: {
|
|
||||||
finishedAt: null,
|
|
||||||
problems: [],
|
|
||||||
startedAt: "2026-09-24T10:30:00Z",
|
|
||||||
state: "running",
|
|
||||||
},
|
|
||||||
lastSuccessfulAt: null,
|
|
||||||
resourceKey: "portfolio/waiting",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
),
|
),
|
||||||
|
]),
|
||||||
},
|
},
|
||||||
name: "Независимая свежесть и ошибка сводок",
|
};
|
||||||
};
|
|
||||||
|
|||||||
+176
-96
@@ -5,122 +5,202 @@ import { describe, expect, it } from "vitest";
|
|||||||
|
|
||||||
import { resource } from "@/test/resource";
|
import { resource } from "@/test/resource";
|
||||||
|
|
||||||
|
import type { BrokerageAccount } from "../../api/useBrokerageAccounts";
|
||||||
|
|
||||||
import { brokerageAccountCards } from "../../model/display";
|
import { brokerageAccountCards } from "../../model/display";
|
||||||
import { BrokerageAccountList } from "./BrokerageAccountList";
|
import { BrokerageAccountList } from "./BrokerageAccountList";
|
||||||
|
|
||||||
describe("BrokerageAccountList", () => {
|
type PortfolioSummary = NonNullable<BrokerageAccount["portfolioSummary"]>;
|
||||||
it("renders account details and an account link", () => {
|
|
||||||
render(
|
const portfolioSummary = {
|
||||||
<MantineProvider>
|
|
||||||
<MemoryRouter>
|
|
||||||
<BrokerageAccountList
|
|
||||||
accounts={brokerageAccountCards([
|
|
||||||
{
|
|
||||||
id: "account-1",
|
|
||||||
name: "Основной",
|
|
||||||
openedOn: "2024-08-13",
|
|
||||||
portfolioSummary: {
|
|
||||||
bondPositionCount: 12,
|
bondPositionCount: 12,
|
||||||
|
cashBalances: [
|
||||||
|
{ currency: "RUB", value: "82500.5" },
|
||||||
|
{ currency: "USD", value: "20" },
|
||||||
|
],
|
||||||
|
fundPositionCount: 0,
|
||||||
stockPositionCount: 5,
|
stockPositionCount: 5,
|
||||||
|
structure: {
|
||||||
|
currencies: [{
|
||||||
|
categories: [
|
||||||
|
{ sharePercent: "50.000000", type: "STOCK", value: "100" },
|
||||||
|
{ sharePercent: "30.000000", type: "BOND", value: "60" },
|
||||||
|
{ sharePercent: "0.000000", type: "OTHER", value: "0" },
|
||||||
|
{ sharePercent: "20.000000", type: "CASH", value: "40" },
|
||||||
|
],
|
||||||
|
currency: "RUB",
|
||||||
|
hasNegativeValues: false,
|
||||||
|
totalValue: "200",
|
||||||
|
}],
|
||||||
|
unvaluedCategories: [],
|
||||||
|
},
|
||||||
|
totalPositionCount: 17,
|
||||||
totalsByCurrency: [
|
totalsByCurrency: [
|
||||||
{ currency: "RUB", value: "1500" },
|
{ currency: "RUB", value: "123456789012345678901.995" },
|
||||||
{ currency: "USD", value: "20" },
|
{ currency: "USD", value: "20" },
|
||||||
{ currency: "EUR", value: "5" },
|
{ currency: "EUR", value: "5" },
|
||||||
],
|
],
|
||||||
},
|
unrealizedReturnByCurrency: [
|
||||||
type: "BROKERAGE",
|
{
|
||||||
|
absolute: "136900",
|
||||||
|
costBasis: "1000000",
|
||||||
|
currency: "RUB",
|
||||||
|
partial: true,
|
||||||
|
percent: "12.40",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "account-2",
|
absolute: "-4.2",
|
||||||
name: "Недоступный",
|
costBasis: "24.2",
|
||||||
openedOn: null,
|
currency: "USD",
|
||||||
portfolioSummary: null,
|
partial: false,
|
||||||
type: "BROKERAGE",
|
percent: "-3.05",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "account-3",
|
absolute: "0",
|
||||||
name: "Пустой",
|
costBasis: "5",
|
||||||
openedOn: null,
|
currency: "EUR",
|
||||||
portfolioSummary: {
|
partial: false,
|
||||||
bondPositionCount: 0,
|
percent: null,
|
||||||
stockPositionCount: 2,
|
|
||||||
totalsByCurrency: [],
|
|
||||||
},
|
},
|
||||||
type: "BROKERAGE",
|
|
||||||
},
|
|
||||||
])}
|
|
||||||
/>
|
|
||||||
</MemoryRouter>
|
|
||||||
</MantineProvider>,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(screen.getByRole("link", { name: /Основной/ })).toHaveAttribute(
|
|
||||||
"href",
|
|
||||||
"/accounts/account-1",
|
|
||||||
);
|
|
||||||
expect(screen.getAllByText("Брокерский счет")).toHaveLength(3);
|
|
||||||
expect(screen.getByText(/^Открыт /)).toBeInTheDocument();
|
|
||||||
expect(screen.getByText("1 500 ₽")).toBeInTheDocument();
|
|
||||||
expect(screen.getByText("20 USD")).toBeInTheDocument();
|
|
||||||
expect(screen.getByText("Еще 1 валюта")).toBeInTheDocument();
|
|
||||||
expect(screen.getByText("Сводка временно недоступна")).toBeInTheDocument();
|
|
||||||
expect(screen.getByText("Нет текущих сумм")).toBeInTheDocument();
|
|
||||||
expect(screen.getAllByText("Открыть счет")).toHaveLength(3);
|
|
||||||
const available = within(screen.getByRole("link", { name: /Основной/ }));
|
|
||||||
expect(available.getAllByRole("definition")[0]).toHaveTextContent("5");
|
|
||||||
expect(available.getAllByRole("definition")[1]).toHaveTextContent("12");
|
|
||||||
const unvalued = within(screen.getByRole("link", { name: /Пустой/ }));
|
|
||||||
expect(unvalued.getAllByRole("definition")[0]).toHaveTextContent("2");
|
|
||||||
expect(unvalued.getAllByRole("definition")[1]).toHaveTextContent("0");
|
|
||||||
expect(
|
|
||||||
within(screen.getByRole("link", { name: /Недоступный/ })).queryByText(
|
|
||||||
"Акции",
|
|
||||||
),
|
|
||||||
).not.toBeInTheDocument();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("shows portfolio summary freshness independently for each account", () => {
|
|
||||||
const accounts = brokerageAccountCards(
|
|
||||||
["fresh", "stale"].map(
|
|
||||||
|
|
||||||
id =>
|
|
||||||
({
|
|
||||||
id,
|
|
||||||
name: id,
|
|
||||||
openedOn: null,
|
|
||||||
portfolioSummary: {
|
|
||||||
bondPositionCount: 0,
|
|
||||||
stockPositionCount: 1,
|
|
||||||
totalsByCurrency: [{ currency: "RUB", value: "10" }],
|
|
||||||
},
|
|
||||||
type: "BROKERAGE" as const,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
[
|
|
||||||
resource(null, { freshness: "fresh", resourceKey: "portfolio/fresh" })
|
|
||||||
.meta,
|
|
||||||
resource(null, { freshness: "stale", resourceKey: "portfolio/stale" })
|
|
||||||
.meta,
|
|
||||||
],
|
],
|
||||||
);
|
} satisfies PortfolioSummary;
|
||||||
|
|
||||||
render(
|
type BrokerageAccountCardInput = Parameters<typeof BrokerageAccountList>[0][
|
||||||
|
"accounts"
|
||||||
|
];
|
||||||
|
|
||||||
|
function account(
|
||||||
|
id: string,
|
||||||
|
name: string,
|
||||||
|
summary: null | PortfolioSummary,
|
||||||
|
): BrokerageAccount {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
openedOn: null,
|
||||||
|
portfolioSummary: summary,
|
||||||
|
type: "BROKERAGE",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderList(accounts: BrokerageAccountCardInput) {
|
||||||
|
return render(
|
||||||
<MantineProvider>
|
<MantineProvider>
|
||||||
<MemoryRouter>
|
<MemoryRouter>
|
||||||
<BrokerageAccountList accounts={accounts} />
|
<BrokerageAccountList accounts={accounts} />
|
||||||
</MemoryRouter>
|
</MemoryRouter>
|
||||||
</MantineProvider>,
|
</MantineProvider>,
|
||||||
);
|
);
|
||||||
expect(
|
}
|
||||||
within(screen.getByRole("link", { name: /stale/ })).getByText(
|
|
||||||
"Данные требуют обновления",
|
describe("BrokerageAccountList", () => {
|
||||||
),
|
it("renders returns, cash and structure with precise totals", () => {
|
||||||
).toBeVisible();
|
const nullReturnSummary: PortfolioSummary = {
|
||||||
expect(
|
...portfolioSummary,
|
||||||
within(screen.getByRole("link", { name: /fresh/ })).queryByText(
|
cashBalances: [],
|
||||||
"Данные требуют обновления",
|
structure: { currencies: [], unvaluedCategories: [] },
|
||||||
),
|
totalsByCurrency: [{ currency: "EUR", value: "5" }],
|
||||||
).not.toBeInTheDocument();
|
unrealizedReturnByCurrency: [{
|
||||||
|
absolute: "0",
|
||||||
|
costBasis: "5",
|
||||||
|
currency: "EUR",
|
||||||
|
partial: false,
|
||||||
|
percent: null,
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
|
||||||
|
renderList(brokerageAccountCards([
|
||||||
|
account("account-1", "Основной", portfolioSummary),
|
||||||
|
account("account-2", "Без доходности", nullReturnSummary),
|
||||||
|
]));
|
||||||
|
|
||||||
|
const link = screen.getByRole("link", { name: /Основной/ });
|
||||||
|
expect(link).toHaveAttribute("href", "/accounts/account-1");
|
||||||
|
expect(within(link).getByText("123 456 789 012 345 678 902,00 ₽"))
|
||||||
|
.toBeInTheDocument();
|
||||||
|
expect(within(link).getByText("Еще 1 валюта")).toBeInTheDocument();
|
||||||
|
expect(within(link).getByText("+12,40 %")).toBeInTheDocument();
|
||||||
|
expect(within(link).getByText("+136 900 ₽")).toBeInTheDocument();
|
||||||
|
expect(within(link).getByText("−3,05 %")).toBeInTheDocument();
|
||||||
|
expect(within(link).getByText("−4,2 USD")).toBeInTheDocument();
|
||||||
|
const nullReturnLink = screen.getByRole("link", { name: /Без доходности/ });
|
||||||
|
expect(within(nullReturnLink).getByText("—")).toBeInTheDocument();
|
||||||
|
expect(within(link).getByText("частично")).toBeInTheDocument();
|
||||||
|
expect(within(link).getByText("82 500,50 ₽")).toBeInTheDocument();
|
||||||
|
expect(within(link).getAllByText("20,00 USD")).not.toHaveLength(0);
|
||||||
|
expect(within(link).getByText("17 позиций")).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole("img", {
|
||||||
|
name: "Структура в RUB: Акции 50 %; Облигации 30 %; "
|
||||||
|
+ "Другие активы 0 %; Свободные деньги 20 %",
|
||||||
|
})).toBeInTheDocument();
|
||||||
|
const stockLegend = within(link).getByText(/Акции 50 %/);
|
||||||
|
expect(stockLegend).toHaveTextContent("● Акции 50 %");
|
||||||
|
// eslint-disable-next-line testing-library/no-node-access -- The legend is aria-hidden, so only DOM traversal reaches its container.
|
||||||
|
expect(stockLegend.parentElement).toHaveAttribute("aria-hidden", "true");
|
||||||
|
expect(within(link).queryByText(/Другие активы 0 %/)).not.toBeInTheDocument();
|
||||||
|
expect(link).toHaveTextContent("По данным брокера");
|
||||||
|
expect(link).toHaveTextContent("Структура RUB: Акции 100");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves empty, unavailable and stale states", () => {
|
||||||
|
const emptySummary: PortfolioSummary = {
|
||||||
|
...portfolioSummary,
|
||||||
|
cashBalances: [],
|
||||||
|
structure: { currencies: [], unvaluedCategories: [] },
|
||||||
|
totalPositionCount: 0,
|
||||||
|
totalsByCurrency: [],
|
||||||
|
unrealizedReturnByCurrency: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
const cards = brokerageAccountCards([
|
||||||
|
account("empty", "Пустой", emptySummary),
|
||||||
|
account("unavailable", "Недоступный", null),
|
||||||
|
account("stale", "Устаревший", portfolioSummary),
|
||||||
|
account("failed", "Ошибка обновления", null),
|
||||||
|
], resource([], {
|
||||||
|
dependencies: [{
|
||||||
|
availability: "available",
|
||||||
|
completeness: "complete",
|
||||||
|
dataRevision: "stale-revision",
|
||||||
|
freshness: "stale",
|
||||||
|
lastAttempt: {
|
||||||
|
finishedAt: null,
|
||||||
|
problems: [],
|
||||||
|
startedAt: null,
|
||||||
|
state: "none",
|
||||||
|
},
|
||||||
|
lastSuccessfulAt: "2026-08-13T00:00:00Z",
|
||||||
|
resourceKey: "portfolio/stale",
|
||||||
|
}, {
|
||||||
|
availability: "available",
|
||||||
|
completeness: "complete",
|
||||||
|
dataRevision: "failed-revision",
|
||||||
|
freshness: "stale",
|
||||||
|
lastAttempt: {
|
||||||
|
finishedAt: "2026-08-14T00:01:00Z",
|
||||||
|
problems: [],
|
||||||
|
startedAt: "2026-08-14T00:00:00Z",
|
||||||
|
state: "failed",
|
||||||
|
},
|
||||||
|
lastSuccessfulAt: "2026-08-13T00:00:00Z",
|
||||||
|
resourceKey: "portfolio/failed",
|
||||||
|
}],
|
||||||
|
freshness: "stale",
|
||||||
|
lastSuccessfulAt: "2026-08-14T00:00:00Z",
|
||||||
|
}).meta.dependencies);
|
||||||
|
|
||||||
|
renderList(cards);
|
||||||
|
|
||||||
|
expect(screen.getByText("Нет текущих сумм")).toBeInTheDocument();
|
||||||
|
expect(screen.getAllByText("Сводка временно недоступна"))
|
||||||
|
.toHaveLength(2);
|
||||||
|
const staleLink = screen.getByRole("link", { name: /Устаревший/ });
|
||||||
|
expect(within(staleLink).getByText("Данные требуют обновления"))
|
||||||
|
.toBeInTheDocument();
|
||||||
|
expect(within(staleLink).getByText(/Данные на/)).toBeInTheDocument();
|
||||||
|
const failedLink = screen.getByRole("link", { name: /Ошибка обновления/ });
|
||||||
|
expect(within(failedLink).getByText(
|
||||||
|
"Не удалось обновить данные. Показаны последние полученные.",
|
||||||
|
)).toBeInTheDocument();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import type { FC } from "react";
|
import type { CSSProperties, FC } from "react";
|
||||||
|
|
||||||
import { Card, Group, SimpleGrid, Stack, Text } from "@mantine/core";
|
import { Badge, Group, Stack, Text, VisuallyHidden } from "@mantine/core";
|
||||||
import { WalletIcon } from "@wealthledger/icons";
|
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
|
|
||||||
import { formatDate, formatMoney } from "@/shared/lib";
|
import { formatMoney, portfolioCategoryPresentation } from "@/shared/lib";
|
||||||
import { SourceSyncStatus } from "@/shared/ui";
|
import { SourceSyncStatus } from "@/shared/ui";
|
||||||
|
|
||||||
import type { BrokerageAccountCard } from "../../model/display";
|
import type { BrokerageAccountCard } from "../../model/display";
|
||||||
@@ -13,12 +12,176 @@ import type { BrokerageAccountCard } from "../../model/display";
|
|||||||
import { accountTypeKey } from "../../model/display";
|
import { accountTypeKey } from "../../model/display";
|
||||||
import classes from "./BrokerageAccountList.module.css";
|
import classes from "./BrokerageAccountList.module.css";
|
||||||
|
|
||||||
|
const DECIMAL_PART_COUNT = 2;
|
||||||
|
const STRUCTURE_CATEGORY_ORDER = ["STOCK", "BOND", "OTHER", "CASH"] as const;
|
||||||
|
|
||||||
|
type AvailableSummary = Extract<
|
||||||
|
BrokerageAccountCard["summary"],
|
||||||
|
{ state: "available" }
|
||||||
|
>;
|
||||||
|
|
||||||
type BrokerageAccountListProps = { accounts: BrokerageAccountCard[] };
|
type BrokerageAccountListProps = { accounts: BrokerageAccountCard[] };
|
||||||
|
|
||||||
type BrokerageAccountSummaryProps = {
|
type BrokerageAccountSummaryProps = {
|
||||||
summary: BrokerageAccountCard["summary"];
|
summary: BrokerageAccountCard["summary"];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type PortfolioSummary = AvailableSummary["portfolio"];
|
||||||
|
|
||||||
|
type ReturnValueProps = {
|
||||||
|
item: PortfolioSummary["unrealizedReturnByCurrency"][number];
|
||||||
|
};
|
||||||
|
|
||||||
|
type StructureCurrency = PortfolioSummary["structure"]["currencies"][number];
|
||||||
|
|
||||||
|
function formatPercent(value: null | string) {
|
||||||
|
if (value === null) return "—";
|
||||||
|
|
||||||
|
const formatted = `${value.replace(".", ",")}\u{A0}%`;
|
||||||
|
if (isZero(value))
|
||||||
|
return value.startsWith("-") ? formatted.slice(1) : formatted;
|
||||||
|
|
||||||
|
return value.startsWith("-") ? `−${formatted.slice(1)}` : `+${formatted}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatStructurePercent(value: string) {
|
||||||
|
let trimmed = value;
|
||||||
|
while (trimmed.includes(".") && trimmed.endsWith("0"))
|
||||||
|
trimmed = trimmed.slice(0, -1);
|
||||||
|
if (trimmed.endsWith(".")) trimmed = trimmed.slice(0, -1);
|
||||||
|
|
||||||
|
return trimmed.replace(".", ",");
|
||||||
|
}
|
||||||
|
|
||||||
|
function isZero(value: string) {
|
||||||
|
const unsigned = value.startsWith("-") ? value.slice(1) : value;
|
||||||
|
const [integer = "", fraction = ""] = unsigned.split(".", DECIMAL_PART_COUNT);
|
||||||
|
|
||||||
|
return integer.replaceAll("0", "") === ""
|
||||||
|
&& fraction.replaceAll("0", "") === "";
|
||||||
|
}
|
||||||
|
|
||||||
|
const ReturnValue: FC<ReturnValueProps> = (props) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { item } = props;
|
||||||
|
|
||||||
|
const isNegative = item.percent !== null
|
||||||
|
&& item.percent.startsWith("-")
|
||||||
|
&& !isZero(item.percent);
|
||||||
|
|
||||||
|
const isPositive = item.percent !== null
|
||||||
|
&& !item.percent.startsWith("-")
|
||||||
|
&& !isZero(item.percent);
|
||||||
|
|
||||||
|
let toneClass = classes.neutral;
|
||||||
|
if (isNegative) toneClass = classes.negative;
|
||||||
|
else if (isPositive) toneClass = classes.positive;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Group className={classes.return} gap="xs" wrap="nowrap">
|
||||||
|
<Text className={toneClass} fw={700} size="sm">
|
||||||
|
{formatPercent(item.percent)}
|
||||||
|
</Text>
|
||||||
|
|
||||||
|
<Text className={toneClass} size="sm">
|
||||||
|
{formatMoney(
|
||||||
|
{ currency: item.currency, value: item.absolute },
|
||||||
|
{ withSign: true },
|
||||||
|
)}
|
||||||
|
</Text>
|
||||||
|
|
||||||
|
{item.partial && (
|
||||||
|
<Text c="dimmed" size="xs">
|
||||||
|
{t("accounts.partial")}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Group>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
type StructureBarProps = { item: StructureCurrency };
|
||||||
|
|
||||||
|
const StructureBar: FC<StructureBarProps> = (props) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
const categories = STRUCTURE_CATEGORY_ORDER.flatMap((type) => {
|
||||||
|
const category = props.item.categories.find(item => item.type === type);
|
||||||
|
|
||||||
|
return category ? [category] : [];
|
||||||
|
});
|
||||||
|
|
||||||
|
const description = categories.map((category) => {
|
||||||
|
const label = t(portfolioCategoryPresentation[category.type].label);
|
||||||
|
|
||||||
|
const percent = category.sharePercent === null
|
||||||
|
? null
|
||||||
|
: formatStructurePercent(category.sharePercent);
|
||||||
|
|
||||||
|
return percent === null
|
||||||
|
? t("accounts.structure.incomplete", { category: label })
|
||||||
|
: t("accounts.structure.category", { category: label, percent });
|
||||||
|
}).join("; ");
|
||||||
|
|
||||||
|
const label = t("accounts.structure.label", {
|
||||||
|
currency: props.item.currency,
|
||||||
|
value: description,
|
||||||
|
});
|
||||||
|
|
||||||
|
const legendCategories = categories.filter(category =>
|
||||||
|
category.sharePercent === null || !isZero(category.sharePercent));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Stack gap={4}>
|
||||||
|
<div
|
||||||
|
aria-label={label}
|
||||||
|
className={classes.structureBar}
|
||||||
|
role="img"
|
||||||
|
title={label}
|
||||||
|
>
|
||||||
|
{categories.map((category) => {
|
||||||
|
const presentation = portfolioCategoryPresentation[category.type];
|
||||||
|
|
||||||
|
const style = {
|
||||||
|
"--category-color": `var(--mantine-color-${presentation.color.replace(".", "-")})`,
|
||||||
|
"width": `${category.sharePercent ?? 0}%`,
|
||||||
|
} as CSSProperties;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
aria-hidden
|
||||||
|
className={classes.structureSection}
|
||||||
|
key={category.type}
|
||||||
|
style={style}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Group aria-hidden gap="xs" wrap="wrap">
|
||||||
|
{legendCategories.map((category) => {
|
||||||
|
const presentation = portfolioCategoryPresentation[category.type];
|
||||||
|
const categoryLabel = t(presentation.label);
|
||||||
|
|
||||||
|
const text = category.sharePercent === null
|
||||||
|
? categoryLabel
|
||||||
|
: t("accounts.structure.category", {
|
||||||
|
category: categoryLabel,
|
||||||
|
percent: formatStructurePercent(category.sharePercent),
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Text c="dimmed" key={category.type} size="xs">
|
||||||
|
<Text c={presentation.color} component="span">●</Text>
|
||||||
|
{" "}
|
||||||
|
{text}
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Group>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
const BrokerageAccountSummary: FC<BrokerageAccountSummaryProps> = (props) => {
|
const BrokerageAccountSummary: FC<BrokerageAccountSummaryProps> = (props) => {
|
||||||
const { summary } = props;
|
const { summary } = props;
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -36,10 +199,12 @@ const BrokerageAccountSummary: FC<BrokerageAccountSummaryProps> = (props) => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<Stack className={classes.balance} gap="xs">
|
||||||
|
<Group align="flex-start" gap="lg" justify="flex-end" wrap="nowrap">
|
||||||
<Stack className={classes.summary} gap={4}>
|
<Stack className={classes.summary} gap={4}>
|
||||||
{summary.totals.map(total => (
|
{summary.totals.map(total => (
|
||||||
<Text className={classes.total} fw={700} key={total.currency}>
|
<Text className={classes.total} fw={700} key={total.currency}>
|
||||||
{formatMoney(total)}
|
{formatMoney(total, { withRoundedCents: true })}
|
||||||
</Text>
|
</Text>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
@@ -51,6 +216,36 @@ const BrokerageAccountSummary: FC<BrokerageAccountSummaryProps> = (props) => {
|
|||||||
</Text>
|
</Text>
|
||||||
)}
|
)}
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
|
<Stack gap={4}>
|
||||||
|
{summary.totals.map((total) => {
|
||||||
|
const item = summary.portfolio.unrealizedReturnByCurrency.find(
|
||||||
|
returnItem => returnItem.currency === total.currency,
|
||||||
|
);
|
||||||
|
|
||||||
|
return item
|
||||||
|
? <ReturnValue item={item} key={total.currency} />
|
||||||
|
: null;
|
||||||
|
})}
|
||||||
|
</Stack>
|
||||||
|
</Group>
|
||||||
|
|
||||||
|
{summary.portfolio.cashBalances.length > 0 && (
|
||||||
|
<Group className={classes.cash} gap="xs" justify="flex-end">
|
||||||
|
<Text c="dimmed" size="xs">
|
||||||
|
{t("accounts.cash")}
|
||||||
|
</Text>
|
||||||
|
|
||||||
|
<Stack gap={0}>
|
||||||
|
{summary.portfolio.cashBalances.map(cash => (
|
||||||
|
<Text className={classes.cashValue} key={cash.currency} size="sm">
|
||||||
|
{formatMoney(cash, { withRoundedCents: true })}
|
||||||
|
</Text>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
</Group>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -61,13 +256,13 @@ type BrokerageAccountSourceStatusProps = {
|
|||||||
const BrokerageAccountSourceStatus: FC<BrokerageAccountSourceStatusProps> = (
|
const BrokerageAccountSourceStatus: FC<BrokerageAccountSourceStatusProps> = (
|
||||||
props,
|
props,
|
||||||
) => {
|
) => {
|
||||||
const { source } = props;
|
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const { source } = props;
|
||||||
const isSyncing = source?.lastAttempt.state === "running";
|
const isSyncing = source?.lastAttempt.state === "running";
|
||||||
|
|
||||||
const errorText
|
const errorText = source?.lastAttempt.state === "failed"
|
||||||
= source?.lastAttempt.state === "failed" ? t("accounts.refreshError") : null;
|
? t("accounts.refreshError")
|
||||||
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -87,86 +282,110 @@ const BrokerageAccountSourceStatus: FC<BrokerageAccountSourceStatusProps> = (
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type AccountDescriptionProps = {
|
||||||
|
account: BrokerageAccountCard;
|
||||||
|
};
|
||||||
|
|
||||||
|
const AccountDescription: FC<AccountDescriptionProps> = (props) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { account, summary } = props.account;
|
||||||
|
if (summary.state !== "available") return null;
|
||||||
|
|
||||||
|
const returns = summary.portfolio.unrealizedReturnByCurrency.map(item =>
|
||||||
|
t("accounts.description.return", {
|
||||||
|
absolute: formatMoney(
|
||||||
|
{ currency: item.currency, value: item.absolute },
|
||||||
|
{ withSign: true },
|
||||||
|
),
|
||||||
|
currency: item.currency,
|
||||||
|
percent: formatPercent(item.percent),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const structures = summary.portfolio.structure.currencies.map((item) => {
|
||||||
|
const categories = item.categories.map(category =>
|
||||||
|
t("accounts.description.structureCategory", {
|
||||||
|
category: t(portfolioCategoryPresentation[category.type].label),
|
||||||
|
value: formatMoney(
|
||||||
|
{ currency: item.currency, value: category.value },
|
||||||
|
{ withRoundedCents: true },
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
).join(", ");
|
||||||
|
|
||||||
|
return t("accounts.description.structure", {
|
||||||
|
currency: item.currency,
|
||||||
|
value: categories,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const hasPartialReturn = summary.portfolio.unrealizedReturnByCurrency.some(
|
||||||
|
item => item.partial,
|
||||||
|
);
|
||||||
|
|
||||||
|
const details = [...returns, ...structures].join(". ");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<VisuallyHidden>
|
||||||
|
{t("accounts.description.start", {
|
||||||
|
name: account.name,
|
||||||
|
type: t(accountTypeKey(account.type)),
|
||||||
|
})}
|
||||||
|
{t("accounts.description.currentValue", {
|
||||||
|
value: summary.portfolio.totalsByCurrency
|
||||||
|
.map(total => formatMoney(total)).join(", "),
|
||||||
|
})}
|
||||||
|
{details ? `${details}. ` : ""}
|
||||||
|
{hasPartialReturn ? t("accounts.brokerDescription") : ""}
|
||||||
|
</VisuallyHidden>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
const BrokerageAccountList: FC<BrokerageAccountListProps> = (props) => {
|
const BrokerageAccountList: FC<BrokerageAccountListProps> = (props) => {
|
||||||
const { accounts } = props;
|
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SimpleGrid className={classes.list} cols={1} spacing="lg">
|
<ul className={classes.list}>
|
||||||
{accounts.map(({ account, positionCounts, source, summary }) => (
|
{props.accounts.map(({ account, positionCounts, source, summary }) => (
|
||||||
<Card
|
<li key={account.id}>
|
||||||
className={classes.card}
|
<Link className={classes.row} to={`/accounts/${account.id}`}>
|
||||||
component={Link}
|
<Group className={classes.identity} wrap="nowrap">
|
||||||
key={account.id}
|
<h2 className={classes.name}>{account.name}</h2>
|
||||||
padding="xl"
|
|
||||||
radius="lg"
|
<Badge className={classes.accountType} variant="light">
|
||||||
to={`/accounts/${account.id}`}
|
|
||||||
withBorder
|
|
||||||
>
|
|
||||||
<Stack className={classes.identity} gap="sm">
|
|
||||||
<Group gap="sm" justify="space-between" wrap="nowrap">
|
|
||||||
<Text className={classes.kicker} fw={700} size="xs">
|
|
||||||
{t(accountTypeKey(account.type))}
|
{t(accountTypeKey(account.type))}
|
||||||
</Text>
|
</Badge>
|
||||||
|
|
||||||
<WalletIcon className={classes.accountIcon} />
|
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
<Text className={classes.name} component="h2" fw={700}>
|
|
||||||
{account.name}
|
|
||||||
</Text>
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
<Stack className={classes.balance} gap="xs">
|
|
||||||
<Text c="dimmed" size="sm">
|
|
||||||
{t("accounts.currentValue")}
|
|
||||||
</Text>
|
|
||||||
|
|
||||||
<BrokerageAccountSummary summary={summary} />
|
<BrokerageAccountSummary summary={summary} />
|
||||||
|
|
||||||
<BrokerageAccountSourceStatus source={source} />
|
<Stack className={classes.details} gap={2}>
|
||||||
</Stack>
|
{positionCounts && (
|
||||||
|
|
||||||
{!!positionCounts && (
|
|
||||||
<dl className={classes.positions}>
|
|
||||||
<div className={classes.stocks}>
|
|
||||||
<dt>{t("accounts.stocks")}</dt>
|
|
||||||
|
|
||||||
<dd>
|
|
||||||
{new Intl.NumberFormat("ru-RU").format(positionCounts.stocks)}
|
|
||||||
</dd>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className={classes.bonds}>
|
|
||||||
<dt>{t("accounts.bonds")}</dt>
|
|
||||||
|
|
||||||
<dd>
|
|
||||||
{new Intl.NumberFormat("ru-RU").format(positionCounts.bonds)}
|
|
||||||
</dd>
|
|
||||||
</div>
|
|
||||||
</dl>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Group className={classes.footer} gap="sm" justify="space-between">
|
|
||||||
{!!account.openedOn && (
|
|
||||||
<Text c="dimmed" size="xs">
|
<Text c="dimmed" size="xs">
|
||||||
{t("accounts.openedOn", {
|
{t("accounts.positions", {
|
||||||
date: formatDate(account.openedOn),
|
count: positionCounts.total,
|
||||||
})}
|
})}
|
||||||
</Text>
|
</Text>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Text className={classes.open} component="span" fw={600} size="sm">
|
<BrokerageAccountSourceStatus source={source} />
|
||||||
{t("accounts.openAccount")}
|
</Stack>
|
||||||
|
|
||||||
<span aria-hidden="true" className={classes.arrow}>
|
{summary.state === "available" && (
|
||||||
→
|
<Stack className={classes.structure} gap={4}>
|
||||||
</span>
|
{summary.portfolio.structure.currencies.map(item => (
|
||||||
</Text>
|
<StructureBar item={item} key={item.currency} />
|
||||||
</Group>
|
|
||||||
</Card>
|
|
||||||
))}
|
))}
|
||||||
</SimpleGrid>
|
</Stack>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<AccountDescription
|
||||||
|
account={{ account, positionCounts, source, summary }}
|
||||||
|
/>
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -31,6 +31,19 @@ function configureTestAuth() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function portfolioSummary(totals: { currency: string; value: string }[]) {
|
||||||
|
return {
|
||||||
|
bondPositionCount: 1,
|
||||||
|
cashBalances: [],
|
||||||
|
fundPositionCount: 0,
|
||||||
|
stockPositionCount: 0,
|
||||||
|
structure: { currencies: [], unvaluedCategories: [] },
|
||||||
|
totalPositionCount: 1,
|
||||||
|
totalsByCurrency: totals,
|
||||||
|
unrealizedReturnByCurrency: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function renderPage(queryClient: QueryClient) {
|
function renderPage(queryClient: QueryClient) {
|
||||||
configureTestAuth();
|
configureTestAuth();
|
||||||
|
|
||||||
@@ -46,6 +59,65 @@ function renderPage(queryClient: QueryClient) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("AccountsPage", () => {
|
describe("AccountsPage", () => {
|
||||||
|
it("summarizes currencies separately and reports excluded accounts", async () => {
|
||||||
|
server.use(http.get("*/api/v1/brokerage-accounts", () =>
|
||||||
|
HttpResponse.json(resource([
|
||||||
|
{
|
||||||
|
...account,
|
||||||
|
portfolioSummary: portfolioSummary([
|
||||||
|
{ currency: "RUB", value: "100.10" },
|
||||||
|
{ currency: "USD", value: "20" },
|
||||||
|
]),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
...account,
|
||||||
|
id: "account-2",
|
||||||
|
name: "Второй",
|
||||||
|
portfolioSummary: portfolioSummary([
|
||||||
|
{ currency: "RUB", value: "50.20" },
|
||||||
|
]),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
...account,
|
||||||
|
id: "account-3",
|
||||||
|
name: "Без сводки",
|
||||||
|
portfolioSummary: null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
...account,
|
||||||
|
id: "account-4",
|
||||||
|
name: "Только деньги",
|
||||||
|
portfolioSummary: {
|
||||||
|
...portfolioSummary([{ currency: "RUB", value: "25" }]),
|
||||||
|
bondPositionCount: 0,
|
||||||
|
cashBalances: [{ currency: "RUB", value: "25" }],
|
||||||
|
totalPositionCount: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
...account,
|
||||||
|
id: "account-5",
|
||||||
|
name: "Без сумм",
|
||||||
|
portfolioSummary: {
|
||||||
|
...portfolioSummary([]),
|
||||||
|
totalPositionCount: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])),
|
||||||
|
));
|
||||||
|
const client = createTestQueryClient();
|
||||||
|
|
||||||
|
renderPage(client);
|
||||||
|
|
||||||
|
expect(await screen.findByText("175,30 ₽")).toBeInTheDocument();
|
||||||
|
expect(screen.getAllByText("20,00 USD")).not.toHaveLength(0);
|
||||||
|
expect(screen.getByText("5 счетов")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Нет текущих сумм")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(
|
||||||
|
"Ещё 1 счёт не включён: нет актуального портфеля",
|
||||||
|
)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
it("loads accounts after retrying an initial HTTP failure", async () => {
|
it("loads accounts after retrying an initial HTTP failure", async () => {
|
||||||
const modes: (null | string)[] = [];
|
const modes: (null | string)[] = [];
|
||||||
server.use(
|
server.use(
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { FC } from "react";
|
import type { FC } from "react";
|
||||||
|
|
||||||
import { Button, Stack, Text, Title } from "@mantine/core";
|
import { Button, SimpleGrid, Stack, Text, Title } from "@mantine/core";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
|
|
||||||
@@ -10,15 +10,82 @@ import {
|
|||||||
type BrokerageAccountCard,
|
type BrokerageAccountCard,
|
||||||
BrokerageAccountList,
|
BrokerageAccountList,
|
||||||
} from "@/entities/brokerage-account";
|
} from "@/entities/brokerage-account";
|
||||||
|
import { formatMoney } from "@/shared/lib";
|
||||||
import { SourceSyncStatus } from "@/shared/ui";
|
import { SourceSyncStatus } from "@/shared/ui";
|
||||||
|
|
||||||
|
const DECIMAL_BASE = 10n;
|
||||||
|
const DECIMAL_PART_COUNT = 2;
|
||||||
|
const ZERO = 0n;
|
||||||
|
|
||||||
type AccountsPageLoadedProps = {
|
type AccountsPageLoadedProps = {
|
||||||
accounts: BrokerageAccountCard[];
|
accounts: BrokerageAccountCard[];
|
||||||
meta: InvestmentResourceMeta;
|
meta: InvestmentResourceMeta;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type Money = { currency: string; value: string };
|
||||||
|
|
||||||
|
function accountTotals(accounts: BrokerageAccountCard[]) {
|
||||||
|
const values = new Map<string, string[]>();
|
||||||
|
let excludedCount = 0;
|
||||||
|
|
||||||
|
for (const { summary } of accounts) {
|
||||||
|
if (summary.state === "empty") continue;
|
||||||
|
|
||||||
|
if (summary.state === "unavailable") {
|
||||||
|
excludedCount += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
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[]) {
|
||||||
|
const scale = Math.max(
|
||||||
|
0,
|
||||||
|
...values.map(value =>
|
||||||
|
value.split(".", DECIMAL_PART_COUNT)[1]?.length ?? 0),
|
||||||
|
);
|
||||||
|
|
||||||
|
const factor = DECIMAL_BASE ** BigInt(scale);
|
||||||
|
let sum = ZERO;
|
||||||
|
|
||||||
|
for (const value of values) {
|
||||||
|
const isNegative = value.startsWith("-");
|
||||||
|
|
||||||
|
const [integer = "0", fraction = ""] = (isNegative
|
||||||
|
? value.slice(1)
|
||||||
|
: value).split(".", DECIMAL_PART_COUNT);
|
||||||
|
|
||||||
|
const units = BigInt(integer) * factor
|
||||||
|
+ BigInt(fraction.padEnd(scale, "0") || "0");
|
||||||
|
|
||||||
|
sum += isNegative ? -units : units;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isNegative = sum < ZERO;
|
||||||
|
const digits = (isNegative ? -sum : sum).toString().padStart(scale + 1, "0");
|
||||||
|
const integer = scale ? digits.slice(0, -scale) : digits;
|
||||||
|
const fraction = scale ? `.${digits.slice(-scale)}` : "";
|
||||||
|
|
||||||
|
return `${isNegative ? "-" : ""}${integer}${fraction}`;
|
||||||
|
}
|
||||||
|
|
||||||
const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
|
const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const { excludedCount, totals } = accountTotals(props.accounts);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap="lg">
|
<Stack gap="lg">
|
||||||
@@ -28,6 +95,37 @@ const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
|
|||||||
<Text c="dimmed" size="sm">
|
<Text c="dimmed" size="sm">
|
||||||
{t("accounts.subtitle")}
|
{t("accounts.subtitle")}
|
||||||
</Text>
|
</Text>
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
<Stack gap="xs">
|
||||||
|
<SimpleGrid cols={{ base: 1, xs: 2 }} spacing="xs">
|
||||||
|
<Stack gap={4}>
|
||||||
|
<Text c="dimmed" size="sm">
|
||||||
|
{t("accounts.currentValue")}
|
||||||
|
</Text>
|
||||||
|
|
||||||
|
{totals.length > 0
|
||||||
|
? totals.map(total => (
|
||||||
|
<Text fw={700} key={total.currency} size="lg">
|
||||||
|
{formatMoney(total, { withRoundedCents: true })}
|
||||||
|
</Text>
|
||||||
|
))
|
||||||
|
: <Text c="dimmed">{t("accounts.summaryNoTotals")}</Text>}
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
<Stack gap={4}>
|
||||||
|
<Text fw={600}>{t("accounts.count", {
|
||||||
|
count: props.accounts.length,
|
||||||
|
})}
|
||||||
|
</Text>
|
||||||
|
|
||||||
|
{excludedCount > 0 && (
|
||||||
|
<Text c="dimmed" size="sm">
|
||||||
|
{t("accounts.summaryExcluded", { count: excludedCount })}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
</SimpleGrid>
|
||||||
|
|
||||||
<SourceSyncStatus
|
<SourceSyncStatus
|
||||||
lastAttempt={props.meta.lastAttempt}
|
lastAttempt={props.meta.lastAttempt}
|
||||||
|
|||||||
Vendored
+42
-25
@@ -909,12 +909,54 @@ export interface components {
|
|||||||
version: number;
|
version: number;
|
||||||
archived?: boolean;
|
archived?: boolean;
|
||||||
};
|
};
|
||||||
|
PortfolioStructureCategoryDto: {
|
||||||
|
/** @enum {string} */
|
||||||
|
type: "STOCK" | "BOND" | "OTHER" | "CASH";
|
||||||
|
/** @description Exact known value as a decimal string. */
|
||||||
|
value: string;
|
||||||
|
/** @description Percentage including cash, rounded to six decimal places. Null for incomplete, negative or zero-total compositions. */
|
||||||
|
sharePercent: string | null;
|
||||||
|
};
|
||||||
|
PortfolioStructureCurrencyDto: {
|
||||||
|
currency: string;
|
||||||
|
totalValue: string;
|
||||||
|
/** @description Any negative constituent, even if netted positive. */
|
||||||
|
hasNegativeValues: boolean;
|
||||||
|
categories: components["schemas"]["PortfolioStructureCategoryDto"][];
|
||||||
|
};
|
||||||
|
PortfolioUnvaluedCategoryDto: {
|
||||||
|
/** @enum {string} */
|
||||||
|
type: "STOCK" | "BOND" | "OTHER";
|
||||||
|
count: number;
|
||||||
|
};
|
||||||
|
PortfolioStructureDto: {
|
||||||
|
currencies: components["schemas"]["PortfolioStructureCurrencyDto"][];
|
||||||
|
/** @description Positions without current value and known valuation currency. Shares are unavailable across all currencies when nonempty. */
|
||||||
|
unvaluedCategories: components["schemas"]["PortfolioUnvaluedCategoryDto"][];
|
||||||
|
};
|
||||||
|
UnrealizedReturnDto: {
|
||||||
|
currency: string;
|
||||||
|
/** @example 12.345678901 */
|
||||||
|
absolute: string;
|
||||||
|
/** @example 100.00 */
|
||||||
|
costBasis: string;
|
||||||
|
/** @example 12.34 */
|
||||||
|
percent: string | null;
|
||||||
|
partial: boolean;
|
||||||
|
};
|
||||||
PortfolioSummaryDto: {
|
PortfolioSummaryDto: {
|
||||||
totalsByCurrency: components["schemas"]["MoneyDto"][];
|
totalsByCurrency: components["schemas"]["MoneyDto"][];
|
||||||
|
cashBalances: components["schemas"]["MoneyDto"][];
|
||||||
|
structure: components["schemas"]["PortfolioStructureDto"];
|
||||||
|
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. */
|
||||||
bondPositionCount: number;
|
bondPositionCount: number;
|
||||||
|
/** @description Number of non-zero fund positions, not the number of units. */
|
||||||
|
fundPositionCount: number;
|
||||||
|
/** @description Number of all non-zero positions, not the number of units. */
|
||||||
|
totalPositionCount: number;
|
||||||
};
|
};
|
||||||
BrokerageAccountDto: {
|
BrokerageAccountDto: {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -1026,31 +1068,6 @@ export interface components {
|
|||||||
ticker: string | null;
|
ticker: string | null;
|
||||||
logoName: string | null;
|
logoName: string | null;
|
||||||
};
|
};
|
||||||
PortfolioStructureCategoryDto: {
|
|
||||||
/** @enum {string} */
|
|
||||||
type: "STOCK" | "BOND" | "OTHER" | "CASH";
|
|
||||||
/** @description Exact known value as a decimal string. */
|
|
||||||
value: string;
|
|
||||||
/** @description Percentage including cash, rounded to six decimal places. Null for incomplete, negative or zero-total compositions. */
|
|
||||||
sharePercent: string | null;
|
|
||||||
};
|
|
||||||
PortfolioStructureCurrencyDto: {
|
|
||||||
currency: string;
|
|
||||||
totalValue: string;
|
|
||||||
/** @description Any negative constituent, even if netted positive. */
|
|
||||||
hasNegativeValues: boolean;
|
|
||||||
categories: components["schemas"]["PortfolioStructureCategoryDto"][];
|
|
||||||
};
|
|
||||||
PortfolioUnvaluedCategoryDto: {
|
|
||||||
/** @enum {string} */
|
|
||||||
type: "STOCK" | "BOND" | "OTHER";
|
|
||||||
count: number;
|
|
||||||
};
|
|
||||||
PortfolioStructureDto: {
|
|
||||||
currencies: components["schemas"]["PortfolioStructureCurrencyDto"][];
|
|
||||||
/** @description Positions without current value and known valuation currency. Shares are unavailable across all currencies when nonempty. */
|
|
||||||
unvaluedCategories: components["schemas"]["PortfolioUnvaluedCategoryDto"][];
|
|
||||||
};
|
|
||||||
PortfolioDto: {
|
PortfolioDto: {
|
||||||
/** Format: date-time */
|
/** Format: date-time */
|
||||||
lastSuccessfulAt: string;
|
lastSuccessfulAt: string;
|
||||||
|
|||||||
@@ -5819,6 +5819,135 @@
|
|||||||
"version"
|
"version"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
"PortfolioStructureCategoryDto": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"type": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": [
|
||||||
|
"STOCK",
|
||||||
|
"BOND",
|
||||||
|
"OTHER",
|
||||||
|
"CASH"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"value": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Exact known value as a decimal string."
|
||||||
|
},
|
||||||
|
"sharePercent": {
|
||||||
|
"type": "string",
|
||||||
|
"nullable": true,
|
||||||
|
"description": "Percentage including cash, rounded to six decimal places. Null for incomplete, negative or zero-total compositions."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"type",
|
||||||
|
"value",
|
||||||
|
"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": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"type": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": [
|
||||||
|
"STOCK",
|
||||||
|
"BOND",
|
||||||
|
"OTHER"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": {
|
||||||
|
"type": "number",
|
||||||
|
"minimum": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"type",
|
||||||
|
"count"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"PortfolioStructureDto": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"currencies": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/PortfolioStructureCurrencyDto"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"unvaluedCategories": {
|
||||||
|
"description": "Positions without current value and known valuation currency. Shares are unavailable across all currencies when nonempty.",
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/PortfolioUnvaluedCategoryDto"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"currencies",
|
||||||
|
"unvaluedCategories"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"UnrealizedReturnDto": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"currency": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"absolute": {
|
||||||
|
"type": "string",
|
||||||
|
"example": "12.345678901"
|
||||||
|
},
|
||||||
|
"costBasis": {
|
||||||
|
"type": "string",
|
||||||
|
"example": "100.00"
|
||||||
|
},
|
||||||
|
"percent": {
|
||||||
|
"type": "string",
|
||||||
|
"nullable": true,
|
||||||
|
"example": "12.34"
|
||||||
|
},
|
||||||
|
"partial": {
|
||||||
|
"type": "boolean"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"currency",
|
||||||
|
"absolute",
|
||||||
|
"costBasis",
|
||||||
|
"percent",
|
||||||
|
"partial"
|
||||||
|
]
|
||||||
|
},
|
||||||
"PortfolioSummaryDto": {
|
"PortfolioSummaryDto": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
@@ -5828,6 +5957,21 @@
|
|||||||
"$ref": "#/components/schemas/MoneyDto"
|
"$ref": "#/components/schemas/MoneyDto"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"cashBalances": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/MoneyDto"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"structure": {
|
||||||
|
"$ref": "#/components/schemas/PortfolioStructureDto"
|
||||||
|
},
|
||||||
|
"unrealizedReturnByCurrency": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/UnrealizedReturnDto"
|
||||||
|
}
|
||||||
|
},
|
||||||
"stockPositionCount": {
|
"stockPositionCount": {
|
||||||
"type": "integer",
|
"type": "integer",
|
||||||
"minimum": 0,
|
"minimum": 0,
|
||||||
@@ -5837,12 +5981,27 @@
|
|||||||
"type": "integer",
|
"type": "integer",
|
||||||
"minimum": 0,
|
"minimum": 0,
|
||||||
"description": "Number of non-zero bond positions, not the number of units."
|
"description": "Number of non-zero bond positions, not the number of units."
|
||||||
|
},
|
||||||
|
"fundPositionCount": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 0,
|
||||||
|
"description": "Number of non-zero fund positions, not the number of units."
|
||||||
|
},
|
||||||
|
"totalPositionCount": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 0,
|
||||||
|
"description": "Number of all non-zero positions, not the number of units."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"totalsByCurrency",
|
"totalsByCurrency",
|
||||||
|
"cashBalances",
|
||||||
|
"structure",
|
||||||
|
"unrealizedReturnByCurrency",
|
||||||
"stockPositionCount",
|
"stockPositionCount",
|
||||||
"bondPositionCount"
|
"bondPositionCount",
|
||||||
|
"fundPositionCount",
|
||||||
|
"totalPositionCount"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"BrokerageAccountDto": {
|
"BrokerageAccountDto": {
|
||||||
@@ -6314,104 +6473,6 @@
|
|||||||
"logoName"
|
"logoName"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"PortfolioStructureCategoryDto": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"type": {
|
|
||||||
"type": "string",
|
|
||||||
"enum": [
|
|
||||||
"STOCK",
|
|
||||||
"BOND",
|
|
||||||
"OTHER",
|
|
||||||
"CASH"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"value": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "Exact known value as a decimal string."
|
|
||||||
},
|
|
||||||
"sharePercent": {
|
|
||||||
"type": "string",
|
|
||||||
"nullable": true,
|
|
||||||
"description": "Percentage including cash, rounded to six decimal places. Null for incomplete, negative or zero-total compositions."
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": [
|
|
||||||
"type",
|
|
||||||
"value",
|
|
||||||
"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": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"type": {
|
|
||||||
"type": "string",
|
|
||||||
"enum": [
|
|
||||||
"STOCK",
|
|
||||||
"BOND",
|
|
||||||
"OTHER"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"count": {
|
|
||||||
"type": "number",
|
|
||||||
"minimum": 1
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": [
|
|
||||||
"type",
|
|
||||||
"count"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"PortfolioStructureDto": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"currencies": {
|
|
||||||
"type": "array",
|
|
||||||
"items": {
|
|
||||||
"$ref": "#/components/schemas/PortfolioStructureCurrencyDto"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"unvaluedCategories": {
|
|
||||||
"description": "Positions without current value and known valuation currency. Shares are unavailable across all currencies when nonempty.",
|
|
||||||
"type": "array",
|
|
||||||
"items": {
|
|
||||||
"$ref": "#/components/schemas/PortfolioUnvaluedCategoryDto"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": [
|
|
||||||
"currencies",
|
|
||||||
"unvaluedCategories"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"PortfolioDto": {
|
"PortfolioDto": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
|
|||||||
@@ -5,7 +5,20 @@ const ru = {
|
|||||||
all: "Все счета",
|
all: "Все счета",
|
||||||
allDescription: "Портфель по всем доступным инвестиционным счетам",
|
allDescription: "Портфель по всем доступным инвестиционным счетам",
|
||||||
bonds: "Облигации",
|
bonds: "Облигации",
|
||||||
|
brokerDescription: "По данным брокера",
|
||||||
|
cash: "Деньги на счёте",
|
||||||
|
count_few: "{{count}} счёта",
|
||||||
|
count_many: "{{count}} счетов",
|
||||||
|
count_one: "{{count}} счёт",
|
||||||
|
count_other: "{{count}} счёта",
|
||||||
currentValue: "Текущая стоимость",
|
currentValue: "Текущая стоимость",
|
||||||
|
description: {
|
||||||
|
currentValue: "Текущая стоимость: {{value}}. ",
|
||||||
|
return: "Доходность {{currency}}: {{percent}}, {{absolute}}",
|
||||||
|
start: "Счёт {{name}}, {{type}}. ",
|
||||||
|
structure: "Структура {{currency}}: {{value}}",
|
||||||
|
structureCategory: "{{category}} {{value}}",
|
||||||
|
},
|
||||||
emptyText:
|
emptyText:
|
||||||
"Откройте инвестиционный счет в T-Bank, чтобы он появился здесь.",
|
"Откройте инвестиционный счет в T-Bank, чтобы он появился здесь.",
|
||||||
emptyTitle: "Нет инвестиционных счетов",
|
emptyTitle: "Нет инвестиционных счетов",
|
||||||
@@ -18,6 +31,11 @@ const ru = {
|
|||||||
openAll: "Портфель по всем счетам",
|
openAll: "Портфель по всем счетам",
|
||||||
openedOn: "Открыт {{date}}",
|
openedOn: "Открыт {{date}}",
|
||||||
openSettings: "Открыть настройки T-Bank",
|
openSettings: "Открыть настройки T-Bank",
|
||||||
|
partial: "частично",
|
||||||
|
positions_few: "{{count}} позиции",
|
||||||
|
positions_many: "{{count}} позиций",
|
||||||
|
positions_one: "{{count}} позиция",
|
||||||
|
positions_other: "{{count}} позиции",
|
||||||
refreshError:
|
refreshError:
|
||||||
"Не удалось обновить данные. Показаны последние полученные.",
|
"Не удалось обновить данные. Показаны последние полученные.",
|
||||||
refreshing: "Обновляем данные",
|
refreshing: "Обновляем данные",
|
||||||
@@ -28,8 +46,22 @@ const ru = {
|
|||||||
retry: "Повторить",
|
retry: "Повторить",
|
||||||
scope: "Счёт",
|
scope: "Счёт",
|
||||||
stocks: "Акции",
|
stocks: "Акции",
|
||||||
|
structure: {
|
||||||
|
category: "{{category}} {{percent}} %",
|
||||||
|
incomplete: "{{category}}: доля неизвестна",
|
||||||
|
label: "Структура в {{currency}}: {{value}}",
|
||||||
|
},
|
||||||
subtitle: "Ваши инвестиции по счетам",
|
subtitle: "Ваши инвестиции по счетам",
|
||||||
summaryEmpty: "Нет текущих сумм",
|
summaryEmpty: "Нет текущих сумм",
|
||||||
|
summaryExcluded_few:
|
||||||
|
"Ещё {{count}} счёта не включены: нет актуального портфеля",
|
||||||
|
summaryExcluded_many:
|
||||||
|
"Ещё {{count}} счетов не включены: нет актуального портфеля",
|
||||||
|
summaryExcluded_one:
|
||||||
|
"Ещё {{count}} счёт не включён: нет актуального портфеля",
|
||||||
|
summaryExcluded_other:
|
||||||
|
"Ещё {{count}} счёта не включены: нет актуального портфеля",
|
||||||
|
summaryNoTotals: "Нет данных для сводки",
|
||||||
summaryUnavailable: "Сводка временно недоступна",
|
summaryUnavailable: "Сводка временно недоступна",
|
||||||
title: "Счета",
|
title: "Счета",
|
||||||
types: {
|
types: {
|
||||||
|
|||||||
@@ -42,6 +42,18 @@ describe("shared display helpers", () => {
|
|||||||
formatMoney({ currency: "RUB", value: "1.5" }, { withZeroCents: true }),
|
formatMoney({ currency: "RUB", value: "1.5" }, { withZeroCents: true }),
|
||||||
).toBe("1,50 ₽");
|
).toBe("1,50 ₽");
|
||||||
expect(formatMoney(null)).toBe("—");
|
expect(formatMoney(null)).toBe("—");
|
||||||
|
expect(formatMoney(
|
||||||
|
{ currency: "RUB", value: "136900" },
|
||||||
|
{ withSign: true },
|
||||||
|
)).toBe("+136 900 ₽");
|
||||||
|
expect(formatMoney(
|
||||||
|
{ currency: "RUB", value: "-4200" },
|
||||||
|
{ withSign: true },
|
||||||
|
)).toBe("−4 200 ₽");
|
||||||
|
expect(formatMoney(
|
||||||
|
{ currency: "RUB", value: "-0.00" },
|
||||||
|
{ withSign: true },
|
||||||
|
)).toBe("0,00 ₽");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("builds the brand logo url from an upstream file name", () => {
|
it("builds the brand logo url from an upstream file name", () => {
|
||||||
|
|||||||
@@ -2,9 +2,18 @@ const DECIMAL_PART_COUNT = 2;
|
|||||||
const CENTS_PRECISION = 2;
|
const CENTS_PRECISION = 2;
|
||||||
|
|
||||||
type FormatMoneyOptions = {
|
type FormatMoneyOptions = {
|
||||||
|
withRoundedCents?: boolean;
|
||||||
|
withSign?: boolean;
|
||||||
withZeroCents?: boolean;
|
withZeroCents?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const portfolioCategoryPresentation = {
|
||||||
|
BOND: { color: "grape.6", label: "portfolio.bonds" },
|
||||||
|
CASH: { color: "green.6", label: "portfolio.structure.cash" },
|
||||||
|
OTHER: { color: "orange.6", label: "portfolio.structure.other" },
|
||||||
|
STOCK: { color: "blue.6", label: "portfolio.stocks" },
|
||||||
|
} as const;
|
||||||
|
|
||||||
type Money = { currency: string; value: string };
|
type Money = { currency: string; value: string };
|
||||||
|
|
||||||
const dateFormatter = new Intl.DateTimeFormat("ru-RU", {
|
const dateFormatter = new Intl.DateTimeFormat("ru-RU", {
|
||||||
@@ -39,16 +48,24 @@ function formatMoney(
|
|||||||
money: Money
|
money: Money
|
||||||
| null
|
| null
|
||||||
| undefined,
|
| undefined,
|
||||||
{ withZeroCents = false }: FormatMoneyOptions = {},
|
{
|
||||||
|
withRoundedCents = false,
|
||||||
|
withSign = false,
|
||||||
|
withZeroCents = false,
|
||||||
|
}: FormatMoneyOptions = {},
|
||||||
): string {
|
): string {
|
||||||
if (!money) return "—";
|
if (!money) return "—";
|
||||||
|
|
||||||
const [integerPart = "", fractionPart = ""] = money.value.split(
|
const value = withRoundedCents
|
||||||
|
? roundDecimalToCents(money.value)
|
||||||
|
: money.value;
|
||||||
|
|
||||||
|
const [integerPart = "", fractionPart = ""] = value.split(
|
||||||
".",
|
".",
|
||||||
DECIMAL_PART_COUNT,
|
DECIMAL_PART_COUNT,
|
||||||
);
|
);
|
||||||
|
|
||||||
const normalizedFraction = withZeroCents
|
const normalizedFraction = withRoundedCents || withZeroCents
|
||||||
? fractionPart.padEnd(CENTS_PRECISION, "0")
|
? fractionPart.padEnd(CENTS_PRECISION, "0")
|
||||||
: fractionPart;
|
: fractionPart;
|
||||||
|
|
||||||
@@ -57,8 +74,42 @@ function formatMoney(
|
|||||||
: integerPart;
|
: integerPart;
|
||||||
|
|
||||||
const currency = money.currency === "RUB" ? "₽" : money.currency;
|
const currency = money.currency === "RUB" ? "₽" : money.currency;
|
||||||
|
const formatted = `${formatDecimal(decimal)} ${currency}`;
|
||||||
|
|
||||||
return `${formatDecimal(decimal)} ${currency}`;
|
if (!withSign) return formatted;
|
||||||
|
if (isZeroDecimal(value))
|
||||||
|
return value.startsWith("-") ? formatted.slice(1) : formatted;
|
||||||
|
|
||||||
|
return value.startsWith("-") ? `−${formatted.slice(1)}` : `+${formatted}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isZeroDecimal(value: string) {
|
||||||
|
const unsigned = value.startsWith("-") ? value.slice(1) : value;
|
||||||
|
|
||||||
|
const [integer = "", fraction = ""] = unsigned.split(
|
||||||
|
".",
|
||||||
|
DECIMAL_PART_COUNT,
|
||||||
|
);
|
||||||
|
|
||||||
|
return integer.replaceAll("0", "") === ""
|
||||||
|
&& fraction.replaceAll("0", "") === "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function roundDecimalToCents(value: string): string {
|
||||||
|
const [integer = "", fraction = ""] = value.split(".", DECIMAL_PART_COUNT);
|
||||||
|
const sign = integer.startsWith("-") ? "-" : "";
|
||||||
|
const digits = sign ? integer.slice(1) : integer;
|
||||||
|
const roundedFraction = fraction.padEnd(CENTS_PRECISION + 1, "0");
|
||||||
|
const cents = `${digits}${roundedFraction.slice(0, CENTS_PRECISION)}`;
|
||||||
|
const roundingDigit = roundedFraction.at(CENTS_PRECISION) ?? "0";
|
||||||
|
|
||||||
|
const rounded = roundingDigit >= "5"
|
||||||
|
? (BigInt(cents) + 1n).toString().padStart(cents.length, "0")
|
||||||
|
: cents;
|
||||||
|
|
||||||
|
const roundedInteger = rounded.slice(0, -CENTS_PRECISION) || "0";
|
||||||
|
|
||||||
|
return `${sign}${roundedInteger}.${rounded.slice(-CENTS_PRECISION)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Без timeZone Intl берёт часовой пояс браузера пользователя.
|
// Без timeZone Intl берёт часовой пояс браузера пользователя.
|
||||||
@@ -94,4 +145,5 @@ export {
|
|||||||
formatMoney,
|
formatMoney,
|
||||||
formatSnapshotTime,
|
formatSnapshotTime,
|
||||||
instrumentLogoUrl,
|
instrumentLogoUrl,
|
||||||
|
portfolioCategoryPresentation,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ export {
|
|||||||
formatMoney,
|
formatMoney,
|
||||||
formatSnapshotTime,
|
formatSnapshotTime,
|
||||||
instrumentLogoUrl,
|
instrumentLogoUrl,
|
||||||
|
portfolioCategoryPresentation,
|
||||||
} from "./display";
|
} from "./display";
|
||||||
export { useInitialAvailability } from "./initial-availability";
|
export { useInitialAvailability } from "./initial-availability";
|
||||||
export { useUrlPeriod } from "./useUrlPeriod";
|
export { useUrlPeriod } from "./useUrlPeriod";
|
||||||
|
|||||||
@@ -5,20 +5,13 @@ import { useTranslation } from "react-i18next";
|
|||||||
|
|
||||||
import type { Portfolio } from "@/entities/portfolio";
|
import type { Portfolio } from "@/entities/portfolio";
|
||||||
|
|
||||||
import { formatMoney } from "@/shared/lib";
|
import { formatMoney, portfolioCategoryPresentation } from "@/shared/lib";
|
||||||
|
|
||||||
const MIN_VISIBLE_SHARE_PERCENT = 0.01;
|
const MIN_VISIBLE_SHARE_PERCENT = 0.01;
|
||||||
|
|
||||||
// A cached snapshot or an older running server can predate this response field.
|
// A cached snapshot or an older running server can predate this response field.
|
||||||
type PortfolioStructureProps = { structure?: null | Portfolio["structure"] };
|
type PortfolioStructureProps = { structure?: null | Portfolio["structure"] };
|
||||||
|
|
||||||
const categoryPresentation = {
|
|
||||||
BOND: { color: "grape.6", label: "portfolio.bonds" },
|
|
||||||
CASH: { color: "green.6", label: "portfolio.structure.cash" },
|
|
||||||
OTHER: { color: "orange.6", label: "portfolio.structure.other" },
|
|
||||||
STOCK: { color: "blue.6", label: "portfolio.stocks" },
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
const usePortfolioStructureVm = (props: PortfolioStructureProps) => {
|
const usePortfolioStructureVm = (props: PortfolioStructureProps) => {
|
||||||
const { structure } = props;
|
const { structure } = props;
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -45,7 +38,7 @@ const usePortfolioStructureVm = (props: PortfolioStructureProps) => {
|
|||||||
unvalued:
|
unvalued:
|
||||||
structure?.unvaluedCategories.map(category =>
|
structure?.unvaluedCategories.map(category =>
|
||||||
t("portfolio.structure.unvaluedCategory", {
|
t("portfolio.structure.unvaluedCategory", {
|
||||||
category: t(categoryPresentation[category.type].label),
|
category: t(portfolioCategoryPresentation[category.type].label),
|
||||||
count: category.count,
|
count: category.count,
|
||||||
}),
|
}),
|
||||||
) ?? [],
|
) ?? [],
|
||||||
@@ -61,7 +54,7 @@ function portfolioRows(
|
|||||||
if (!selected) return [];
|
if (!selected) return [];
|
||||||
|
|
||||||
return selected.categories.map((category) => {
|
return selected.categories.map((category) => {
|
||||||
const presentation = categoryPresentation[category.type];
|
const presentation = portfolioCategoryPresentation[category.type];
|
||||||
|
|
||||||
const percentage
|
const percentage
|
||||||
= category.sharePercent === null
|
= category.sharePercent === null
|
||||||
|
|||||||
Reference in New Issue
Block a user