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

This commit is contained in:
2026-09-23 08:34:58 +03:00
parent 85fcfe3d07
commit b987fd8e78
190 changed files with 131 additions and 108 deletions
@@ -0,0 +1,36 @@
import { Stack, Text, Title } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import type { BrokerageAccount } from "@/entities/brokerage-account";
import { accountTypeKey } from "@/entities/brokerage-account";
type AccountHeadingProps = {
account?: BrokerageAccount;
accountId?: string;
};
const AccountHeading: FC<AccountHeadingProps> = (props) => {
const { account } = props;
const { t } = useTranslation();
return (
<Stack gap={2}>
<Title order={1}>
{props.accountId === "all"
? t("accounts.all")
: (account?.name ?? t("portfolio.title"))}
</Title>
{props.accountId === "all" ? (
<Text c="dimmed" size="sm">
{t("accounts.allDescription")}
</Text>
) : account ? (
<Text c="dimmed" size="sm">
{t(accountTypeKey(account.type))}
</Text>
) : null}
</Stack>
);
};
export { AccountHeading };
@@ -0,0 +1,57 @@
import { Stack } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import type { BrokerageAccount } from "@/entities/brokerage-account";
import { BrokerageEventsPreview } from "@/entities/brokerage-event";
import type {
AccountPageIncomeSummary,
AccountPageRecentEvents,
AccountPageRecentOperations,
} from "../AccountPage.vm";
import { AccountHeading } from "./AccountHeading.view";
import { IncomeSummary } from "./IncomeSummary.view";
import { PortfolioRefreshState } from "./PortfolioRefreshState/PortfolioRefreshState.view";
import { PortfolioStructure } from "./PortfolioStructure/PortfolioStructure";
import { RecentOperations } from "./RecentOperations.view";
type AccountPageEmptyProps = {
account?: BrokerageAccount;
accountId?: string;
refreshing?: boolean;
refreshError?: boolean;
retry?: () => void;
recentOperations: AccountPageRecentOperations;
recentEvents: AccountPageRecentEvents;
incomeSummary?: AccountPageIncomeSummary;
};
const AccountPageEmpty: FC<AccountPageEmptyProps> = (props) => {
const { t } = useTranslation();
return (
<Stack>
<AccountHeading account={props.account} accountId={props.accountId} />
<PortfolioRefreshState
refreshing={props.refreshing ?? false}
refreshError={props.refreshError ?? false}
retry={props.retry}
/>
<StateView
title={t("portfolio.emptyTitle")}
text={t(
props.accountId === "all"
? "portfolio.allEmptyText"
: "portfolio.emptyText",
)}
/>
<PortfolioStructure
structure={{ currencies: [], unvaluedCategories: [] }}
/>
<RecentOperations operations={props.recentOperations} />
<BrokerageEventsPreview events={props.recentEvents} />
{props.incomeSummary ? <IncomeSummary {...props.incomeSummary} /> : null}
</Stack>
);
};
export { AccountPageEmpty };
@@ -0,0 +1,57 @@
import { Button } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
type AccountPageErrorProps = { code?: string; retry: () => void };
const AccountPageError: FC<AccountPageErrorProps> = (props) => {
const { code, retry } = props;
const { t } = useTranslation();
if (code === "NOT_FOUND")
return (
<StateView
error
title={t("portfolio.accountUnavailableTitle")}
text={t("portfolio.accountUnavailableText")}
action={
<Button component={Link} to="/accounts">
{t("portfolio.back")}
</Button>
}
/>
);
if (code === "TBANK_NOT_CONNECTED" || code === "INVALID_TBANK_TOKEN")
return (
<StateView
error
title={t("portfolio.connectionErrorTitle")}
text={t("portfolio.connectionErrorText")}
action={
<Button component={Link} to="/settings">
{t("accounts.openSettings")}
</Button>
}
/>
);
if (code === "TBANK_UNAVAILABLE")
return (
<StateView
error
title={t("accounts.unavailableTitle")}
text={t("accounts.unavailableText")}
action={<Button onClick={retry}>{t("accounts.retry")}</Button>}
/>
);
return (
<StateView
error
title={t("states.errorTitle")}
text={t("states.errorText")}
action={<Button onClick={retry}>{t("accounts.retry")}</Button>}
/>
);
};
export { AccountPageError };
@@ -0,0 +1,127 @@
import { Accordion, Alert, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import type { BrokerageAccount } from "@/entities/brokerage-account";
import { BrokerageEventsPreview } from "@/entities/brokerage-event";
import type { Portfolio } from "@/entities/portfolio";
import { formatSnapshotTime } from "@/shared/lib";
import classes from "../AccountPage.module.css";
import type {
AccountPageIncomeSummary,
AccountPagePositionSection,
AccountPageRecentEvents,
AccountPageRecentOperations,
} from "../AccountPage.vm";
import { AccountHeading } from "./AccountHeading.view";
import { CurrencyCards } from "./CurrencyCards/CurrencyCards.view";
import { IncomeSummary } from "./IncomeSummary.view";
import { PortfolioRefreshState } from "./PortfolioRefreshState/PortfolioRefreshState.view";
import { PortfolioStructure } from "./PortfolioStructure/PortfolioStructure";
import { PositionSection } from "./PositionSection.view";
import { RecentOperations } from "./RecentOperations.view";
type AccountPageLoadedProps = {
account?: BrokerageAccount;
accountId?: string;
portfolio: Portfolio;
positionSections: AccountPagePositionSection[];
refreshing?: boolean;
refreshError?: boolean;
retry?: () => void;
recentOperations: AccountPageRecentOperations;
recentEvents: AccountPageRecentEvents;
incomeSummary?: AccountPageIncomeSummary;
};
const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
const { t } = useTranslation();
return (
<Stack gap="lg">
<AccountHeading account={props.account} accountId={props.accountId} />
<PortfolioRefreshState
refreshing={props.refreshing ?? false}
refreshError={props.refreshError ?? false}
retry={props.retry}
/>
{props.portfolio.isStale ? (
<Alert color="blue">{t("portfolio.staleWarning")}</Alert>
) : null}
<Text c="dimmed" size="sm">
{t(
props.accountId === "all"
? "portfolio.allUpdatedAt"
: "portfolio.updatedAt",
{
date: formatSnapshotTime(props.portfolio.lastSuccessfulAt),
},
)}
</Text>
<CurrencyCards amounts={props.portfolio.totalsByCurrency} />
<PortfolioStructure
key={props.accountId}
structure={props.portfolio.structure}
/>
<Accordion
multiple
defaultValue={[
...props.positionSections.map((section) => section.kind),
"cash",
"recentOperations",
"recentEvents",
"incomeSummary",
]}
classNames={{
control: classes.accordionControl,
label: classes.accordionLabel,
chevron: classes.accordionChevron,
panel: classes.accordionPanel,
}}
>
{props.positionSections.map((section) => (
<Accordion.Item key={section.kind} value={section.kind}>
<Accordion.Control>
{t(positionSectionTitleKey(section.kind))}
</Accordion.Control>
<Accordion.Panel>
<PositionSection section={section} />
</Accordion.Panel>
</Accordion.Item>
))}
<Accordion.Item value="cash">
<Accordion.Control>{t("portfolio.cashBalances")}</Accordion.Control>
<Accordion.Panel>
<CurrencyCards amounts={props.portfolio.cashBalances} />
</Accordion.Panel>
</Accordion.Item>
<Accordion.Item value="recentOperations">
<Accordion.Control>{t("ledger.recentTitle")}</Accordion.Control>
<Accordion.Panel>
<RecentOperations operations={props.recentOperations} />
</Accordion.Panel>
</Accordion.Item>
<Accordion.Item value="recentEvents">
<Accordion.Control>{t("events.recentTitle")}</Accordion.Control>
<Accordion.Panel>
<BrokerageEventsPreview events={props.recentEvents} />
</Accordion.Panel>
</Accordion.Item>
<Accordion.Item value="incomeSummary">
<Accordion.Control>{t("income.summaryTitle")}</Accordion.Control>
<Accordion.Panel>
{props.incomeSummary ? (
<IncomeSummary {...props.incomeSummary} />
) : null}
</Accordion.Panel>
</Accordion.Item>
</Accordion>
</Stack>
);
};
function positionSectionTitleKey(kind: AccountPagePositionSection["kind"]) {
if (kind === "stocks") return "portfolio.stocks";
if (kind === "bonds") return "portfolio.bonds";
return "portfolio.otherPositions";
}
export { AccountPageLoaded };
@@ -0,0 +1,21 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { AccountPageLoading } from "./AccountPageLoading.view";
const meta = {
title: "Product/AccountPageLoading",
component: AccountPageLoading,
tags: ["autodocs"],
parameters: {
docs: {
description: {
component:
"Начальная загрузка страницы счёта без доступных данных: настоящий page-owned skeleton заголовка, сводки и строк. Shared LoadingSkeleton предоставляет busy-region, фигуры декоративны и не получают фокус. Не используйте вместо сохранённых данных при refetch; запросы в витрине не выполняются.",
},
},
},
} satisfies Meta<typeof AccountPageLoading>;
export default meta;
type Story = StoryObj<typeof meta>;
export const InitialLoading: Story = { name: "Начальная загрузка счёта" };
@@ -0,0 +1,37 @@
import { Paper, SimpleGrid, Skeleton } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import classes from "../../AccountPage.module.css";
const AccountPageLoading: FC = () => {
const { t } = useTranslation();
return (
<LoadingSkeleton label={t("states.loadingTitle")}>
<Skeleton height={32} width="35%" />
<SimpleGrid
cols={{ base: 1, sm: 2, md: 3 }}
spacing={10}
aria-hidden="true"
>
{[0, 1, 2].map((index) => (
<Paper key={index} className={classes.total} withBorder>
<Skeleton height={24} width={40} radius={4} />
<Skeleton
height={21}
width={180}
radius={4}
className={classes.totalAmountSkeleton}
/>
</Paper>
))}
</SimpleGrid>
<Skeleton height={260} radius="sm" />
{[0, 1, 2].map((index) => (
<Skeleton key={index} height={52} radius="sm" />
))}
</LoadingSkeleton>
);
};
export { AccountPageLoading };
@@ -0,0 +1,85 @@
import { MantineProvider } from "@mantine/core";
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { CurrencyCards } from "./CurrencyCards.view";
describe("CurrencyCards currency presentation", () => {
it.each([0, 1, 3, 5])(
"renders only the %i supplied totals in upstream order",
(count) => {
const totals = [
{ currency: "EUR", value: "3.00" },
{ currency: "USD", value: "2.00" },
{ currency: "RUB", value: "1.00" },
{ currency: "CAD", value: "4.00" },
{ currency: "XYZ", value: "5.00" },
].slice(0, count);
const { container } = render(
<MantineProvider>
<CurrencyCards amounts={totals} />
</MantineProvider>,
);
expect(
screen.queryAllByRole("definition").map((node) => node.textContent),
).toEqual(
["3,00 €", "2,00 $", "1,00 ₽", "4,00 CAD", "5,00 XYZ"].slice(0, count),
);
expect(container.querySelectorAll("dl")).toHaveLength(count);
expect(
container.querySelector("[tabindex], button, a, input"),
).toBeNull();
},
);
it.each([
["RUB", "125000.50", "125 000,50 ₽", "Российский рубль", "₽"],
["USD", "320.00", "320,00 $", "Доллар США", "$"],
["EUR", "9876.54321", "9 876,54321 €", "Евро", "€"],
[
"RUB",
"123456789012.345678901",
"123 456 789 012,345678901 ₽",
"Российский рубль",
"₽",
],
["USD", "-1234567.890123", "-1 234 567,890123 $", "Доллар США", "$"],
["EUR", "987654321.000001", "987 654 321,000001 €", "Евро", "€"],
["USD", "-0.5", "-0,5 $", "Доллар США", "$"],
["CAD", "20.00", "20,00 CAD", "CAD", "CAD"],
["XYZ", "1.000", "1,000 XYZ", "XYZ", "XYZ"],
])(
"preserves %s %s and its currency identity",
(currency, value, expected, name, symbol) => {
render(
<MantineProvider>
<CurrencyCards amounts={[{ currency, value }]} />
</MantineProvider>,
);
const term = screen.getByRole("term");
expect(term).toHaveTextContent(name);
expect(term.querySelector('[aria-hidden="true"]')).toHaveTextContent(
symbol,
);
expect(screen.getByRole("definition")).toHaveTextContent(expected);
expect(term.parentElement).toBe(
screen.getByRole("definition").parentElement,
);
},
);
it("keeps USD and CAD as distinct supplied values", () => {
render(
<MantineProvider>
<CurrencyCards
amounts={[
{ currency: "USD", value: "1.00" },
{ currency: "CAD", value: "2.00" },
]}
/>
</MantineProvider>,
);
expect(
screen.getAllByRole("definition").map((node) => node.textContent),
).toEqual(["1,00 $", "2,00 CAD"]);
});
});
@@ -0,0 +1,61 @@
import { Paper, SimpleGrid, Text, VisuallyHidden } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import type { Portfolio } from "@/entities/portfolio";
import { formatDecimal } from "@/shared/lib";
import classes from "../../AccountPage.module.css";
type CurrencyCardsProps = {
amounts: Portfolio["totalsByCurrency"];
};
const CurrencyCards: FC<CurrencyCardsProps> = (props) => {
const { amounts } = props;
const { t } = useTranslation();
const currencies: Record<string, { symbol: string; name: string }> = {
RUB: { symbol: "₽", name: t("portfolio.currencies.RUB") },
USD: { symbol: "$", name: t("portfolio.currencies.USD") },
EUR: { symbol: "€", name: t("portfolio.currencies.EUR") },
};
return (
<SimpleGrid cols={{ base: 1, sm: 2, md: 3 }} spacing={10}>
{amounts.map((money) => {
const amount = formatDecimal(money.value);
return (
<Paper
component="dl"
m={0}
className={classes.total}
key={money.currency}
withBorder
>
<Text component="dt" className={classes.totalBadge}>
<span aria-hidden="true">
{currencies[money.currency]?.symbol ?? money.currency}
</span>
<VisuallyHidden>
{currencies[money.currency]?.name ?? money.currency}
</VisuallyHidden>
</Text>
<Text component="dd" m={0} className={classes.totalAmount}>
{amount.startsWith("-") ? (
<>
<span className={classes.totalLeadingDigits}>
{amount.slice(0, 2)}
</span>
{amount.slice(2)}
</>
) : (
amount
)}{" "}
{currencies[money.currency]?.symbol ?? money.currency}
</Text>
</Paper>
);
})}
</SimpleGrid>
);
};
export { CurrencyCards };
@@ -0,0 +1,57 @@
import { Button, Paper, Stack, Text } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import type { IncomeSummary as IncomeSummaryData } from "@/entities/income";
import { formatMoney } from "@/shared/lib";
type IncomeSummaryProps =
| { state: "loading"; to: string }
| { state: "error"; to: string; retry: () => void }
| { state: "empty"; to: string }
| { state: "loaded"; to: string; summary: IncomeSummaryData };
const IncomeSummary: FC<IncomeSummaryProps> = (props) => {
const { t } = useTranslation();
if (props.state === "loading")
return <Text c="dimmed">{t("income.summaryLoading")}</Text>;
if (props.state === "error")
return (
<StateView
error
title={t("income.summaryError")}
text={t("income.errorText")}
action={
<Button onClick={props.retry}>{t("income.summaryRetry")}</Button>
}
/>
);
if (props.state === "empty")
return (
<Stack gap="xs">
<Text c="dimmed">{t("income.summaryEmpty")}</Text>
<Button component={Link} to={props.to} variant="subtle">
{t("income.open")}
</Button>
</Stack>
);
return (
<Stack gap="xs">
{props.summary.totalsByCurrency.map((total) => (
<Paper key={total.currency} p="sm" withBorder>
<Text fw={700}>{formatMoney(total.total)}</Text>
<Text c="dimmed" size="sm">
{t("income.coupon")}: {formatMoney(total.coupon)} ·{" "}
{t("income.dividend")}: {formatMoney(total.dividend)}
</Text>
</Paper>
))}
<Button component={Link} to={props.to} variant="subtle">
{t("income.open")}
</Button>
</Stack>
);
};
export { IncomeSummary };
@@ -0,0 +1,49 @@
import { Stack } from "@mantine/core";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { fn } from "storybook/test";
import { CurrencyCards } from "../CurrencyCards/CurrencyCards.view";
import { PortfolioRefreshState } from "./PortfolioRefreshState.view";
const meta = {
title: "Product/PortfolioRefreshState",
component: PortfolioRefreshState,
tags: ["autodocs"],
args: { refreshing: false, refreshError: false, retry: fn() },
argTypes: {
refreshing: { control: "boolean" },
refreshError: { control: "boolean" },
retry: { control: false },
},
parameters: {
docs: {
description: {
component:
"Обновление уже показанных данных портфеля. Реальные CurrencyCards остаются видимыми вместе с PortfolioRefreshState при refetch и его ошибке. Суммы синтетические; это presentation Client Cached Snapshot, без QueryClient и запроса API. Retry регистрирует локальное действие в Actions и не доказывает восстановление API.",
},
},
},
render: (args) => (
<Stack>
<CurrencyCards
amounts={[
{ currency: "RUB", value: "125000.50" },
{ currency: "USD", value: "320" },
]}
/>
<PortfolioRefreshState {...args} />
</Stack>
),
} satisfies Meta<typeof PortfolioRefreshState>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Idle: Story = { name: "Сохранённые данные" };
export const Refreshing: Story = {
name: "Фоновое обновление",
args: { refreshing: true },
};
export const RefreshError: Story = {
name: "Ошибка обновления с retry",
args: { refreshError: true },
};
@@ -0,0 +1,40 @@
import { Alert, Button, Group, Loader, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
type PortfolioRefreshStateProps = {
refreshing: boolean;
refreshError: boolean;
retry?: () => void;
};
const PortfolioRefreshState: FC<PortfolioRefreshStateProps> = (props) => {
const { refreshing, refreshError, retry } = props;
const { t } = useTranslation();
if (!refreshing && !refreshError) return null;
return (
<>
{refreshing ? (
<Group gap="xs" role="status" aria-label={t("portfolio.refreshing")}>
<Loader size="sm" />
<Text c="dimmed" size="sm">
{t("portfolio.refreshing")}
</Text>
</Group>
) : null}
{refreshError ? (
<Alert color="orange">
<Stack gap="sm">
<Text>{t("portfolio.refreshError")}</Text>
<Button onClick={retry} variant="light">
{t("accounts.retry")}
</Button>
</Stack>
</Alert>
) : null}
</>
);
};
export { PortfolioRefreshState };
@@ -0,0 +1,72 @@
.section {
padding-block: var(--mantine-spacing-sm);
}
.content {
animation: currency-change 220ms ease-out;
}
@keyframes currency-change {
from {
opacity: 0;
transform: translateY(4px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@media (prefers-reduced-motion: reduce) {
.content {
animation: none;
}
}
.layout {
display: grid;
grid-template-columns: 220px minmax(0, 1fr);
align-items: center;
gap: var(--mantine-spacing-xl);
}
.list {
list-style: none;
padding: 0;
margin: 0;
min-width: 0;
}
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--mantine-spacing-md);
padding-block: var(--mantine-spacing-sm);
}
.marker {
width: 10px;
height: 10px;
border-radius: 50%;
flex-shrink: 0;
}
.values {
min-width: 0;
text-align: right;
font-variant-numeric: tabular-nums;
overflow-wrap: anywhere;
}
@media (max-width: 48em) {
.layout {
grid-template-columns: minmax(0, 1fr);
gap: var(--mantine-spacing-sm);
}
.layout > :first-child {
justify-self: center;
}
}
@@ -0,0 +1,114 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import type { Portfolio } from "@/entities/portfolio";
import { PortfolioStructure } from "./PortfolioStructure";
const rub: Portfolio["structure"]["currencies"][number] = {
currency: "RUB",
totalValue: "1250000",
hasNegativeValues: false,
categories: [
{ type: "STOCK", value: "650000", sharePercent: "52" },
{ type: "BOND", value: "375000", sharePercent: "30" },
{ type: "OTHER", value: "125000", sharePercent: "10" },
{ type: "CASH", value: "100000", sharePercent: "8" },
],
};
const meta = {
title: "Product/PortfolioStructure",
component: PortfolioStructure,
tags: ["autodocs"],
args: { structure: { currencies: [rub], unvaluedCategories: [] } },
parameters: {
docs: {
description: {
component:
"Структура по типам активов, включая доступные деньги. Синтетические серверные суммы и доли, без запросов API и финансовых расчётов на клиенте. При неполной или отрицательной оценке остаётся текстовый список.",
},
},
},
} satisfies Meta<typeof PortfolioStructure>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Regular: Story = {};
export const MultipleCurrencies: Story = {
args: {
structure: {
currencies: [
rub,
{
currency: "USD",
totalValue: "500",
hasNegativeValues: false,
categories: [{ type: "CASH", value: "500", sharePercent: "100" }],
},
],
unvaluedCategories: [],
},
},
};
export const CashOnly: Story = {
args: {
structure: {
currencies: [
{
currency: "RUB",
totalValue: "100000",
hasNegativeValues: false,
categories: rub.categories.map((row) => ({
...row,
value: row.type === "CASH" ? "100000" : "0",
sharePercent: row.type === "CASH" ? "100" : "0",
})),
},
],
unvaluedCategories: [],
},
},
};
export const Empty: Story = {
args: { structure: { currencies: [], unvaluedCategories: [] } },
};
export const Incomplete: Story = {
args: {
structure: {
currencies: [
{
...rub,
categories: rub.categories.map((row) => ({
...row,
sharePercent: null,
})),
},
],
unvaluedCategories: [{ type: "STOCK", count: 2 }],
},
},
};
export const UnknownOnly: Story = {
args: {
structure: {
currencies: [],
unvaluedCategories: [{ type: "BOND", count: 1 }],
},
},
};
export const Negative: Story = {
args: {
structure: {
currencies: [
{
...rub,
hasNegativeValues: true,
totalValue: "1150000",
categories: rub.categories.map((row) => ({
...row,
value: row.type === "OTHER" ? "25000" : row.value,
sharePercent: null,
})),
},
],
unvaluedCategories: [],
},
},
};
@@ -0,0 +1,148 @@
import { MantineProvider } from "@mantine/core";
import { fireEvent, render, screen, within } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import type { Portfolio } from "@/entities/portfolio";
import { PortfolioStructure } from "./PortfolioStructure";
const rub: Portfolio["structure"]["currencies"][number] = {
currency: "RUB",
totalValue: "100",
hasNegativeValues: false,
categories: [
{ type: "STOCK", value: "60", sharePercent: "60" },
{ type: "BOND", value: "20", sharePercent: "20" },
{ type: "OTHER", value: "0", sharePercent: "0" },
{ type: "CASH", value: "20", sharePercent: "20" },
],
};
const ui = (structure: Portfolio["structure"] | null | undefined) => (
<MantineProvider>
<PortfolioStructure structure={structure} />
</MantineProvider>
);
describe("portfolio structure", () => {
it.each([undefined, null])(
"keeps an older snapshot without structure available (%s) and recovers on refresh",
(structure) => {
const view = render(ui(structure));
expect(
screen.getByRole("region", { name: "Структура портфеля" }),
).toHaveTextContent("Данные о структуре портфеля пока недоступны.");
expect(
screen.queryByText(/Нет положительной стоимости/),
).not.toBeInTheDocument();
expect(screen.queryByRole("list")).not.toBeInTheDocument();
view.rerender(ui({ currencies: [rub], unvaluedCategories: [] }));
expect(screen.getByRole("list")).toHaveTextContent("Акции60 ₽60 %");
expect(
screen.queryByText("Данные о структуре портфеля пока недоступны."),
).not.toBeInTheDocument();
},
);
it("shows exact server amounts and cash-inclusive shares without hovering", () => {
render(ui({ currencies: [rub], unvaluedCategories: [] }));
const list = screen.getByRole("list", { name: "Категории активов" });
expect(list).toHaveTextContent("Акции60 ₽60 %");
expect(list).toHaveTextContent("Свободные деньги20 ₽20 %");
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
});
it("switches currencies and falls back when a refresh removes the selection", () => {
const usd = { ...rub, currency: "USD" };
const view = render(ui({ currencies: [rub, usd], unvaluedCategories: [] }));
fireEvent.click(
screen.getByRole("combobox", { name: "Валюта структуры портфеля" }),
);
fireEvent.click(screen.getByRole("option", { name: "USD" }));
expect(screen.getByRole("list")).toHaveTextContent("60 USD");
expect(screen.getByRole("list")).not.toHaveTextContent("₽");
view.rerender(ui({ currencies: [rub], unvaluedCategories: [] }));
expect(screen.getByRole("list")).toHaveTextContent("60 ₽");
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
});
it("retains known amounts and names unvalued categories without inventing a zero", () => {
render(
ui({
currencies: [
{
...rub,
categories: rub.categories.map((row) => ({
...row,
sharePercent: null,
})),
},
],
unvaluedCategories: [
{ type: "OTHER", count: 2 },
{ type: "STOCK", count: 1 },
],
}),
);
expect(screen.getByText(/Оценка неполная/)).toBeInTheDocument();
expect(screen.getByRole("list")).toHaveTextContent("Известно: 60 ₽");
expect(screen.getByRole("list")).toHaveTextContent(
"Другие активыНет оценки",
);
expect(
screen.queryByLabelText(/Структура по типам/),
).not.toBeInTheDocument();
});
it("keeps negative amounts visible without a donut or invented positive shares", () => {
render(
ui({
currencies: [
{
...rub,
hasNegativeValues: true,
categories: rub.categories.map((row) => ({
...row,
value: row.type === "STOCK" ? "-60" : row.value,
sharePercent: null,
})),
},
],
unvaluedCategories: [],
}),
);
expect(screen.getByText(/Есть отрицательные/)).toBeInTheDocument();
expect(screen.getByRole("list")).toHaveTextContent("-60 ₽");
expect(
within(screen.getByRole("list")).getAllByText("Доля недоступна"),
).toHaveLength(4);
expect(
screen.queryByLabelText(/Структура по типам/),
).not.toBeInTheDocument();
});
it("handles unknown-only and empty compositions", () => {
const view = render(
ui({ currencies: [], unvaluedCategories: [{ type: "BOND", count: 1 }] }),
);
expect(screen.getByText("Облигации: без оценки — 1")).toBeInTheDocument();
expect(screen.queryByRole("list")).not.toBeInTheDocument();
view.rerender(ui({ currencies: [], unvaluedCategories: [] }));
expect(screen.getByText(/Нет положительной стоимости/)).toBeInTheDocument();
});
it("keeps full decimal amounts and describes tiny shares", () => {
render(
ui({
currencies: [
{
...rub,
categories: [
{
type: "CASH",
value: "9007199254740993.000000001",
sharePercent: "0.000001",
},
],
},
],
unvaluedCategories: [],
}),
);
expect(screen.getByRole("list")).toHaveTextContent(
"9 007 199 254 740 993,000000001 ₽",
);
expect(screen.getByRole("list")).toHaveTextContent("< 0,01 %");
});
});
@@ -0,0 +1,80 @@
import { type FC, useState } from "react";
import { useTranslation } from "react-i18next";
import type { Portfolio } from "@/entities/portfolio";
import { formatMoney } from "@/shared/lib";
import { PortfolioStructureView } from "./PortfolioStructure.view";
const MIN_VISIBLE_SHARE_PERCENT = 0.01;
// A cached snapshot or an older running server can predate this response field.
type PortfolioStructureProps = { structure?: Portfolio["structure"] | null };
const categoryPresentation = {
STOCK: { label: "portfolio.stocks", color: "blue.6" },
BOND: { label: "portfolio.bonds", color: "grape.6" },
OTHER: { label: "portfolio.structure.other", color: "orange.6" },
CASH: { label: "portfolio.structure.cash", color: "green.6" },
} as const;
const PortfolioStructure: FC<PortfolioStructureProps> = (props) => {
const { structure } = props;
const { t } = useTranslation();
const [currency, setCurrency] = useState<string | null>(null);
const selected =
structure?.currencies.find((item) => item.currency === currency) ??
structure?.currencies[0];
const incomplete = (structure?.unvaluedCategories.length ?? 0) > 0;
const rows = selected
? selected.categories.map((category) => {
const presentation = categoryPresentation[category.type];
const percentage =
category.sharePercent === null ? null : Number(category.sharePercent);
const unknown = structure?.unvaluedCategories.some(
(item) => item.type === category.type,
);
const amount = formatMoney({
currency: selected.currency,
value: category.value,
});
return {
name: t(presentation.label),
color: presentation.color,
amount: unknown
? category.value === "0"
? t("portfolio.structure.unvalued")
: t("portfolio.structure.knownAmount", { amount })
: amount,
share:
percentage === null
? t("portfolio.structure.shareUnavailable")
: percentage > 0 && percentage < MIN_VISIBLE_SHARE_PERCENT
? t("portfolio.structure.smallShare")
: `${new Intl.NumberFormat("ru-RU", { maximumFractionDigits: 2 }).format(percentage)} %`,
value: percentage ?? 0,
};
})
: [];
const chartData = rows.filter((row) => row.value > 0);
return (
<PortfolioStructureView
unavailable={!structure}
currencies={structure?.currencies.map((item) => item.currency) ?? []}
currency={selected?.currency ?? null}
onCurrencyChange={setCurrency}
rows={rows}
chartData={chartData}
incomplete={incomplete}
negative={selected?.hasNegativeValues ?? false}
unvalued={
structure?.unvaluedCategories.map((category) =>
t("portfolio.structure.unvaluedCategory", {
category: t(categoryPresentation[category.type].label),
count: category.count,
}),
) ?? []
}
/>
);
};
export { PortfolioStructure };
@@ -0,0 +1,147 @@
import { DonutChart } from "@mantine/charts";
import { Box, Group, Paper, Select, Stack, Text, Title } from "@mantine/core";
import { type FC, useId } from "react";
import { useTranslation } from "react-i18next";
import classes from "./PortfolioStructure.module.css";
type StructureRow = {
name: string;
color: string;
amount: string;
share: string;
value: number;
};
type PortfolioStructureViewProps = {
unavailable: boolean;
currencies: string[];
currency: string | null;
onCurrencyChange: (currency: string | null) => void;
rows: StructureRow[];
chartData: StructureRow[];
incomplete: boolean;
negative: boolean;
unvalued: string[];
};
const PortfolioStructureView: FC<PortfolioStructureViewProps> = (props) => {
const { t } = useTranslation();
const titleId = useId();
return (
<Stack
component="section"
aria-labelledby={titleId}
gap="md"
className={classes.section}
>
<Group justify="space-between" align="center">
<Title order={2} size="h4" id={titleId}>
{t("portfolio.structure.title")}
</Title>
{props.currencies.length > 1 ? (
<Select
aria-label={t("portfolio.structure.currency")}
data={props.currencies}
value={props.currency}
onChange={props.onCurrencyChange}
allowDeselect={false}
w={112}
/>
) : null}
</Group>
<Text size="sm" c="dimmed">
{t(
props.unavailable
? "portfolio.structure.unavailable"
: "portfolio.structure.basis",
)}
</Text>
{props.incomplete ? (
<Stack gap={4}>
<Text size="sm">{t("portfolio.structure.incomplete")}</Text>
{props.unvalued.map((message) => (
<Text size="sm" c="dimmed" key={message}>
{message}
</Text>
))}
</Stack>
) : null}
{props.negative ? (
<Text size="sm">{t("portfolio.structure.negative")}</Text>
) : null}
{!props.unavailable &&
!props.chartData.length &&
!props.incomplete &&
!props.negative ? (
<Text size="sm" c="dimmed">
{t("portfolio.structure.empty")}
</Text>
) : null}
<div
key={props.currency}
className={`${classes.content} ${props.chartData.length ? classes.layout : ""}`}
>
{props.chartData.length ? (
<DonutChart
data={props.chartData}
size={220}
thickness={32}
strokeWidth={2}
startAngle={90}
endAngle={-270}
chartLabel={props.currency ?? undefined}
tooltipDataSource="segment"
pieProps={{ isAnimationActive: false }}
pieChartProps={{ title: t("portfolio.structure.chartLabel") }}
aria-label={t("portfolio.structure.chartLabel")}
tooltipProps={{
content: ({ active, payload }) => {
const row = props.chartData.find(
(item) => item.name === payload?.[0]?.name,
);
return active && row ? (
<Paper shadow="sm" p="sm" radius="md">
<Text size="sm" fw={600}>
{row.name}
</Text>
<Text size="sm">
{row.amount} · {row.share}
</Text>
</Paper>
) : null;
},
}}
/>
) : null}
{props.rows.length ? (
<ul
className={classes.list}
aria-label={t("portfolio.structure.categories")}
>
{props.rows.map((row) => (
<li key={row.name} className={classes.row}>
<Group gap="xs" wrap="nowrap">
<Box
aria-hidden="true"
bg={row.color}
className={classes.marker}
/>
<Text size="sm">{row.name}</Text>
</Group>
<div className={classes.values}>
<Text size="sm" fw={600}>
{row.amount}
</Text>
<Text size="sm" c="dimmed">
{row.share}
</Text>
</div>
</li>
))}
</ul>
) : null}
</div>
</Stack>
);
};
export { PortfolioStructureView };
@@ -0,0 +1,134 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import type { AccountPagePosition } from "../../AccountPage.vm";
import { PositionCard } from "./PositionCard.view";
const syntheticPosition = {
figi: null,
displayName: "Учебные технологии",
type: "STOCK",
quantity: "100",
currentValue: { currency: "RUB", value: "25000" },
averagePurchasePrice: { currency: "RUB", value: "200" },
absoluteReturn: { currency: "RUB", value: "5000" },
isin: null,
ticker: "DEMO",
logoName: null,
shareText: "20%",
returnText: "+5 000 ₽",
returnTone: "positive",
logoSrc: null,
} satisfies AccountPagePosition;
const meta = {
title: "Product/PositionCard",
component: PositionCard,
tags: ["autodocs"],
argTypes: {
kind: {
control: "inline-radio",
options: ["stocks", "bonds", "other"],
},
position: { control: false },
},
parameters: {
docs: {
description: {
component:
"Позиция портфеля WealthLedger: количество, стоимость, результат и доля. Доля и текст результата поступают готовыми из модели представления. Карточка не рассчитывает доходность. Все данные вымышлены; логотип заменён буквенным обозначением.",
},
},
},
args: { kind: "stocks", position: syntheticPosition },
} satisfies Meta<typeof PositionCard>;
export default meta;
type Story = StoryObj<typeof meta>;
export const StockGain: Story = {
name: "Акция с положительным результатом",
parameters: {
docs: {
description: {
story:
"Развёрнутая карточка акции показывает тикер, оценку позиции и положительный результат. Цвет дополняет знак суммы.",
},
},
},
};
export const BondLoss: Story = {
name: "Облигация с отрицательным результатом",
args: {
kind: "bonds",
position: {
...syntheticPosition,
displayName: "Учебные облигации для долгосрочных накоплений, выпуск 2030",
type: "BOND",
quantity: "10",
currentValue: { currency: "RUB", value: "9500" },
averagePurchasePrice: { currency: "RUB", value: "1000" },
absoluteReturn: { currency: "RUB", value: "-500" },
isin: "DEMO-BOND-2030",
ticker: null,
shareText: "7,6%",
returnText: "−500 ₽",
returnTone: "negative",
},
},
parameters: {
docs: {
description: {
story:
"Для облигации используется идентификатор выпуска. Длинное имя и отрицательная сумма позволяют проверить компактное представление на узком экране.",
},
},
},
};
export const Other: Story = {
name: "Прочий инструмент",
args: {
kind: "other",
position: {
...syntheticPosition,
displayName: "Учебный фонд",
type: "FUND",
isin: "DEMO-FUND",
ticker: null,
},
},
parameters: {
docs: {
description: {
story:
"Компактный вариант для остальных инструментов сохраняет количество, стоимость и пояснение результата без оформления акции или облигации.",
},
},
},
};
export const MissingValuation: Story = {
name: "Оценка и идентификаторы отсутствуют",
args: {
position: {
...syntheticPosition,
displayName: "Учебная позиция без текущей оценки",
currentValue: null,
averagePurchasePrice: null,
absoluteReturn: null,
ticker: null,
shareText: null,
returnText: null,
returnTone: undefined,
},
},
parameters: {
docs: {
description: {
story:
"При отсутствии оценки остаются название и количество. Неизвестная стоимость, доля и результат не изображаются нулевыми значениями.",
},
},
},
};
@@ -0,0 +1,159 @@
import { Anchor, Card, Group, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { formatMoney } from "@/shared/lib";
import classes from "../../AccountPage.module.css";
import type {
AccountPagePosition,
AccountPagePositionSection,
} from "../../AccountPage.vm";
import { PositionLogo } from "../PositionLogo.view";
type PositionCardProps = {
kind: AccountPagePositionSection["kind"];
position: AccountPagePosition;
};
const PositionCard: FC<PositionCardProps> = (props) => {
const { kind, position } = props;
const { t } = useTranslation();
const isExpanded = kind !== "other";
const returnClass = position.returnTone
? classes[position.returnTone]
: undefined;
const returnText =
position.returnText && isExpanded
? position.returnText
: position.returnText
? t("portfolio.return", {
value: position.returnText,
})
: null;
const instrumentTo = position.instrumentTo;
const identifier =
kind === "stocks" ? (position.ticker ?? position.isin) : position.isin;
const identifierText = [
t("portfolio.quantity", { value: position.quantity }),
identifier,
]
.filter(Boolean)
.join(" · ");
const accountLink = position.account ? (
<Anchor
component={Link}
to={`/accounts/${encodeURIComponent(position.account.id)}`}
size="xs"
>
{position.account.name}
</Anchor>
) : null;
const secondaryText = [
position.averagePurchasePrice
? t("portfolio.avgPrice", {
value: formatMoney(position.averagePurchasePrice),
})
: null,
position.shareText
? t("portfolio.share", { value: position.shareText })
: null,
]
.filter(Boolean)
.join(" · ");
if (isExpanded)
return (
<Card className={`${classes.tile} ${classes.expandedCard}`} withBorder>
<div className={classes.expandedMain}>
<PositionLogo
key={position.logoSrc ?? "no-logo"}
src={position.logoSrc}
label={position.displayName}
to={instrumentTo}
/>
<Stack gap={2} miw={0} className={classes.expandedIdentity}>
{instrumentTo ? (
<Anchor component={Link} to={instrumentTo} c="inherit" fw={600}>
{position.displayName}
</Anchor>
) : (
<Text fw={600} lineClamp={1}>
{position.displayName}
</Text>
)}
{accountLink}
<Text c="dimmed" size="xs" className={classes.expandedIdentifiers}>
{identifierText}
</Text>
</Stack>
<Stack gap={2} align="flex-end" className={classes.expandedValue}>
{position.currentValue ? (
<Text fw={700} size="lg">
{formatMoney(position.currentValue)}
</Text>
) : null}
{returnText ? (
<Text size="sm" fw={600} className={returnClass}>
{returnText}
</Text>
) : null}
</Stack>
</div>
{secondaryText ? (
<Text c="dimmed" size="xs" className={classes.expandedMeta}>
{secondaryText}
</Text>
) : null}
</Card>
);
return (
<Card className={classes.tile} withBorder>
<Group justify="space-between" align="flex-start" wrap="nowrap">
<Stack gap={2} miw={0}>
<Text fw={700} lineClamp={1}>
{position.displayName}
</Text>
{accountLink}
{position.isin ? (
<Text c="dimmed" size="xs" className={classes.mono}>
{position.isin}
</Text>
) : null}
<Text c="dimmed" size="xs">
{t("portfolio.quantity", { value: position.quantity })}
</Text>
</Stack>
<Stack gap={2} align="flex-end">
{position.currentValue ? (
<Text fw={800} size="lg">
{formatMoney(position.currentValue)}
</Text>
) : null}
{returnText ? (
<Text size="sm" fw={600} className={returnClass}>
{returnText}
</Text>
) : null}
</Stack>
</Group>
{position.averagePurchasePrice || position.shareText ? (
<Group justify="space-between" mt="xs">
{position.averagePurchasePrice ? (
<Text c="dimmed" size="xs">
{t("portfolio.avgPrice", {
value: formatMoney(position.averagePurchasePrice),
})}
</Text>
) : null}
{position.shareText ? (
<Text c="dimmed" size="xs">
{t("portfolio.share", { value: position.shareText })}
</Text>
) : null}
</Group>
) : null}
</Card>
);
};
export { PositionCard };
@@ -0,0 +1,115 @@
import { Anchor, Card, Group, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { formatMoney } from "@/shared/lib";
import classes from "../AccountPage.module.css";
import type {
AccountPagePositionGroup,
AccountPagePositionSection,
} from "../AccountPage.vm";
import { PositionLogo } from "./PositionLogo.view";
type PositionGroupCardProps = {
group: AccountPagePositionGroup;
kind: AccountPagePositionSection["kind"];
};
const PositionGroupCard: FC<PositionGroupCardProps> = (props) => {
const { group, kind } = props;
const { t } = useTranslation();
const identity = group.positions[0];
const instrumentTo = identity.instrumentTo;
return (
<Card className={classes.tile} withBorder>
<Group wrap="nowrap" gap="sm">
{kind !== "other" ? (
<PositionLogo
key={identity.logoSrc ?? "no-logo"}
src={identity.logoSrc}
label={identity.displayName}
to={instrumentTo}
/>
) : null}
<Stack gap={2} miw={0}>
{instrumentTo ? (
<Anchor component={Link} to={instrumentTo} c="inherit" fw={600}>
{identity.displayName}
</Anchor>
) : (
<Text fw={600}>{identity.displayName}</Text>
)}
<Text c="dimmed" size="xs">
{identity.ticker ?? identity.isin ?? identity.figi}
</Text>
</Stack>
</Group>
<Stack
component="ul"
gap={0}
className={classes.accountPositions}
aria-label={t("portfolio.byAccount")}
>
{group.positions.map((position) => (
<Stack
component="li"
key={position.account?.id}
gap={4}
className={classes.accountPosition}
>
<Group justify="space-between" align="flex-start" gap="xs">
{position.account ? (
<Anchor
component={Link}
to={`/accounts/${encodeURIComponent(position.account.id)}`}
size="sm"
className={classes.accountPositionName}
>
{position.account.name}
</Anchor>
) : null}
<Text size="sm" fw={600}>
{t("portfolio.quantity", { value: position.quantity })}
</Text>
</Group>
<Group justify="space-between" gap="xs">
{position.currentValue ? (
<Text size="sm">{formatMoney(position.currentValue)}</Text>
) : null}
{position.returnText ? (
<Text
size="sm"
className={
position.returnTone
? classes[position.returnTone]
: undefined
}
>
{kind === "other"
? t("portfolio.return", { value: position.returnText })
: position.returnText}
</Text>
) : null}
</Group>
<Group gap="xs">
{position.averagePurchasePrice ? (
<Text c="dimmed" size="xs">
{t("portfolio.avgPrice", {
value: formatMoney(position.averagePurchasePrice),
})}
</Text>
) : null}
{position.shareText ? (
<Text c="dimmed" size="xs">
{t("portfolio.share", { value: position.shareText })}
</Text>
) : null}
</Group>
</Stack>
))}
</Stack>
</Card>
);
};
export { PositionGroupCard };
@@ -0,0 +1,47 @@
import { Anchor, Avatar } from "@mantine/core";
import type { FC } from "react";
import { useState } from "react";
import { Link } from "react-router";
type PositionLogoProps = {
src: string | null;
label: string;
to?: string;
};
const PositionLogo: FC<PositionLogoProps> = (props) => {
const { src, label } = props;
const [failed, setFailed] = useState(false);
const logo =
src && !failed ? (
<Avatar
src={src}
alt={label}
size={40}
radius="md"
onError={() => setFailed(true)}
/>
) : (
<Avatar size={40} radius="md">
{(label.trim()[0] ?? "?").toUpperCase()}
</Avatar>
);
return props.to ? (
<Anchor
component={Link}
to={props.to}
aria-label={label}
c="inherit"
underline="never"
display="block"
style={{ borderRadius: "var(--mantine-radius-md)" }}
>
{logo}
</Anchor>
) : (
logo
);
};
export { PositionLogo };
@@ -0,0 +1,36 @@
import { SimpleGrid } from "@mantine/core";
import type { FC } from "react";
import type { AccountPagePositionSection } from "../AccountPage.vm";
import { PositionCard } from "./PositionCard/PositionCard.view";
import { PositionGroupCard } from "./PositionGroupCard.view";
type PositionSectionProps = {
section: AccountPagePositionSection;
};
const PositionSection: FC<PositionSectionProps> = (props) => {
const { section } = props;
const expanded = section.kind !== "other";
return (
<SimpleGrid cols={expanded ? 1 : { base: 1, sm: 2, md: 3 }}>
{section.groups.map((group) =>
group.positions.length > 1 ? (
<PositionGroupCard
key={group.key}
group={group}
kind={section.kind}
/>
) : (
<PositionCard
key={group.key}
position={group.positions[0]}
kind={section.kind}
/>
),
)}
</SimpleGrid>
);
};
export { PositionSection };
@@ -0,0 +1,51 @@
import { Alert, Button, Skeleton, Stack, Text } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { LedgerEntryRow } from "@/entities/broker-operation";
import type { AccountPageRecentOperations } from "../AccountPage.vm";
type RecentOperationsProps = {
operations: AccountPageRecentOperations;
};
const RecentOperations: FC<RecentOperationsProps> = (props) => {
const { operations } = props;
const { t } = useTranslation();
return (
<Stack gap="sm">
{operations.state === "loading" ? (
<LoadingSkeleton label={t("ledger.recentLoading")}>
{[0, 1, 2].map((index) => (
<Skeleton key={index} height={48} radius="sm" />
))}
</LoadingSkeleton>
) : null}
{operations.state === "error" ? (
<Alert color="red">{t("ledger.recentError")}</Alert>
) : null}
{operations.state === "empty" ? (
<Text c="dimmed">{t("ledger.recentEmpty")}</Text>
) : null}
{operations.state === "loaded"
? operations.items.map((operation) => (
<LedgerEntryRow
key={JSON.stringify([
operation.account?.id,
operation.id,
operation.logoName,
])}
operation={operation}
/>
))
: null}
<Button component={Link} to={operations.to} variant="subtle">
{t("ledger.open")}
</Button>
</Stack>
);
};
export { RecentOperations };