feat: improve ledger event rows

This commit is contained in:
2026-08-26 15:03:48 +03:00
parent c1a8674f16
commit 488ccad540
12 changed files with 480 additions and 193 deletions
+1
View File
@@ -4,3 +4,4 @@ export {
operationCategories,
useBrokerageOperations,
} from "./api/useBrokerageOperations";
export { LedgerEntryRow } from "./ui/LedgerEntryRow";
@@ -0,0 +1,42 @@
.row {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
gap: var(--mantine-spacing-sm);
align-items: center;
padding: var(--mantine-spacing-md);
border-color: var(--mantine-color-gray-3);
background: var(--mantine-color-gray-0);
}
.identity,
.amount {
min-width: 0;
}
.amount {
text-align: right;
white-space: nowrap;
}
.positive {
color: var(--mantine-color-green-6);
}
.negative {
color: var(--mantine-color-red-6);
}
.neutral {
color: var(--mantine-color-dimmed);
}
@media (max-width: 36em) {
.row {
grid-template-columns: auto minmax(0, 1fr);
}
.amount {
grid-column: 2;
text-align: left;
}
}
@@ -0,0 +1,100 @@
import { Avatar, Paper, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import {
formatMoney,
formatSnapshotTime,
instrumentLogoUrl,
} from "@/entities/portfolio";
import type { BrokerageOperation } from "../api/useBrokerageOperations";
import classes from "./LedgerEntryRow.module.css";
type LedgerEntryRowProps = {
operation: BrokerageOperation;
};
type PaymentPresentation = {
amount: string;
direction: "incoming" | "outgoing" | "neutral";
tone: "positive" | "negative" | "neutral";
};
const LedgerEntryRow: FC<LedgerEntryRowProps> = (props) => {
const { operation } = props;
const { t } = useTranslation();
const [imageFailed, setImageFailed] = useState(false);
const instrument =
operation.ticker ?? operation.instrumentType ?? t("ledger.noInstrument");
const logoSrc = imageFailed ? null : instrumentLogoUrl(operation.logoName);
const payment = paymentPresentation(operation);
const metadata = [
formatSnapshotTime(operation.occurredAt),
instrument,
t(`ledger.category.${operation.category}`),
].join(" · ");
return (
<Paper className={classes.row} withBorder>
<Avatar
alt=""
aria-hidden="true"
radius="md"
size={40}
src={logoSrc}
onError={() => setImageFailed(true)}
>
{(instrument.trim()[0] ?? "?").toUpperCase()}
</Avatar>
<Stack className={classes.identity} gap={2}>
<Text fw={700} lineClamp={1}>
{operation.description || operation.type}
</Text>
<Text c="dimmed" size="sm">
{metadata}
</Text>
</Stack>
<Stack className={classes.amount} gap={2}>
<Text className={classes[payment.tone]} fw={700}>
{payment.amount}
</Text>
<Text className={classes[payment.tone]} size="sm">
{t(`ledger.direction.${payment.direction}`)}
</Text>
</Stack>
</Paper>
);
};
function paymentPresentation(
operation: BrokerageOperation,
): PaymentPresentation {
if (!operation.payment)
return { amount: "—", direction: "neutral", tone: "neutral" };
if (isZeroDecimal(operation.payment.value))
return {
amount: formatMoney(operation.payment),
direction: "neutral",
tone: "neutral",
};
if (operation.payment.value.startsWith("-"))
return {
amount: `−${formatMoney({
...operation.payment,
value: operation.payment.value.slice(1),
})}`,
direction: "outgoing",
tone: "negative",
};
return {
amount: `+${formatMoney(operation.payment)}`,
direction: "incoming",
tone: "positive",
};
}
function isZeroDecimal(value: string): boolean {
return /^-?0(?:\.0+)?$/.test(value);
}
export { LedgerEntryRow };
@@ -1,6 +1,12 @@
import { MantineProvider } from "@mantine/core";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import {
cleanup,
fireEvent,
render,
screen,
waitFor,
} from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { MemoryRouter, Route, Routes } from "react-router";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -19,6 +25,7 @@ const operation: BrokerageOperation = {
instrumentUid: null,
ticker: "SBER",
instrumentType: "share",
logoName: null,
payment: null,
quantity: "2",
price: { currency: "RUB", value: "100" },
@@ -34,6 +41,8 @@ function configureTestAuth() {
});
}
afterEach(cleanup);
describe("OperationRow", () => {
it("marks cashless operations without rendering operation details", () => {
render(
@@ -51,6 +60,54 @@ describe("OperationRow", () => {
expect(screen.queryByText("Цена: 100 ₽")).toBeNull();
expect(screen.queryByText("Количество: 2")).toBeNull();
});
it("labels a positive payment as a Russian incoming amount", () => {
render(
<MantineProvider>
<MemoryRouter>
<OperationRow
operation={{
...operation,
payment: { currency: "RUB", value: "15" },
}}
/>
</MemoryRouter>
</MantineProvider>,
);
expect(screen.getByText("Поступление")).toBeInTheDocument();
expect(screen.getByText("+15 ₽")).toBeInTheDocument();
});
it("keeps a zero payment neutral", () => {
render(
<MantineProvider>
<MemoryRouter>
<OperationRow
operation={{
...operation,
payment: { currency: "RUB", value: "0" },
}}
/>
</MemoryRouter>
</MantineProvider>,
);
expect(screen.getByText("Без движения денег")).toBeInTheDocument();
expect(screen.queryByText("Поступление")).toBeNull();
});
it("uses an instrument initial when the ledger entry has no logo", () => {
render(
<MantineProvider>
<MemoryRouter>
<OperationRow operation={operation} />
</MemoryRouter>
</MantineProvider>,
);
expect(screen.getByText("S")).toBeInTheDocument();
});
});
describe("AccountOperationsPage", () => {
@@ -1,188 +1,19 @@
import {
Button,
Card,
Checkbox,
Group,
Stack,
Text,
TextInput,
Title,
} from "@mantine/core";
import type { FC } from "react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router";
import { LedgerEntryRow } from "@/entities/broker-operation";
import {
type BrokerageOperation,
type OperationCategory,
operationCategories,
useBrokerageOperations,
} from "@/entities/broker-operation";
import { formatMoney, formatSnapshotTime } from "@/entities/portfolio";
import { StateView } from "@/shared/ui";
function dateStart(value: string) {
return value ? `${value}T00:00:00.000Z` : undefined;
}
function dateEnd(value: string) {
return value ? `${value}T23:59:59.999Z` : undefined;
}
type OperationRowProps = {
operation: BrokerageOperation;
};
AccountOperationsPageError,
AccountOperationsPageLoaded,
AccountOperationsPageLoading,
} from "./AccountOperationsPage.view";
import { useAccountOperationsPageVm } from "./AccountOperationsPage.vm";
const AccountOperationsPage: FC = () => {
const { accountId } = useParams();
const { t } = useTranslation();
const [from, setFrom] = useState("");
const [to, setTo] = useState("");
const [categories, setCategories] = useState<OperationCategory[]>([]);
const [cursors, setCursors] = useState<string[]>([]);
const cursor = cursors.at(-1);
const operations = useBrokerageOperations(accountId, {
from: dateStart(from),
to: dateEnd(to),
...(categories.length ? { categories } : {}),
...(cursor ? { cursor } : {}),
limit: 100,
});
const reset = () => setCursors([]);
const viewModel = useAccountOperationsPageVm();
if (operations.isLoading)
return (
<StateView
loading
title={t("states.loadingTitle")}
text={t("states.loadingText")}
/>
);
if (operations.isError)
return (
<StateView
error
title={t("ledger.errorTitle")}
text={t("ledger.errorText")}
action={
<Button onClick={() => operations.refetch()}>
{t("ledger.retry")}
</Button>
}
/>
);
if (!operations.data)
return (
<StateView
loading
title={t("states.loadingTitle")}
text={t("states.loadingText")}
/>
);
const { data } = operations;
const nextCursor = data.nextCursor;
return (
<Stack maw={960} gap="lg">
<Title order={1}>{t("ledger.title")}</Title>
<Group align="end">
<TextInput
label={t("ledger.from")}
type="date"
value={from}
onChange={(event) => {
setFrom(event.currentTarget.value);
reset();
}}
/>
<TextInput
label={t("ledger.to")}
type="date"
value={to}
onChange={(event) => {
setTo(event.currentTarget.value);
reset();
}}
/>
</Group>
<Checkbox.Group
label={t("ledger.categories")}
value={categories}
onChange={(value) => {
setCategories(value as OperationCategory[]);
reset();
}}
>
<Group mt="xs">
{operationCategories.map((category) => (
<Checkbox
key={category}
value={category}
label={t(`ledger.category.${category}`)}
/>
))}
</Group>
</Checkbox.Group>
{data.items.length ? (
data.items.map((operation) => (
<OperationRow key={operation.id} operation={operation} />
))
) : (
<StateView
title={t("ledger.emptyTitle")}
text={t("ledger.emptyText")}
/>
)}
{data.hasNext || cursors.length ? (
<Group justify="space-between">
<Button
disabled={!cursors.length}
onClick={() => setCursors((value) => value.slice(0, -1))}
>
{t("ledger.previous")}
</Button>
<Button
disabled={!data.hasNext || !nextCursor}
onClick={() => {
if (nextCursor) setCursors((value) => [...value, nextCursor]);
}}
>
{t("ledger.next")}
</Button>
</Group>
) : null}
</Stack>
);
if (viewModel.state === "loading") return <AccountOperationsPageLoading />;
if (viewModel.state === "error")
return <AccountOperationsPageError {...viewModel} />;
return <AccountOperationsPageLoaded {...viewModel} />;
};
const OperationRow: FC<OperationRowProps> = (props) => {
const { operation } = props;
const { t } = useTranslation();
return (
<Card withBorder>
<Group justify="space-between" align="flex-start">
<Stack gap={2}>
<Text fw={700}>{operation.description || operation.type}</Text>
<Text c="dimmed" size="sm">
{formatSnapshotTime(operation.occurredAt)} ·{" "}
{operation.ticker ??
operation.instrumentType ??
t("ledger.noInstrument")}
</Text>
</Stack>
<Stack gap={2} align="end">
<Text fw={700}>
{operation.payment
? formatMoney(operation.payment)
: t("ledger.noMoney")}
</Text>
<Text c="dimmed" size="sm">
{t(`ledger.category.${operation.category}`)}
</Text>
</Stack>
</Group>
</Card>
);
};
export { AccountOperationsPage, OperationRow };
export { AccountOperationsPage, LedgerEntryRow as OperationRow };
@@ -0,0 +1,135 @@
import {
Button,
Checkbox,
Group,
Stack,
TextInput,
Title,
} from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import {
LedgerEntryRow,
type OperationCategory,
operationCategories,
} from "@/entities/broker-operation";
import { StateView } from "@/shared/ui";
import type { AccountOperationsPageViewModel } from "./AccountOperationsPage.vm";
type AccountOperationsPageLoadedProps = Extract<
AccountOperationsPageViewModel,
{ state: "loaded" }
>;
type AccountOperationsPageErrorProps = Extract<
AccountOperationsPageViewModel,
{ state: "error" }
>;
const AccountOperationsPageLoading: FC = () => {
const { t } = useTranslation();
return (
<StateView
loading
title={t("states.loadingTitle")}
text={t("states.loadingText")}
/>
);
};
const AccountOperationsPageError: FC<AccountOperationsPageErrorProps> = (
props,
) => {
const { retry } = props;
const { t } = useTranslation();
return (
<StateView
error
title={t("ledger.errorTitle")}
text={t("ledger.errorText")}
action={<Button onClick={retry}>{t("ledger.retry")}</Button>}
/>
);
};
const AccountOperationsPageLoaded: FC<AccountOperationsPageLoadedProps> = (
props,
) => {
const {
categories,
from,
hasNext,
hasPrevious,
items,
onCategoriesChange,
onFromChange,
onNext,
onPrevious,
onToChange,
to,
} = props;
const { t } = useTranslation();
return (
<Stack maw={960} gap="lg">
<Title order={1}>{t("ledger.title")}</Title>
<Group align="end">
<TextInput
label={t("ledger.from")}
type="date"
value={from}
onChange={(event) => onFromChange(event.currentTarget.value)}
/>
<TextInput
label={t("ledger.to")}
type="date"
value={to}
onChange={(event) => onToChange(event.currentTarget.value)}
/>
</Group>
<Checkbox.Group
label={t("ledger.categories")}
value={categories}
onChange={(value) => onCategoriesChange(value as OperationCategory[])}
>
<Group mt="xs">
{operationCategories.map((category) => (
<Checkbox
key={category}
value={category}
label={t(`ledger.category.${category}`)}
/>
))}
</Group>
</Checkbox.Group>
{items.length ? (
items.map((operation) => (
<LedgerEntryRow key={operation.id} operation={operation} />
))
) : (
<StateView
title={t("ledger.emptyTitle")}
text={t("ledger.emptyText")}
/>
)}
{hasNext || hasPrevious ? (
<Group justify="space-between">
<Button disabled={!hasPrevious} onClick={onPrevious}>
{t("ledger.previous")}
</Button>
<Button disabled={!hasNext} onClick={onNext}>
{t("ledger.next")}
</Button>
</Group>
) : null}
</Stack>
);
};
export {
AccountOperationsPageError,
AccountOperationsPageLoaded,
AccountOperationsPageLoading,
};
@@ -0,0 +1,84 @@
import { useState } from "react";
import { useParams } from "react-router";
import {
type BrokerageOperation,
type OperationCategory,
useBrokerageOperations,
} from "@/entities/broker-operation";
type AccountOperationsPageViewModel =
| { state: "loading" }
| { state: "error"; retry: () => void }
| {
state: "loaded";
from: string;
to: string;
categories: OperationCategory[];
items: BrokerageOperation[];
hasNext: boolean;
hasPrevious: boolean;
onFromChange: (value: string) => void;
onToChange: (value: string) => void;
onCategoriesChange: (value: OperationCategory[]) => void;
onNext: () => void;
onPrevious: () => void;
};
const useAccountOperationsPageVm = (): AccountOperationsPageViewModel => {
const { accountId } = useParams();
const [from, setFrom] = useState("");
const [to, setTo] = useState("");
const [categories, setCategories] = useState<OperationCategory[]>([]);
const [cursors, setCursors] = useState<string[]>([]);
const cursor = cursors.at(-1);
const operations = useBrokerageOperations(accountId, {
from: dateStart(from),
to: dateEnd(to),
...(categories.length ? { categories } : {}),
...(cursor ? { cursor } : {}),
limit: 100,
});
const reset = () => setCursors([]);
if (operations.isLoading) return { state: "loading" };
if (operations.isError)
return { state: "error", retry: () => operations.refetch() };
if (!operations.data) return { state: "loading" };
const nextCursor = operations.data.nextCursor;
return {
state: "loaded",
from,
to,
categories,
items: operations.data.items,
hasNext: Boolean(operations.data.hasNext && nextCursor),
hasPrevious: Boolean(cursors.length),
onFromChange: (value) => {
setFrom(value);
reset();
},
onToChange: (value) => {
setTo(value);
reset();
},
onCategoriesChange: (value) => {
setCategories(value);
reset();
},
onNext: () => {
if (nextCursor) setCursors((value) => [...value, nextCursor]);
},
onPrevious: () => setCursors((value) => value.slice(0, -1)),
};
};
function dateStart(value: string) {
return value ? `${value}T00:00:00.000Z` : undefined;
}
function dateEnd(value: string) {
return value ? `${value}T23:59:59.999Z` : undefined;
}
export { type AccountOperationsPageViewModel, useAccountOperationsPageVm };
+34
View File
@@ -399,6 +399,40 @@ describe("AccountPage states", () => {
expect(screen.getByText("Вторая")).toBeInTheDocument();
});
it("uses the ledger row for a recent outgoing operation", () => {
renderPage(
<AccountPageLoaded
{...loadedProps()}
recentOperations={{
state: "loaded",
to: "/accounts/account-1/operations",
items: [
{
id: "operation-1",
occurredAt: "2026-08-14T10:00:00Z",
type: "OPERATION_TYPE_BUY",
category: "trade",
description: "Покупка акции",
figi: "FIGI-1",
instrumentUid: "UID-1",
ticker: "SBER",
instrumentType: "share",
logoName: null,
payment: { currency: "RUB", value: "-12" },
quantity: null,
price: null,
accruedInterest: null,
commission: null,
},
],
}}
/>,
);
expect(screen.getByText("Списание")).toBeInTheDocument();
expect(screen.getByText("−12 ₽")).toBeInTheDocument();
});
it("keeps the portfolio visible when upcoming events fail", () => {
renderPage(
<AccountPageLoaded
@@ -1,9 +1,8 @@
import { Alert, Button, Paper, Stack, Text } from "@mantine/core";
import { Alert, Button, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { formatMoney } from "@/entities/portfolio";
import classes from "../AccountPage.module.css";
import { LedgerEntryRow } from "@/entities/broker-operation";
import type { AccountPageRecentOperations } from "../AccountPage.vm";
type RecentOperationsProps = {
@@ -27,14 +26,7 @@ const RecentOperations: FC<RecentOperationsProps> = (props) => {
) : null}
{operations.state === "loaded"
? operations.items.map((operation) => (
<Paper className={classes.cash} key={operation.id} withBorder>
<Text>{operation.description || operation.type}</Text>
<Text fw={700}>
{operation.payment
? formatMoney(operation.payment)
: t("ledger.noMoney")}
</Text>
</Paper>
<LedgerEntryRow key={operation.id} operation={operation} />
))
: null}
<Button component={Link} to={operations.to} variant="subtle">
+1
View File
@@ -229,6 +229,7 @@ export interface components {
instrumentUid: string | null;
ticker: string | null;
instrumentType: string | null;
logoName: string | null;
payment: components["schemas"]["MoneyDto"] | null;
quantity: string | null;
price: components["schemas"]["MoneyDto"] | null;
+5
View File
@@ -1198,6 +1198,10 @@
"type": "string",
"nullable": true
},
"logoName": {
"type": "string",
"nullable": true
},
"payment": {
"nullable": true,
"type": "object",
@@ -1249,6 +1253,7 @@
"instrumentUid",
"ticker",
"instrumentType",
"logoName",
"payment",
"quantity",
"price",
+5
View File
@@ -98,6 +98,11 @@ const ru = {
emptyText: "Измените период или фильтры.",
noMoney: "Без движения денег",
noInstrument: "Без инструмента",
direction: {
incoming: "Поступление",
outgoing: "Списание",
neutral: "Без движения денег",
},
category: {
trade: "Сделка",
income: "Доход",