Compare commits
10
Commits
9469dd2fdc
...
9bb385b9f0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9bb385b9f0 | ||
|
|
8e58c016d2 | ||
|
|
d3ac8c242d | ||
|
|
9a65687d38 | ||
|
|
ae06f6e6e0 | ||
|
|
6b310db0b8 | ||
|
|
dedfec10d1 | ||
|
|
ff4e88edbe | ||
|
|
427ca23a43 | ||
|
|
a42f104bed |
+5
-5
@@ -4,11 +4,11 @@
|
||||
| --- | --- |
|
||||
| Какое implementation-решение принять | [CONVENTIONS](CONVENTIONS.md) |
|
||||
| HTTP wire contract и направление генерации | Backend runtime OpenAPI → [snapshot/types workflow](../../docs/development/runtime-openapi-verification.md) |
|
||||
| Error codes/validation/error envelope | [docs: HTTP API](../../docs/AI_INDEX.md#http-api) |
|
||||
| Auth/session, token storage и refresh | [docs: Security](../../docs/AI_INDEX.md#security) |
|
||||
| Значение Money, cached snapshot, account/position/income | [docs: Domain](../../docs/AI_INDEX.md#domain) |
|
||||
| Mantine/theme/tokens и существующие stories | [docs: UI](../../docs/AI_INDEX.md#ui) |
|
||||
| As-built behavior нужной feature | [docs: Features](../../docs/AI_INDEX.md#features) |
|
||||
| Error codes/validation/error envelope | [docs: HTTP API](../../docs/architecture/http-api.md) |
|
||||
| Auth/session, token storage и refresh | [Аутентификация](../../docs/domains/authentication/overview.md), [подключение брокера](../../docs/integrations/tbank.md) |
|
||||
| Значение Money, cached snapshot, account/position/income | [docs: Domain](../../docs/glossary.md) |
|
||||
| Mantine/theme/tokens и существующие stories | [Дизайн-система](../../docs/development/design-system.md), [UI-каталог](../../docs/development/ui-catalog.md) |
|
||||
| As-built behavior нужной feature | [docs: Features](../../docs/README.md#предметные-области) |
|
||||
| Существующие behavioral requirements, если нужны по задаче | [specs index](../../specs/AI_INDEX.md) |
|
||||
| Действующие versions/scripts/check scope | package.json, lockfile, Biome/TS/dependency configs |
|
||||
|
||||
|
||||
@@ -36,10 +36,10 @@ Authorization. Auth endpoints исключены из Bearer/retry middleware. R
|
||||
|
||||
Protected queries используют existing session-aware boundary; logout очищает
|
||||
session-scoped cache. При auth/token change читай [security](../../../backend/.ai/conventions/security-auth.md)
|
||||
и [authentication](../../../docs/features/authentication.md).
|
||||
и [authentication](../../../docs/domains/authentication/overview.md).
|
||||
Успешная connection mutation коммитит подтверждённый status и сбрасывает financial
|
||||
GET subtree; ошибка mutation не меняет generation/cache. Это отдельная граница
|
||||
от обычного фонового refetch: [connection policy](../../../docs/features/tbank-connection.md#граница-финансового-кэша).
|
||||
от обычного фонового refetch: [connection policy](../../../docs/integrations/tbank.md#граница-финансового-кэша).
|
||||
|
||||
Default focus refetch выключен; freshness и retry определяются существующей
|
||||
[query policy](../../../docs/adr/007-react-query-fetch-policy.md) и feature source.
|
||||
|
||||
@@ -28,6 +28,8 @@ MSW запускается только Vitest setup в `src/test/`, без brow
|
||||
Независимый case получает свой `createTestQueryClient`; rerender сохраняет
|
||||
экземпляр и seeded cache. Providers выбирай явно. Existing teardown выполняет
|
||||
RTL cleanup, auth reset и MSW reset: [test client](../../src/test/query.tsx).
|
||||
Тестовый клиент отключает retries запросов и мутаций для предсказуемого исхода;
|
||||
это не меняет [политику обновления приложения](../../../docs/adr/007-react-query-fetch-policy.md).
|
||||
|
||||
## Важные случаи
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import "@mantine/dates/styles.css";
|
||||
import "dayjs/locale/ru";
|
||||
import "../src/shared/i18n";
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { DatesProvider } from "@mantine/dates";
|
||||
import type { Preview } from "@storybook/react-vite";
|
||||
import { cssVariablesResolver, theme } from "@/shared/theme";
|
||||
|
||||
@@ -33,7 +34,9 @@ const preview: Preview = {
|
||||
forceColorScheme="light"
|
||||
colorSchemeManager={colorSchemeManager}
|
||||
>
|
||||
<Story />
|
||||
<DatesProvider settings={{ locale: "ru" }}>
|
||||
<Story />
|
||||
</DatesProvider>
|
||||
</MantineProvider>
|
||||
),
|
||||
],
|
||||
|
||||
@@ -39,10 +39,10 @@ document и затем выполните `npm run openapi:generate`.
|
||||
- [Data/API/cache](.ai/conventions/frontend-data.md)
|
||||
- [Testing](.ai/conventions/frontend-testing.md)
|
||||
- [Поставленный UI-каталог Storybook](../docs/development/ui-catalog.md)
|
||||
- [Обзор поставленной системы](../docs/architecture/system-overview.md)
|
||||
- [Обзор поставленной системы](../docs/overview.md)
|
||||
- [Engineering governance и risk-based testing](../docs/development/engineering-governance.md)
|
||||
- [Карта проектных фактов](../docs/AI_INDEX.md)
|
||||
- [Frontend workflow](../docs/development/frontend-workflow.md)
|
||||
- [Карта проектных фактов](../docs/README.md)
|
||||
- [Границы проверки интерфейса](../docs/development/verification.md#интерфейс)
|
||||
- [Remediation registry](../docs/development/audit-remediation.md)
|
||||
|
||||
Runtime OpenAPI backend сверяется с frontend snapshot отдельной read-only
|
||||
|
||||
@@ -37,6 +37,7 @@ describe("AppRoutes", () => {
|
||||
["/accounts/demo", "Вход"],
|
||||
["/accounts/demo/operations", "Вход"],
|
||||
["/settings", "Вход"],
|
||||
["/cards?month=2026-08", "Вход"],
|
||||
["/unknown", "Страница не найдена"],
|
||||
])("renders %s with its page title", async (path, title) => {
|
||||
renderRoutes(path);
|
||||
@@ -94,6 +95,41 @@ describe("AppRoutes", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("returns after login to cards with the selected month without T-Bank", async () => {
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/categories", () => HttpResponse.json([])),
|
||||
http.post("*/api/v1/auth/login", () =>
|
||||
HttpResponse.json({
|
||||
accessToken: "test",
|
||||
user: { id: "user-1", email: "user@example.com" },
|
||||
}),
|
||||
),
|
||||
http.get("*/api/v1/bank-cards", () => HttpResponse.json([])),
|
||||
http.get("*/api/v1/bank-cards/summary", () =>
|
||||
HttpResponse.json({
|
||||
month: "2026-08",
|
||||
cardId: null,
|
||||
expenses: { currency: "RUB", value: "0" },
|
||||
refunds: { currency: "RUB", value: "0" },
|
||||
net: { currency: "RUB", value: "0" },
|
||||
categories: [],
|
||||
}),
|
||||
),
|
||||
);
|
||||
renderRoutes("/cards?month=2026-08");
|
||||
await screen.findByRole("heading", { name: "Вход" });
|
||||
fireEvent.change(screen.getByLabelText("Email"), {
|
||||
target: { value: "user@example.com" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("Пароль"), {
|
||||
target: { value: "a secure password" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Вход" }));
|
||||
await screen.findByRole("heading", { name: "Добавьте первую карту" });
|
||||
expect(screen.getByLabelText("Месяц")).toHaveTextContent("August 2026");
|
||||
expect(document.title).toBe("Карты — WealthLedger");
|
||||
});
|
||||
|
||||
it("lazy-loads the protected shell for an authenticated accounts route", async () => {
|
||||
server.use(
|
||||
http.post("*/api/v1/auth/refresh", () =>
|
||||
|
||||
@@ -4,6 +4,14 @@ import { Navigate, Route, Routes } from "react-router";
|
||||
import { LazyPage } from "./RouteFallback";
|
||||
import { Protected, Public } from "./RouteGuards";
|
||||
|
||||
const CardPage = lazy(async () => {
|
||||
const { CardPage } = await import("@/pages/card");
|
||||
return { default: CardPage };
|
||||
});
|
||||
const CardsPage = lazy(async () => {
|
||||
const { CardsPage } = await import("@/pages/cards");
|
||||
return { default: CardsPage };
|
||||
});
|
||||
const BondPage = lazy(async () => {
|
||||
const { BondPage } = await import("@/pages/bond");
|
||||
return { default: BondPage };
|
||||
@@ -93,6 +101,22 @@ const AppRoutes: FC = () => (
|
||||
</Protected>
|
||||
}
|
||||
>
|
||||
<Route
|
||||
path="/cards/:cardId"
|
||||
element={
|
||||
<LazyPage variant="content">
|
||||
<CardPage />
|
||||
</LazyPage>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/cards"
|
||||
element={
|
||||
<LazyPage variant="content">
|
||||
<CardsPage />
|
||||
</LazyPage>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/bonds"
|
||||
element={
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useDocumentTitle } from "@mantine/hooks";
|
||||
import type { FC } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useMatch } from "react-router";
|
||||
import { useBankCard } from "@/entities/bank-card";
|
||||
import { useBond } from "@/entities/bond";
|
||||
import { useBrokerageAccounts } from "@/entities/brokerage-account";
|
||||
import { useStock } from "@/entities/stock";
|
||||
@@ -52,14 +53,23 @@ const StockDocumentTitle: FC<InstrumentDocumentTitleProps> = (props) => {
|
||||
return <DocumentTitle title={data?.name ?? t("stock.share")} />;
|
||||
};
|
||||
|
||||
const CardDocumentTitle: FC<InstrumentDocumentTitleProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
const { data } = useBankCard(props.identifier);
|
||||
return <DocumentTitle title={data?.name ?? t("bank.card")} />;
|
||||
};
|
||||
|
||||
const ProtectedDocumentTitle: FC = () => {
|
||||
const { t } = useTranslation();
|
||||
const account = useMatch("/accounts/:accountId/:section?");
|
||||
const bond = useMatch("/bonds/:bondId");
|
||||
const stock = useMatch("/stocks/:stockId");
|
||||
const card = useMatch("/cards/:cardId");
|
||||
const cards = useMatch("/cards");
|
||||
const bonds = useMatch("/bonds");
|
||||
const stocks = useMatch("/stocks");
|
||||
const settings = useMatch("/settings");
|
||||
if (card) return <CardDocumentTitle identifier={card.params.cardId ?? ""} />;
|
||||
if (account)
|
||||
return (
|
||||
<AccountDocumentTitle
|
||||
@@ -73,13 +83,15 @@ const ProtectedDocumentTitle: FC = () => {
|
||||
return (
|
||||
<DocumentTitle
|
||||
title={t(
|
||||
bonds
|
||||
? "navigation.bonds"
|
||||
: stocks
|
||||
? "navigation.stocks"
|
||||
: settings
|
||||
? "navigation.settings"
|
||||
: "navigation.accounts",
|
||||
cards
|
||||
? "navigation.cards"
|
||||
: bonds
|
||||
? "navigation.bonds"
|
||||
: stocks
|
||||
? "navigation.stocks"
|
||||
: settings
|
||||
? "navigation.settings"
|
||||
: "navigation.accounts",
|
||||
)}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -22,8 +22,16 @@ const Protected: FC<PropsWithChildren> = (props) => {
|
||||
const Public: FC<PropsWithChildren> = (props) => {
|
||||
const { children } = props;
|
||||
const { user, ready } = useAuth();
|
||||
const location = useLocation();
|
||||
const requested = (location.state as { returnTo?: string } | null)?.returnTo;
|
||||
const returnTo =
|
||||
typeof requested === "string" &&
|
||||
requested.startsWith("/") &&
|
||||
!requested.startsWith("//")
|
||||
? requested
|
||||
: "/accounts";
|
||||
if (!ready) return <RouteSkeleton variant="shell" />;
|
||||
return user ? <Navigate to="/accounts" replace /> : children;
|
||||
return user ? <Navigate to={returnTo} replace /> : children;
|
||||
};
|
||||
|
||||
export { Protected, Public };
|
||||
|
||||
@@ -6,6 +6,7 @@ import { AccountBreadcrumbs } from "./AccountBreadcrumbs";
|
||||
import { AccountScopeSwitch } from "./AccountScopeSwitch";
|
||||
import { BondBreadcrumbs } from "./BondBreadcrumbs";
|
||||
import { BreadcrumbTrail } from "./BreadcrumbTrail";
|
||||
import { CardBreadcrumbs } from "./CardBreadcrumbs";
|
||||
import { StockBreadcrumbs } from "./StockBreadcrumbs";
|
||||
|
||||
const AppBreadcrumbs: FC = () => {
|
||||
@@ -17,6 +18,8 @@ const AppBreadcrumbs: FC = () => {
|
||||
const events = useMatch({ path: "/accounts/:accountId/events", end: true });
|
||||
const income = useMatch({ path: "/accounts/:accountId/income", end: true });
|
||||
const account = useMatch({ path: "/accounts/:accountId", end: true });
|
||||
const card = useMatch("/cards/:cardId");
|
||||
const cards = useMatch("/cards");
|
||||
const accounts = useMatch({ path: "/accounts", end: true });
|
||||
const settings = useMatch({ path: "/settings", end: true });
|
||||
|
||||
@@ -71,6 +74,8 @@ const AppBreadcrumbs: FC = () => {
|
||||
<AccountScopeSwitch accountId={account.params.accountId ?? ""} />
|
||||
</Stack>
|
||||
);
|
||||
if (card) return <CardBreadcrumbs identifier={card.params.cardId ?? ""} />;
|
||||
if (cards) return <BreadcrumbTrail items={[{ label: t("bank.title") }]} />;
|
||||
if (accounts)
|
||||
return <BreadcrumbTrail items={[{ label: t("breadcrumbs.accounts") }]} />;
|
||||
if (settings)
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { FC } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useBankCard } from "@/entities/bank-card";
|
||||
import { BreadcrumbTrail } from "./BreadcrumbTrail";
|
||||
|
||||
type CardBreadcrumbsProps = { identifier: string };
|
||||
const CardBreadcrumbs: FC<CardBreadcrumbsProps> = (props) => {
|
||||
const { data } = useBankCard(props.identifier);
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<BreadcrumbTrail
|
||||
items={[
|
||||
{ label: t("bank.title"), to: "/cards" },
|
||||
{ label: data?.name ?? t("bank.card") },
|
||||
]}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export { CardBreadcrumbs };
|
||||
@@ -0,0 +1,424 @@
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import { HttpResponse, http } from "msw";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { apiClient, configureAuthClient } from "@/shared/api";
|
||||
import { createQueryWrapper } from "@/test/query";
|
||||
import { server } from "@/test/server";
|
||||
import { useBankMutations } from "./mutations";
|
||||
import {
|
||||
type BankCard,
|
||||
type CreateBankOperation,
|
||||
useBankCard,
|
||||
useBankCards,
|
||||
useBankCategories,
|
||||
useBankExpenses,
|
||||
useBankOperation,
|
||||
useBankOperations,
|
||||
useBankSummary,
|
||||
} from "./queries";
|
||||
|
||||
const card: BankCard = {
|
||||
id: "a",
|
||||
name: "Daily",
|
||||
bankName: null,
|
||||
lastFour: null,
|
||||
paymentSystem: null,
|
||||
openingBalance: { currency: "RUB", value: "100" },
|
||||
openingDate: "2026-09-01",
|
||||
balance: { currency: "RUB", value: "100" },
|
||||
archivedAt: null,
|
||||
version: 1,
|
||||
};
|
||||
const transfer: CreateBankOperation = {
|
||||
id: "4e6caa65-dd52-4629-81e2-ce8a139a0612",
|
||||
kind: "transfer",
|
||||
cardId: "a",
|
||||
targetCardId: "b",
|
||||
amount: { currency: "RUB", value: "90071992547409.93" },
|
||||
date: "2026-09-12",
|
||||
};
|
||||
|
||||
function authenticate() {
|
||||
configureAuthClient({
|
||||
accessToken: () => "token",
|
||||
refresh: async () => true,
|
||||
clear: vi.fn(),
|
||||
});
|
||||
}
|
||||
|
||||
function readHandlers(counts: Map<string, number>, categoryName = "Food") {
|
||||
return [
|
||||
http.get("*/api/v1/bank-cards", ({ request }) => {
|
||||
const key = new URL(request.url).pathname + new URL(request.url).search;
|
||||
counts.set(key, (counts.get(key) ?? 0) + 1);
|
||||
return HttpResponse.json([card]);
|
||||
}),
|
||||
http.get("*/api/v1/bank-cards/*", ({ request }) => {
|
||||
const url = new URL(request.url);
|
||||
const key = url.pathname + url.search;
|
||||
counts.set(key, (counts.get(key) ?? 0) + 1);
|
||||
if (url.pathname.endsWith("/categories"))
|
||||
return HttpResponse.json([
|
||||
{ id: "food", name: categoryName, isDefault: true, version: 1 },
|
||||
]);
|
||||
if (url.pathname.endsWith("/summary"))
|
||||
return HttpResponse.json({
|
||||
month: url.searchParams.get("month"),
|
||||
cardId: url.searchParams.get("cardId"),
|
||||
expenses: { currency: "RUB", value: "0" },
|
||||
refunds: { currency: "RUB", value: "0" },
|
||||
net: { currency: "RUB", value: "0" },
|
||||
categories: [],
|
||||
});
|
||||
if (
|
||||
url.pathname.endsWith("/operations") ||
|
||||
url.pathname.endsWith("/expenses")
|
||||
)
|
||||
return HttpResponse.json({
|
||||
items: [],
|
||||
page: 1,
|
||||
total: 0,
|
||||
hasNext: false,
|
||||
});
|
||||
if (url.pathname.includes("/operations/"))
|
||||
return HttpResponse.json({ ...transfer, version: 1 });
|
||||
return HttpResponse.json({ ...card, id: url.pathname.split("/").at(-1) });
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
function useReadModels() {
|
||||
const cards = useBankCards(true);
|
||||
const a = useBankCard("a");
|
||||
const b = useBankCard("b");
|
||||
const categories = useBankCategories();
|
||||
const history = useBankOperations("a", {
|
||||
month: "2026-09",
|
||||
page: 2,
|
||||
limit: 20,
|
||||
});
|
||||
const expenses = useBankExpenses("a", { page: 1 });
|
||||
const september = useBankSummary("2026-09");
|
||||
const august = useBankSummary("2026-08", "b");
|
||||
const original = useBankOperation("original");
|
||||
return {
|
||||
reads: [
|
||||
cards,
|
||||
a,
|
||||
b,
|
||||
categories,
|
||||
history,
|
||||
expenses,
|
||||
september,
|
||||
august,
|
||||
original,
|
||||
],
|
||||
mutations: useBankMutations(),
|
||||
};
|
||||
}
|
||||
|
||||
describe("banking API", () => {
|
||||
beforeEach(authenticate);
|
||||
|
||||
it("loads every page for all mode and fails without exposing partial results", async () => {
|
||||
const pages: number[] = [];
|
||||
let fail = false;
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/a/operations", ({ request }) => {
|
||||
const url = new URL(request.url);
|
||||
const page = Number(url.searchParams.get("page"));
|
||||
pages.push(page);
|
||||
expect(url.searchParams.get("limit")).toBe("100");
|
||||
expect(url.searchParams.get("month")).toBe("2026-09");
|
||||
if (fail && page === 2)
|
||||
return HttpResponse.json({ code: "FAILED" }, { status: 500 });
|
||||
return HttpResponse.json({
|
||||
items: [{ ...transfer, id: String(page) }],
|
||||
total: 2,
|
||||
page,
|
||||
hasNext: page === 1,
|
||||
});
|
||||
}),
|
||||
);
|
||||
const { result } = renderHook(
|
||||
() => useBankOperations("a", { month: "2026-09", page: 1, limit: "all" }),
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
expect(pages).toEqual([1, 2]);
|
||||
expect(result.current.data?.items.map((item) => item.id)).toEqual([
|
||||
"1",
|
||||
"2",
|
||||
]);
|
||||
fail = true;
|
||||
const failed = renderHook(
|
||||
() => useBankOperations("a", { month: "2026-09", page: 1, limit: "all" }),
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
await waitFor(() => expect(failed.result.current.isError).toBe(true));
|
||||
expect(failed.result.current.data).toBeUndefined();
|
||||
});
|
||||
|
||||
it("uses session-aware banking endpoints and explicit month/page without T-Bank", async () => {
|
||||
const counts = new Map<string, number>();
|
||||
server.use(...readHandlers(counts));
|
||||
const { result } = renderHook(useReadModels, {
|
||||
wrapper: createQueryWrapper().wrapper,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current.reads.every((read) => read.isSuccess)).toBe(true),
|
||||
);
|
||||
expect([...counts.keys()]).toContain(
|
||||
"/api/v1/bank-cards?includeArchived=true",
|
||||
);
|
||||
expect([...counts.keys()]).toContain(
|
||||
"/api/v1/bank-cards/a/operations?month=2026-09&page=2&limit=20",
|
||||
);
|
||||
expect([...counts.keys()]).toContain(
|
||||
"/api/v1/bank-cards/summary?month=2026-08&cardId=b",
|
||||
);
|
||||
expect(counts.size).toBe(9);
|
||||
});
|
||||
|
||||
it("replays the exact UUID and large Money string once across shared auth refresh", async () => {
|
||||
let token = "expired";
|
||||
const refresh = vi.fn(async () => {
|
||||
token = "renewed";
|
||||
return true;
|
||||
});
|
||||
configureAuthClient({ accessToken: () => token, refresh, clear: vi.fn() });
|
||||
const bodies: unknown[] = [];
|
||||
const headers: (string | null)[] = [];
|
||||
server.use(
|
||||
http.post("*/api/v1/bank-cards/operations", async ({ request }) => {
|
||||
bodies.push(await request.json());
|
||||
headers.push(request.headers.get("Authorization"));
|
||||
return bodies.length === 1
|
||||
? HttpResponse.json({ code: "UNAUTHORIZED" }, { status: 401 })
|
||||
: HttpResponse.json({ ...transfer, version: 1 });
|
||||
}),
|
||||
);
|
||||
const { result } = renderHook(useBankMutations, {
|
||||
wrapper: createQueryWrapper().wrapper,
|
||||
});
|
||||
await act(() => result.current.createOperation.mutateAsync(transfer));
|
||||
expect(bodies).toEqual([transfer, transfer]);
|
||||
expect(headers).toEqual(["Bearer expired", "Bearer renewed"]);
|
||||
expect(refresh).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not automatically retry a network failure and preserves the form-supplied intent on repeat", async () => {
|
||||
const bodies: unknown[] = [];
|
||||
server.use(
|
||||
http.post("*/api/v1/bank-cards/operations", async ({ request }) => {
|
||||
bodies.push(await request.json());
|
||||
return bodies.length === 1
|
||||
? HttpResponse.error()
|
||||
: HttpResponse.json({ ...transfer, version: 1 });
|
||||
}),
|
||||
);
|
||||
const { result } = renderHook(useBankMutations, {
|
||||
wrapper: createQueryWrapper().wrapper,
|
||||
});
|
||||
await act(async () => {
|
||||
await expect(
|
||||
result.current.createOperation.mutateAsync(transfer),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
expect(bodies).toEqual([transfer]);
|
||||
await act(() => result.current.createOperation.mutateAsync(transfer));
|
||||
expect(bodies).toEqual([transfer, transfer]);
|
||||
});
|
||||
|
||||
it("keeps the confirmed balance while a mutation is pending or fails, and on refetch failure", async () => {
|
||||
server.use(...readHandlers(new Map()));
|
||||
let finish: () => void = () => {};
|
||||
const pending = new Promise<void>((resolve) => {
|
||||
finish = resolve;
|
||||
});
|
||||
server.use(
|
||||
http.post("*/api/v1/bank-cards/operations", async () => {
|
||||
await pending;
|
||||
return HttpResponse.json({ code: "INTERNAL_ERROR" }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
const { result } = renderHook(
|
||||
() => ({ query: useBankCard("a"), mutations: useBankMutations() }),
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
await waitFor(() => expect(result.current.query.isSuccess).toBe(true));
|
||||
let saving: Promise<unknown>;
|
||||
act(() => {
|
||||
saving = result.current.mutations.createOperation
|
||||
.mutateAsync(transfer)
|
||||
.catch(() => undefined);
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current.mutations.createOperation.isPending).toBe(true),
|
||||
);
|
||||
expect(result.current.query.data?.balance.value).toBe("100");
|
||||
await act(async () => {
|
||||
finish();
|
||||
await saving;
|
||||
});
|
||||
expect(result.current.query.data?.balance.value).toBe("100");
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/a", () =>
|
||||
HttpResponse.json({ code: "INTERNAL_ERROR" }, { status: 500 }),
|
||||
),
|
||||
);
|
||||
await act(() => result.current.query.refetch());
|
||||
expect(result.current.query.isError).toBe(true);
|
||||
expect(result.current.query.data?.balance.value).toBe("100");
|
||||
});
|
||||
|
||||
it("refetches both cards, every month, categories, journal and source expenses after a transfer without invalidating brokerage", async () => {
|
||||
const counts = new Map<string, number>();
|
||||
server.use(
|
||||
...readHandlers(counts),
|
||||
http.post("*/api/v1/bank-cards/operations", () =>
|
||||
HttpResponse.json({ ...transfer, version: 1 }),
|
||||
),
|
||||
);
|
||||
const { wrapper, queryClient } = createQueryWrapper();
|
||||
const brokerKey = ["get", "/api/v1/brokerage-accounts"];
|
||||
queryClient.setQueryData(brokerKey, []);
|
||||
const { result } = renderHook(useReadModels, { wrapper });
|
||||
await waitFor(() =>
|
||||
expect(result.current.reads.every((read) => read.isSuccess)).toBe(true),
|
||||
);
|
||||
await act(() =>
|
||||
result.current.mutations.createOperation.mutateAsync(transfer),
|
||||
);
|
||||
expect([...counts.values()]).toEqual(Array(9).fill(2));
|
||||
expect(queryClient.getQueryState(brokerKey)?.isInvalidated).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"BANK_VERSION_CONFLICT",
|
||||
"BANK_INTENT_CONFLICT",
|
||||
"BANK_REFUND_LIMIT",
|
||||
])("fetches current state after %s", async (code) => {
|
||||
let reads = 0;
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/a", () =>
|
||||
HttpResponse.json({ ...card, version: ++reads }),
|
||||
),
|
||||
http.patch("*/api/v1/bank-cards/a", () =>
|
||||
HttpResponse.json({ code }, { status: 409 }),
|
||||
),
|
||||
);
|
||||
const { result } = renderHook(
|
||||
() => ({ card: useBankCard("a"), mutations: useBankMutations() }),
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
await waitFor(() => expect(result.current.card.data?.version).toBe(1));
|
||||
await act(async () => {
|
||||
await expect(
|
||||
result.current.mutations.updateCard.mutateAsync({
|
||||
id: "a",
|
||||
body: { name: "changed", version: 1 },
|
||||
}),
|
||||
).rejects.toEqual({ code });
|
||||
});
|
||||
await waitFor(() => expect(result.current.card.data?.version).toBe(2));
|
||||
});
|
||||
|
||||
it("sends edit/delete versions and refreshes category names without optimistic updates", async () => {
|
||||
const requests: unknown[] = [];
|
||||
let name = "Food";
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/categories", () =>
|
||||
HttpResponse.json([{ id: "food", name, isDefault: true, version: 1 }]),
|
||||
),
|
||||
http.patch("*/api/v1/bank-cards/categories/food", async ({ request }) => {
|
||||
const body = await request.json();
|
||||
requests.push(body);
|
||||
name = "Groceries";
|
||||
return HttpResponse.json({
|
||||
id: "food",
|
||||
name,
|
||||
isDefault: true,
|
||||
version: 2,
|
||||
});
|
||||
}),
|
||||
http.patch(
|
||||
"*/api/v1/bank-cards/operations/original",
|
||||
async ({ request }) => {
|
||||
requests.push(await request.json());
|
||||
return HttpResponse.json({ ...transfer, version: 2 });
|
||||
},
|
||||
),
|
||||
http.delete("*/api/v1/bank-cards/operations/original", ({ request }) => {
|
||||
requests.push(new URL(request.url).searchParams.get("version"));
|
||||
return new HttpResponse(null, { status: 204 });
|
||||
}),
|
||||
);
|
||||
const { result } = renderHook(
|
||||
() => ({
|
||||
categories: useBankCategories(),
|
||||
mutations: useBankMutations(),
|
||||
}),
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(result.current.categories.data?.[0].name).toBe("Food"),
|
||||
);
|
||||
await act(() =>
|
||||
result.current.mutations.updateCategory.mutateAsync({
|
||||
id: "food",
|
||||
body: { name: "Groceries", version: 1 },
|
||||
}),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(result.current.categories.data?.[0].name).toBe("Groceries"),
|
||||
);
|
||||
await act(() =>
|
||||
result.current.mutations.updateOperation.mutateAsync({
|
||||
id: "original",
|
||||
body: { description: "corrected", version: 1 },
|
||||
}),
|
||||
);
|
||||
await act(() =>
|
||||
result.current.mutations.deleteOperation.mutateAsync({
|
||||
id: "original",
|
||||
version: 2,
|
||||
}),
|
||||
);
|
||||
expect(requests).toEqual([
|
||||
{ name: "Groceries", version: 1 },
|
||||
{ description: "corrected", version: 1 },
|
||||
"2",
|
||||
]);
|
||||
});
|
||||
|
||||
it("disables reads after session removal and retains banking data across a T-Bank API mutation", async () => {
|
||||
const counts = new Map<string, number>();
|
||||
server.use(
|
||||
...readHandlers(counts),
|
||||
http.put("*/api/v1/tbank-connection", () =>
|
||||
HttpResponse.json({
|
||||
connected: true,
|
||||
connectedAt: "2026-09-12T00:00:00Z",
|
||||
}),
|
||||
),
|
||||
);
|
||||
const { wrapper, queryClient } = createQueryWrapper();
|
||||
const { result, rerender } = renderHook(() => useBankCard("a"), {
|
||||
wrapper,
|
||||
});
|
||||
await waitFor(() => expect(result.current.data?.balance.value).toBe("100"));
|
||||
await apiClient.PUT("/api/v1/tbank-connection", {
|
||||
body: { token: "synthetic" },
|
||||
});
|
||||
expect(result.current.data?.balance.value).toBe("100");
|
||||
act(() => {
|
||||
configureAuthClient(null);
|
||||
queryClient.clear();
|
||||
});
|
||||
rerender();
|
||||
await waitFor(() => expect(result.current.fetchStatus).toBe("idle"));
|
||||
expect(result.current.data).toBeUndefined();
|
||||
expect(counts.get("/api/v1/bank-cards/a")).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { apiClient, apiErrorCode } from "@/shared/api";
|
||||
import type {
|
||||
CreateBankCard,
|
||||
CreateBankOperation,
|
||||
CreateExpenseCategory,
|
||||
UpdateBankCard,
|
||||
UpdateBankOperation,
|
||||
UpdateExpenseCategory,
|
||||
} from "./queries";
|
||||
|
||||
async function mutationData<T>(
|
||||
request: Promise<{ data?: T; error?: unknown }>,
|
||||
) {
|
||||
const { data, error } = await request;
|
||||
if (error) throw error;
|
||||
return data;
|
||||
}
|
||||
|
||||
function useBankMutations() {
|
||||
const queryClient = useQueryClient();
|
||||
const invalidate = () =>
|
||||
queryClient.invalidateQueries({
|
||||
predicate: ({ queryKey: [method, path] }) =>
|
||||
method === "get" &&
|
||||
typeof path === "string" &&
|
||||
(path === "/api/v1/bank-cards" ||
|
||||
path.startsWith("/api/v1/bank-cards/")),
|
||||
});
|
||||
const options = {
|
||||
retry: false,
|
||||
onSuccess: invalidate,
|
||||
onError: (error: unknown) => {
|
||||
if (
|
||||
[
|
||||
"BANK_VERSION_CONFLICT",
|
||||
"BANK_WRITE_CONFLICT",
|
||||
"BANK_INTENT_CONFLICT",
|
||||
"BANK_REFUND_LIMIT",
|
||||
"BANK_DEPENDENT_REFUNDS",
|
||||
].includes(apiErrorCode(error) ?? "")
|
||||
)
|
||||
return invalidate();
|
||||
},
|
||||
} as const;
|
||||
const createCard = useMutation({
|
||||
...options,
|
||||
mutationFn: (body: CreateBankCard) =>
|
||||
mutationData(apiClient.POST("/api/v1/bank-cards", { body })),
|
||||
});
|
||||
const updateCard = useMutation({
|
||||
...options,
|
||||
mutationFn: ({ id, body }: { id: string; body: UpdateBankCard }) =>
|
||||
mutationData(
|
||||
apiClient.PATCH("/api/v1/bank-cards/{id}", {
|
||||
params: { path: { id } },
|
||||
body,
|
||||
}),
|
||||
),
|
||||
});
|
||||
const createOperation = useMutation({
|
||||
...options,
|
||||
mutationFn: (body: CreateBankOperation) =>
|
||||
mutationData(apiClient.POST("/api/v1/bank-cards/operations", { body })),
|
||||
});
|
||||
const updateOperation = useMutation({
|
||||
...options,
|
||||
mutationFn: ({ id, body }: { id: string; body: UpdateBankOperation }) =>
|
||||
mutationData(
|
||||
apiClient.PATCH("/api/v1/bank-cards/operations/{id}", {
|
||||
params: { path: { id } },
|
||||
body,
|
||||
}),
|
||||
),
|
||||
});
|
||||
const deleteOperation = useMutation({
|
||||
...options,
|
||||
mutationFn: ({ id, version }: { id: string; version: number }) =>
|
||||
mutationData(
|
||||
apiClient.DELETE("/api/v1/bank-cards/operations/{id}", {
|
||||
params: { path: { id }, query: { version } },
|
||||
}),
|
||||
),
|
||||
});
|
||||
const createCategory = useMutation({
|
||||
...options,
|
||||
mutationFn: (body: CreateExpenseCategory) =>
|
||||
mutationData(apiClient.POST("/api/v1/bank-cards/categories", { body })),
|
||||
});
|
||||
const updateCategory = useMutation({
|
||||
...options,
|
||||
mutationFn: ({ id, body }: { id: string; body: UpdateExpenseCategory }) =>
|
||||
mutationData(
|
||||
apiClient.PATCH("/api/v1/bank-cards/categories/{id}", {
|
||||
params: { path: { id } },
|
||||
body,
|
||||
}),
|
||||
),
|
||||
});
|
||||
return {
|
||||
createCard,
|
||||
updateCard,
|
||||
createOperation,
|
||||
updateOperation,
|
||||
deleteOperation,
|
||||
createCategory,
|
||||
updateCategory,
|
||||
};
|
||||
}
|
||||
|
||||
export { useBankMutations };
|
||||
@@ -0,0 +1,192 @@
|
||||
import {
|
||||
apiClient,
|
||||
apiQueryClient,
|
||||
type paths,
|
||||
useAuthenticatedQuery,
|
||||
} from "@/shared/api";
|
||||
|
||||
import { moneyCents } from "../model/form-validation";
|
||||
|
||||
type BankCard =
|
||||
paths["/api/v1/bank-cards/{id}"]["get"]["responses"][200]["content"]["application/json"];
|
||||
type BankOperation =
|
||||
paths["/api/v1/bank-cards/operations/{id}"]["get"]["responses"][200]["content"]["application/json"];
|
||||
type BankOperations =
|
||||
paths["/api/v1/bank-cards/{id}/operations"]["get"]["responses"][200]["content"]["application/json"];
|
||||
type BankSummary =
|
||||
paths["/api/v1/bank-cards/summary"]["get"]["responses"][200]["content"]["application/json"];
|
||||
type ExpenseCategory =
|
||||
paths["/api/v1/bank-cards/categories"]["get"]["responses"][200]["content"]["application/json"][number];
|
||||
type CreateBankCard =
|
||||
paths["/api/v1/bank-cards"]["post"]["requestBody"]["content"]["application/json"];
|
||||
type UpdateBankCard =
|
||||
paths["/api/v1/bank-cards/{id}"]["patch"]["requestBody"]["content"]["application/json"];
|
||||
type CreateBankOperation =
|
||||
paths["/api/v1/bank-cards/operations"]["post"]["requestBody"]["content"]["application/json"];
|
||||
type UpdateBankOperation =
|
||||
paths["/api/v1/bank-cards/operations/{id}"]["patch"]["requestBody"]["content"]["application/json"];
|
||||
type CreateExpenseCategory =
|
||||
paths["/api/v1/bank-cards/categories"]["post"]["requestBody"]["content"]["application/json"];
|
||||
type UpdateExpenseCategory =
|
||||
paths["/api/v1/bank-cards/categories/{id}"]["patch"]["requestBody"]["content"]["application/json"];
|
||||
|
||||
function useBankCards(includeArchived = false) {
|
||||
return useAuthenticatedQuery(
|
||||
apiQueryClient.queryOptions("get", "/api/v1/bank-cards", {
|
||||
params: {
|
||||
query: { includeArchived: includeArchived ? "true" : "false" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function useBankCard(id: string | undefined) {
|
||||
return useAuthenticatedQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bank-cards/{id}", {
|
||||
params: { path: { id: id ?? "" } },
|
||||
}),
|
||||
enabled: Boolean(id),
|
||||
});
|
||||
}
|
||||
|
||||
function useBankCategories() {
|
||||
return useAuthenticatedQuery(
|
||||
apiQueryClient.queryOptions("get", "/api/v1/bank-cards/categories"),
|
||||
);
|
||||
}
|
||||
|
||||
function useBankOperations(
|
||||
id: string | undefined,
|
||||
query: {
|
||||
month?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
page: number;
|
||||
limit?: number | "all";
|
||||
},
|
||||
) {
|
||||
const all = query.limit === "all";
|
||||
const params = {
|
||||
path: { id: id ?? "" },
|
||||
query: {
|
||||
...query,
|
||||
page: all ? 1 : query.page,
|
||||
limit: query.limit === "all" ? 100 : query.limit,
|
||||
},
|
||||
};
|
||||
const options = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/bank-cards/{id}/operations",
|
||||
{ params },
|
||||
);
|
||||
return useAuthenticatedQuery({
|
||||
queryKey: all ? ([...options.queryKey, "all"] as const) : options.queryKey,
|
||||
placeholderData: (
|
||||
previousData: BankOperations | undefined,
|
||||
previousQuery,
|
||||
) => {
|
||||
const previous = previousQuery?.queryKey[2]?.params;
|
||||
return !all &&
|
||||
previousQuery?.queryKey.length === 3 &&
|
||||
previous?.path?.id === id &&
|
||||
previous?.query?.month === query.month &&
|
||||
previous?.query?.from === query.from &&
|
||||
previous?.query?.to === query.to &&
|
||||
previous?.query?.limit === query.limit
|
||||
? previousData
|
||||
: undefined;
|
||||
},
|
||||
queryFn: async ({ signal }) => {
|
||||
const items: BankOperation[] = [];
|
||||
for (let page = params.query.page; ; page++) {
|
||||
const { data, error } = await apiClient.GET(
|
||||
"/api/v1/bank-cards/{id}/operations",
|
||||
{
|
||||
params: { ...params, query: { ...params.query, page } },
|
||||
signal,
|
||||
},
|
||||
);
|
||||
if (error) throw error;
|
||||
if (!data) throw new Error("Missing bank operations response");
|
||||
if (!all) return data;
|
||||
items.push(...data.items);
|
||||
if (!data.hasNext) return { ...data, items, page: 1, hasNext: false };
|
||||
}
|
||||
},
|
||||
enabled: Boolean(id && (query.month || (query.from && query.to))),
|
||||
});
|
||||
}
|
||||
|
||||
function useBankExpenses(
|
||||
id: string | undefined,
|
||||
query: { page: number; limit?: number },
|
||||
) {
|
||||
return useAuthenticatedQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bank-cards/{id}/expenses", {
|
||||
params: { path: { id: id ?? "" }, query },
|
||||
}),
|
||||
enabled: Boolean(id),
|
||||
});
|
||||
}
|
||||
|
||||
function sortBankSummary(data: BankSummary): BankSummary {
|
||||
return {
|
||||
...data,
|
||||
categories: data.categories.toSorted((a, b) => {
|
||||
const left = moneyCents(a.net.value);
|
||||
const right = moneyCents(b.net.value);
|
||||
if (left === null || right === null)
|
||||
throw new Error("Invalid bank summary amount");
|
||||
return left > right ? -1 : left < right ? 1 : 0;
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function useBankSummary(
|
||||
period: string | { from: string; to: string },
|
||||
cardId?: string,
|
||||
) {
|
||||
const query =
|
||||
typeof period === "string"
|
||||
? { month: period, cardId }
|
||||
: { ...period, cardId };
|
||||
return useAuthenticatedQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bank-cards/summary", {
|
||||
params: { query },
|
||||
}),
|
||||
select: sortBankSummary,
|
||||
enabled: Boolean(period),
|
||||
});
|
||||
}
|
||||
|
||||
function useBankOperation(id: string | undefined) {
|
||||
return useAuthenticatedQuery({
|
||||
...apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/bank-cards/operations/{id}",
|
||||
{ params: { path: { id: id ?? "" } } },
|
||||
),
|
||||
enabled: Boolean(id),
|
||||
});
|
||||
}
|
||||
|
||||
export {
|
||||
type BankCard,
|
||||
type BankOperation,
|
||||
type BankSummary,
|
||||
type CreateBankCard,
|
||||
type CreateBankOperation,
|
||||
type CreateExpenseCategory,
|
||||
type ExpenseCategory,
|
||||
sortBankSummary,
|
||||
type UpdateBankCard,
|
||||
type UpdateBankOperation,
|
||||
type UpdateExpenseCategory,
|
||||
useBankCard,
|
||||
useBankCards,
|
||||
useBankCategories,
|
||||
useBankExpenses,
|
||||
useBankOperation,
|
||||
useBankOperations,
|
||||
useBankSummary,
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { type BankSummary, sortBankSummary } from "./queries";
|
||||
|
||||
it("orders displayed expenses descending, preserving cents, ties and source data", () => {
|
||||
const values = [
|
||||
"-10",
|
||||
"9007199254740992.01",
|
||||
"0",
|
||||
"9007199254740992.02",
|
||||
"-2",
|
||||
"0",
|
||||
];
|
||||
const money = (value: string) => ({ currency: "RUB", value });
|
||||
const data: BankSummary = {
|
||||
month: "2026-09",
|
||||
cardId: "a",
|
||||
expenses: money("0"),
|
||||
refunds: money("0"),
|
||||
net: money("0"),
|
||||
categories: values.map((value, index) => ({
|
||||
categoryId: String(index),
|
||||
categoryName: String(index),
|
||||
expenses: money("100"),
|
||||
refunds: money("0"),
|
||||
net: money(value),
|
||||
})),
|
||||
};
|
||||
expect(sortBankSummary(data).categories.map((row) => row.categoryId)).toEqual(
|
||||
["3", "1", "2", "5", "4", "0"],
|
||||
);
|
||||
expect(data.categories.map((row) => row.net.value)).toEqual(values);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
export { useBankMutations } from "./api/mutations";
|
||||
export {
|
||||
type BankCard,
|
||||
type BankOperation,
|
||||
useBankCard,
|
||||
useBankCards,
|
||||
useBankCategories,
|
||||
useBankExpenses,
|
||||
useBankOperation,
|
||||
useBankOperations,
|
||||
useBankSummary,
|
||||
} from "./api/queries";
|
||||
export {
|
||||
bankDateInputValue,
|
||||
bankDateSchema,
|
||||
bankMoneyValue,
|
||||
bankMonth,
|
||||
bankToday,
|
||||
moneyCents,
|
||||
positiveMoneySchema,
|
||||
} from "./model/form-validation";
|
||||
export { BankCardFace } from "./ui/BankCardFace";
|
||||
export { BankCardForm } from "./ui/BankCardForm";
|
||||
export { BankFeedback } from "./ui/BankFeedback";
|
||||
export { BankOperationIcon } from "./ui/BankOperationIcon";
|
||||
export { BankSummaryView } from "./ui/BankSummary.view";
|
||||
export { CategoryManager } from "./ui/CategoryManager";
|
||||
export { useBankFormFocus } from "./ui/useBankFormFocus";
|
||||
@@ -0,0 +1,69 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
bankCardSchema,
|
||||
bankDateInputValue,
|
||||
bankDateSchema,
|
||||
bankMoneyValue,
|
||||
bankMonth,
|
||||
bankToday,
|
||||
positiveMoneySchema,
|
||||
} from "./form-validation";
|
||||
|
||||
afterEach(() => vi.useRealTimers());
|
||||
describe("bank form input", () => {
|
||||
it("keeps input bounds exact without rounding and canonicalizes leading zeros", () => {
|
||||
expect(positiveMoneySchema.safeParse("92233720368547758.07").success).toBe(
|
||||
true,
|
||||
);
|
||||
for (const invalid of [
|
||||
"92233720368547758.08",
|
||||
"1.001",
|
||||
"0",
|
||||
"-1",
|
||||
"abc",
|
||||
"1e3",
|
||||
]) {
|
||||
expect(positiveMoneySchema.safeParse(invalid).success).toBe(false);
|
||||
}
|
||||
expect(bankMoneyValue(" -00010,20 ")).toBe("-10.20");
|
||||
const values = {
|
||||
name: "A",
|
||||
bankName: "",
|
||||
lastFour: "",
|
||||
openingBalance: "-92233720368547758.08",
|
||||
openingDate: "2026-01-01",
|
||||
};
|
||||
expect(bankCardSchema.safeParse(values).success).toBe(true);
|
||||
expect(
|
||||
bankCardSchema.safeParse({
|
||||
...values,
|
||||
openingBalance: "-92233720368547758.09",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
bankCardSchema.safeParse({ ...values, lastFour: "123" }).success,
|
||||
).toBe(false);
|
||||
});
|
||||
it("uses Moscow date and refuses nonexistent or future calendar days", () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-08-31T21:30:00Z"));
|
||||
expect(bankToday()).toBe("2026-09-01");
|
||||
expect(bankMonth(null)).toBe("2026-09");
|
||||
expect(bankMonth("2026-13")).toBe("2026-09");
|
||||
expect(bankDateSchema.safeParse("2026-09-01").success).toBe(true);
|
||||
expect(bankDateSchema.safeParse("2026-09-02").success).toBe(false);
|
||||
expect(bankDateSchema.safeParse("2026-02-30").success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it("converts local date input without accepting impossible or unfinished dates", () => {
|
||||
expect(bankDateInputValue("07.08.2026")).toBe("2026-08-07");
|
||||
expect(
|
||||
bankDateSchema.safeParse(bankDateInputValue("29.02.2024")).success,
|
||||
).toBe(true);
|
||||
for (const value of ["31.02.2026", "07.08.", ""]) {
|
||||
expect(bankDateSchema.safeParse(bankDateInputValue(value)).success).toBe(
|
||||
false,
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { z } from "zod";
|
||||
import { validationMessage } from "@/shared/i18n";
|
||||
|
||||
function bankToday() {
|
||||
return new Intl.DateTimeFormat("en-CA", {
|
||||
timeZone: "Europe/Moscow",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
}).format(new Date());
|
||||
}
|
||||
function bankDateInputValue(value: string) {
|
||||
return value.replace(/^(\d{2})\.(\d{2})\.(\d{4})$/, "$3-$2-$1");
|
||||
}
|
||||
function bankMonth(value: string | null) {
|
||||
return value && /^\d{4}-(0[1-9]|1[0-2])$/.test(value)
|
||||
? value
|
||||
: bankToday().slice(0, 7);
|
||||
}
|
||||
function bankMoneyValue(value: string) {
|
||||
return value
|
||||
.trim()
|
||||
.replace(",", ".")
|
||||
.replace(/^(-?)0+(?=\d)/, "$1");
|
||||
}
|
||||
function moneyCents(value: string): bigint | null {
|
||||
const normalized = value.trim().replace(",", ".");
|
||||
if (!/^-?\d+(\.\d{1,2})?$/.test(normalized)) return null;
|
||||
const [whole, fraction = ""] = normalized.replace("-", "").split(".");
|
||||
return (
|
||||
BigInt(`${whole}${fraction.padEnd(2, "0")}`) *
|
||||
(normalized.startsWith("-") ? -1n : 1n)
|
||||
);
|
||||
}
|
||||
const moneySchema = z.string().refine((value) => {
|
||||
const cents = moneyCents(value);
|
||||
return (
|
||||
cents !== null &&
|
||||
cents >= -9223372036854775808n &&
|
||||
cents <= 9223372036854775807n
|
||||
);
|
||||
}, validationMessage("bank.validation.money"));
|
||||
const positiveMoneySchema = moneySchema.refine((value) => {
|
||||
const cents = moneyCents(value);
|
||||
return cents === null || cents > 0n;
|
||||
}, validationMessage("bank.validation.positive"));
|
||||
const bankDateSchema = z
|
||||
.string()
|
||||
.refine(
|
||||
(value) =>
|
||||
/^\d{4}-\d{2}-\d{2}$/.test(value) &&
|
||||
value >= "0001-01-01" &&
|
||||
!Number.isNaN(Date.parse(`${value}T00:00:00Z`)) &&
|
||||
new Date(`${value}T00:00:00Z`).toISOString().slice(0, 10) === value &&
|
||||
value <= bankToday(),
|
||||
validationMessage("bank.validation.date"),
|
||||
);
|
||||
const bankCardSchema = z.object({
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, validationMessage("bank.validation.name")(undefined))
|
||||
.max(100, validationMessage("bank.validation.name")(undefined)),
|
||||
bankName: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(100, validationMessage("bank.validation.bankName")(undefined)),
|
||||
lastFour: z
|
||||
.string()
|
||||
.refine(
|
||||
(value) => !value || /^\d{4}$/.test(value),
|
||||
validationMessage("bank.validation.lastFour"),
|
||||
),
|
||||
paymentSystem: z
|
||||
.enum(["", "mir", "visa", "mastercard"], {
|
||||
errorMap: validationMessage("bank.validation.paymentSystem"),
|
||||
})
|
||||
.optional(),
|
||||
openingBalance: moneySchema,
|
||||
openingDate: bankDateSchema,
|
||||
});
|
||||
type BankCardValues = z.infer<typeof bankCardSchema>;
|
||||
|
||||
export {
|
||||
type BankCardValues,
|
||||
bankCardSchema,
|
||||
bankDateInputValue,
|
||||
bankDateSchema,
|
||||
bankMoneyValue,
|
||||
bankMonth,
|
||||
bankToday,
|
||||
moneyCents,
|
||||
positiveMoneySchema,
|
||||
};
|
||||
@@ -0,0 +1,140 @@
|
||||
import type { BankOperation } from "../api/queries";
|
||||
|
||||
type OperationIcon = { path: string; color: string; animation?: string };
|
||||
|
||||
const categoryIcons: Record<string, OperationIcon> = {
|
||||
алкоголь: {
|
||||
animation: "wine",
|
||||
path: "M7 3h10v5a5 5 0 0 1-10 0V3Z M7 7h10v1a5 5 0 0 1-10 0V7Z M12 13v8 M8 21h8",
|
||||
color: "grape",
|
||||
},
|
||||
вклады: {
|
||||
animation: "deposit",
|
||||
path: "M6 9a6 6 0 1 0 12 0a6 6 0 1 0-12 0 M10.5 12V6h2a1.5 1.5 0 0 1 0 3h-3m0 1.5h3 M4 16c0 4 16 4 16 0 M4 19c0 4 16 4 16 0",
|
||||
color: "green",
|
||||
},
|
||||
"инвестиции и накопления": {
|
||||
animation: "growth",
|
||||
path: "M3 3v18h18 M6 15l5-5 4 3 6-8 M16 5h5v5",
|
||||
color: "green",
|
||||
},
|
||||
образование: {
|
||||
path: "M2 8l10-5 10 5-10 5L2 8Z M6 10v7c4 3 8 3 12 0v-7 M22 8v9",
|
||||
color: "blue",
|
||||
},
|
||||
переводы: {
|
||||
animation: "transfer",
|
||||
path: "M3 7h18l-4-4 M21 17H3l4 4",
|
||||
color: "blue",
|
||||
},
|
||||
"погашение кредита": {
|
||||
animation: "repayment",
|
||||
path: "M3 5h18v14H3V5Z M3 9h18 M10 18v-7h3a2 2 0 0 1 0 4H9m0 1.5h4",
|
||||
color: "orange",
|
||||
},
|
||||
подписки: {
|
||||
path: "M4 10a8 8 0 0 1 13-6l3 3 M20 3v4h-4 M20 14a8 8 0 0 1-13 6l-3-3 M4 21v-4h4",
|
||||
color: "grape",
|
||||
},
|
||||
путешествия: {
|
||||
path: "M10 3h4v7l7 5v3l-7-3v5l2 1v1l-4-1-4 1v-1l2-1v-5l-7 3v-3l7-5V3Z",
|
||||
color: "blue",
|
||||
},
|
||||
"связь и интернет": {
|
||||
animation: "wifi",
|
||||
path: "M3 7a14 14 0 0 1 18 0 M6 11a9 9 0 0 1 12 0 M9 15a4 4 0 0 1 6 0 M12 19h.01",
|
||||
color: "blue",
|
||||
},
|
||||
"снятие наличных": {
|
||||
path: "M4 10V3h16v7 M7 7h10v14H7V7Z M7 11h10 M10 16h4",
|
||||
color: "green",
|
||||
},
|
||||
ставки: {
|
||||
path: "M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2Z M7 7h.01 M17 7h.01 M12 12h.01 M7 17h.01 M17 17h.01",
|
||||
color: "grape",
|
||||
},
|
||||
страхование: {
|
||||
path: "M12 2l8 4v6c0 5-8 10-8 10S4 17 4 12V6l8-4Z M8 12l3 3 5-6",
|
||||
color: "green",
|
||||
},
|
||||
табак: {
|
||||
path: "M3 14h18v5H3v-5Z M16 14v5 M8 10V8c0-2 3-2 3-4V2 M15 10V8c0-2 3-2 3-4",
|
||||
color: "orange",
|
||||
},
|
||||
"хостинг и ии-сервисы": {
|
||||
animation: "server",
|
||||
path: "M3 3h18v7H3V3Z M3 14h18v7H3v-7Z M7 6.5h.01 M7 17.5h.01 M15 6.5h3 M15 17.5h3",
|
||||
color: "grape",
|
||||
},
|
||||
"цифровые покупки": {
|
||||
path: "M3 3h18v13H3V3Z M8 21h8 M12 16v5 M12 6v7 M9 10l3 3 3-3",
|
||||
color: "blue",
|
||||
},
|
||||
продукты: {
|
||||
animation: "basket",
|
||||
path: "M3 9h18l-2 11H5L3 9Z M8 9l4-6 4 6 M9 13v3 M15 13v3 M10 6a2 2 0 1 0 4 0a2 2 0 1 0-4 0",
|
||||
color: "green",
|
||||
},
|
||||
кафе: {
|
||||
animation: "coffee",
|
||||
path: "M4 8h12v7a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4V8Z M16 9h2a3 3 0 0 1 0 6h-2 M8 6c-2-1 2-2 0-4 M12 6c-2-1 2-2 0-4 M3 22h15",
|
||||
color: "orange",
|
||||
},
|
||||
такси: {
|
||||
path: "M4 10l2-6h12l2 6 M3 10h18v8H3v-8Z M6 18v3 M18 18v3 M6 14h2 M16 14h2 M10 4V2h4v2",
|
||||
color: "yellow",
|
||||
},
|
||||
транспорт: {
|
||||
animation: "car",
|
||||
path: "M4 16H2v-4l3-1 3-4h6l4 4 4 1v4h-2 M8 16h8 M6 11h12m-6-4v4 M4 16a2 2 0 1 0 4 0a2 2 0 1 0-4 0m2-2v4m-2-2h4 M16 16a2 2 0 1 0 4 0a2 2 0 1 0-4 0m2-2v4m-2-2h4",
|
||||
color: "blue",
|
||||
},
|
||||
жилье: { path: "M3 11l9-8 9 8 M5 10v11h14V10 M9 21v-8h6v8", color: "orange" },
|
||||
здоровье: { path: "M9 3h6v6h6v6h-6v6H9v-6H3V9h6V3Z", color: "red" },
|
||||
покупки: {
|
||||
path: "M5 7h14l2 14H3L5 7Z M8 8V6a4 4 0 0 1 8 0v2",
|
||||
color: "grape",
|
||||
},
|
||||
развлечения: {
|
||||
path: "M9 5v14a3 3 0 1 1-3-3h3 M9 5l11-2v14a3 3 0 1 1-3-3h3 M9 9l11-2",
|
||||
color: "grape",
|
||||
},
|
||||
};
|
||||
const otherIcon: OperationIcon = {
|
||||
animation: "grid",
|
||||
path: "M4 4h6v6H4V4Z M14 4h6v6h-6V4Z M4 14h6v6H4v-6Z M14 14h6v6h-6v-6Z",
|
||||
color: "gray",
|
||||
};
|
||||
const operationIcons: Record<
|
||||
Exclude<BankOperation["kind"], "expense">,
|
||||
OperationIcon
|
||||
> = {
|
||||
topup: {
|
||||
animation: "topup",
|
||||
path: "M20 8V5H5a2 2 0 0 1 0-4h13v4 M3 3v16a2 2 0 0 0 2 2h15V8H5 M16 12v5m-2.5-2.5h5",
|
||||
color: "green",
|
||||
},
|
||||
transfer: {
|
||||
animation: "transfer",
|
||||
path: "M3 7h18l-4-4 M21 17H3l4 4",
|
||||
color: "blue",
|
||||
},
|
||||
refund: { path: "M8 4L3 9l5 5 M3 9h11a7 7 0 0 1 0 14", color: "teal" },
|
||||
};
|
||||
|
||||
function bankOperationAppearance(
|
||||
kind: BankOperation["kind"],
|
||||
categoryName?: string | null,
|
||||
) {
|
||||
const name = categoryName
|
||||
?.trim()
|
||||
.toLocaleLowerCase("ru-RU")
|
||||
.replaceAll("ё", "е");
|
||||
return kind === "expense"
|
||||
? name && Object.hasOwn(categoryIcons, name)
|
||||
? categoryIcons[name]
|
||||
: otherIcon
|
||||
: operationIcons[kind];
|
||||
}
|
||||
|
||||
export { bankOperationAppearance };
|
||||
@@ -0,0 +1,160 @@
|
||||
.face {
|
||||
--card-base: #242b35;
|
||||
--card-light: #485666;
|
||||
position: relative;
|
||||
isolation: isolate;
|
||||
overflow: hidden;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
max-width: 28rem;
|
||||
min-height: 15rem;
|
||||
padding: clamp(1.1rem, 3vw, 1.6rem);
|
||||
border-radius: 1.25rem;
|
||||
color: #fff;
|
||||
background: linear-gradient(125deg, var(--card-light), var(--card-base) 75%);
|
||||
box-shadow:
|
||||
inset 0 1px 0 #ffffff40,
|
||||
0 8px 18px #18233118;
|
||||
}
|
||||
.face::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
z-index: -1;
|
||||
width: 24rem;
|
||||
height: 24rem;
|
||||
border: 1px solid #ffffff20;
|
||||
border-radius: 50%;
|
||||
right: -13rem;
|
||||
top: -9rem;
|
||||
box-shadow:
|
||||
0 0 0 2.5rem #ffffff08,
|
||||
0 0 0 5rem #ffffff06;
|
||||
}
|
||||
.face[data-tone="green"] {
|
||||
--card-base: #07543c;
|
||||
--card-light: #21844a;
|
||||
}
|
||||
.face[data-tone="yellow"] {
|
||||
--card-base: #edbe26;
|
||||
--card-light: #ffe478;
|
||||
color: #252316;
|
||||
}
|
||||
.face[data-tone="red"] {
|
||||
--card-base: #980f28;
|
||||
--card-light: #d63244;
|
||||
}
|
||||
.face[data-tone="blue"] {
|
||||
--card-base: #073f86;
|
||||
--card-light: #226db8;
|
||||
}
|
||||
.top,
|
||||
.bottom {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
.bank {
|
||||
font-size: 1.05rem;
|
||||
font-weight: 750;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.archive {
|
||||
font-size: 0.7rem;
|
||||
border: 1px solid currentColor;
|
||||
border-radius: 2rem;
|
||||
padding: 0.2rem 0.5rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.hardware {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.7rem;
|
||||
margin: 1.4rem 0 1.1rem;
|
||||
}
|
||||
.chip {
|
||||
display: block;
|
||||
width: 2.5rem;
|
||||
height: 1.9rem;
|
||||
border: 1px solid #a99054;
|
||||
border-radius: 0.4rem;
|
||||
background:
|
||||
linear-gradient(
|
||||
90deg,
|
||||
transparent 30%,
|
||||
#9b875a 31%,
|
||||
transparent 33%,
|
||||
transparent 66%,
|
||||
#9b875a 67%,
|
||||
transparent 69%
|
||||
),
|
||||
linear-gradient(
|
||||
0deg,
|
||||
transparent 32%,
|
||||
#9b875a 33%,
|
||||
transparent 36%,
|
||||
transparent 65%,
|
||||
#9b875a 66%,
|
||||
transparent 69%
|
||||
),
|
||||
linear-gradient(135deg, #e5d6a6, #bfaa75 50%, #f1e6c4);
|
||||
}
|
||||
.number {
|
||||
font-family: var(--mantine-font-family-monospace);
|
||||
font-size: clamp(1rem, 2.3vw, 1.35rem);
|
||||
letter-spacing: 0.06em;
|
||||
white-space: nowrap;
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
.details {
|
||||
min-width: 0;
|
||||
}
|
||||
.name {
|
||||
font-size: 0.8rem;
|
||||
opacity: 0.9;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.balance {
|
||||
font-size: clamp(1.2rem, 2.5vw, 1.55rem);
|
||||
font-weight: 650;
|
||||
overflow-wrap: anywhere;
|
||||
margin-top: 0.2rem;
|
||||
}
|
||||
|
||||
.network {
|
||||
flex-shrink: 0;
|
||||
font-weight: 850;
|
||||
font-style: italic;
|
||||
font-size: 1.35rem;
|
||||
}
|
||||
.network[data-network="mastercard"] {
|
||||
font-size: 0.65rem;
|
||||
font-weight: 600;
|
||||
font-style: normal;
|
||||
text-align: center;
|
||||
}
|
||||
.circles {
|
||||
display: block;
|
||||
width: 3.3rem;
|
||||
height: 2rem;
|
||||
margin: 0 auto 0.15rem;
|
||||
position: relative;
|
||||
}
|
||||
.circles::before,
|
||||
.circles::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 0;
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
border-radius: 50%;
|
||||
}
|
||||
.circles::before {
|
||||
left: 0;
|
||||
background: #eb302b;
|
||||
}
|
||||
.circles::after {
|
||||
right: 0;
|
||||
background: #ffad19;
|
||||
opacity: 0.9;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { SimpleGrid } from "@mantine/core";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { BankCardFace } from "./BankCardFace";
|
||||
|
||||
const meta = {
|
||||
title: "Product/BankCards/CardAppearance",
|
||||
component: BankCardFace,
|
||||
tags: ["autodocs"],
|
||||
args: {
|
||||
card: {
|
||||
id: "fictional",
|
||||
name: "Для повседневных покупок",
|
||||
bankName: "Сбербанк",
|
||||
lastFour: "4829",
|
||||
paymentSystem: "mir",
|
||||
openingBalance: { value: "0", currency: "RUB" },
|
||||
openingDate: "2026-01-01",
|
||||
balance: { value: "128450.75", currency: "RUB" },
|
||||
archivedAt: null,
|
||||
version: 1,
|
||||
},
|
||||
},
|
||||
} satisfies Meta<typeof BankCardFace>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
export const Banks: Story = {
|
||||
render: (args) => (
|
||||
<SimpleGrid cols={{ base: 1, sm: 2 }} maw={920}>
|
||||
{["Сбербанк", "Т-Банк", "Альфа-Банк", "ВТБ", null].map(
|
||||
(bankName, index) => (
|
||||
<BankCardFace
|
||||
key={bankName ?? "unknown"}
|
||||
card={{
|
||||
...args.card,
|
||||
bankName,
|
||||
paymentSystem:
|
||||
(["mir", "mastercard", "visa", "mir", null] as const)[index] ??
|
||||
null,
|
||||
}}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</SimpleGrid>
|
||||
),
|
||||
};
|
||||
export const MissingDetails: Story = {
|
||||
args: {
|
||||
card: {
|
||||
...meta.args.card,
|
||||
bankName: null,
|
||||
lastFour: null,
|
||||
paymentSystem: null,
|
||||
},
|
||||
},
|
||||
};
|
||||
export const LongArchived: Story = {
|
||||
args: {
|
||||
card: {
|
||||
...meta.args.card,
|
||||
name: "Карта с очень длинным пользовательским названием для повседневных покупок",
|
||||
bankName: "Банк с очень длинным названием без пробелов".repeat(2),
|
||||
archivedAt: "2026-09-12",
|
||||
paymentSystem: "mastercard",
|
||||
balance: { value: "184467440737095516.14", currency: "RUB" },
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { FC } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { formatMoney } from "@/shared/lib";
|
||||
import type { BankCard } from "../api/queries";
|
||||
import classes from "./BankCardFace.module.css";
|
||||
|
||||
type BankCardFaceProps = { card: BankCard };
|
||||
const BankCardFace: FC<BankCardFaceProps> = (props) => {
|
||||
const { card } = props;
|
||||
const { t } = useTranslation();
|
||||
const bank = card.bankName?.toLocaleLowerCase("ru") ?? "";
|
||||
const tone = /сбер|sber/.test(bank)
|
||||
? "green"
|
||||
: /тинькофф|т[ -]?банк|t[ -]?bank|tinkoff/.test(bank)
|
||||
? "yellow"
|
||||
: /альфа|alfa/.test(bank)
|
||||
? "red"
|
||||
: /втб|vtb|газпром|gazprom/.test(bank)
|
||||
? "blue"
|
||||
: "graphite";
|
||||
return (
|
||||
<div className={classes.face} data-tone={tone}>
|
||||
<div className={classes.top}>
|
||||
<span className={classes.bank}>{card.bankName || t("bank.card")}</span>
|
||||
{card.archivedAt && (
|
||||
<span className={classes.archive}>{t("bank.archived")}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className={classes.hardware} aria-hidden="true">
|
||||
<span className={classes.chip} />
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
width="24"
|
||||
height="30"
|
||||
viewBox="0 0 24 30"
|
||||
fill="none"
|
||||
>
|
||||
<path
|
||||
d="M7 11a8 8 0 0 1 0 8m5-12a15 15 0 0 1 0 16m5-20a23 23 0 0 1 0 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div
|
||||
className={classes.number}
|
||||
>{`•••• •••• •••• ${card.lastFour || "••••"}`}</div>
|
||||
<div className={classes.bottom}>
|
||||
<div className={classes.details}>
|
||||
<div className={classes.name}>{card.name}</div>
|
||||
<div className={classes.balance}>{formatMoney(card.balance)}</div>
|
||||
</div>
|
||||
{card.paymentSystem && (
|
||||
<span className={classes.network} data-network={card.paymentSystem}>
|
||||
{card.paymentSystem === "mastercard" && (
|
||||
<span className={classes.circles} aria-hidden="true" />
|
||||
)}
|
||||
{t(`bank.paymentSystems.${card.paymentSystem}`)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export { BankCardFace };
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import type { BankCardValues } from "../model/form-validation";
|
||||
import { BankCardFields } from "./BankCardForm.view";
|
||||
|
||||
const meta = {
|
||||
title: "Product/BankCards/CardFields",
|
||||
component: BankCardFields,
|
||||
tags: ["autodocs"],
|
||||
args: { archived: false },
|
||||
decorators: [
|
||||
(Story) => {
|
||||
const methods = useForm<BankCardValues>({
|
||||
defaultValues: {
|
||||
name: "Учебная повседневная карта",
|
||||
bankName: "Вымышленный банк",
|
||||
lastFour: "1234",
|
||||
openingBalance: "-92233720368547758.08",
|
||||
openingDate: "2026-08-01",
|
||||
},
|
||||
});
|
||||
return (
|
||||
<FormProvider {...methods}>
|
||||
<Story />
|
||||
</FormProvider>
|
||||
);
|
||||
},
|
||||
],
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
"Поля ручной дебетовой карты на вымышленных данных. Сохранения и обращения к API нет. Архив оставляет описательные сведения доступными, а финансовые поля — только для чтения.",
|
||||
},
|
||||
},
|
||||
},
|
||||
} satisfies Meta<typeof BankCardFields>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
export const Active: Story = { name: "Независимая карта в рублях" };
|
||||
export const Archived: Story = {
|
||||
name: "Финансовые поля архивной карты",
|
||||
args: { archived: true },
|
||||
};
|
||||
@@ -0,0 +1,145 @@
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { HttpResponse, http } from "msw";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createTestQueryClient } from "@/test/query";
|
||||
import { server } from "@/test/server";
|
||||
import type { BankCard } from "../api/queries";
|
||||
import { BankCardForm } from "./BankCardForm";
|
||||
|
||||
const card: BankCard = {
|
||||
id: "a",
|
||||
name: "Основная",
|
||||
bankName: "Банк",
|
||||
lastFour: "1234",
|
||||
paymentSystem: null,
|
||||
openingBalance: { currency: "RUB", value: "100" },
|
||||
balance: { currency: "RUB", value: "50" },
|
||||
openingDate: "2026-01-01",
|
||||
archivedAt: null,
|
||||
version: 1,
|
||||
};
|
||||
function setup(value: BankCard) {
|
||||
configureAuthClient({
|
||||
accessToken: () => "test",
|
||||
refresh: async () => false,
|
||||
clear: () => {},
|
||||
});
|
||||
server.use(http.get("*/api/v1/bank-cards/a", () => HttpResponse.json(value)));
|
||||
const close = vi.fn();
|
||||
render(
|
||||
<QueryClientProvider client={createTestQueryClient()}>
|
||||
<MantineProvider env="test">
|
||||
<BankCardForm card={value} onClose={close} />
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
return close;
|
||||
}
|
||||
describe("BankCardForm", () => {
|
||||
it("clears optional metadata on archive while omitting protected financial fields", async () => {
|
||||
const close = setup({ ...card, archivedAt: "2026-09-01" });
|
||||
expect(screen.getByLabelText(/Начальный остаток/)).toHaveAttribute(
|
||||
"readonly",
|
||||
);
|
||||
expect(screen.getByLabelText(/Дата начала/)).toHaveAttribute("readonly");
|
||||
fireEvent.change(screen.getByLabelText(/Банк/), { target: { value: "" } });
|
||||
fireEvent.change(screen.getByLabelText(/Последние четыре/), {
|
||||
target: { value: "" },
|
||||
});
|
||||
let body: unknown;
|
||||
server.use(
|
||||
http.patch("*/api/v1/bank-cards/a", async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json(card);
|
||||
}),
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||
expect(body).toEqual({
|
||||
version: 1,
|
||||
name: "Основная",
|
||||
bankName: null,
|
||||
lastFour: null,
|
||||
paymentSystem: null,
|
||||
});
|
||||
});
|
||||
it("loads and saves the selected payment system", async () => {
|
||||
const close = setup({ ...card, paymentSystem: "mir" });
|
||||
expect(
|
||||
screen.getByRole("combobox", { name: /Платёжная система/ }),
|
||||
).toHaveValue("МИР");
|
||||
fireEvent.click(
|
||||
screen.getByRole("combobox", { name: /Платёжная система/ }),
|
||||
);
|
||||
fireEvent.click(await screen.findByRole("option", { name: "Visa" }));
|
||||
let body: unknown;
|
||||
server.use(
|
||||
http.patch("*/api/v1/bank-cards/a", async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({ ...card, paymentSystem: "visa" });
|
||||
}),
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||
expect(body).toMatchObject({ paymentSystem: "visa" });
|
||||
});
|
||||
|
||||
it("retains an invalid opening date draft and explains conflict with saved history", async () => {
|
||||
const close = setup(card);
|
||||
fireEvent.change(screen.getByLabelText(/Дата начала/), {
|
||||
target: { value: "01.08.2026" },
|
||||
});
|
||||
server.use(
|
||||
http.patch("*/api/v1/bank-cards/a", () =>
|
||||
HttpResponse.json(
|
||||
{ code: "BANK_OPENING_DATE_CONFLICT" },
|
||||
{ status: 400 },
|
||||
),
|
||||
),
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await screen.findByText(
|
||||
"Дата начала противоречит сохранённой истории карты.",
|
||||
);
|
||||
expect(screen.getByLabelText(/Дата начала/)).toHaveValue("01.08.2026");
|
||||
expect(close).not.toHaveBeenCalled();
|
||||
});
|
||||
it("keeps card edit version until explicit refresh adoption", async () => {
|
||||
const close = setup(card);
|
||||
let version = 1;
|
||||
const bodies: Record<string, unknown>[] = [];
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/a", () =>
|
||||
HttpResponse.json({ ...card, version }),
|
||||
),
|
||||
http.patch("*/api/v1/bank-cards/a", async ({ request }) => {
|
||||
const body = (await request.json()) as Record<string, unknown>;
|
||||
bodies.push(body);
|
||||
version = 2;
|
||||
return body.version === 1
|
||||
? HttpResponse.json(
|
||||
{ code: "BANK_VERSION_CONFLICT" },
|
||||
{ status: 409 },
|
||||
)
|
||||
: HttpResponse.json(card);
|
||||
}),
|
||||
);
|
||||
fireEvent.change(screen.getByLabelText(/Название карты/), {
|
||||
target: { value: "Мой черновик" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await screen.findByText(/Запись уже изменена/);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Перечитать запись" }));
|
||||
const adopt = await screen.findByRole("button", {
|
||||
name: "Использовать актуальную версию 2",
|
||||
});
|
||||
expect(screen.getByLabelText(/Название карты/)).toHaveValue("Мой черновик");
|
||||
fireEvent.click(adopt);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||
expect(bodies.map((b) => b.version)).toEqual([1, 2]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,147 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Button, Group, Modal, Stack, Text } from "@mantine/core";
|
||||
import { type FC, useState } from "react";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { formatDate } from "@/shared/lib";
|
||||
import { useBankMutations } from "../api/mutations";
|
||||
import { type BankCard, useBankCard } from "../api/queries";
|
||||
import {
|
||||
type BankCardValues,
|
||||
bankCardSchema,
|
||||
bankMoneyValue,
|
||||
bankToday,
|
||||
} from "../model/form-validation";
|
||||
import { BankCardFields } from "./BankCardForm.view";
|
||||
import { BankFeedback } from "./BankFeedback";
|
||||
import classes from "./BankForms.module.css";
|
||||
import { useBankFormFocus } from "./useBankFormFocus";
|
||||
|
||||
type BankCardFormProps = { card?: BankCard; onClose: () => void };
|
||||
const BankCardForm: FC<BankCardFormProps> = (props) => {
|
||||
useBankFormFocus();
|
||||
const { t } = useTranslation();
|
||||
const [intent] = useState(() => crypto.randomUUID());
|
||||
const [version, setVersion] = useState(props.card?.version ?? 1);
|
||||
const [error, setError] = useState<unknown>();
|
||||
const [latest, setLatest] = useState<BankCard>();
|
||||
const fresh = useBankCard(props.card?.id);
|
||||
const mutation = useBankMutations();
|
||||
const methods = useForm<BankCardValues>({
|
||||
resolver: zodResolver(bankCardSchema),
|
||||
defaultValues: {
|
||||
name: props.card?.name ?? "",
|
||||
bankName: props.card?.bankName ?? "",
|
||||
lastFour: props.card?.lastFour ?? "",
|
||||
paymentSystem: props.card?.paymentSystem ?? "",
|
||||
openingBalance: props.card?.openingBalance.value ?? "0",
|
||||
openingDate: props.card?.openingDate ?? bankToday(),
|
||||
},
|
||||
});
|
||||
const pending =
|
||||
methods.formState.isSubmitting || (fresh.isFetching && Boolean(error));
|
||||
return (
|
||||
<Modal
|
||||
opened
|
||||
onClose={() => !pending && props.onClose()}
|
||||
title={t(props.card ? "bank.editCard" : "bank.addCard")}
|
||||
closeButtonProps={{ "aria-label": t("bank.close"), disabled: pending }}
|
||||
closeOnClickOutside={!pending}
|
||||
closeOnEscape={!pending}
|
||||
>
|
||||
<FormProvider {...methods}>
|
||||
<form
|
||||
onSubmit={methods.handleSubmit(async (values) => {
|
||||
setError(undefined);
|
||||
try {
|
||||
const metadata = {
|
||||
name: values.name,
|
||||
bankName: values.bankName || null,
|
||||
lastFour: values.lastFour || null,
|
||||
paymentSystem: values.paymentSystem || null,
|
||||
};
|
||||
const financial = {
|
||||
openingBalance: {
|
||||
currency: "RUB" as const,
|
||||
value: bankMoneyValue(values.openingBalance),
|
||||
},
|
||||
openingDate: values.openingDate,
|
||||
};
|
||||
if (props.card)
|
||||
await mutation.updateCard.mutateAsync({
|
||||
id: props.card.id,
|
||||
body: {
|
||||
...metadata,
|
||||
...(!props.card.archivedAt ? financial : {}),
|
||||
version,
|
||||
},
|
||||
});
|
||||
else
|
||||
await mutation.createCard.mutateAsync({
|
||||
id: intent,
|
||||
...metadata,
|
||||
...financial,
|
||||
});
|
||||
props.onClose();
|
||||
} catch (failure) {
|
||||
setError(failure);
|
||||
}
|
||||
})}
|
||||
>
|
||||
<fieldset className={classes.fieldset} disabled={pending}>
|
||||
<Stack>
|
||||
<BankCardFields archived={Boolean(props.card?.archivedAt)} />
|
||||
{error ? (
|
||||
<>
|
||||
<BankFeedback error={error} />
|
||||
{props.card && (
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={async () => {
|
||||
const response = await fresh.refetch();
|
||||
if (response.data && !response.error)
|
||||
setLatest(response.data);
|
||||
else setError(response.error);
|
||||
}}
|
||||
>
|
||||
{t("bank.reloadRecord")}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
{latest && (
|
||||
<>
|
||||
<Text>
|
||||
{t("bank.versionHint", {
|
||||
details: `${latest.name} · ${latest.openingBalance.value} RUB · ${formatDate(latest.openingDate)}`,
|
||||
})}
|
||||
</Text>
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={() => {
|
||||
setVersion(latest.version);
|
||||
setLatest(undefined);
|
||||
setError(undefined);
|
||||
}}
|
||||
>
|
||||
{t("bank.adoptVersion", { version: latest.version })}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Group>
|
||||
<Button type="submit" loading={pending}>
|
||||
{t("bank.save")}
|
||||
</Button>
|
||||
<Button variant="default" onClick={props.onClose}>
|
||||
{t("bank.cancel")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</fieldset>
|
||||
</form>
|
||||
</FormProvider>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export { BankCardForm };
|
||||
@@ -0,0 +1,112 @@
|
||||
import { Select, Stack, Text, TextInput } from "@mantine/core";
|
||||
import { DateInput } from "@mantine/dates";
|
||||
import type { FC } from "react";
|
||||
import { Controller, useFormContext } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
type BankCardValues,
|
||||
bankDateInputValue,
|
||||
bankDateSchema,
|
||||
bankToday,
|
||||
} from "../model/form-validation";
|
||||
|
||||
type BankCardFieldsProps = { archived: boolean };
|
||||
const BankCardFields: FC<BankCardFieldsProps> = (props) => {
|
||||
const {
|
||||
control,
|
||||
register,
|
||||
formState: { errors },
|
||||
} = useFormContext<BankCardValues>();
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Stack>
|
||||
<TextInput
|
||||
label={t("bank.name")}
|
||||
required
|
||||
{...register("name")}
|
||||
error={errors.name?.message}
|
||||
/>
|
||||
<TextInput
|
||||
label={t("bank.bankName")}
|
||||
{...register("bankName")}
|
||||
error={errors.bankName?.message}
|
||||
/>
|
||||
<TextInput
|
||||
label={t("bank.lastFour")}
|
||||
inputMode="numeric"
|
||||
{...register("lastFour")}
|
||||
error={errors.lastFour?.message}
|
||||
/>
|
||||
<Controller
|
||||
control={control}
|
||||
name="paymentSystem"
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
{...field}
|
||||
value={field.value || null}
|
||||
onChange={(value) => field.onChange(value ?? "")}
|
||||
label={t("bank.paymentSystem")}
|
||||
placeholder={t("bank.paymentSystemUnknown")}
|
||||
clearable
|
||||
data={["mir", "visa", "mastercard"].map((value) => ({
|
||||
value,
|
||||
label: t(`bank.paymentSystems.${value}`),
|
||||
}))}
|
||||
comboboxProps={{ withinPortal: false }}
|
||||
error={errors.paymentSystem?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<TextInput
|
||||
label={t("bank.openingBalance")}
|
||||
required
|
||||
inputMode="decimal"
|
||||
readOnly={props.archived}
|
||||
{...register("openingBalance")}
|
||||
error={errors.openingBalance?.message}
|
||||
/>
|
||||
<Controller
|
||||
control={control}
|
||||
name="openingDate"
|
||||
render={({ field }) => (
|
||||
<DateInput
|
||||
{...field}
|
||||
label={t("bank.openingDate")}
|
||||
required
|
||||
valueFormat="DD.MM.YYYY"
|
||||
value={
|
||||
bankDateSchema.safeParse(field.value).success ? field.value : null
|
||||
}
|
||||
dateParser={(value) =>
|
||||
bankDateSchema.safeParse(bankDateInputValue(value)).success
|
||||
? bankDateInputValue(value)
|
||||
: null
|
||||
}
|
||||
fixOnBlur={false}
|
||||
onInput={(event) =>
|
||||
field.onChange(bankDateInputValue(event.currentTarget.value))
|
||||
}
|
||||
onChange={(value) => field.onChange(value ?? "")}
|
||||
onBlur={(event) => {
|
||||
field.onChange(bankDateInputValue(event.currentTarget.value));
|
||||
field.onBlur();
|
||||
}}
|
||||
maxDate={bankToday()}
|
||||
popoverProps={{
|
||||
withinPortal: false,
|
||||
middlewares: { shift: { crossAxis: true } },
|
||||
}}
|
||||
readOnly={props.archived}
|
||||
error={errors.openingDate?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("bank.openingHint")}
|
||||
</Text>
|
||||
{props.archived && <Text>{t("bank.archiveHint")}</Text>}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export { BankCardFields };
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Alert, Button, Group, Text } from "@mantine/core";
|
||||
import type { FC } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { apiErrorCode } from "@/shared/api";
|
||||
|
||||
type BankFeedbackProps = {
|
||||
error: unknown;
|
||||
retry?: () => void;
|
||||
cached?: boolean;
|
||||
loadingError?: boolean;
|
||||
};
|
||||
const BankFeedback: FC<BankFeedbackProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
const code = apiErrorCode(props.error);
|
||||
return (
|
||||
<Alert color="orange" role="alert">
|
||||
<Group>
|
||||
<Text>
|
||||
{props.cached
|
||||
? t("bank.refreshError")
|
||||
: t(`bank.errors.${code}` as "bank.errors.BANK_INVALID_INPUT", {
|
||||
defaultValue: t(
|
||||
props.loadingError ? "bank.error" : "bank.requestError",
|
||||
),
|
||||
})}
|
||||
</Text>
|
||||
{props.retry && (
|
||||
<Button variant="default" onClick={props.retry}>
|
||||
{t("bank.retry")}
|
||||
</Button>
|
||||
)}
|
||||
</Group>
|
||||
</Alert>
|
||||
);
|
||||
};
|
||||
|
||||
export { BankFeedback };
|
||||
@@ -0,0 +1,6 @@
|
||||
.fieldset {
|
||||
border: 0;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
.icon {
|
||||
overflow: visible;
|
||||
|
||||
& path {
|
||||
--motion: none;
|
||||
transform-box: fill-box;
|
||||
transform-origin: center;
|
||||
}
|
||||
}
|
||||
|
||||
.deposit path:nth-child(-n + 2) {
|
||||
transform-box: view-box;
|
||||
transform-origin: 12px 9px;
|
||||
--motion: bank-operation-coin-turn 1000ms ease-in-out both;
|
||||
}
|
||||
|
||||
.repayment path:last-child {
|
||||
--motion: bank-operation-ruble-in 1000ms ease-out both;
|
||||
}
|
||||
|
||||
.topup path:last-child {
|
||||
--motion: bank-operation-plus-in 900ms ease-out both;
|
||||
}
|
||||
|
||||
.transfer path {
|
||||
--shift: 3px;
|
||||
--motion: bank-operation-exchange 700ms ease-in-out both;
|
||||
&:last-child {
|
||||
--shift: -3px;
|
||||
}
|
||||
}
|
||||
|
||||
.growth {
|
||||
& path:nth-child(2) {
|
||||
stroke-dasharray: 1;
|
||||
--motion: bank-operation-draw 450ms ease-out both;
|
||||
}
|
||||
& path:last-child {
|
||||
--motion: bank-operation-arrow-rise 350ms ease-out 400ms both;
|
||||
}
|
||||
}
|
||||
|
||||
.server {
|
||||
& path:nth-child(3) {
|
||||
--motion: bank-operation-blink 500ms ease-in-out both;
|
||||
}
|
||||
& path:nth-child(4) {
|
||||
--motion: bank-operation-blink 500ms ease-in-out 220ms both;
|
||||
}
|
||||
}
|
||||
|
||||
.basket {
|
||||
& path:not(:last-child) {
|
||||
--motion: bank-operation-settle 850ms ease-in-out both;
|
||||
}
|
||||
& path:last-child {
|
||||
opacity: 0;
|
||||
fill: currentColor;
|
||||
--motion: bank-operation-grocery-drop 850ms ease-out both;
|
||||
}
|
||||
}
|
||||
|
||||
.wine {
|
||||
--motion: bank-operation-cheers 1100ms ease-in-out both;
|
||||
transform-origin: 12px 21px;
|
||||
& path:nth-child(2) {
|
||||
fill: currentColor;
|
||||
fill-opacity: 0.2;
|
||||
transform-origin: bottom;
|
||||
--motion: bank-operation-fill-glass 1100ms ease-out both;
|
||||
}
|
||||
}
|
||||
|
||||
.coffee {
|
||||
& path:nth-child(3),
|
||||
& path:nth-child(4) {
|
||||
--motion: bank-operation-steam 1000ms ease-out var(--delay, 0ms) both;
|
||||
}
|
||||
& path:nth-child(4) {
|
||||
--delay: 180ms;
|
||||
}
|
||||
}
|
||||
|
||||
.grid path {
|
||||
--x: -1.5px;
|
||||
--y: -1.5px;
|
||||
--turn: 0deg;
|
||||
--motion: bank-operation-rearrange 850ms ease-in-out both;
|
||||
&:nth-child(2) {
|
||||
--x: 1.5px;
|
||||
--turn: 90deg;
|
||||
}
|
||||
&:nth-child(3) {
|
||||
--y: 1.5px;
|
||||
}
|
||||
&:nth-child(4) {
|
||||
--x: 1.5px;
|
||||
--y: 1.5px;
|
||||
}
|
||||
}
|
||||
|
||||
.wifi path {
|
||||
--motion: bank-operation-signal 450ms ease-out var(--delay, 0ms) both;
|
||||
&:nth-child(1) {
|
||||
--delay: 360ms;
|
||||
}
|
||||
&:nth-child(2) {
|
||||
--delay: 240ms;
|
||||
}
|
||||
&:nth-child(3) {
|
||||
--delay: 120ms;
|
||||
}
|
||||
}
|
||||
|
||||
.car {
|
||||
--motion: bank-operation-drive 1100ms ease-in-out both;
|
||||
& path:nth-child(-n + 3) {
|
||||
--motion: bank-operation-suspension 275ms ease-in-out 4 both;
|
||||
}
|
||||
& path:nth-last-child(-n + 2) {
|
||||
--motion: bank-operation-wheel-roll 1100ms ease-in-out both;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.icon[data-icon-animating] {
|
||||
animation: var(--motion, none);
|
||||
& path {
|
||||
animation: var(--motion, none);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-coin-turn) {
|
||||
0%,
|
||||
100% {
|
||||
transform: scaleX(1);
|
||||
}
|
||||
35%,
|
||||
65% {
|
||||
transform: scaleX(0.12);
|
||||
}
|
||||
50% {
|
||||
transform: scaleX(-1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-settle) {
|
||||
0%,
|
||||
30%,
|
||||
100% {
|
||||
transform: translateY(0);
|
||||
}
|
||||
45% {
|
||||
transform: translateY(1.5px);
|
||||
}
|
||||
65% {
|
||||
transform: translateY(-0.5px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-ruble-in) {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateY(-9px) scale(0.7);
|
||||
}
|
||||
25% {
|
||||
opacity: 1;
|
||||
}
|
||||
65% {
|
||||
transform: translateY(0) scale(1.15);
|
||||
}
|
||||
80% {
|
||||
transform: scale(0.95);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-plus-in) {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateY(-5px) scale(0.5);
|
||||
}
|
||||
55% {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1.3);
|
||||
}
|
||||
75% {
|
||||
transform: scale(0.9);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-exchange) {
|
||||
0%,
|
||||
100% {
|
||||
transform: translateX(0);
|
||||
}
|
||||
45% {
|
||||
transform: translateX(var(--shift));
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-draw) {
|
||||
from {
|
||||
stroke-dashoffset: 1;
|
||||
}
|
||||
to {
|
||||
stroke-dashoffset: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-arrow-rise) {
|
||||
0%,
|
||||
100% {
|
||||
transform: translateY(0);
|
||||
}
|
||||
45% {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-blink) {
|
||||
0%,
|
||||
100% {
|
||||
stroke-width: 1.6;
|
||||
}
|
||||
45% {
|
||||
stroke: var(--mantine-color-green-6);
|
||||
stroke-width: 3;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-grocery-drop) {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateY(-5px);
|
||||
}
|
||||
20% {
|
||||
opacity: 1;
|
||||
}
|
||||
55% {
|
||||
opacity: 1;
|
||||
transform: translateY(7px);
|
||||
}
|
||||
80%,
|
||||
100% {
|
||||
opacity: 0;
|
||||
transform: translateY(7px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-fill-glass) {
|
||||
0% {
|
||||
transform: scaleY(0.05);
|
||||
}
|
||||
45%,
|
||||
75% {
|
||||
transform: scaleY(1);
|
||||
fill-opacity: 0.5;
|
||||
}
|
||||
100% {
|
||||
transform: scaleY(1);
|
||||
fill-opacity: 0.2;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-cheers) {
|
||||
0%,
|
||||
40%,
|
||||
100% {
|
||||
transform: rotate(0);
|
||||
}
|
||||
65% {
|
||||
transform: rotate(8deg);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-steam) {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateY(2px);
|
||||
}
|
||||
25% {
|
||||
opacity: 1;
|
||||
}
|
||||
70% {
|
||||
opacity: 0;
|
||||
transform: translateY(-3px);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-rearrange) {
|
||||
0%,
|
||||
100% {
|
||||
transform: translate(0, 0) rotate(0);
|
||||
}
|
||||
50% {
|
||||
transform: translate(var(--x), var(--y)) rotate(var(--turn));
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-signal) {
|
||||
0% {
|
||||
opacity: 0.1;
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-drive) {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateX(-4px);
|
||||
}
|
||||
20% {
|
||||
opacity: 1;
|
||||
}
|
||||
80% {
|
||||
opacity: 1;
|
||||
transform: translateX(3px);
|
||||
}
|
||||
90% {
|
||||
opacity: 0;
|
||||
transform: translateX(4px);
|
||||
}
|
||||
91% {
|
||||
opacity: 0;
|
||||
transform: translateX(0);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-suspension) {
|
||||
0%,
|
||||
100% {
|
||||
transform: translateY(0);
|
||||
}
|
||||
50% {
|
||||
transform: translateY(-0.5px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-wheel-roll) {
|
||||
from {
|
||||
transform: rotate(0);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { Stack } from "@mantine/core";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { EntryCard } from "@/shared/ui";
|
||||
import { BankOperationIcon } from "./BankOperationIcon";
|
||||
|
||||
const meta = {
|
||||
title: "Product/BankCards/OperationIcons",
|
||||
component: BankOperationIcon,
|
||||
tags: ["autodocs"],
|
||||
args: { kind: "expense", categoryName: "Продукты" },
|
||||
} satisfies Meta<typeof BankOperationIcon>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
export const Categories: Story = {
|
||||
render: () => (
|
||||
<Stack maw={640}>
|
||||
{[
|
||||
"Алкоголь",
|
||||
"Вклады",
|
||||
"Другое",
|
||||
"Жильё",
|
||||
"Здоровье",
|
||||
"Инвестиции и накопления",
|
||||
"Кафе",
|
||||
"Образование",
|
||||
"Переводы",
|
||||
"Погашение кредита",
|
||||
"Подписки",
|
||||
"Покупки",
|
||||
"Продукты",
|
||||
"Путешествия",
|
||||
"Развлечения",
|
||||
"Связь и интернет",
|
||||
"Снятие наличных",
|
||||
"Ставки",
|
||||
"Страхование",
|
||||
"Табак",
|
||||
"Такси",
|
||||
"Транспорт",
|
||||
"Хостинг и ИИ-сервисы",
|
||||
"Цифровые покупки",
|
||||
"Моя категория",
|
||||
].map((name) => (
|
||||
<EntryCard
|
||||
key={name}
|
||||
title="Расход"
|
||||
metadata={`12.09.2026 · ${name}`}
|
||||
initial="Р"
|
||||
color="red"
|
||||
icon={<BankOperationIcon kind="expense" categoryName={name} />}
|
||||
value="−1 250,00 ₽"
|
||||
valueLabel="Расход"
|
||||
tone="negative"
|
||||
/>
|
||||
))}
|
||||
<EntryCard
|
||||
title="Пополнение"
|
||||
metadata="12.09.2026"
|
||||
initial="П"
|
||||
color="green"
|
||||
icon={<BankOperationIcon kind="topup" />}
|
||||
value="+15 000,00 ₽"
|
||||
valueLabel="Пополнение"
|
||||
tone="positive"
|
||||
/>
|
||||
</Stack>
|
||||
),
|
||||
};
|
||||
@@ -0,0 +1,66 @@
|
||||
import { render } from "@testing-library/react";
|
||||
import { expect, it } from "vitest";
|
||||
import { BankOperationIcon } from "./BankOperationIcon";
|
||||
|
||||
it("matches normalized category names, falls back after renaming and distinguishes operation kinds", () => {
|
||||
const { container, rerender } = render(
|
||||
<BankOperationIcon kind="expense" categoryName="Жильё" />,
|
||||
);
|
||||
const path = () => container.querySelector("path")?.getAttribute("d");
|
||||
const housing = path();
|
||||
rerender(<BankOperationIcon kind="expense" categoryName=" ЖИЛЬЕ " />);
|
||||
expect(path()).toBe(housing);
|
||||
rerender(<BankOperationIcon kind="expense" categoryName="Другое" />);
|
||||
const fallback = path();
|
||||
expect(fallback).not.toBe(housing);
|
||||
for (const categoryName of ["Моя категория", "constructor", null]) {
|
||||
rerender(<BankOperationIcon kind="expense" categoryName={categoryName} />);
|
||||
expect(path()).toBe(fallback);
|
||||
}
|
||||
const paths = [fallback, housing];
|
||||
for (const kind of ["topup", "transfer", "refund"] as const) {
|
||||
rerender(<BankOperationIcon kind={kind} categoryName="Жильё" />);
|
||||
expect(path()).toBeTruthy();
|
||||
paths.push(path());
|
||||
}
|
||||
expect(new Set(paths).size).toBe(5);
|
||||
expect(container.querySelector("svg")).toHaveAttribute("aria-hidden", "true");
|
||||
});
|
||||
|
||||
it("provides a distinct icon for every existing named category", () => {
|
||||
const { container, rerender } = render(
|
||||
<BankOperationIcon kind="expense" categoryName="Другое" />,
|
||||
);
|
||||
const paths = new Set([container.querySelector("path")?.getAttribute("d")]);
|
||||
for (const categoryName of [
|
||||
"Алкоголь",
|
||||
"Вклады",
|
||||
"Жильё",
|
||||
"Здоровье",
|
||||
"Инвестиции и накопления",
|
||||
"Кафе",
|
||||
"Образование",
|
||||
"Переводы",
|
||||
"Погашение кредита",
|
||||
"Подписки",
|
||||
"Покупки",
|
||||
"Продукты",
|
||||
"Путешествия",
|
||||
"Развлечения",
|
||||
"Связь и интернет",
|
||||
"Снятие наличных",
|
||||
"Ставки",
|
||||
"Страхование",
|
||||
"Табак",
|
||||
"Такси",
|
||||
"Транспорт",
|
||||
"Хостинг и ИИ-сервисы",
|
||||
"Цифровые покупки",
|
||||
]) {
|
||||
rerender(<BankOperationIcon kind="expense" categoryName={categoryName} />);
|
||||
const path = container.querySelector("path")?.getAttribute("d");
|
||||
expect(path).toBeTruthy();
|
||||
expect(paths.has(path), categoryName).toBe(false);
|
||||
paths.add(path);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { FC } from "react";
|
||||
import { bindIconAnimation } from "@/shared/lib";
|
||||
import type { BankOperation } from "../api/queries";
|
||||
|
||||
import { bankOperationAppearance } from "../model/operation-appearance";
|
||||
import classes from "./BankOperationIcon.module.css";
|
||||
|
||||
type BankOperationIconProps = {
|
||||
kind: BankOperation["kind"];
|
||||
categoryName?: string | null;
|
||||
};
|
||||
const BankOperationIcon: FC<BankOperationIconProps> = (props) => {
|
||||
const icon = bankOperationAppearance(props.kind, props.categoryName);
|
||||
return (
|
||||
<svg
|
||||
ref={bindIconAnimation}
|
||||
className={`${classes.icon} ${icon.animation ? classes[icon.animation] : ""}`}
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.6"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
style={{ flexShrink: 0, color: `var(--mantine-color-${icon.color}-7)` }}
|
||||
>
|
||||
{icon.path.split(" M").map((part, index) => (
|
||||
<path key={part} d={index ? `M${part}` : part} pathLength={1} />
|
||||
))}
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export { BankOperationIcon };
|
||||
@@ -0,0 +1,64 @@
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--mantine-spacing-xs) var(--mantine-spacing-lg);
|
||||
}
|
||||
|
||||
.total {
|
||||
font-size: var(--mantine-font-size-xl);
|
||||
font-weight: 650;
|
||||
letter-spacing: -0.025em;
|
||||
font-variant-numeric: tabular-nums;
|
||||
overflow-wrap: anywhere;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.categories {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
grid-template-rows: repeat(var(--category-rows), auto);
|
||||
grid-auto-flow: column;
|
||||
column-gap: var(--mantine-spacing-xl);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.category {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--mantine-spacing-md);
|
||||
padding-block: var(--mantine-spacing-sm);
|
||||
border-top: 1px solid var(--mantine-color-gray-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--mantine-spacing-xs);
|
||||
min-width: 0;
|
||||
font-size: var(--mantine-font-size-sm);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.amount {
|
||||
flex-shrink: 0;
|
||||
max-width: 60%;
|
||||
margin: 0;
|
||||
font-size: var(--mantine-font-size-sm);
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
text-align: right;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
@media (max-width: 48em) {
|
||||
.categories {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
grid-template-rows: none;
|
||||
grid-auto-flow: row;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { BankSummaryView } from "./BankSummary.view";
|
||||
|
||||
const money = (value: string) => ({ currency: "RUB", value });
|
||||
const meta = {
|
||||
title: "Product/BankCards/Summary",
|
||||
component: BankSummaryView,
|
||||
tags: ["autodocs"],
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
"Месячные расходы ручного учёта. Вымышленные суммы, без API и сохранения. Один итог с учётом возвратов и компактные строки категорий. Отрицательные суммы сохраняют знак.",
|
||||
},
|
||||
},
|
||||
},
|
||||
args: {
|
||||
loading: false,
|
||||
error: false,
|
||||
fetching: false,
|
||||
retry: () => {},
|
||||
data: {
|
||||
month: "2026-09",
|
||||
cardId: null,
|
||||
expenses: money("8500"),
|
||||
refunds: money("1000"),
|
||||
net: money("7500"),
|
||||
categories: [
|
||||
{
|
||||
categoryId: "food",
|
||||
categoryName: "Продукты",
|
||||
expenses: money("3500"),
|
||||
refunds: money("1000"),
|
||||
net: money("2500"),
|
||||
},
|
||||
{
|
||||
categoryId: "cafe",
|
||||
categoryName: "Кафе",
|
||||
expenses: money("2200"),
|
||||
refunds: money("0"),
|
||||
net: money("2200"),
|
||||
},
|
||||
{
|
||||
categoryId: "taxi",
|
||||
categoryName: "Такси",
|
||||
expenses: money("1800"),
|
||||
refunds: money("0"),
|
||||
net: money("1800"),
|
||||
},
|
||||
{
|
||||
categoryId: "health",
|
||||
categoryName: "Здоровье",
|
||||
expenses: money("1000"),
|
||||
refunds: money("0"),
|
||||
net: money("1000"),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
} satisfies Meta<typeof BankSummaryView>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
export const Loaded: Story = { name: "Расходы по категориям" };
|
||||
export const RefundMonth: Story = {
|
||||
name: "Возврат покупки прошлого месяца",
|
||||
args: {
|
||||
data: {
|
||||
month: "2026-09",
|
||||
cardId: null,
|
||||
expenses: money("0"),
|
||||
refunds: money("600"),
|
||||
net: money("-600"),
|
||||
categories: [
|
||||
{
|
||||
categoryId: "shopping",
|
||||
categoryName:
|
||||
"Покупки с длинным пользовательским названием категории",
|
||||
expenses: money("0"),
|
||||
refunds: money("600"),
|
||||
net: money("-600"),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
export const Empty: Story = {
|
||||
name: "Известные нули",
|
||||
args: {
|
||||
data: {
|
||||
month: "2026-09",
|
||||
cardId: null,
|
||||
expenses: money("0"),
|
||||
refunds: money("0"),
|
||||
net: money("0"),
|
||||
categories: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
export const Loading: Story = {
|
||||
name: "Начальная загрузка",
|
||||
args: { data: undefined, loading: true },
|
||||
};
|
||||
export const Failed: Story = {
|
||||
name: "Ошибка без данных",
|
||||
args: { data: undefined, error: true },
|
||||
};
|
||||
export const CachedError: Story = {
|
||||
name: "Сохранённые суммы при ошибке обновления",
|
||||
args: { error: true },
|
||||
};
|
||||
export const LongAmounts: Story = {
|
||||
name: "Точный итог длиннее предела отдельного ввода",
|
||||
args: {
|
||||
data: {
|
||||
month: "2026-09",
|
||||
cardId: null,
|
||||
expenses: money("184467440737095516.14"),
|
||||
refunds: money("0"),
|
||||
net: money("184467440737095516.14"),
|
||||
categories: [
|
||||
{
|
||||
categoryId: "shopping",
|
||||
categoryName: "Покупки",
|
||||
expenses: money("184467440737095516.14"),
|
||||
refunds: money("0"),
|
||||
net: money("184467440737095516.14"),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,86 @@
|
||||
import { Button, Group, Skeleton, Stack, Text, Title } from "@mantine/core";
|
||||
import type { CSSProperties, FC } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { formatMoney } from "@/shared/lib";
|
||||
import { LoadingSkeleton } from "@/shared/ui";
|
||||
import type { BankSummary } from "../api/queries";
|
||||
import { BankOperationIcon } from "./BankOperationIcon";
|
||||
import classes from "./BankSummary.module.css";
|
||||
|
||||
type BankSummaryViewProps = {
|
||||
data?: BankSummary;
|
||||
loading: boolean;
|
||||
error: boolean;
|
||||
fetching: boolean;
|
||||
retry: () => void;
|
||||
all?: boolean;
|
||||
};
|
||||
const BankSummaryView: FC<BankSummaryViewProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Stack gap="md" aria-busy={props.loading || props.fetching}>
|
||||
<div className={classes.header}>
|
||||
<Title order={2}>
|
||||
{t(props.all ? "bank.allSummary" : "bank.summary")}
|
||||
</Title>
|
||||
{props.data && (
|
||||
<Text className={classes.total}>
|
||||
{formatMoney(props.data.net, { withZeroCents: true })}
|
||||
</Text>
|
||||
)}
|
||||
</div>
|
||||
{props.data ? (
|
||||
props.data.categories.length ? (
|
||||
<dl
|
||||
className={classes.categories}
|
||||
style={
|
||||
{
|
||||
"--category-rows": Math.ceil(props.data.categories.length / 2),
|
||||
} as CSSProperties
|
||||
}
|
||||
>
|
||||
{props.data.categories.map((category) => (
|
||||
<div className={classes.category} key={category.categoryId}>
|
||||
<dt className={classes.label}>
|
||||
<BankOperationIcon
|
||||
kind="expense"
|
||||
categoryName={category.categoryName}
|
||||
/>
|
||||
<span>{category.categoryName}</span>
|
||||
</dt>
|
||||
<dd className={classes.amount}>
|
||||
{formatMoney(category.net, { withZeroCents: true })}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
) : (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("bank.noExpenses")}
|
||||
</Text>
|
||||
)
|
||||
) : props.loading ? (
|
||||
<LoadingSkeleton label={t("bank.loading")}>
|
||||
<Stack gap="sm">
|
||||
<Skeleton h={32} w="35%" />
|
||||
<Skeleton h={40} />
|
||||
<Skeleton h={40} />
|
||||
</Stack>
|
||||
</LoadingSkeleton>
|
||||
) : null}
|
||||
{props.error && (
|
||||
<Group role="alert">
|
||||
<Text>{t(props.data ? "bank.refreshError" : "bank.error")}</Text>
|
||||
<Button variant="default" onClick={props.retry}>
|
||||
{t("bank.retry")}
|
||||
</Button>
|
||||
</Group>
|
||||
)}
|
||||
{props.data && props.fetching && (
|
||||
<Text role="status">{t("bank.refreshing")}</Text>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export { BankSummaryView };
|
||||
@@ -0,0 +1,74 @@
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { HttpResponse, http } from "msw";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createTestQueryClient } from "@/test/query";
|
||||
import { server } from "@/test/server";
|
||||
import { CategoryManager } from "./CategoryManager";
|
||||
|
||||
describe("CategoryManager", () => {
|
||||
it("rejects duplicate case-insensitive and too long names then renames default identity", async () => {
|
||||
configureAuthClient({
|
||||
accessToken: () => "test",
|
||||
refresh: async () => false,
|
||||
clear: () => {},
|
||||
});
|
||||
let category = {
|
||||
id: "default",
|
||||
name: "Другое",
|
||||
isDefault: true,
|
||||
version: 1,
|
||||
};
|
||||
let creates = 0;
|
||||
let body: unknown;
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/categories", () =>
|
||||
HttpResponse.json([category]),
|
||||
),
|
||||
http.post("*/api/v1/bank-cards/categories", () => {
|
||||
creates++;
|
||||
return HttpResponse.json({});
|
||||
}),
|
||||
http.patch(
|
||||
"*/api/v1/bank-cards/categories/default",
|
||||
async ({ request }) => {
|
||||
body = await request.json();
|
||||
category = { ...category, name: "Остальное", version: 2 };
|
||||
return HttpResponse.json(category);
|
||||
},
|
||||
),
|
||||
);
|
||||
render(
|
||||
<QueryClientProvider client={createTestQueryClient()}>
|
||||
<MantineProvider env="test">
|
||||
<CategoryManager onClose={() => {}} />
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
await screen.findByText("Другое");
|
||||
fireEvent.change(screen.getByLabelText(/Название категории/), {
|
||||
target: { value: " другое " },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Добавить категорию" }));
|
||||
await screen.findByText("Категория с таким названием уже есть.");
|
||||
fireEvent.change(screen.getByLabelText(/Название категории/), {
|
||||
target: { value: "a".repeat(81) },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Добавить категорию" }));
|
||||
await screen.findByText("Введите название от 1 до 80 символов.");
|
||||
expect(creates).toBe(0);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Переименовать" }));
|
||||
fireEvent.input(screen.getByLabelText(/Название категории/), {
|
||||
target: { value: "Остальное" },
|
||||
});
|
||||
fireEvent.blur(screen.getByLabelText(/Название категории/));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await screen.findByText("Остальное");
|
||||
await waitFor(() =>
|
||||
expect(body).toEqual({ name: "Остальное", version: 1 }),
|
||||
);
|
||||
expect(screen.getByText("По умолчанию")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Group,
|
||||
Modal,
|
||||
Stack,
|
||||
Text,
|
||||
TextInput,
|
||||
} from "@mantine/core";
|
||||
import { type FC, useState } from "react";
|
||||
import {
|
||||
Controller,
|
||||
FormProvider,
|
||||
useForm,
|
||||
useFormContext,
|
||||
} from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { z } from "zod";
|
||||
import { validationMessage } from "@/shared/i18n";
|
||||
import { useBankMutations } from "../api/mutations";
|
||||
import { type ExpenseCategory, useBankCategories } from "../api/queries";
|
||||
import { BankFeedback } from "./BankFeedback";
|
||||
import classes from "./BankForms.module.css";
|
||||
import { BankOperationIcon } from "./BankOperationIcon";
|
||||
import { useBankFormFocus } from "./useBankFormFocus";
|
||||
|
||||
type CategoryManagerProps = {
|
||||
onClose: () => void;
|
||||
onCreated?: (id: string) => void;
|
||||
};
|
||||
type CategoryValues = { name: string };
|
||||
const CategoryFields: FC = () => {
|
||||
const { t } = useTranslation();
|
||||
const {
|
||||
control,
|
||||
formState: { errors },
|
||||
} = useFormContext<CategoryValues>();
|
||||
return (
|
||||
<Controller
|
||||
control={control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<TextInput
|
||||
label={t("bank.categoryName")}
|
||||
required
|
||||
{...field}
|
||||
error={errors.name?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
const CategoryManager: FC<CategoryManagerProps> = (props) => {
|
||||
useBankFormFocus();
|
||||
const { t } = useTranslation();
|
||||
const categories = useBankCategories();
|
||||
const mutation = useBankMutations();
|
||||
const [editing, setEditing] = useState<ExpenseCategory>();
|
||||
const [error, setError] = useState<unknown>();
|
||||
const [latest, setLatest] = useState<ExpenseCategory>();
|
||||
const methods = useForm<CategoryValues>({
|
||||
resolver: zodResolver(
|
||||
z.object({
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.refine(
|
||||
(value) => value.length > 0 && value.length <= 80,
|
||||
validationMessage("bank.validation.category"),
|
||||
)
|
||||
.refine(
|
||||
(value) =>
|
||||
!categories.data?.some(
|
||||
(c) =>
|
||||
c.id !== editing?.id &&
|
||||
c.name.toLocaleLowerCase("ru-RU") ===
|
||||
value.toLocaleLowerCase("ru-RU"),
|
||||
),
|
||||
validationMessage("bank.validation.duplicate"),
|
||||
),
|
||||
}),
|
||||
),
|
||||
defaultValues: { name: "" },
|
||||
});
|
||||
const pending = methods.formState.isSubmitting;
|
||||
return (
|
||||
<Modal
|
||||
opened
|
||||
onClose={() => !pending && props.onClose()}
|
||||
title={t("bank.categories")}
|
||||
closeOnClickOutside={!pending}
|
||||
closeOnEscape={!pending}
|
||||
closeButtonProps={{ "aria-label": t("bank.close"), disabled: pending }}
|
||||
>
|
||||
<FormProvider {...methods}>
|
||||
<form
|
||||
onSubmit={methods.handleSubmit(async (values) => {
|
||||
setError(undefined);
|
||||
try {
|
||||
if (editing)
|
||||
await mutation.updateCategory.mutateAsync({
|
||||
id: editing.id,
|
||||
body: { name: values.name, version: editing.version },
|
||||
});
|
||||
else {
|
||||
const result = await mutation.createCategory.mutateAsync({
|
||||
name: values.name,
|
||||
});
|
||||
if (result) props.onCreated?.(result.id);
|
||||
}
|
||||
setEditing(undefined);
|
||||
methods.reset({ name: "" });
|
||||
} catch (failure) {
|
||||
setError(failure);
|
||||
}
|
||||
})}
|
||||
>
|
||||
<fieldset disabled={pending} className={classes.fieldset}>
|
||||
<Stack>
|
||||
{categories.data?.map((category) => (
|
||||
<Group justify="space-between" key={category.id}>
|
||||
<Group gap="xs">
|
||||
<BankOperationIcon
|
||||
kind="expense"
|
||||
categoryName={category.name}
|
||||
/>
|
||||
<Text>{category.name}</Text>
|
||||
{category.isDefault && (
|
||||
<Badge>{t("bank.defaultCategory")}</Badge>
|
||||
)}
|
||||
</Group>
|
||||
<Button
|
||||
variant="subtle"
|
||||
onClick={() => {
|
||||
setEditing(category);
|
||||
methods.reset({ name: category.name });
|
||||
setError(undefined);
|
||||
setLatest(undefined);
|
||||
}}
|
||||
>
|
||||
{t("bank.rename")}
|
||||
</Button>
|
||||
</Group>
|
||||
))}
|
||||
{categories.isLoading && (
|
||||
<Text role="status">{t("bank.loading")}</Text>
|
||||
)}
|
||||
{categories.isError && (
|
||||
<BankFeedback
|
||||
loadingError
|
||||
error={categories.error}
|
||||
cached={Boolean(categories.data)}
|
||||
retry={() => void categories.refetch()}
|
||||
/>
|
||||
)}
|
||||
<CategoryFields />
|
||||
{error ? (
|
||||
<>
|
||||
<BankFeedback error={error} />
|
||||
{editing && (
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={async () => {
|
||||
const response = await categories.refetch();
|
||||
if (response.error) setError(response.error);
|
||||
else
|
||||
setLatest(
|
||||
response.data?.find((c) => c.id === editing.id),
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t("bank.reloadRecord")}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
{latest && (
|
||||
<>
|
||||
<Text>{t("bank.versionHint", { details: latest.name })}</Text>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setEditing(latest);
|
||||
setLatest(undefined);
|
||||
setError(undefined);
|
||||
}}
|
||||
>
|
||||
{t("bank.adoptVersion", { version: latest.version })}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Group>
|
||||
<Button type="submit" loading={pending}>
|
||||
{t(editing ? "bank.save" : "bank.addCategory")}
|
||||
</Button>
|
||||
{editing && (
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={() => {
|
||||
setEditing(undefined);
|
||||
methods.reset({ name: "" });
|
||||
setError(undefined);
|
||||
}}
|
||||
>
|
||||
{t("bank.cancel")}
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="default" onClick={props.onClose}>
|
||||
{t("bank.close")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</fieldset>
|
||||
</form>
|
||||
</FormProvider>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export { CategoryManager };
|
||||
@@ -0,0 +1,16 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
function useBankFormFocus() {
|
||||
const [trigger] = useState(() => document.activeElement);
|
||||
useEffect(
|
||||
() => () => {
|
||||
queueMicrotask(() => {
|
||||
if (trigger instanceof HTMLElement && trigger.isConnected)
|
||||
trigger.focus();
|
||||
});
|
||||
},
|
||||
[trigger],
|
||||
);
|
||||
}
|
||||
|
||||
export { useBankFormFocus };
|
||||
@@ -8,6 +8,10 @@ import { createTestQueryClient } from "@/test/query";
|
||||
import { server } from "@/test/server";
|
||||
import { AuthProvider, useAuth } from "./auth";
|
||||
|
||||
const bankCardsKey = apiQueryClient.queryOptions("get", "/api/v1/bank-cards", {
|
||||
params: { query: { includeArchived: "false" } },
|
||||
}).queryKey;
|
||||
|
||||
describe("AuthProvider", () => {
|
||||
it("authorizes requests after restoring the initial session", async () => {
|
||||
let authorization: string | null = null;
|
||||
@@ -54,6 +58,7 @@ describe("AuthProvider", () => {
|
||||
server.use(http.post("*/api/v1/auth/refresh", () => HttpResponse.error()));
|
||||
const queryClient = createTestQueryClient();
|
||||
queryClient.setQueryData(["cached-query"], { value: "stale" });
|
||||
queryClient.setQueryData(bankCardsKey, [{ id: "bank-card-1" }]);
|
||||
const wrapper: FC<PropsWithChildren> = (props) => {
|
||||
const { children } = props;
|
||||
|
||||
@@ -70,6 +75,7 @@ describe("AuthProvider", () => {
|
||||
expect(result.current.user).toBeNull();
|
||||
expect(result.current.accessToken).toBeNull();
|
||||
expect(queryClient.getQueryData(["cached-query"])).toBeUndefined();
|
||||
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps the original protected 401 when serialized refresh has a transport error", async () => {
|
||||
@@ -90,6 +96,7 @@ describe("AuthProvider", () => {
|
||||
);
|
||||
const queryClient = createTestQueryClient();
|
||||
queryClient.setQueryData(["cached-query"], { value: "stale" });
|
||||
queryClient.setQueryData(bankCardsKey, [{ id: "bank-card-1" }]);
|
||||
const wrapper: FC<PropsWithChildren> = (props) => {
|
||||
const { children } = props;
|
||||
|
||||
@@ -110,6 +117,7 @@ describe("AuthProvider", () => {
|
||||
await waitFor(() => expect(result.current.user).toBeNull());
|
||||
expect(result.current.accessToken).toBeNull();
|
||||
expect(queryClient.getQueryData(["cached-query"])).toBeUndefined();
|
||||
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("clears connection status and financial cache independently on logout", async () => {
|
||||
@@ -136,6 +144,7 @@ describe("AuthProvider", () => {
|
||||
connectedAt: "2026-08-14T00:00:00Z",
|
||||
});
|
||||
queryClient.setQueryData(portfolioKey, { source: "current-connection" });
|
||||
queryClient.setQueryData(bankCardsKey, [{ id: "bank-card-1" }]);
|
||||
const wrapper: FC<PropsWithChildren> = (props) => {
|
||||
const { children } = props;
|
||||
return (
|
||||
@@ -147,11 +156,15 @@ describe("AuthProvider", () => {
|
||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||
await waitFor(() => expect(result.current.accessToken).toBe("test-token"));
|
||||
|
||||
expect(queryClient.getQueryData(bankCardsKey)).toEqual([
|
||||
{ id: "bank-card-1" },
|
||||
]);
|
||||
await act(() => result.current.logout());
|
||||
|
||||
expect(result.current.user).toBeNull();
|
||||
expect(result.current.accessToken).toBeNull();
|
||||
expect(queryClient.getQueryData(statusKey)).toBeUndefined();
|
||||
expect(queryClient.getQueryData(portfolioKey)).toBeUndefined();
|
||||
expect(queryClient.getQueryData(bankCardsKey)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -32,6 +32,13 @@ const bondQueryKey = apiQueryClient.queryOptions(
|
||||
"/api/v1/bonds/{uid}/position",
|
||||
{ params: { path: { uid: "e6123145-9665-43e0-8413-cd61b8aa9b13" } } },
|
||||
).queryKey;
|
||||
const bankCardsQueryKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/bank-cards",
|
||||
{
|
||||
params: { query: { includeArchived: "false" } },
|
||||
},
|
||||
).queryKey;
|
||||
const unrelatedQueryKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/auth/me",
|
||||
@@ -66,6 +73,7 @@ function seededClient() {
|
||||
client.setQueryData(stockQueryKey, { source: "previous-connection" });
|
||||
client.setQueryData(bondQueryKey, { source: "previous-connection" });
|
||||
client.setQueryData(unrelatedQueryKey, { id: "user-1" });
|
||||
client.setQueryData(bankCardsQueryKey, [{ id: "bank-card-1" }]);
|
||||
return client;
|
||||
}
|
||||
|
||||
@@ -86,6 +94,10 @@ describe("TbankConnectionSection", () => {
|
||||
).toBeInTheDocument(),
|
||||
);
|
||||
expect(client.getQueryData(brokerageAccountsQueryKey)).toBeUndefined();
|
||||
expect(client.getQueryData(bankCardsQueryKey)).toEqual([
|
||||
{ id: "bank-card-1" },
|
||||
]);
|
||||
expect(client.getQueryState(bankCardsQueryKey)?.isInvalidated).toBe(false);
|
||||
expect(client.getQueryData(portfolioQueryKey)).toBeUndefined();
|
||||
expect(client.getQueryData(stockQueryKey)).toBeUndefined();
|
||||
expect(client.getQueryData(bondQueryKey)).toBeUndefined();
|
||||
@@ -114,6 +126,10 @@ describe("TbankConnectionSection", () => {
|
||||
expect(client.getQueryData(portfolioQueryKey)).toBeUndefined(),
|
||||
);
|
||||
expect(client.getQueryData(brokerageAccountsQueryKey)).toBeUndefined();
|
||||
expect(client.getQueryData(bankCardsQueryKey)).toEqual([
|
||||
{ id: "bank-card-1" },
|
||||
]);
|
||||
expect(client.getQueryState(bankCardsQueryKey)?.isInvalidated).toBe(false);
|
||||
});
|
||||
|
||||
it("commits disconnected status and resets financial queries after deleting", async () => {
|
||||
@@ -139,6 +155,10 @@ describe("TbankConnectionSection", () => {
|
||||
).toBeInTheDocument(),
|
||||
);
|
||||
expect(client.getQueryData(brokerageAccountsQueryKey)).toBeUndefined();
|
||||
expect(client.getQueryData(bankCardsQueryKey)).toEqual([
|
||||
{ id: "bank-card-1" },
|
||||
]);
|
||||
expect(client.getQueryState(bankCardsQueryKey)?.isInvalidated).toBe(false);
|
||||
expect(client.getQueryData(portfolioQueryKey)).toBeUndefined();
|
||||
expect(client.getQueryData(stockQueryKey)).toBeUndefined();
|
||||
expect(client.getQueryData(bondQueryKey)).toBeUndefined();
|
||||
|
||||
@@ -123,11 +123,13 @@ function emptyProps() {
|
||||
describe("AccountPage states", () => {
|
||||
it.each(
|
||||
["account-1", "all"].flatMap((accountId) =>
|
||||
["STOCK", "BOND"].map((type) => ({ accountId, type })),
|
||||
["STOCK", "BOND"].flatMap((type) =>
|
||||
[true, false].map((hasMetadata) => ({ accountId, type, hasMetadata })),
|
||||
),
|
||||
),
|
||||
)(
|
||||
"links name and logo to the exact issue in $accountId for $type",
|
||||
async ({ accountId, type }) => {
|
||||
"keeps portfolio metadata authoritative and links the exact issue in $accountId for $type (metadata: $hasMetadata)",
|
||||
async ({ accountId, type, hasMetadata }) => {
|
||||
const collection = type === "STOCK" ? "stocks" : "bonds";
|
||||
const slug = type === "STOCK" ? "SBERP" : "SU26238RMFS4";
|
||||
const uid = "c190ff1f-1447-4227-b543-316332699ca5";
|
||||
@@ -136,8 +138,9 @@ describe("AccountPage states", () => {
|
||||
...portfolio.positions[0],
|
||||
type,
|
||||
instrumentUid: uid,
|
||||
ticker: slug,
|
||||
displayName: "Сбербанк привилегированные",
|
||||
ticker: hasMetadata ? slug : null,
|
||||
displayName: hasMetadata ? "Сбербанк привилегированные" : "FIGI-2",
|
||||
logoName: hasMetadata ? "vtoraya.png" : null,
|
||||
};
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
|
||||
@@ -154,7 +157,14 @@ describe("AccountPage states", () => {
|
||||
),
|
||||
http.get(`*/api/v1/${collection}/:uid`, () => {
|
||||
requests();
|
||||
return HttpResponse.json({ instrumentUid: uid, slug });
|
||||
return HttpResponse.json({
|
||||
instrumentUid: uid,
|
||||
slug,
|
||||
name: "Название из карточки инструмента",
|
||||
ticker: "OTHER-TICKER",
|
||||
isin: "OTHER-ISIN",
|
||||
logoName: "other.png",
|
||||
});
|
||||
}),
|
||||
);
|
||||
configureTestAuth();
|
||||
@@ -171,6 +181,19 @@ describe("AccountPage states", () => {
|
||||
);
|
||||
});
|
||||
expect(requests).toHaveBeenCalledTimes(type === "STOCK" ? 1 : 0);
|
||||
expect(
|
||||
screen.queryByText("Название из карточки инструмента"),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByText(/OTHER-TICKER|OTHER-ISIN/),
|
||||
).not.toBeInTheDocument();
|
||||
const logo = screen.queryByRole("img", { name: position.displayName });
|
||||
if (hasMetadata)
|
||||
expect(logo).toHaveAttribute(
|
||||
"src",
|
||||
"https://invest-brands.cdn-tinkoff.ru/vtorayax160.png",
|
||||
);
|
||||
else expect(logo).not.toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export { CardPage } from "./ui/CardPage";
|
||||
@@ -0,0 +1,39 @@
|
||||
.wrap {
|
||||
overflow-wrap: anywhere;
|
||||
min-width: 0;
|
||||
}
|
||||
.operation {
|
||||
min-width: 0;
|
||||
}
|
||||
.operation p {
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.operation > div > div {
|
||||
min-width: 0;
|
||||
}
|
||||
@media (min-width: 36em) {
|
||||
.operation > div:first-child {
|
||||
grid-template-columns: auto minmax(0, 1fr) minmax(0, 40%);
|
||||
}
|
||||
}
|
||||
|
||||
.operations[data-pending] {
|
||||
opacity: 0.55;
|
||||
}
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.operations {
|
||||
animation: operations-appear 200ms ease-out;
|
||||
transition: opacity 150ms ease;
|
||||
}
|
||||
@keyframes operations-appear {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(4px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import {
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
within,
|
||||
} from "@testing-library/react";
|
||||
import { HttpResponse, http } from "msw";
|
||||
import { MemoryRouter, Route, Routes } from "react-router";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createTestQueryClient } from "@/test/query";
|
||||
import { server } from "@/test/server";
|
||||
import { CardPage } from "./CardPage";
|
||||
|
||||
const money = (value: string) => ({ currency: "RUB", value });
|
||||
const card = {
|
||||
id: "a",
|
||||
name: "Повседневная",
|
||||
bankName: null,
|
||||
lastFour: null,
|
||||
balance: money("10000"),
|
||||
openingBalance: money("10000"),
|
||||
openingDate: "2026-01-01",
|
||||
archivedAt: null,
|
||||
version: 1,
|
||||
};
|
||||
const operation = {
|
||||
id: "transfer",
|
||||
kind: "transfer",
|
||||
cardId: "a",
|
||||
cardName: "Повседневная",
|
||||
targetCardId: "b",
|
||||
targetCardName: "Запасная",
|
||||
categoryId: null,
|
||||
categoryName: null,
|
||||
originalExpenseId: null,
|
||||
amount: money("50.01"),
|
||||
availableRefund: null,
|
||||
date: "2026-08-03",
|
||||
description: null,
|
||||
version: 1,
|
||||
createdAt: "2026-08-03T00:00:00Z",
|
||||
};
|
||||
function setup(
|
||||
options: {
|
||||
missing?: boolean;
|
||||
summaryError?: boolean;
|
||||
cardsError?: boolean;
|
||||
} = {},
|
||||
) {
|
||||
configureAuthClient({
|
||||
accessToken: () => "test",
|
||||
refresh: async () => false,
|
||||
clear: () => {},
|
||||
});
|
||||
const requests: string[] = [];
|
||||
const summaryRequests: string[] = [];
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/a", () =>
|
||||
options.missing
|
||||
? HttpResponse.json({ code: "BANK_NOT_FOUND" }, { status: 404 })
|
||||
: HttpResponse.json(card),
|
||||
),
|
||||
http.get("*/api/v1/bank-cards", () =>
|
||||
options.cardsError
|
||||
? HttpResponse.error()
|
||||
: HttpResponse.json([card, { ...card, id: "b", name: "Запасная" }]),
|
||||
),
|
||||
http.get("*/api/v1/bank-cards/a/operations", ({ request }) => {
|
||||
requests.push(new URL(request.url).search);
|
||||
return HttpResponse.json({
|
||||
items: [
|
||||
{
|
||||
...operation,
|
||||
id: `operation-${new URL(request.url).searchParams.get("page")}`,
|
||||
},
|
||||
],
|
||||
page: Number(new URL(request.url).searchParams.get("page")),
|
||||
total: 30,
|
||||
hasNext: Number(new URL(request.url).searchParams.get("page")) < 3,
|
||||
});
|
||||
}),
|
||||
http.get("*/api/v1/bank-cards/summary", ({ request }) => {
|
||||
summaryRequests.push(new URL(request.url).search);
|
||||
return options.summaryError
|
||||
? HttpResponse.error()
|
||||
: HttpResponse.json({
|
||||
month: "2026-08",
|
||||
cardId: "a",
|
||||
expenses: money("0"),
|
||||
refunds: money("50"),
|
||||
net: money("-50"),
|
||||
categories: [],
|
||||
});
|
||||
}),
|
||||
);
|
||||
const client = createTestQueryClient();
|
||||
render(
|
||||
<QueryClientProvider client={client}>
|
||||
<MantineProvider env="test">
|
||||
<MemoryRouter initialEntries={["/cards/a?month=2026-08"]}>
|
||||
<Routes>
|
||||
<Route path="/cards/:cardId" element={<CardPage />} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
return { requests, summaryRequests, client };
|
||||
}
|
||||
describe("CardPage", () => {
|
||||
it("shares date range with history, pages the journal and keeps current balance", async () => {
|
||||
const { requests, summaryRequests } = setup();
|
||||
await screen.findByRole("heading", { name: "Повседневная" });
|
||||
expect(
|
||||
await screen.findByText("Перевод на «Запасная»"),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText("03.08.2026")).toBeInTheDocument();
|
||||
expect(screen.getByText("−50,01 ₽")).toBeInTheDocument();
|
||||
expect(await screen.findByText("-50,00 ₽")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Назад" })).toBeDisabled();
|
||||
expect(requests.every((value) => value.includes("limit=10"))).toBe(true);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Далее" }));
|
||||
await waitFor(() =>
|
||||
expect(requests.some((v) => v.includes("page=2"))).toBe(true),
|
||||
);
|
||||
const lastPage = await screen.findByRole("button", { name: "Страница 3" });
|
||||
await waitFor(() => expect(lastPage).toBeEnabled());
|
||||
fireEvent.click(lastPage);
|
||||
await waitFor(() => expect(requests.at(-1)).toContain("page=3"));
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("button", { name: "Далее" })).toBeDisabled(),
|
||||
);
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Страница 3" }),
|
||||
).toHaveTextContent("3");
|
||||
fireEvent.click(screen.getByLabelText("Период"));
|
||||
fireEvent.click(
|
||||
await screen.findByRole("button", { name: "10 August 2026" }),
|
||||
);
|
||||
fireEvent.click(
|
||||
await screen.findByRole("button", { name: "20 August 2026" }),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
requests.some(
|
||||
(v) =>
|
||||
v.includes("from=2026-08-10") &&
|
||||
v.includes("to=2026-08-20") &&
|
||||
v.includes("page=1"),
|
||||
),
|
||||
).toBe(true),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(summaryRequests.at(-1)).toContain("from=2026-08-10&to=2026-08-20"),
|
||||
);
|
||||
expect(screen.getByRole("link", { name: "Карта" })).toHaveAttribute(
|
||||
"href",
|
||||
"/cards/b?from=2026-08-10&to=2026-08-20",
|
||||
);
|
||||
expect(screen.getByText(/10\s000 ₽/)).toBeInTheDocument();
|
||||
});
|
||||
it("keeps the journal in place while the next page loads", async () => {
|
||||
const scroll = vi.spyOn(window, "scrollBy").mockImplementation(() => {});
|
||||
setup();
|
||||
await screen.findByText("Перевод на «Запасная»");
|
||||
const navigation = screen.getByRole("navigation", {
|
||||
name: "Страницы операций",
|
||||
});
|
||||
const measure = vi
|
||||
.spyOn(navigation, "getBoundingClientRect")
|
||||
.mockReturnValue({ top: 600 } as DOMRect);
|
||||
let release = () => {};
|
||||
const pending = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/a/operations", async () => {
|
||||
await pending;
|
||||
return HttpResponse.json({
|
||||
items: [{ ...operation, id: "next", description: "Новая страница" }],
|
||||
page: 2,
|
||||
total: 30,
|
||||
hasNext: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Далее" }));
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("button", { name: "Далее" })).toBeDisabled(),
|
||||
);
|
||||
expect(screen.getByText("Перевод на «Запасная»")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Изменить" })).toBeDisabled();
|
||||
expect(
|
||||
screen.queryByLabelText("Загрузка операций"),
|
||||
).not.toBeInTheDocument();
|
||||
expect(scroll).not.toHaveBeenCalled();
|
||||
measure.mockReturnValue({ top: 200 } as DOMRect);
|
||||
release();
|
||||
await screen.findByText(/Новая страница/);
|
||||
const list = screen.getByText(/Новая страница/).closest("[aria-busy]");
|
||||
expect(list?.parentElement?.style.minHeight).toBe("");
|
||||
expect(scroll).toHaveBeenCalledExactlyOnceWith({
|
||||
top: -400,
|
||||
behavior: "instant",
|
||||
});
|
||||
measure.mockRestore();
|
||||
scroll.mockRestore();
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("button", { name: "Далее" })).toBeEnabled(),
|
||||
);
|
||||
});
|
||||
it("changes page size, resets the page and shows all monthly operations", async () => {
|
||||
const { requests } = setup();
|
||||
await screen.findByText("Перевод на «Запасная»");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Страница 3" }));
|
||||
await waitFor(() => expect(requests.at(-1)).toContain("page=3"));
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("button", { name: "Страница 1" })).toBeEnabled(),
|
||||
);
|
||||
fireEvent.click(
|
||||
screen.getByRole("combobox", { name: "Операций на странице" }),
|
||||
);
|
||||
fireEvent.click(await screen.findByRole("option", { name: "20" }));
|
||||
await waitFor(() => {
|
||||
expect(requests.at(-1)).toContain("limit=20");
|
||||
expect(requests.at(-1)).toContain("page=1");
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("button", { name: "Страница 1" })).toBeEnabled(),
|
||||
);
|
||||
fireEvent.click(
|
||||
screen.getByRole("combobox", { name: "Операций на странице" }),
|
||||
);
|
||||
fireEvent.click(await screen.findByRole("option", { name: "Все" }));
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.queryByRole("navigation", { name: "Страницы операций" }),
|
||||
).not.toBeInTheDocument(),
|
||||
);
|
||||
await waitFor(() => expect(requests.at(-1)).toContain("limit=100"));
|
||||
await waitFor(() =>
|
||||
expect(screen.getAllByText("Перевод на «Запасная»")).toHaveLength(3),
|
||||
);
|
||||
});
|
||||
it("keeps card and journal when summary fails", async () => {
|
||||
setup({ summaryError: true });
|
||||
await screen.findByRole("heading", { name: "Повседневная" });
|
||||
await screen.findByRole("alert");
|
||||
expect(
|
||||
await screen.findByText("Перевод на «Запасная»"),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByText("0 ₽")).not.toBeInTheDocument();
|
||||
});
|
||||
it("keeps cached card and history after refetch failure", async () => {
|
||||
const { client } = setup();
|
||||
await screen.findByText("Перевод на «Запасная»");
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/a", () => HttpResponse.error()),
|
||||
http.get("*/api/v1/bank-cards/a/operations", () => HttpResponse.error()),
|
||||
);
|
||||
await client.invalidateQueries();
|
||||
await screen.findAllByRole("alert");
|
||||
expect(
|
||||
screen.getByRole("heading", { name: "Повседневная" }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText("Перевод на «Запасная»")).toBeInTheDocument();
|
||||
});
|
||||
it("handles inaccessible card neutrally", async () => {
|
||||
setup({ missing: true });
|
||||
await screen.findByRole("heading", { name: "Карта не найдена" });
|
||||
expect(screen.getByRole("link", { name: "К картам" })).toHaveAttribute(
|
||||
"href",
|
||||
"/cards",
|
||||
);
|
||||
expect(screen.queryByText(/10\s000 ₽/)).not.toBeInTheDocument();
|
||||
});
|
||||
it("archives without deleting history and restores financial actions", async () => {
|
||||
setup();
|
||||
await screen.findByText("Перевод на «Запасная»");
|
||||
let current = card;
|
||||
const bodies: unknown[] = [];
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/a", () => HttpResponse.json(current)),
|
||||
http.get("*/api/v1/bank-cards", () =>
|
||||
HttpResponse.json([current, { ...card, id: "b", name: "Запасная" }]),
|
||||
),
|
||||
http.patch("*/api/v1/bank-cards/a", async ({ request }) => {
|
||||
const body = (await request.json()) as {
|
||||
version: number;
|
||||
archived: boolean;
|
||||
};
|
||||
bodies.push(body);
|
||||
current = {
|
||||
...current,
|
||||
version: current.version + 1,
|
||||
archivedAt: body.archived ? "2026-09-01" : null,
|
||||
} as typeof card;
|
||||
return HttpResponse.json(current);
|
||||
}),
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Убрать в архив" }));
|
||||
await screen.findByRole("button", { name: "Вернуть из архива" });
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Добавить операцию" }),
|
||||
).toBeDisabled();
|
||||
expect(screen.getByRole("button", { name: "Изменить" })).toBeDisabled();
|
||||
expect(screen.getByText("Перевод на «Запасная»")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Вернуть из архива" }));
|
||||
await screen.findByRole("button", { name: "Убрать в архив" });
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Добавить операцию" }),
|
||||
).toBeEnabled();
|
||||
expect(bodies).toEqual([
|
||||
{ version: 1, archived: true },
|
||||
{ version: 2, archived: false },
|
||||
]);
|
||||
});
|
||||
it("recovers the prerequisite card list while preserving the visible balance and journal", async () => {
|
||||
setup({ cardsError: true });
|
||||
await screen.findByText("Перевод на «Запасная»");
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent(
|
||||
"Не удалось загрузить данные карт.",
|
||||
);
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Добавить операцию" }),
|
||||
).toBeDisabled();
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards", () =>
|
||||
HttpResponse.json([card, { ...card, id: "b", name: "Запасная" }]),
|
||||
),
|
||||
);
|
||||
fireEvent.click(
|
||||
within(screen.getByRole("alert")).getByRole("button", {
|
||||
name: "Повторить",
|
||||
}),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Добавить операцию" }),
|
||||
).toBeEnabled(),
|
||||
);
|
||||
expect(screen.getByText("Перевод на «Запасная»")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { FC } from "react";
|
||||
import { BankCardForm } from "@/entities/bank-card";
|
||||
import { CardPageView } from "./CardPage.view";
|
||||
import { useCardPageVm } from "./CardPage.vm";
|
||||
import { DeleteOperation } from "./DeleteOperation";
|
||||
import { OperationForm } from "./OperationForm";
|
||||
|
||||
const CardPage: FC = () => {
|
||||
const vm = useCardPageVm();
|
||||
return (
|
||||
<>
|
||||
<CardPageView vm={vm} />
|
||||
{vm.editingCard && vm.card.data && (
|
||||
<BankCardForm
|
||||
card={vm.card.data}
|
||||
onClose={() => vm.setEditingCard(false)}
|
||||
/>
|
||||
)}
|
||||
{vm.operation && vm.card.data && vm.cards.data && (
|
||||
<OperationForm
|
||||
card={vm.card.data}
|
||||
cards={vm.cards.data}
|
||||
operation={vm.operation === "new" ? undefined : vm.operation}
|
||||
onClose={() => vm.setOperation(null)}
|
||||
/>
|
||||
)}
|
||||
{vm.deleting && (
|
||||
<DeleteOperation
|
||||
operation={vm.deleting}
|
||||
onClose={() => vm.setDeleting(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export { CardPage };
|
||||
@@ -0,0 +1,361 @@
|
||||
import {
|
||||
ActionIcon,
|
||||
Anchor,
|
||||
Button,
|
||||
Group,
|
||||
Pagination,
|
||||
Paper,
|
||||
Select,
|
||||
Skeleton,
|
||||
Stack,
|
||||
Text,
|
||||
Title,
|
||||
} from "@mantine/core";
|
||||
import { DatePickerInput } from "@mantine/dates";
|
||||
import { type FC, useLayoutEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
import {
|
||||
BankCardFace,
|
||||
BankFeedback,
|
||||
BankOperationIcon,
|
||||
BankSummaryView,
|
||||
} from "@/entities/bank-card";
|
||||
import { EntryCard, LoadingSkeleton, StateView } from "@/shared/ui";
|
||||
import classes from "./CardPage.module.css";
|
||||
import type { CardPageVm } from "./CardPage.vm";
|
||||
|
||||
type PeriodPickerProps = {
|
||||
period: CardPageVm["period"];
|
||||
onChange: CardPageVm["setPeriod"];
|
||||
};
|
||||
const PeriodPicker: FC<PeriodPickerProps> = (props) => {
|
||||
const { period, onChange } = props;
|
||||
const { t } = useTranslation();
|
||||
const scope = `${period.from}-${period.to}`;
|
||||
const [draft, setDraft] = useState<{
|
||||
scope: string;
|
||||
value: [string | null, string | null];
|
||||
}>();
|
||||
const value: [string | null, string | null] =
|
||||
draft?.scope === scope ? draft.value : [period.from, period.to];
|
||||
return (
|
||||
<DatePickerInput
|
||||
type="range"
|
||||
allowSingleDateInRange
|
||||
label={t("bank.period")}
|
||||
valueFormat="DD.MM.YYYY"
|
||||
value={value}
|
||||
onChange={(next) => {
|
||||
setDraft({ scope, value: next });
|
||||
onChange(next);
|
||||
}}
|
||||
popoverProps={{
|
||||
returnFocus: true,
|
||||
middlewares: { shift: { crossAxis: true } },
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
type CardPageViewProps = { vm: CardPageVm };
|
||||
const CardPageView: FC<CardPageViewProps> = (props) => {
|
||||
const { vm } = props;
|
||||
const { t } = useTranslation();
|
||||
const card = vm.card.data;
|
||||
const paginationRef = useRef<HTMLDivElement>(null);
|
||||
const pendingPage = useRef<{
|
||||
scope: string;
|
||||
page: number;
|
||||
top: number;
|
||||
} | null>(null);
|
||||
const scope = `${card?.id}-${vm.period.from}-${vm.period.to}-${vm.pageSize}`;
|
||||
useLayoutEffect(() => {
|
||||
const pending = pendingPage.current;
|
||||
if (!pending) return;
|
||||
if (pending.scope !== scope || vm.history.isError) {
|
||||
pendingPage.current = null;
|
||||
return;
|
||||
}
|
||||
if (vm.history.isPlaceholderData || vm.history.data?.page !== pending.page)
|
||||
return;
|
||||
const pagination = paginationRef.current;
|
||||
if (pagination) {
|
||||
const delta = pagination.getBoundingClientRect().top - pending.top;
|
||||
if (delta) window.scrollBy({ top: delta, behavior: "instant" });
|
||||
}
|
||||
pendingPage.current = null;
|
||||
}, [
|
||||
scope,
|
||||
vm.history.data,
|
||||
vm.history.isPlaceholderData,
|
||||
vm.history.isError,
|
||||
]);
|
||||
if (!card) {
|
||||
if (vm.card.isLoading)
|
||||
return (
|
||||
<LoadingSkeleton label={t("bank.loading")}>
|
||||
<Stack>
|
||||
<Skeleton h={130} />
|
||||
<Skeleton h={160} />
|
||||
<Skeleton h={90} />
|
||||
<Skeleton h={90} />
|
||||
</Stack>
|
||||
</LoadingSkeleton>
|
||||
);
|
||||
return (
|
||||
<StateView
|
||||
error
|
||||
title={t(vm.notFound ? "bank.notFound" : "bank.error")}
|
||||
text={t("bank.back")}
|
||||
action={
|
||||
<Group>
|
||||
<Button component={Link} to="/cards">
|
||||
{t("bank.back")}
|
||||
</Button>
|
||||
{!vm.notFound && (
|
||||
<Button onClick={() => void vm.card.refetch()}>
|
||||
{t("bank.retry")}
|
||||
</Button>
|
||||
)}
|
||||
</Group>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Stack gap="lg">
|
||||
<Paper p="md" withBorder>
|
||||
<Stack>
|
||||
<Title order={1} className={classes.wrap}>
|
||||
{card.name}
|
||||
</Title>
|
||||
<BankCardFace card={card} />
|
||||
<Text c="dimmed">{t("bank.manualBalance")}</Text>
|
||||
<Group>
|
||||
<Button
|
||||
disabled={Boolean(card.archivedAt) || !vm.cards.data}
|
||||
onClick={() => vm.setOperation("new")}
|
||||
>
|
||||
{t("bank.addOperation")}
|
||||
</Button>
|
||||
<Button variant="default" onClick={() => vm.setEditingCard(true)}>
|
||||
{t("bank.editCard")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="default"
|
||||
loading={vm.archivePending}
|
||||
onClick={() => void vm.toggleArchive()}
|
||||
>
|
||||
{t(card.archivedAt ? "bank.restore" : "bank.archive")}
|
||||
</Button>
|
||||
</Group>
|
||||
{vm.archiveError ? (
|
||||
<BankFeedback
|
||||
error={vm.archiveError}
|
||||
retry={() => void vm.card.refetch()}
|
||||
/>
|
||||
) : null}
|
||||
{card.archivedAt && <Text>{t("bank.archiveHint")}</Text>}
|
||||
</Stack>
|
||||
</Paper>
|
||||
{vm.card.isError && (
|
||||
<Group role="alert">
|
||||
<Text>{t("bank.refreshError")}</Text>
|
||||
<Button onClick={() => void vm.card.refetch()}>
|
||||
{t("bank.retry")}
|
||||
</Button>
|
||||
</Group>
|
||||
)}
|
||||
{vm.card.isFetching && <Text role="status">{t("bank.refreshing")}</Text>}
|
||||
{vm.cards.isError && (
|
||||
<BankFeedback
|
||||
loadingError
|
||||
error={vm.cards.error}
|
||||
cached={Boolean(vm.cards.data)}
|
||||
retry={() => void vm.cards.refetch()}
|
||||
/>
|
||||
)}
|
||||
<PeriodPicker period={vm.period} onChange={vm.setPeriod} />
|
||||
<BankSummaryView
|
||||
data={vm.summary.data}
|
||||
loading={vm.summary.isLoading}
|
||||
fetching={vm.summary.isFetching}
|
||||
error={vm.summary.isError}
|
||||
retry={() => void vm.summary.refetch()}
|
||||
/>
|
||||
<Group justify="space-between" align="end">
|
||||
<Title order={2}>{t("bank.operations")}</Title>
|
||||
<Select
|
||||
label={t("bank.pageSize")}
|
||||
value={vm.pageSize}
|
||||
onChange={vm.setPageSize}
|
||||
allowDeselect={false}
|
||||
w={180}
|
||||
data={[
|
||||
"5",
|
||||
"10",
|
||||
"20",
|
||||
"50",
|
||||
"100",
|
||||
{ value: "all", label: t("bank.allOperations") },
|
||||
]}
|
||||
/>
|
||||
</Group>
|
||||
<Stack
|
||||
key={`${vm.period.from}-${vm.period.to}-${vm.pageSize}-${vm.history.data?.page ?? "loading"}`}
|
||||
gap="lg"
|
||||
className={classes.operations}
|
||||
aria-busy={vm.history.isFetching}
|
||||
data-pending={vm.history.isPlaceholderData || undefined}
|
||||
>
|
||||
{vm.rows ? (
|
||||
vm.rows.length ? (
|
||||
vm.rows.map((row) => (
|
||||
<section
|
||||
key={row.item.id}
|
||||
className={classes.operation}
|
||||
aria-label={`${row.title} ${row.item.date}`}
|
||||
>
|
||||
<EntryCard
|
||||
title={row.title}
|
||||
metadata={row.metadata}
|
||||
color={row.color}
|
||||
initial={row.title[0]}
|
||||
icon={
|
||||
<BankOperationIcon
|
||||
kind={row.item.kind}
|
||||
categoryName={row.item.categoryName}
|
||||
/>
|
||||
}
|
||||
value={row.value}
|
||||
valueLabel={t(`bank.kinds.${row.item.kind}`)}
|
||||
tone={row.tone}
|
||||
details={
|
||||
row.otherCard ? (
|
||||
<Anchor
|
||||
component={Link}
|
||||
to={`/cards/${row.otherCard}?from=${vm.period.from}&to=${vm.period.to}`}
|
||||
>
|
||||
{t("bank.card")}
|
||||
</Anchor>
|
||||
) : null
|
||||
}
|
||||
actions={
|
||||
<Group gap={4} wrap="nowrap">
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
disabled={
|
||||
vm.history.isPlaceholderData ||
|
||||
!row.editable ||
|
||||
Boolean(card.archivedAt)
|
||||
}
|
||||
size="sm"
|
||||
aria-label={t("bank.edit")}
|
||||
title={t("bank.edit")}
|
||||
onClick={() => vm.setOperation(row.item)}
|
||||
>
|
||||
<svg
|
||||
width="18"
|
||||
height="18"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="m16 3 5 5-12 12-6 1 1-6L16 3Z M13 6l5 5" />
|
||||
</svg>
|
||||
</ActionIcon>
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
color="red"
|
||||
disabled={
|
||||
vm.history.isPlaceholderData ||
|
||||
!row.editable ||
|
||||
Boolean(card.archivedAt)
|
||||
}
|
||||
size="sm"
|
||||
aria-label={t("bank.delete")}
|
||||
title={t("bank.delete")}
|
||||
onClick={() => vm.setDeleting(row.item)}
|
||||
>
|
||||
<svg
|
||||
width="18"
|
||||
height="18"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="M3 6h18 M9 6V3h6v3 M5 6l1 15h12l1-15 M10 10v7 M14 10v7" />
|
||||
</svg>
|
||||
</ActionIcon>
|
||||
</Group>
|
||||
}
|
||||
/>
|
||||
</section>
|
||||
))
|
||||
) : (
|
||||
<Text>{t("bank.noOperations")}</Text>
|
||||
)
|
||||
) : vm.history.isLoading ? (
|
||||
<LoadingSkeleton label={t("bank.loadingHistory")}>
|
||||
<Stack>
|
||||
<Skeleton h={90} />
|
||||
<Skeleton h={90} />
|
||||
</Stack>
|
||||
</LoadingSkeleton>
|
||||
) : null}
|
||||
</Stack>
|
||||
{vm.history.isError && (
|
||||
<Group role="alert">
|
||||
<Text>{t(vm.rows ? "bank.refreshError" : "bank.error")}</Text>
|
||||
<Button onClick={() => void vm.history.refetch()}>
|
||||
{t("bank.retry")}
|
||||
</Button>
|
||||
</Group>
|
||||
)}
|
||||
{vm.history.data && vm.pageSize !== "all" && (
|
||||
<Group
|
||||
component="nav"
|
||||
ref={paginationRef}
|
||||
aria-label={t("bank.pagination")}
|
||||
justify="center"
|
||||
py="sm"
|
||||
>
|
||||
<Pagination
|
||||
total={vm.totalPages}
|
||||
value={vm.page}
|
||||
onChange={(page) => {
|
||||
if (paginationRef.current)
|
||||
pendingPage.current = {
|
||||
scope,
|
||||
page,
|
||||
top: paginationRef.current.getBoundingClientRect().top,
|
||||
};
|
||||
vm.setPage(page);
|
||||
}}
|
||||
disabled={vm.history.isFetching}
|
||||
siblings={0}
|
||||
getItemProps={(page) => ({
|
||||
"aria-label": t("bank.page", { page }),
|
||||
})}
|
||||
getControlProps={(control) => ({
|
||||
"aria-label": t(
|
||||
control === "previous" ? "bank.previous" : "bank.next",
|
||||
),
|
||||
})}
|
||||
/>
|
||||
</Group>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export { CardPageView };
|
||||
@@ -0,0 +1,144 @@
|
||||
import dayjs from "dayjs";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useParams, useSearchParams } from "react-router";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
type BankOperation,
|
||||
bankMonth,
|
||||
useBankCard,
|
||||
useBankCards,
|
||||
useBankMutations,
|
||||
useBankOperations,
|
||||
useBankSummary,
|
||||
} from "@/entities/bank-card";
|
||||
import { apiErrorCode } from "@/shared/api";
|
||||
import { formatDate, formatMoney } from "@/shared/lib";
|
||||
|
||||
const calendarDate = z.string().date();
|
||||
|
||||
const PAGE_SIZES = ["5", "10", "20", "50", "100", "all"];
|
||||
|
||||
function useCardPageVm() {
|
||||
const { cardId } = useParams();
|
||||
const [params, setParams] = useSearchParams();
|
||||
const { t } = useTranslation();
|
||||
const month = bankMonth(params.get("month"));
|
||||
const from = params.get("from");
|
||||
const to = params.get("to");
|
||||
const period =
|
||||
from &&
|
||||
to &&
|
||||
calendarDate.safeParse(from).success &&
|
||||
calendarDate.safeParse(to).success &&
|
||||
from >= "0001-01-01" &&
|
||||
from <= to
|
||||
? { from, to }
|
||||
: {
|
||||
from: `${month}-01`,
|
||||
to: dayjs(`${month}-01`).endOf("month").format("YYYY-MM-DD"),
|
||||
};
|
||||
const requestedSize = params.get("limit") ?? "10";
|
||||
const pageSize = PAGE_SIZES.includes(requestedSize) ? requestedSize : "10";
|
||||
const rawPage = Number(params.get("page") ?? 1);
|
||||
const page =
|
||||
pageSize !== "all" && Number.isSafeInteger(rawPage) && rawPage > 0
|
||||
? rawPage
|
||||
: 1;
|
||||
const card = useBankCard(cardId);
|
||||
const { updateCard } = useBankMutations();
|
||||
const [archiveError, setArchiveError] = useState<unknown>();
|
||||
const cards = useBankCards(true);
|
||||
const history = useBankOperations(cardId, {
|
||||
...period,
|
||||
page,
|
||||
limit: pageSize === "all" ? "all" : Number(pageSize),
|
||||
});
|
||||
const summary = useBankSummary(period, cardId);
|
||||
const [editingCard, setEditingCard] = useState(false);
|
||||
const [operation, setOperation] = useState<BankOperation | "new" | null>(
|
||||
null,
|
||||
);
|
||||
const [deleting, setDeleting] = useState<BankOperation | null>(null);
|
||||
const rows = history.data?.items.map((item) => {
|
||||
const outgoing =
|
||||
item.kind === "expense" ||
|
||||
(item.kind === "transfer" && item.cardId === cardId);
|
||||
return {
|
||||
item,
|
||||
color: outgoing ? "red" : "green",
|
||||
title:
|
||||
item.kind === "transfer"
|
||||
? t(outgoing ? "bank.transferTo" : "bank.transferFrom", {
|
||||
name: outgoing ? item.targetCardName : item.cardName,
|
||||
})
|
||||
: t(`bank.kinds.${item.kind}`),
|
||||
metadata: [formatDate(item.date), item.categoryName, item.description]
|
||||
.filter(Boolean)
|
||||
.join(" · "),
|
||||
value: `${outgoing ? "−" : "+"}${formatMoney(item.amount)}`,
|
||||
tone: outgoing ? ("negative" as const) : ("positive" as const),
|
||||
otherCard:
|
||||
item.kind === "transfer"
|
||||
? outgoing
|
||||
? item.targetCardId
|
||||
: item.cardId
|
||||
: null,
|
||||
editable:
|
||||
Boolean(cards.data) &&
|
||||
!cards.data?.some(
|
||||
(c) =>
|
||||
(c.id === item.cardId || c.id === item.targetCardId) &&
|
||||
c.archivedAt,
|
||||
),
|
||||
};
|
||||
});
|
||||
return {
|
||||
card,
|
||||
cards,
|
||||
archiveError,
|
||||
archivePending: updateCard.isPending,
|
||||
toggleArchive: async () => {
|
||||
if (!card.data) return;
|
||||
setArchiveError(undefined);
|
||||
try {
|
||||
await updateCard.mutateAsync({
|
||||
id: card.data.id,
|
||||
body: { version: card.data.version, archived: !card.data.archivedAt },
|
||||
});
|
||||
} catch (failure) {
|
||||
setArchiveError(failure);
|
||||
}
|
||||
},
|
||||
history,
|
||||
summary,
|
||||
period,
|
||||
page,
|
||||
pageSize,
|
||||
totalPages:
|
||||
pageSize === "all"
|
||||
? 1
|
||||
: Math.max(1, Math.ceil((history.data?.total ?? 0) / Number(pageSize))),
|
||||
rows,
|
||||
editingCard,
|
||||
setEditingCard,
|
||||
operation,
|
||||
setOperation,
|
||||
deleting,
|
||||
setDeleting,
|
||||
notFound: apiErrorCode(card.error) === "BANK_NOT_FOUND",
|
||||
setPeriod: (value: [string | null, string | null]) => {
|
||||
if (value[0] && value[1])
|
||||
setParams({ from: value[0], to: value[1], limit: pageSize });
|
||||
},
|
||||
setPageSize: (value: string | null) => {
|
||||
if (value && PAGE_SIZES.includes(value))
|
||||
setParams({ ...period, limit: value });
|
||||
},
|
||||
setPage: (value: number) =>
|
||||
setParams({ ...period, page: String(value), limit: pageSize }),
|
||||
};
|
||||
}
|
||||
type CardPageVm = ReturnType<typeof useCardPageVm>;
|
||||
|
||||
export { type CardPageVm, useCardPageVm };
|
||||
@@ -0,0 +1,76 @@
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { HttpResponse, http } from "msw";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { BankOperation } from "@/entities/bank-card";
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createTestQueryClient } from "@/test/query";
|
||||
import { server } from "@/test/server";
|
||||
import { DeleteOperation } from "./DeleteOperation";
|
||||
|
||||
const transfer: BankOperation = {
|
||||
id: "transfer",
|
||||
kind: "transfer",
|
||||
cardId: "a",
|
||||
cardName: "Основная",
|
||||
targetCardId: "b",
|
||||
targetCardName: "Запасная",
|
||||
categoryId: null,
|
||||
categoryName: null,
|
||||
originalExpenseId: null,
|
||||
amount: { currency: "RUB", value: "100" },
|
||||
availableRefund: null,
|
||||
date: "2026-08-01",
|
||||
description: null,
|
||||
version: 1,
|
||||
createdAt: "2026-08-01T00:00:00Z",
|
||||
};
|
||||
describe("DeleteOperation", () => {
|
||||
it("names both sides and requires a deliberate fresh version after conflict", async () => {
|
||||
configureAuthClient({
|
||||
accessToken: () => "test",
|
||||
refresh: async () => false,
|
||||
clear: () => {},
|
||||
});
|
||||
const versions: string[] = [];
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/operations/transfer", () =>
|
||||
HttpResponse.json({ ...transfer, version: 2 }),
|
||||
),
|
||||
http.delete("*/api/v1/bank-cards/operations/transfer", ({ request }) => {
|
||||
const version = new URL(request.url).searchParams.get("version") ?? "";
|
||||
versions.push(version);
|
||||
return version === "1"
|
||||
? HttpResponse.json(
|
||||
{ code: "BANK_VERSION_CONFLICT" },
|
||||
{ status: 409 },
|
||||
)
|
||||
: new HttpResponse(null, { status: 204 });
|
||||
}),
|
||||
);
|
||||
const close = vi.fn();
|
||||
render(
|
||||
<QueryClientProvider client={createTestQueryClient()}>
|
||||
<MantineProvider env="test">
|
||||
<DeleteOperation operation={transfer} onClose={close} />
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
expect(screen.getByText(/«Основная» → «Запасная»/)).toHaveTextContent(
|
||||
"Обе стороны перевода будут удалены.",
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Удалить" }));
|
||||
await screen.findByText(/Запись уже изменена/);
|
||||
expect(close).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Перечитать запись" }));
|
||||
fireEvent.click(
|
||||
await screen.findByRole("button", {
|
||||
name: "Использовать актуальную версию 2",
|
||||
}),
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Удалить" }));
|
||||
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||
expect(versions).toEqual(["1", "2"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { Button, Group, Modal, Stack, Text } from "@mantine/core";
|
||||
import { type FC, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
BankFeedback,
|
||||
type BankOperation,
|
||||
useBankFormFocus,
|
||||
useBankMutations,
|
||||
useBankOperation,
|
||||
} from "@/entities/bank-card";
|
||||
import { formatDate, formatMoney } from "@/shared/lib";
|
||||
|
||||
type DeleteOperationProps = { operation: BankOperation; onClose: () => void };
|
||||
const DeleteOperation: FC<DeleteOperationProps> = (props) => {
|
||||
useBankFormFocus();
|
||||
const { t } = useTranslation();
|
||||
const [record, setRecord] = useState(props.operation);
|
||||
const [latest, setLatest] = useState<BankOperation>();
|
||||
const [error, setError] = useState<unknown>();
|
||||
const query = useBankOperation(record.id);
|
||||
const { deleteOperation } = useBankMutations();
|
||||
const pending =
|
||||
deleteOperation.isPending || (query.isFetching && Boolean(error));
|
||||
return (
|
||||
<Modal
|
||||
opened
|
||||
onClose={() => !pending && props.onClose()}
|
||||
title={t("bank.deleteTitle")}
|
||||
closeOnEscape={!pending}
|
||||
closeOnClickOutside={!pending}
|
||||
closeButtonProps={{ "aria-label": t("bank.close"), disabled: pending }}
|
||||
>
|
||||
<Stack>
|
||||
<Text>
|
||||
{record.kind === "transfer"
|
||||
? t("bank.deleteTransfer", {
|
||||
amount: formatMoney(record.amount),
|
||||
source: record.cardName,
|
||||
target: record.targetCardName,
|
||||
})
|
||||
: t("bank.deleteHint", {
|
||||
kind: t(`bank.kinds.${record.kind}`),
|
||||
amount: formatMoney(record.amount),
|
||||
card: record.cardName,
|
||||
})}
|
||||
</Text>
|
||||
{error ? (
|
||||
<>
|
||||
<BankFeedback error={error} />
|
||||
<Button
|
||||
variant="default"
|
||||
disabled={pending}
|
||||
onClick={async () => {
|
||||
const result = await query.refetch();
|
||||
if (result.data && !result.error) setLatest(result.data);
|
||||
else setError(result.error);
|
||||
}}
|
||||
>
|
||||
{t("bank.reloadRecord")}
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
{latest && (
|
||||
<>
|
||||
<Text>
|
||||
{t("bank.versionHint", {
|
||||
details: `${formatDate(latest.date)} · ${formatMoney(latest.amount)} · ${latest.description ?? ""}`,
|
||||
})}
|
||||
</Text>
|
||||
<Button
|
||||
variant="default"
|
||||
disabled={pending}
|
||||
onClick={() => {
|
||||
setRecord(latest);
|
||||
setLatest(undefined);
|
||||
setError(undefined);
|
||||
}}
|
||||
>
|
||||
{t("bank.adoptVersion", { version: latest.version })}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Group>
|
||||
<Button
|
||||
color="red"
|
||||
loading={pending}
|
||||
onClick={async () => {
|
||||
setError(undefined);
|
||||
try {
|
||||
await deleteOperation.mutateAsync({
|
||||
id: record.id,
|
||||
version: record.version,
|
||||
});
|
||||
props.onClose();
|
||||
} catch (failure) {
|
||||
setError(failure);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t("bank.delete")}
|
||||
</Button>
|
||||
<Button variant="default" disabled={pending} onClick={props.onClose}>
|
||||
{t("bank.cancel")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export { DeleteOperation };
|
||||
@@ -0,0 +1,6 @@
|
||||
.fieldset {
|
||||
border: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
@@ -0,0 +1,465 @@
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import {
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
within,
|
||||
} from "@testing-library/react";
|
||||
import { HttpResponse, http } from "msw";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { BankCard, BankOperation } from "@/entities/bank-card";
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createTestQueryClient } from "@/test/query";
|
||||
import { server } from "@/test/server";
|
||||
import { OperationForm } from "./OperationForm";
|
||||
|
||||
const money = (value: string) => ({ currency: "RUB", value });
|
||||
const card: BankCard = {
|
||||
id: "a",
|
||||
name: "Повседневная",
|
||||
bankName: null,
|
||||
lastFour: null,
|
||||
paymentSystem: null,
|
||||
balance: money("0"),
|
||||
openingBalance: money("0"),
|
||||
openingDate: "2026-01-01",
|
||||
archivedAt: null,
|
||||
version: 1,
|
||||
};
|
||||
function setup(operation?: BankOperation) {
|
||||
configureAuthClient({
|
||||
accessToken: () => "test",
|
||||
refresh: async () => false,
|
||||
clear: () => {},
|
||||
});
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/categories", () =>
|
||||
HttpResponse.json([
|
||||
{ id: "default", name: "Остальное", isDefault: true, version: 2 },
|
||||
]),
|
||||
),
|
||||
);
|
||||
const close = vi.fn();
|
||||
render(
|
||||
<QueryClientProvider client={createTestQueryClient()}>
|
||||
<MantineProvider env="test">
|
||||
<OperationForm
|
||||
operation={operation}
|
||||
card={card}
|
||||
cards={[
|
||||
card,
|
||||
{ ...card, id: "b", name: "Запасная", openingDate: "2026-08-01" },
|
||||
{
|
||||
...card,
|
||||
id: "archived",
|
||||
name: "Архивная",
|
||||
archivedAt: "2026-01-02",
|
||||
},
|
||||
]}
|
||||
onClose={close}
|
||||
/>
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
return close;
|
||||
}
|
||||
async function select(label: string, value: string | RegExp) {
|
||||
fireEvent.click(screen.getByRole("combobox", { name: new RegExp(label) }));
|
||||
fireEvent.click(await screen.findByRole("option", { name: value }));
|
||||
}
|
||||
describe("OperationForm", () => {
|
||||
it("uses renamed default category and exact maximum positive money despite zero balance", async () => {
|
||||
const close = setup();
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("combobox", { name: /Категория/ })).toHaveValue(
|
||||
"Остальное",
|
||||
),
|
||||
);
|
||||
fireEvent.change(screen.getByLabelText(/Дата операции/), {
|
||||
target: { value: "07.08.2026" },
|
||||
});
|
||||
fireEvent.blur(screen.getByLabelText(/Дата операции/));
|
||||
expect(screen.getByLabelText(/Дата операции/)).toHaveValue("07.08.2026");
|
||||
let body: unknown;
|
||||
server.use(
|
||||
http.post("*/api/v1/bank-cards/operations", async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({}, { status: 201 });
|
||||
}),
|
||||
);
|
||||
fireEvent.change(screen.getByLabelText(/Сумма/), {
|
||||
target: { value: "92233720368547758,07" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||
expect(body).toMatchObject({
|
||||
categoryId: "default",
|
||||
date: "2026-08-07",
|
||||
amount: money("92233720368547758.07"),
|
||||
});
|
||||
});
|
||||
it("checks both transfer opening dates, excludes archive and reuses intent after a lost response", async () => {
|
||||
setup();
|
||||
await select("Вид операции", "Перевод");
|
||||
await select("Карта-получатель", "Запасная");
|
||||
fireEvent.change(screen.getByLabelText(/Сумма/), {
|
||||
target: { value: "0" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText(/Дата операции/), {
|
||||
target: { value: "31.07.2026" },
|
||||
});
|
||||
const bodies: unknown[] = [];
|
||||
server.use(
|
||||
http.post("*/api/v1/bank-cards/operations", async ({ request }) => {
|
||||
bodies.push(await request.json());
|
||||
return bodies.length === 1
|
||||
? HttpResponse.error()
|
||||
: HttpResponse.json({}, { status: 201 });
|
||||
}),
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
expect(
|
||||
await screen.findByText("Сумма операции должна быть больше нуля."),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText(/Дата не может быть раньше/)).toBeInTheDocument();
|
||||
expect(bodies).toHaveLength(0);
|
||||
fireEvent.change(screen.getByLabelText(/Сумма/), {
|
||||
target: { value: "150,01" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText(/Дата операции/), {
|
||||
target: { value: "02.08.2026" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await screen.findByText(/Не удалось подтвердить сохранение/);
|
||||
expect(screen.getByLabelText(/Сумма/)).toHaveValue("150,01");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await waitFor(() => expect(bodies).toHaveLength(2));
|
||||
expect(bodies[0]).toEqual(bodies[1]);
|
||||
expect(bodies[0]).toMatchObject({
|
||||
kind: "transfer",
|
||||
cardId: "a",
|
||||
targetCardId: "b",
|
||||
amount: money("150.01"),
|
||||
});
|
||||
});
|
||||
it("topup omits categories and preserves entered description", async () => {
|
||||
setup();
|
||||
await select("Вид операции", "Пополнение");
|
||||
expect(
|
||||
screen.queryByRole("combobox", { name: /Категория/ }),
|
||||
).not.toBeInTheDocument();
|
||||
let body: unknown;
|
||||
server.use(
|
||||
http.post("*/api/v1/bank-cards/operations", async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({}, { status: 201 });
|
||||
}),
|
||||
);
|
||||
fireEvent.change(screen.getByLabelText(/Сумма/), {
|
||||
target: { value: "0.10" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText(/Описание/), {
|
||||
target: { value: "Внесение" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await waitFor(() => expect(body).toBeDefined());
|
||||
expect(body).toMatchObject({
|
||||
kind: "topup",
|
||||
amount: money("0.10"),
|
||||
description: "Внесение",
|
||||
});
|
||||
expect(body).not.toHaveProperty("categoryId");
|
||||
});
|
||||
it("finds a previous-month purchase across pages, checks remaining refund and retains the complete-refund intent", async () => {
|
||||
const purchase: BankOperation = {
|
||||
id: "purchase",
|
||||
kind: "expense",
|
||||
cardId: "a",
|
||||
cardName: card.name,
|
||||
targetCardId: null,
|
||||
targetCardName: null,
|
||||
categoryId: "default",
|
||||
categoryName: "Остальное",
|
||||
originalExpenseId: null,
|
||||
amount: money("500"),
|
||||
availableRefund: money("500"),
|
||||
date: "2026-07-01",
|
||||
description: "Прошлая покупка",
|
||||
version: 1,
|
||||
createdAt: "2026-07-01T00:00:00Z",
|
||||
};
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/a/expenses", ({ request }) => {
|
||||
return HttpResponse.json({
|
||||
items:
|
||||
new URL(request.url).searchParams.get("page") === "2"
|
||||
? [purchase]
|
||||
: [],
|
||||
page: 1,
|
||||
total: 1,
|
||||
hasNext: new URL(request.url).searchParams.get("page") !== "2",
|
||||
});
|
||||
}),
|
||||
http.get("*/api/v1/bank-cards/operations/purchase", () =>
|
||||
HttpResponse.json(purchase),
|
||||
),
|
||||
);
|
||||
const close = setup();
|
||||
await select("Вид операции", "Возврат");
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("button", { name: "Далее" })).toBeEnabled(),
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Далее" }));
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("button", { name: "Назад" })).toBeEnabled(),
|
||||
);
|
||||
await select("Исходная покупка", /Прошлая покупка/);
|
||||
await screen.findByText("Доступно к возврату: 500 ₽");
|
||||
fireEvent.change(screen.getByLabelText(/Сумма/), {
|
||||
target: { value: "500.01" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await screen.findByText("Сумма превышает доступный возврат.");
|
||||
const bodies: unknown[] = [];
|
||||
server.use(
|
||||
http.post("*/api/v1/bank-cards/operations", async ({ request }) => {
|
||||
bodies.push(await request.json());
|
||||
purchase.availableRefund = money("0");
|
||||
return bodies.length === 1
|
||||
? HttpResponse.error()
|
||||
: HttpResponse.json({}, { status: 201 });
|
||||
}),
|
||||
);
|
||||
fireEvent.change(screen.getByLabelText(/Сумма/), {
|
||||
target: { value: "500" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText(/Дата операции/), {
|
||||
target: { value: "01.08.2026" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await screen.findByText(/Не удалось подтвердить сохранение/);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Перечитать запись" }));
|
||||
await screen.findByText("Доступно к возврату: 0 ₽");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||
expect(bodies[0]).toEqual(bodies[1]);
|
||||
expect(bodies[0]).toMatchObject({
|
||||
kind: "refund",
|
||||
originalExpenseId: "purchase",
|
||||
date: "2026-08-01",
|
||||
});
|
||||
});
|
||||
it("edits a full refund with its own amount excluded from the limit and immutable purchase", async () => {
|
||||
const refund: BankOperation = {
|
||||
id: "refund",
|
||||
kind: "refund",
|
||||
cardId: "a",
|
||||
cardName: card.name,
|
||||
targetCardId: null,
|
||||
targetCardName: null,
|
||||
categoryId: "default",
|
||||
categoryName: "Остальное",
|
||||
originalExpenseId: "purchase",
|
||||
amount: money("500"),
|
||||
availableRefund: money("500"),
|
||||
date: "2026-08-01",
|
||||
description: "",
|
||||
version: 2,
|
||||
createdAt: "2026-08-01T00:00:00Z",
|
||||
};
|
||||
const purchase = {
|
||||
...refund,
|
||||
id: "purchase",
|
||||
kind: "expense",
|
||||
date: "2026-07-01",
|
||||
availableRefund: money("0"),
|
||||
};
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/a/expenses", () =>
|
||||
HttpResponse.json({
|
||||
items: [purchase],
|
||||
page: 1,
|
||||
total: 1,
|
||||
hasNext: false,
|
||||
}),
|
||||
),
|
||||
http.get("*/api/v1/bank-cards/operations/purchase", () =>
|
||||
HttpResponse.json(purchase),
|
||||
),
|
||||
http.get("*/api/v1/bank-cards/operations/refund", () =>
|
||||
HttpResponse.json(refund),
|
||||
),
|
||||
);
|
||||
const close = setup(refund);
|
||||
await screen.findByText("Доступно к возврату: 500 ₽");
|
||||
expect(
|
||||
screen.getByRole("combobox", { name: /Исходная покупка/ }),
|
||||
).toBeDisabled();
|
||||
expect(
|
||||
screen.getByRole("combobox", { name: /Вид операции/ }),
|
||||
).toBeDisabled();
|
||||
fireEvent.change(screen.getByLabelText(/Описание/), {
|
||||
target: { value: "Полностью возвращено" },
|
||||
});
|
||||
let body: unknown;
|
||||
server.use(
|
||||
http.patch(
|
||||
"*/api/v1/bank-cards/operations/refund",
|
||||
async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json(refund);
|
||||
},
|
||||
),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("button", { name: "Сохранить" })).toBeEnabled(),
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||
expect(body).toMatchObject({
|
||||
version: 2,
|
||||
amount: money("500"),
|
||||
originalExpenseId: "purchase",
|
||||
description: "Полностью возвращено",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps edit draft and stale version until explicit adoption after conflict", async () => {
|
||||
const operation: BankOperation = {
|
||||
id: "expense",
|
||||
kind: "expense",
|
||||
cardId: "a",
|
||||
cardName: card.name,
|
||||
targetCardId: null,
|
||||
targetCardName: null,
|
||||
categoryId: "default",
|
||||
categoryName: "Остальное",
|
||||
originalExpenseId: null,
|
||||
amount: money("100"),
|
||||
availableRefund: money("100"),
|
||||
date: "2026-08-01",
|
||||
description: "Первое",
|
||||
version: 1,
|
||||
createdAt: "2026-08-01T00:00:00Z",
|
||||
};
|
||||
let readVersion = 1;
|
||||
const bodies: Record<string, unknown>[] = [];
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/operations/expense", () =>
|
||||
HttpResponse.json({
|
||||
...operation,
|
||||
version: readVersion,
|
||||
description: readVersion === 1 ? "Первое" : "Другое исправление",
|
||||
}),
|
||||
),
|
||||
http.patch(
|
||||
"*/api/v1/bank-cards/operations/expense",
|
||||
async ({ request }) => {
|
||||
const body = (await request.json()) as Record<string, unknown>;
|
||||
bodies.push(body);
|
||||
readVersion = 2;
|
||||
return body.version === 1
|
||||
? HttpResponse.json(
|
||||
{ code: "BANK_VERSION_CONFLICT" },
|
||||
{ status: 409 },
|
||||
)
|
||||
: HttpResponse.json({ ...operation, ...body });
|
||||
},
|
||||
),
|
||||
);
|
||||
const close = setup(operation);
|
||||
fireEvent.change(screen.getByLabelText(/Описание/), {
|
||||
target: { value: "Мой черновик" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText(/Сумма/), {
|
||||
target: { value: "150" },
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("button", { name: "Сохранить" })).toBeEnabled(),
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await screen.findByText(/Запись уже изменена/);
|
||||
expect(screen.getByLabelText(/Описание/)).toHaveValue("Мой черновик");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Перечитать запись" }));
|
||||
await screen.findByRole("button", {
|
||||
name: "Использовать актуальную версию 2",
|
||||
});
|
||||
expect(screen.getByLabelText(/Сумма/)).toHaveValue("150");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await waitFor(() => expect(bodies).toHaveLength(2));
|
||||
expect(bodies[1].version).toBe(1);
|
||||
fireEvent.click(
|
||||
screen.getByRole("button", { name: "Использовать актуальную версию 2" }),
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||
expect(bodies[2]).toMatchObject({
|
||||
version: 2,
|
||||
description: "Мой черновик",
|
||||
amount: money("150"),
|
||||
});
|
||||
});
|
||||
it("creates a category inside expense without losing operation fields", async () => {
|
||||
setup();
|
||||
fireEvent.change(screen.getByLabelText(/Сумма/), {
|
||||
target: { value: "001.20" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText(/Описание/), {
|
||||
target: { value: "Черновик расхода" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Добавить категорию" }));
|
||||
const dialog = screen.getByRole("dialog", { name: "Категории" });
|
||||
fireEvent.change(within(dialog).getByLabelText(/Название категории/), {
|
||||
target: { value: " кафе " },
|
||||
});
|
||||
let created = false;
|
||||
server.use(
|
||||
http.post("*/api/v1/bank-cards/categories", () => {
|
||||
created = true;
|
||||
return HttpResponse.json(
|
||||
{ id: "new", name: "кафе", version: 1, isDefault: false },
|
||||
{ status: 201 },
|
||||
);
|
||||
}),
|
||||
http.get("*/api/v1/bank-cards/categories", () =>
|
||||
HttpResponse.json([
|
||||
{ id: "default", name: "Остальное", isDefault: true, version: 2 },
|
||||
...(created
|
||||
? [{ id: "new", name: "кафе", isDefault: false, version: 1 }]
|
||||
: []),
|
||||
]),
|
||||
),
|
||||
);
|
||||
fireEvent.click(
|
||||
within(dialog).getByRole("button", { name: "Добавить категорию" }),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.queryByRole("dialog", { name: "Категории" }),
|
||||
).not.toBeInTheDocument(),
|
||||
);
|
||||
expect(screen.getByLabelText(/Сумма/)).toHaveValue("001.20");
|
||||
expect(screen.getByLabelText(/Описание/)).toHaveValue("Черновик расхода");
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("combobox", { name: /Категория/ })).toHaveValue(
|
||||
"кафе",
|
||||
),
|
||||
);
|
||||
let body: unknown;
|
||||
server.use(
|
||||
http.post("*/api/v1/bank-cards/operations", async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({}, { status: 201 });
|
||||
}),
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await waitFor(() => expect(body).toBeDefined());
|
||||
expect(body).toMatchObject({
|
||||
categoryId: "new",
|
||||
description: "Черновик расхода",
|
||||
amount: money("1.20"),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,417 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Button, Group, Modal, Stack, Text } from "@mantine/core";
|
||||
import { type FC, useState } from "react";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
type BankCard,
|
||||
BankFeedback,
|
||||
type BankOperation,
|
||||
bankDateSchema,
|
||||
bankMoneyValue,
|
||||
bankToday,
|
||||
CategoryManager,
|
||||
moneyCents,
|
||||
positiveMoneySchema,
|
||||
useBankCategories,
|
||||
useBankExpenses,
|
||||
useBankFormFocus,
|
||||
useBankMutations,
|
||||
useBankOperation,
|
||||
} from "@/entities/bank-card";
|
||||
import { validationMessage } from "@/shared/i18n";
|
||||
import { formatDate, formatMoney } from "@/shared/lib";
|
||||
import classes from "./OperationForm.module.css";
|
||||
import type { OperationValues } from "./OperationForm.types";
|
||||
import { OperationFields, RefundFields } from "./OperationForm.view";
|
||||
|
||||
const operationSchema = z.object({
|
||||
kind: z.enum(["expense", "topup", "transfer", "refund"]),
|
||||
cardId: z.string(),
|
||||
targetCardId: z.string(),
|
||||
categoryId: z.string(),
|
||||
originalExpenseId: z.string(),
|
||||
amount: positiveMoneySchema,
|
||||
date: bankDateSchema,
|
||||
description: z
|
||||
.string()
|
||||
.max(500, validationMessage("bank.validation.description")(undefined)),
|
||||
});
|
||||
|
||||
type OperationFormProps = {
|
||||
card: BankCard;
|
||||
cards: BankCard[];
|
||||
operation?: BankOperation;
|
||||
onClose: () => void;
|
||||
};
|
||||
const OperationForm: FC<OperationFormProps> = (props) => {
|
||||
useBankFormFocus();
|
||||
const { t } = useTranslation();
|
||||
const [categoriesOpen, setCategoriesOpen] = useState(false);
|
||||
const [version, setVersion] = useState(props.operation?.version ?? 1);
|
||||
const [latest, setLatest] = useState<BankOperation>();
|
||||
const [sourcePage, setSourcePage] = useState(1);
|
||||
const [sourceId, setSourceId] = useState(
|
||||
props.operation?.originalExpenseId ?? "",
|
||||
);
|
||||
const sourceQuery = useBankOperation(sourceId || undefined);
|
||||
const currentQuery = useBankOperation(props.operation?.id);
|
||||
const [refundLimit, setRefundLimit] = useState(
|
||||
props.operation?.availableRefund,
|
||||
);
|
||||
const [intent] = useState(() => crypto.randomUUID());
|
||||
const [submittedValues, setSubmittedValues] = useState<OperationValues>();
|
||||
const [error, setError] = useState<unknown>();
|
||||
const categories = useBankCategories();
|
||||
const mutation = useBankMutations();
|
||||
const methods = useForm<OperationValues>({
|
||||
resolver: zodResolver(
|
||||
operationSchema.superRefine((values, ctx) => {
|
||||
// Repeated intent reaches server idempotency even after its source changed.
|
||||
if (
|
||||
submittedValues &&
|
||||
JSON.stringify(values) === JSON.stringify(submittedValues)
|
||||
)
|
||||
return;
|
||||
const source = props.cards.find((c) => c.id === values.cardId);
|
||||
const target = props.cards.find((c) => c.id === values.targetCardId);
|
||||
if (!source || source.archivedAt)
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["cardId"],
|
||||
...validationMessage("bank.validation.required")(undefined),
|
||||
});
|
||||
if (
|
||||
values.kind === "transfer" &&
|
||||
(!target || target.archivedAt || target.id === values.cardId)
|
||||
)
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["targetCardId"],
|
||||
...validationMessage("bank.validation.destination")(undefined),
|
||||
});
|
||||
if (
|
||||
(source && values.date < source.openingDate) ||
|
||||
(values.kind === "transfer" &&
|
||||
target &&
|
||||
values.date < target.openingDate)
|
||||
)
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["date"],
|
||||
...validationMessage("bank.validation.start")(undefined),
|
||||
});
|
||||
if (values.kind === "refund") {
|
||||
const expense = sourceQuery.data;
|
||||
if (!expense || expense.cardId !== values.cardId)
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["originalExpenseId"],
|
||||
...validationMessage("bank.validation.required")(undefined),
|
||||
});
|
||||
if (expense && values.date < expense.date)
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["date"],
|
||||
...validationMessage("bank.validation.start")(undefined),
|
||||
});
|
||||
const limit = props.operation
|
||||
? refundLimit
|
||||
: expense?.availableRefund;
|
||||
const amount = moneyCents(values.amount);
|
||||
if (
|
||||
limit &&
|
||||
amount !== null &&
|
||||
amount > (moneyCents(limit.value) ?? 0n)
|
||||
)
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["amount"],
|
||||
...validationMessage("bank.validation.refund")(undefined),
|
||||
});
|
||||
}
|
||||
if (
|
||||
values.kind === "expense" &&
|
||||
!categories.data?.some(
|
||||
(c) =>
|
||||
c.id ===
|
||||
(values.categoryId ||
|
||||
categories.data?.find((c) => c.isDefault)?.id),
|
||||
)
|
||||
)
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["categoryId"],
|
||||
...validationMessage("bank.validation.required")(undefined),
|
||||
});
|
||||
}),
|
||||
),
|
||||
defaultValues: {
|
||||
kind: props.operation?.kind ?? "expense",
|
||||
cardId: props.operation?.cardId ?? props.card.id,
|
||||
targetCardId: props.operation?.targetCardId ?? "",
|
||||
categoryId: props.operation?.categoryId ?? "",
|
||||
originalExpenseId: props.operation?.originalExpenseId ?? "",
|
||||
amount: props.operation?.amount.value ?? "",
|
||||
date: props.operation?.date ?? bankToday(),
|
||||
description: props.operation?.description ?? "",
|
||||
},
|
||||
});
|
||||
const kind = methods.watch("kind");
|
||||
const expenses = useBankExpenses(
|
||||
kind === "refund" ? props.card.id : undefined,
|
||||
{ page: sourcePage },
|
||||
);
|
||||
const source = methods.watch("cardId");
|
||||
const pending = methods.formState.isSubmitting;
|
||||
const options = props.cards
|
||||
.filter((c) => !c.archivedAt)
|
||||
.map((c) => ({ value: c.id, label: c.name }));
|
||||
return (
|
||||
<>
|
||||
<Modal
|
||||
opened
|
||||
onClose={() => !pending && !categoriesOpen && props.onClose()}
|
||||
title={t(props.operation ? "bank.editOperation" : "bank.addOperation")}
|
||||
closeOnEscape={!pending && !categoriesOpen}
|
||||
closeOnClickOutside={!pending && !categoriesOpen}
|
||||
closeButtonProps={{ "aria-label": t("bank.close"), disabled: pending }}
|
||||
>
|
||||
<FormProvider {...methods}>
|
||||
<form
|
||||
onSubmit={methods.handleSubmit(async (values) => {
|
||||
setSubmittedValues(values);
|
||||
setError(undefined);
|
||||
try {
|
||||
const body = {
|
||||
kind: values.kind,
|
||||
cardId: values.cardId,
|
||||
...(values.kind === "transfer"
|
||||
? { targetCardId: values.targetCardId }
|
||||
: {}),
|
||||
...(values.kind === "expense"
|
||||
? {
|
||||
categoryId:
|
||||
values.categoryId ||
|
||||
categories.data?.find((c) => c.isDefault)?.id,
|
||||
}
|
||||
: {}),
|
||||
...(values.kind === "refund"
|
||||
? { originalExpenseId: values.originalExpenseId }
|
||||
: {}),
|
||||
amount: {
|
||||
currency: "RUB" as const,
|
||||
value: bankMoneyValue(values.amount),
|
||||
},
|
||||
date: values.date,
|
||||
description: values.description,
|
||||
};
|
||||
if (props.operation)
|
||||
await mutation.updateOperation.mutateAsync({
|
||||
id: props.operation.id,
|
||||
body: { ...body, version },
|
||||
});
|
||||
else
|
||||
await mutation.createOperation.mutateAsync({
|
||||
id: intent,
|
||||
...body,
|
||||
});
|
||||
props.onClose();
|
||||
} catch (failure) {
|
||||
setError(failure);
|
||||
}
|
||||
})}
|
||||
>
|
||||
<fieldset disabled={pending} className={classes.fieldset}>
|
||||
<Stack>
|
||||
<OperationFields
|
||||
refundCardId={props.card.id}
|
||||
editing={Boolean(props.operation)}
|
||||
kind={kind}
|
||||
cards={options}
|
||||
targets={options.filter((c) => c.value !== source)}
|
||||
categories={
|
||||
categories.data?.map((c) => ({
|
||||
value: c.id,
|
||||
label: c.name,
|
||||
})) ?? []
|
||||
}
|
||||
defaultCategory={
|
||||
categories.data?.find((c) => c.isDefault)?.id ?? ""
|
||||
}
|
||||
/>
|
||||
{kind === "refund" && (
|
||||
<>
|
||||
<RefundFields
|
||||
editing={Boolean(props.operation)}
|
||||
expenses={
|
||||
expenses.data?.items.map((item) => ({
|
||||
value: item.id,
|
||||
label: t("bank.expenseChoice", {
|
||||
date: formatDate(item.date),
|
||||
name: item.description || item.categoryName,
|
||||
amount: formatMoney(item.amount),
|
||||
available: formatMoney(item.availableRefund),
|
||||
}),
|
||||
})) ?? []
|
||||
}
|
||||
selected={
|
||||
sourceQuery.data
|
||||
? {
|
||||
value: sourceQuery.data.id,
|
||||
label: t("bank.expenseChoice", {
|
||||
date: formatDate(sourceQuery.data.date),
|
||||
name:
|
||||
sourceQuery.data.description ||
|
||||
sourceQuery.data.categoryName,
|
||||
amount: formatMoney(sourceQuery.data.amount),
|
||||
available: formatMoney(
|
||||
sourceQuery.data.availableRefund,
|
||||
),
|
||||
}),
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onSelect={setSourceId}
|
||||
limit={
|
||||
props.operation
|
||||
? refundLimit
|
||||
: sourceQuery.data?.availableRefund
|
||||
}
|
||||
/>
|
||||
{expenses.isLoading && (
|
||||
<Text role="status">{t("bank.loadingHistory")}</Text>
|
||||
)}
|
||||
{expenses.data &&
|
||||
!expenses.data.items.length &&
|
||||
!props.operation && <Text>{t("bank.noPurchases")}</Text>}
|
||||
{!props.operation && (
|
||||
<Group>
|
||||
<Button
|
||||
variant="default"
|
||||
disabled={sourcePage === 1 || expenses.isFetching}
|
||||
onClick={() => setSourcePage(sourcePage - 1)}
|
||||
>
|
||||
{t("bank.previous")}
|
||||
</Button>
|
||||
<Text>{t("bank.page", { page: sourcePage })}</Text>
|
||||
<Button
|
||||
variant="default"
|
||||
disabled={
|
||||
!expenses.data?.hasNext || expenses.isFetching
|
||||
}
|
||||
onClick={() => setSourcePage(sourcePage + 1)}
|
||||
>
|
||||
{t("bank.next")}
|
||||
</Button>
|
||||
</Group>
|
||||
)}
|
||||
{expenses.isError && (
|
||||
<BankFeedback
|
||||
loadingError
|
||||
error={expenses.error}
|
||||
retry={() => void expenses.refetch()}
|
||||
/>
|
||||
)}{" "}
|
||||
{sourceQuery.isError && (
|
||||
<BankFeedback
|
||||
loadingError
|
||||
error={sourceQuery.error}
|
||||
retry={() => void sourceQuery.refetch()}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{kind === "expense" && (
|
||||
<Button
|
||||
variant="subtle"
|
||||
onClick={() => setCategoriesOpen(true)}
|
||||
>
|
||||
{t("bank.addCategory")}
|
||||
</Button>
|
||||
)}
|
||||
{categories.isError && (
|
||||
<BankFeedback
|
||||
loadingError
|
||||
error={categories.error}
|
||||
retry={() => void categories.refetch()}
|
||||
/>
|
||||
)}
|
||||
{error ? (
|
||||
<>
|
||||
<BankFeedback error={error} />
|
||||
{(props.operation || sourceId) && (
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={async () => {
|
||||
const query = props.operation
|
||||
? currentQuery
|
||||
: sourceQuery;
|
||||
const result = await query.refetch();
|
||||
if (result.data && !result.error) {
|
||||
if (props.operation) {
|
||||
setLatest(result.data);
|
||||
setRefundLimit(result.data.availableRefund);
|
||||
} else setError(undefined);
|
||||
} else setError(result.error);
|
||||
}}
|
||||
>
|
||||
{t("bank.reloadRecord")}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
{latest && (
|
||||
<>
|
||||
<Text>
|
||||
{t("bank.versionHint", {
|
||||
details: `${formatDate(latest.date)} · ${formatMoney(latest.amount)} · ${latest.description ?? ""}`,
|
||||
})}
|
||||
</Text>
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={() => {
|
||||
setVersion(latest.version);
|
||||
setLatest(undefined);
|
||||
setError(undefined);
|
||||
}}
|
||||
>
|
||||
{t("bank.adoptVersion", { version: latest.version })}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Group>
|
||||
<Button
|
||||
type="submit"
|
||||
loading={pending}
|
||||
disabled={
|
||||
(kind === "expense" && !categories.data) ||
|
||||
(kind === "refund" && !sourceQuery.data)
|
||||
}
|
||||
>
|
||||
{t("bank.save")}
|
||||
</Button>
|
||||
<Button variant="default" onClick={props.onClose}>
|
||||
{t("bank.cancel")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</fieldset>
|
||||
</form>
|
||||
</FormProvider>
|
||||
</Modal>
|
||||
{categoriesOpen && (
|
||||
<CategoryManager
|
||||
onClose={() => setCategoriesOpen(false)}
|
||||
onCreated={(id) => {
|
||||
methods.setValue("categoryId", id);
|
||||
setCategoriesOpen(false);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export { OperationForm };
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { BankOperation } from "@/entities/bank-card";
|
||||
|
||||
type OperationValues = {
|
||||
kind: BankOperation["kind"];
|
||||
cardId: string;
|
||||
targetCardId: string;
|
||||
categoryId: string;
|
||||
originalExpenseId: string;
|
||||
amount: string;
|
||||
date: string;
|
||||
description: string;
|
||||
};
|
||||
|
||||
export type { OperationValues };
|
||||
@@ -0,0 +1,203 @@
|
||||
import { Select, Stack, Text, Textarea, TextInput } from "@mantine/core";
|
||||
import { DateInput } from "@mantine/dates";
|
||||
import type { FC } from "react";
|
||||
import { Controller, useFormContext } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
type BankOperation,
|
||||
bankDateInputValue,
|
||||
bankDateSchema,
|
||||
bankToday,
|
||||
} from "@/entities/bank-card";
|
||||
import { formatMoney } from "@/shared/lib";
|
||||
import type { OperationValues } from "./OperationForm.types";
|
||||
|
||||
type Choice = { value: string; label: string };
|
||||
type OperationFieldsProps = {
|
||||
editing: boolean;
|
||||
refundCardId: string;
|
||||
kind: OperationValues["kind"];
|
||||
cards: Choice[];
|
||||
targets: Choice[];
|
||||
categories: Choice[];
|
||||
defaultCategory: string;
|
||||
};
|
||||
const OperationFields: FC<OperationFieldsProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
const {
|
||||
control,
|
||||
register,
|
||||
setValue,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useFormContext<OperationValues>();
|
||||
return (
|
||||
<Stack>
|
||||
<Controller
|
||||
control={control}
|
||||
name="kind"
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
label={t("bank.kind")}
|
||||
required
|
||||
data={(["expense", "topup", "transfer", "refund"] as const).map(
|
||||
(value) => ({ value, label: t(`bank.kinds.${value}`) }),
|
||||
)}
|
||||
{...field}
|
||||
disabled={isSubmitting || props.editing}
|
||||
onChange={(value) => {
|
||||
field.onChange(value ?? "expense");
|
||||
if (value === "refund") setValue("cardId", props.refundCardId);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
control={control}
|
||||
name="cardId"
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
label={t(
|
||||
props.kind === "transfer" ? "bank.source" : "bank.operationCard",
|
||||
)}
|
||||
required
|
||||
data={props.cards}
|
||||
{...field}
|
||||
disabled={isSubmitting || props.kind === "refund"}
|
||||
error={errors.cardId?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{props.kind === "transfer" && (
|
||||
<Controller
|
||||
control={control}
|
||||
name="targetCardId"
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
label={t("bank.destination")}
|
||||
required
|
||||
data={props.targets}
|
||||
{...field}
|
||||
disabled={isSubmitting}
|
||||
error={errors.targetCardId?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<TextInput
|
||||
label={t("bank.amount")}
|
||||
required
|
||||
inputMode="decimal"
|
||||
{...register("amount")}
|
||||
error={errors.amount?.message}
|
||||
/>
|
||||
<Controller
|
||||
control={control}
|
||||
name="date"
|
||||
render={({ field }) => (
|
||||
<DateInput
|
||||
{...field}
|
||||
label={t("bank.date")}
|
||||
required
|
||||
valueFormat="DD.MM.YYYY"
|
||||
value={
|
||||
bankDateSchema.safeParse(field.value).success ? field.value : null
|
||||
}
|
||||
dateParser={(value) =>
|
||||
bankDateSchema.safeParse(bankDateInputValue(value)).success
|
||||
? bankDateInputValue(value)
|
||||
: null
|
||||
}
|
||||
fixOnBlur={false}
|
||||
onInput={(event) =>
|
||||
field.onChange(bankDateInputValue(event.currentTarget.value))
|
||||
}
|
||||
onChange={(value) => field.onChange(value ?? "")}
|
||||
onBlur={(event) => {
|
||||
field.onChange(bankDateInputValue(event.currentTarget.value));
|
||||
field.onBlur();
|
||||
}}
|
||||
maxDate={bankToday()}
|
||||
popoverProps={{
|
||||
withinPortal: false,
|
||||
middlewares: { shift: { crossAxis: true } },
|
||||
}}
|
||||
error={errors.date?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{props.kind === "expense" && (
|
||||
<Controller
|
||||
control={control}
|
||||
name="categoryId"
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
label={t("bank.category")}
|
||||
required
|
||||
data={props.categories}
|
||||
{...field}
|
||||
value={field.value || props.defaultCategory}
|
||||
disabled={isSubmitting}
|
||||
error={errors.categoryId?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<Textarea
|
||||
label={t("bank.description")}
|
||||
{...register("description")}
|
||||
error={errors.description?.message}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
type RefundFieldsProps = {
|
||||
editing: boolean;
|
||||
expenses: Choice[];
|
||||
selected?: Choice;
|
||||
onSelect: (id: string) => void;
|
||||
limit: BankOperation["availableRefund"] | undefined;
|
||||
};
|
||||
const RefundFields: FC<RefundFieldsProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
const {
|
||||
control,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useFormContext<OperationValues>();
|
||||
return (
|
||||
<Stack>
|
||||
<Controller
|
||||
control={control}
|
||||
name="originalExpenseId"
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
label={t("bank.expense")}
|
||||
required
|
||||
data={
|
||||
props.selected &&
|
||||
!props.expenses.some(
|
||||
(item) => item.value === props.selected?.value,
|
||||
)
|
||||
? [props.selected, ...props.expenses]
|
||||
: props.expenses
|
||||
}
|
||||
{...field}
|
||||
onChange={(value) => {
|
||||
field.onChange(value ?? "");
|
||||
props.onSelect(value ?? "");
|
||||
}}
|
||||
disabled={isSubmitting || props.editing}
|
||||
error={errors.originalExpenseId?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{props.limit && (
|
||||
<Text>
|
||||
{t("bank.availableRefund", { amount: formatMoney(props.limit) })}
|
||||
</Text>
|
||||
)}
|
||||
{props.editing && <Text>{t("bank.purchaseImmutable")}</Text>}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export { OperationFields, RefundFields };
|
||||
@@ -0,0 +1 @@
|
||||
export { CardsPage } from "./ui/CardsPage";
|
||||
@@ -0,0 +1,13 @@
|
||||
.card {
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
min-width: 0;
|
||||
max-width: 28rem;
|
||||
border-radius: 1.25rem;
|
||||
background: transparent;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.card:focus-visible {
|
||||
outline: 2px solid var(--mantine-primary-color-filled);
|
||||
outline-offset: 3px;
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import {
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
within,
|
||||
} from "@testing-library/react";
|
||||
import { HttpResponse, http } from "msw";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createTestQueryClient } from "@/test/query";
|
||||
import { server } from "@/test/server";
|
||||
import { CardsPage } from "./CardsPage";
|
||||
|
||||
const money = (value: string) => ({ currency: "RUB", value });
|
||||
function renderCards(fail = false, categoryFail = false) {
|
||||
configureAuthClient({
|
||||
accessToken: () => "test",
|
||||
refresh: async () => false,
|
||||
clear: () => {},
|
||||
});
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/categories", () =>
|
||||
categoryFail ? HttpResponse.error() : HttpResponse.json([]),
|
||||
),
|
||||
http.get("*/api/v1/bank-cards", () =>
|
||||
fail ? HttpResponse.error() : HttpResponse.json([]),
|
||||
),
|
||||
http.get("*/api/v1/bank-cards/summary", () =>
|
||||
HttpResponse.json({
|
||||
month: "2026-09",
|
||||
cardId: null,
|
||||
expenses: money("0"),
|
||||
refunds: money("0"),
|
||||
net: money("0"),
|
||||
categories: [],
|
||||
}),
|
||||
),
|
||||
);
|
||||
return render(
|
||||
<QueryClientProvider client={createTestQueryClient()}>
|
||||
<MantineProvider>
|
||||
<MemoryRouter initialEntries={["/cards?month=2026-09"]}>
|
||||
<CardsPage />
|
||||
</MemoryRouter>
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
describe("CardsPage", () => {
|
||||
it("preserves exact negative opening amount and the creation intent through unknown failure", async () => {
|
||||
renderCards();
|
||||
await screen.findByRole("heading", { name: "Добавьте первую карту" });
|
||||
fireEvent.click(
|
||||
screen.getAllByRole("button", { name: "Добавить карту" })[0],
|
||||
);
|
||||
const dialog = screen.getByRole("dialog");
|
||||
const submitted: Record<string, unknown>[] = [];
|
||||
let resolve: (() => void) | undefined;
|
||||
server.use(
|
||||
http.post("*/api/v1/bank-cards", async ({ request }) => {
|
||||
submitted.push((await request.json()) as Record<string, unknown>);
|
||||
if (submitted.length === 1) {
|
||||
await new Promise<void>((r) => {
|
||||
resolve = r;
|
||||
});
|
||||
return HttpResponse.error();
|
||||
}
|
||||
return HttpResponse.json({ id: submitted[0].id }, { status: 201 });
|
||||
}),
|
||||
);
|
||||
fireEvent.change(within(dialog).getByLabelText(/Название карты/), {
|
||||
target: { value: " Повседневная " },
|
||||
});
|
||||
fireEvent.change(within(dialog).getByLabelText(/Начальный остаток/), {
|
||||
target: { value: "1,001" },
|
||||
});
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Сохранить" }));
|
||||
expect(
|
||||
await screen.findByText(/Введите сумму в допустимом диапазоне/),
|
||||
).toBeInTheDocument();
|
||||
expect(submitted).toHaveLength(0);
|
||||
fireEvent.change(within(dialog).getByLabelText(/Начальный остаток/), {
|
||||
target: { value: "-92233720368547758,08" },
|
||||
});
|
||||
fireEvent.change(within(dialog).getByLabelText(/Дата начала учёта/), {
|
||||
target: { value: "2026-01-01" },
|
||||
});
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Сохранить" }));
|
||||
await waitFor(() => expect(submitted).toHaveLength(1));
|
||||
expect(
|
||||
within(dialog).getByRole("button", { name: "Отмена" }),
|
||||
).toBeDisabled();
|
||||
expect(
|
||||
within(dialog).getByRole("button", { name: "Закрыть" }),
|
||||
).toBeDisabled();
|
||||
resolve?.();
|
||||
await screen.findByText(/Не удалось подтвердить сохранение/);
|
||||
expect(within(dialog).getByLabelText(/Начальный остаток/)).toHaveValue(
|
||||
"-92233720368547758,08",
|
||||
);
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Сохранить" }));
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),
|
||||
);
|
||||
expect(submitted[0]).toEqual(submitted[1]);
|
||||
expect(submitted[0]).toMatchObject({
|
||||
name: "Повседневная",
|
||||
bankName: null,
|
||||
lastFour: null,
|
||||
openingBalance: money("-92233720368547758.08"),
|
||||
});
|
||||
});
|
||||
it("uses archive only for card list and keeps all-card summary including negative net", async () => {
|
||||
renderCards();
|
||||
const requests: string[] = [];
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards", ({ request }) => {
|
||||
requests.push(new URL(request.url).search);
|
||||
return HttpResponse.json([
|
||||
{
|
||||
id: "demo",
|
||||
name: "Запасная",
|
||||
bankName: null,
|
||||
lastFour: null,
|
||||
balance: money("0"),
|
||||
archivedAt: "2026-09-01",
|
||||
version: 1,
|
||||
openingBalance: money("0"),
|
||||
openingDate: "2026-01-01",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
fireEvent.click(screen.getByLabelText("Показать архив"));
|
||||
await screen.findByText("Запасная");
|
||||
expect(requests).toContain("?includeArchived=true");
|
||||
expect(screen.getByLabelText("Месяц")).toHaveTextContent("September 2026");
|
||||
expect(screen.getByRole("link", { name: /Запасная/ })).toHaveAttribute(
|
||||
"href",
|
||||
"/cards/demo?month=2026-09",
|
||||
);
|
||||
});
|
||||
it("shows retry after failure instead of presenting an empty list", async () => {
|
||||
renderCards(true);
|
||||
// Mount starts asynchronously; this handler owns the request.
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent(
|
||||
"Не удалось загрузить данные карт.",
|
||||
);
|
||||
expect(
|
||||
screen.queryByRole("heading", { name: "Добавьте первую карту" }),
|
||||
).not.toBeInTheDocument();
|
||||
server.use(http.get("*/api/v1/bank-cards", () => HttpResponse.json([])));
|
||||
fireEvent.click(
|
||||
within(screen.getByRole("alert")).getByRole("button", {
|
||||
name: "Повторить",
|
||||
}),
|
||||
);
|
||||
await screen.findByRole("heading", { name: "Добавьте первую карту" });
|
||||
});
|
||||
it("makes failed category loading recoverable without hiding successful cards data", async () => {
|
||||
renderCards(false, true);
|
||||
await screen.findByRole("heading", { name: "Добавьте первую карту" });
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent(
|
||||
"Не удалось загрузить данные карт.",
|
||||
);
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/categories", () =>
|
||||
HttpResponse.json([
|
||||
{ id: "default", name: "Другое", version: 1, isDefault: true },
|
||||
]),
|
||||
),
|
||||
);
|
||||
fireEvent.click(
|
||||
within(screen.getByRole("alert")).getByRole("button", {
|
||||
name: "Повторить",
|
||||
}),
|
||||
);
|
||||
await screen.findByRole("button", { name: "Категории" });
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { FC } from "react";
|
||||
import { BankCardForm, CategoryManager } from "@/entities/bank-card";
|
||||
import { CardsPageView } from "./CardsPage.view";
|
||||
import { useCardsPageVm } from "./CardsPage.vm";
|
||||
|
||||
const CardsPage: FC = () => {
|
||||
const vm = useCardsPageVm();
|
||||
return (
|
||||
<>
|
||||
<CardsPageView vm={vm} />
|
||||
{vm.adding && <BankCardForm onClose={() => vm.setAdding(false)} />}
|
||||
{vm.managingCategories && (
|
||||
<CategoryManager onClose={() => vm.setManagingCategories(false)} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export { CardsPage };
|
||||
@@ -0,0 +1,122 @@
|
||||
import {
|
||||
Button,
|
||||
Group,
|
||||
Paper,
|
||||
SimpleGrid,
|
||||
Skeleton,
|
||||
Stack,
|
||||
Switch,
|
||||
Text,
|
||||
Title,
|
||||
} from "@mantine/core";
|
||||
import { MonthPickerInput } from "@mantine/dates";
|
||||
import type { FC } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
import {
|
||||
BankCardFace,
|
||||
BankFeedback,
|
||||
BankSummaryView,
|
||||
} from "@/entities/bank-card";
|
||||
import { LoadingSkeleton, StateView } from "@/shared/ui";
|
||||
import classes from "./CardsPage.module.css";
|
||||
import type { CardsPageVm } from "./CardsPage.vm";
|
||||
|
||||
type CardsPageViewProps = { vm: CardsPageVm };
|
||||
const CardsPageView: FC<CardsPageViewProps> = (props) => {
|
||||
const { vm } = props;
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Stack gap="lg">
|
||||
<Group justify="space-between">
|
||||
<Title order={1}>{t("bank.title")}</Title>
|
||||
<Button onClick={() => vm.setAdding(true)}>{t("bank.addCard")}</Button>
|
||||
</Group>
|
||||
<Text c="dimmed">{t("bank.manualBalance")}</Text>
|
||||
<Switch
|
||||
label={t("bank.showArchive")}
|
||||
checked={vm.archive}
|
||||
onChange={(event) => vm.setArchive(event.currentTarget.checked)}
|
||||
/>
|
||||
{vm.items ? (
|
||||
vm.items.length ? (
|
||||
<SimpleGrid cols={{ base: 1, sm: 2 }}>
|
||||
{vm.items.map((card) => (
|
||||
<Paper
|
||||
key={card.id}
|
||||
component={Link}
|
||||
to={card.to}
|
||||
p={0}
|
||||
className={classes.card}
|
||||
>
|
||||
<BankCardFace card={card} />
|
||||
</Paper>
|
||||
))}
|
||||
</SimpleGrid>
|
||||
) : (
|
||||
<StateView
|
||||
title={t("bank.empty")}
|
||||
text={t(vm.archive ? "bank.emptyHint" : "bank.noActive")}
|
||||
action={
|
||||
<Button onClick={() => vm.setAdding(true)}>
|
||||
{t("bank.addCard")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)
|
||||
) : vm.cards.isLoading ? (
|
||||
<LoadingSkeleton label={t("bank.loading")}>
|
||||
<SimpleGrid cols={{ base: 1, sm: 2 }}>
|
||||
<Skeleton h={250} />
|
||||
<Skeleton h={250} />
|
||||
</SimpleGrid>
|
||||
</LoadingSkeleton>
|
||||
) : null}
|
||||
{vm.cards.isError && (
|
||||
<Group role="alert">
|
||||
<Text>{t(vm.items ? "bank.refreshError" : "bank.error")}</Text>
|
||||
<Button variant="default" onClick={() => void vm.cards.refetch()}>
|
||||
{t("bank.retry")}
|
||||
</Button>
|
||||
</Group>
|
||||
)}
|
||||
{vm.cards.data && vm.cards.isFetching && (
|
||||
<Text role="status">{t("bank.refreshing")}</Text>
|
||||
)}
|
||||
<MonthPickerInput
|
||||
label={t("bank.month")}
|
||||
value={`${vm.month}-01`}
|
||||
onChange={(value) => {
|
||||
if (value) vm.setMonth(value.slice(0, 7));
|
||||
}}
|
||||
popoverProps={{ middlewares: { shift: { crossAxis: true } } }}
|
||||
/>
|
||||
<BankSummaryView
|
||||
all
|
||||
data={vm.summary.data}
|
||||
loading={vm.summary.isLoading}
|
||||
error={vm.summary.isError}
|
||||
fetching={vm.summary.isFetching}
|
||||
retry={() => void vm.summary.refetch()}
|
||||
/>
|
||||
{vm.categories.isError && (
|
||||
<BankFeedback
|
||||
loadingError
|
||||
error={vm.categories.error}
|
||||
cached={Boolean(vm.categories.data)}
|
||||
retry={() => void vm.categories.refetch()}
|
||||
/>
|
||||
)}
|
||||
{Boolean(vm.categories.data?.length || vm.cards.data?.length) && (
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={() => vm.setManagingCategories(true)}
|
||||
>
|
||||
{t("bank.categories")}
|
||||
</Button>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export { CardsPageView };
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useState } from "react";
|
||||
import { useSearchParams } from "react-router";
|
||||
import {
|
||||
bankMonth,
|
||||
useBankCards,
|
||||
useBankCategories,
|
||||
useBankSummary,
|
||||
} from "@/entities/bank-card";
|
||||
|
||||
function useCardsPageVm() {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const month = bankMonth(params.get("month"));
|
||||
const [archive, setArchive] = useState(false);
|
||||
const categories = useBankCategories();
|
||||
const [managingCategories, setManagingCategories] = useState(false);
|
||||
const [adding, setAdding] = useState(false);
|
||||
const cards = useBankCards(archive);
|
||||
const summary = useBankSummary(month);
|
||||
return {
|
||||
categories,
|
||||
managingCategories,
|
||||
setManagingCategories,
|
||||
month,
|
||||
archive,
|
||||
setArchive,
|
||||
adding,
|
||||
setAdding,
|
||||
cards,
|
||||
summary,
|
||||
setMonth: (value: string) => {
|
||||
if (value) setParams({ month: bankMonth(value) });
|
||||
},
|
||||
items: cards.data?.map((card) => ({
|
||||
...card,
|
||||
to: `/cards/${card.id}?month=${month}`,
|
||||
})),
|
||||
};
|
||||
}
|
||||
type CardsPageVm = ReturnType<typeof useCardsPageVm>;
|
||||
|
||||
export { type CardsPageVm, useCardsPageVm };
|
||||
Vendored
+1487
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -2,6 +2,7 @@ const ru = {
|
||||
translation: {
|
||||
appName: "WealthLedger",
|
||||
navigation: {
|
||||
cards: "Карты",
|
||||
accounts: "Счета",
|
||||
stocks: "Акции",
|
||||
bonds: "Облигации",
|
||||
@@ -16,6 +17,150 @@ const ru = {
|
||||
events: "Будущие события",
|
||||
settings: "Настройки",
|
||||
},
|
||||
bank: {
|
||||
title: "Карты",
|
||||
card: "Карта",
|
||||
addCard: "Добавить карту",
|
||||
editCard: "Изменить карту",
|
||||
manualBalance: "Баланс по внесённым операциям",
|
||||
openingHint:
|
||||
"Остаток до операций с выбранной даты. Валюта — рубли (RUB).",
|
||||
name: "Название карты",
|
||||
bankName: "Банк (необязательно)",
|
||||
paymentSystem: "Платёжная система (необязательно)",
|
||||
paymentSystemUnknown: "Не указана",
|
||||
paymentSystems: { mir: "МИР", visa: "Visa", mastercard: "Mastercard" },
|
||||
lastFour: "Последние четыре цифры (необязательно)",
|
||||
openingBalance: "Начальный остаток, ₽",
|
||||
openingDate: "Дата начала учёта",
|
||||
showArchive: "Показать архив",
|
||||
archived: "В архиве",
|
||||
archive: "Убрать в архив",
|
||||
restore: "Вернуть из архива",
|
||||
archiveHint:
|
||||
"История и деньги сохраняются. Для финансовых изменений верните карту из архива.",
|
||||
empty: "Добавьте первую карту",
|
||||
emptyHint: "Укажите начальный остаток и вносите расходы вручную.",
|
||||
noActive: "Нет активных карт. Включите показ архива.",
|
||||
loading: "Загрузка банковских карт",
|
||||
loadingHistory: "Загрузка операций",
|
||||
error: "Не удалось загрузить данные карт.",
|
||||
retry: "Повторить",
|
||||
refreshing: "Обновляем данные…",
|
||||
refreshError:
|
||||
"Не удалось обновить данные. Показаны последние полученные.",
|
||||
save: "Сохранить",
|
||||
cancel: "Отмена",
|
||||
close: "Закрыть",
|
||||
summary: "Расходы",
|
||||
allSummary: "Расходы по всем картам",
|
||||
month: "Месяц",
|
||||
period: "Период",
|
||||
expenses: "Потрачено",
|
||||
refunds: "Возвращено",
|
||||
net: "После возвратов",
|
||||
summaryHint:
|
||||
"Возвраты учитываются по дате получения. Итог может быть отрицательным.",
|
||||
noExpenses: "За этот период операций по расходам нет.",
|
||||
categories: "Категории",
|
||||
category: "Категория",
|
||||
categoryName: "Название категории",
|
||||
addCategory: "Добавить категорию",
|
||||
rename: "Переименовать",
|
||||
defaultCategory: "По умолчанию",
|
||||
notFound: "Карта не найдена",
|
||||
back: "К картам",
|
||||
operations: "Операции",
|
||||
noOperations: "Операций за период нет.",
|
||||
addOperation: "Добавить операцию",
|
||||
editOperation: "Изменить операцию",
|
||||
kind: "Вид операции",
|
||||
kinds: {
|
||||
expense: "Расход",
|
||||
topup: "Пополнение",
|
||||
transfer: "Перевод",
|
||||
refund: "Возврат",
|
||||
},
|
||||
source: "Карта-источник",
|
||||
destination: "Карта-получатель",
|
||||
operationCard: "Карта операции",
|
||||
amount: "Сумма, ₽",
|
||||
date: "Дата операции",
|
||||
description: "Описание (необязательно)",
|
||||
expense: "Исходная покупка за любой период",
|
||||
availableRefund: "Доступно к возврату: {{amount}}",
|
||||
expenseChoice:
|
||||
"{{date}} · {{name}} · {{amount}} · доступно {{available}}",
|
||||
noPurchases:
|
||||
"На этой странице нет покупок. Проверьте другие страницы истории.",
|
||||
purchaseImmutable: "Исходная покупка и карта возврата не изменяются.",
|
||||
previous: "Назад",
|
||||
next: "Далее",
|
||||
page: "Страница {{page}}",
|
||||
pagination: "Страницы операций",
|
||||
pageSize: "Операций на странице",
|
||||
allOperations: "Все",
|
||||
transferTo: "Перевод на «{{name}}»",
|
||||
transferFrom: "Перевод с «{{name}}»",
|
||||
edit: "Изменить",
|
||||
delete: "Удалить",
|
||||
deleteTitle: "Удалить операцию?",
|
||||
deleteHint:
|
||||
"{{kind}} · {{amount}} · {{card}}. Денежное влияние будет отменено.",
|
||||
deleteTransfer:
|
||||
"Перевод {{amount}}: «{{source}}» → «{{target}}». Обе стороны перевода будут удалены.",
|
||||
reloadRecord: "Перечитать запись",
|
||||
adoptVersion: "Использовать актуальную версию {{version}}",
|
||||
versionHint:
|
||||
"Актуальные данные: {{details}}. Черновик сохранён; проверьте его перед повторной отправкой.",
|
||||
requestError:
|
||||
"Не удалось подтвердить сохранение. Ввод сохранён; повтор использует то же намерение.",
|
||||
errors: {
|
||||
BANK_VERSION_CONFLICT:
|
||||
"Запись уже изменена. Перечитайте её и проверьте черновик перед повторным сохранением.",
|
||||
BANK_WRITE_CONFLICT:
|
||||
"Данные изменяются другим запросом. Перечитайте запись и повторите действие.",
|
||||
BANK_DUPLICATE_CATEGORY: "Категория с таким названием уже есть.",
|
||||
BANK_NOT_FOUND: "Запись не найдена или недоступна.",
|
||||
BANK_INTENT_CONFLICT:
|
||||
"Это намерение уже сохранено с другим содержимым. Закройте форму и проверьте историю перед новым действием.",
|
||||
BANK_CARD_ARCHIVED:
|
||||
"Затронутая карта в архиве. Сначала верните её из архива.",
|
||||
BANK_REFUND_LIMIT:
|
||||
"Сумма превышает доступный возврат. Перечитайте покупку.",
|
||||
BANK_DEPENDENT_REFUNDS:
|
||||
"Изменению мешают связанные возвраты. Сначала исправьте или удалите их.",
|
||||
BANK_OPENING_DATE_CONFLICT:
|
||||
"Дата начала противоречит сохранённой истории карты.",
|
||||
BANK_INVALID_DATE:
|
||||
"Проверьте дату операции и даты начала учёта обеих карт.",
|
||||
BANK_INVALID_MONEY: "Введите допустимую сумму с точностью до копеек.",
|
||||
BANK_INVALID_INPUT: "Проверьте поля и связанные карты.",
|
||||
BANK_INVALID_REFUND: "Исходная покупка недоступна для этого возврата.",
|
||||
BANK_IMMUTABLE_OPERATION:
|
||||
"Вид операции и исходную покупку возврата изменить нельзя.",
|
||||
BANK_OPERATION_DELETED:
|
||||
"Операция уже удалена. Она не будет создана повторно.",
|
||||
},
|
||||
validation: {
|
||||
name: "Введите название от 1 до 100 символов.",
|
||||
paymentSystem: "Выберите платёжную систему из списка.",
|
||||
bankName: "Не более 100 символов.",
|
||||
lastFour: "Укажите ровно четыре цифры или оставьте поле пустым.",
|
||||
money:
|
||||
"Введите сумму в допустимом диапазоне, не более двух знаков после запятой.",
|
||||
positive: "Сумма операции должна быть больше нуля.",
|
||||
date: "Укажите существующую дату не позже сегодняшнего дня по Москве.",
|
||||
start:
|
||||
"Дата не может быть раньше начала учёта затронутых карт или исходной покупки.",
|
||||
required: "Выберите значение.",
|
||||
destination: "Выберите другую активную карту.",
|
||||
description: "Не более 500 символов.",
|
||||
category: "Введите название от 1 до 80 символов.",
|
||||
duplicate: "Категория с таким названием уже есть.",
|
||||
refund: "Сумма превышает доступный возврат.",
|
||||
},
|
||||
},
|
||||
bond: {
|
||||
instrument: "Облигация",
|
||||
searching: "Ищем облигации",
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { fireEvent, render, waitFor } from "@testing-library/react";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { bindIconAnimation } from "./bind-icon-animation";
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it("finishes every delayed part after leaving and does not restart on quick re-entry", async () => {
|
||||
vi.spyOn(window, "matchMedia").mockReturnValue({
|
||||
matches: true,
|
||||
} as MediaQueryList);
|
||||
const { container, getByRole } = render(
|
||||
<button type="button">
|
||||
<svg ref={bindIconAnimation} aria-hidden="true" />
|
||||
Category
|
||||
</button>,
|
||||
);
|
||||
const icon = container.querySelector("svg");
|
||||
if (!icon) throw new Error("Missing icon");
|
||||
const target = getByRole("button");
|
||||
let finishFirst!: () => void;
|
||||
let finishLast!: () => void;
|
||||
const getAnimations = vi.fn(() => [
|
||||
{
|
||||
finished: new Promise<void>((resolve) => {
|
||||
finishFirst = resolve;
|
||||
}),
|
||||
},
|
||||
{
|
||||
finished: new Promise<void>((resolve) => {
|
||||
finishLast = resolve;
|
||||
}),
|
||||
},
|
||||
]);
|
||||
Object.defineProperty(icon, "getAnimations", { value: getAnimations });
|
||||
fireEvent.mouseEnter(target);
|
||||
fireEvent.mouseLeave(target);
|
||||
expect(icon).toHaveAttribute("data-icon-animating");
|
||||
finishFirst();
|
||||
await Promise.resolve();
|
||||
expect(icon).toHaveAttribute("data-icon-animating");
|
||||
fireEvent.mouseEnter(target);
|
||||
expect(getAnimations).toHaveBeenCalledTimes(1);
|
||||
finishLast();
|
||||
await Promise.resolve();
|
||||
expect(icon).toHaveAttribute("data-icon-animating");
|
||||
fireEvent.mouseLeave(target);
|
||||
await waitFor(() => expect(icon).not.toHaveAttribute("data-icon-animating"));
|
||||
fireEvent.mouseEnter(target);
|
||||
expect(getAnimations).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("keeps playing after keyboard blur and releases cancelled animations", async () => {
|
||||
const { container, getByRole, unmount } = render(
|
||||
<button type="button">
|
||||
<svg ref={bindIconAnimation} aria-hidden="true" />
|
||||
Category
|
||||
</button>,
|
||||
);
|
||||
const icon = container.querySelector("svg");
|
||||
if (!icon) throw new Error("Missing icon");
|
||||
const target = getByRole("button");
|
||||
// JSDOM does not model the browser keyboard-focus modality.
|
||||
vi.spyOn(target, "matches").mockImplementation(
|
||||
(selector) => selector === ":focus-visible",
|
||||
);
|
||||
let cancel!: () => void;
|
||||
Object.defineProperty(icon, "getAnimations", {
|
||||
value: () => [
|
||||
{
|
||||
finished: new Promise<void>((_resolve, reject) => {
|
||||
cancel = () => reject(new Error("cancelled"));
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
target.focus();
|
||||
expect(icon).toHaveAttribute("data-icon-animating");
|
||||
target.blur();
|
||||
expect(icon).toHaveAttribute("data-icon-animating");
|
||||
cancel();
|
||||
await waitFor(() => expect(icon).not.toHaveAttribute("data-icon-animating"));
|
||||
target.focus();
|
||||
unmount();
|
||||
cancel();
|
||||
await Promise.resolve();
|
||||
expect(icon).not.toHaveAttribute("data-icon-animating");
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
// React ref cleanup keeps native animation lifetimes tied to the mounted icon.
|
||||
const bindIconAnimation = (icon: SVGSVGElement | null) => {
|
||||
if (!icon) return;
|
||||
const target = icon.closest<HTMLElement>("a, button") ?? icon.parentElement;
|
||||
if (!target) return;
|
||||
let hovered = false;
|
||||
let focused = false;
|
||||
let running = false;
|
||||
let disposed = false;
|
||||
|
||||
const release = () => {
|
||||
if (!running && !hovered && !focused) {
|
||||
icon.removeAttribute("data-icon-animating");
|
||||
}
|
||||
};
|
||||
const start = () => {
|
||||
if (icon.hasAttribute("data-icon-animating")) return;
|
||||
icon.setAttribute("data-icon-animating", "");
|
||||
running = true;
|
||||
// Includes staggered/delayed children and finite iterations, without timers.
|
||||
const animations = icon.getAnimations({ subtree: true });
|
||||
void Promise.allSettled(
|
||||
animations.map((animation) => animation.finished),
|
||||
).then(() => {
|
||||
if (disposed) return;
|
||||
running = false;
|
||||
release();
|
||||
});
|
||||
};
|
||||
const enter = () => {
|
||||
if (!window.matchMedia("(hover: hover)").matches) return;
|
||||
hovered = true;
|
||||
start();
|
||||
};
|
||||
const leave = () => {
|
||||
hovered = false;
|
||||
release();
|
||||
};
|
||||
const focus = () => {
|
||||
focused =
|
||||
target.matches(":focus-visible") ||
|
||||
!!target.querySelector(":focus-visible");
|
||||
if (focused) start();
|
||||
};
|
||||
const blur = (event: FocusEvent) => {
|
||||
if (
|
||||
event.relatedTarget instanceof Node &&
|
||||
target.contains(event.relatedTarget)
|
||||
)
|
||||
return;
|
||||
focused = false;
|
||||
release();
|
||||
};
|
||||
target.addEventListener("mouseenter", enter);
|
||||
target.addEventListener("mouseleave", leave);
|
||||
target.addEventListener("focusin", focus);
|
||||
target.addEventListener("focusout", blur);
|
||||
return () => {
|
||||
disposed = true;
|
||||
target.removeEventListener("mouseenter", enter);
|
||||
target.removeEventListener("mouseleave", leave);
|
||||
target.removeEventListener("focusin", focus);
|
||||
target.removeEventListener("focusout", blur);
|
||||
icon.removeAttribute("data-icon-animating");
|
||||
};
|
||||
};
|
||||
|
||||
export { bindIconAnimation };
|
||||
@@ -1,4 +1,7 @@
|
||||
type Money = { currency: string; value: string };
|
||||
type FormatMoneyOptions = {
|
||||
withZeroCents?: boolean;
|
||||
};
|
||||
|
||||
function formatDecimal(value: string): string {
|
||||
const [integer, fraction] = value.split(".");
|
||||
@@ -10,9 +13,21 @@ function formatDecimal(value: string): string {
|
||||
return `${sign}${grouped}${fraction ? `,${fraction}` : ""}`;
|
||||
}
|
||||
|
||||
function formatMoney(money: Money | null): string {
|
||||
function formatMoney(
|
||||
money: Money | null,
|
||||
{ withZeroCents = false }: FormatMoneyOptions = {},
|
||||
): string {
|
||||
if (!money) return "—";
|
||||
return `${formatDecimal(money.value)} ${money.currency === "RUB" ? "₽" : money.currency}`;
|
||||
const [integerPart, fractionPart = ""] = money.value.split(".");
|
||||
const normalizedFraction =
|
||||
withZeroCents && !fractionPart
|
||||
? "00"
|
||||
: withZeroCents && fractionPart.length === 1
|
||||
? `${fractionPart}0`
|
||||
: fractionPart;
|
||||
return `${formatDecimal(
|
||||
`${integerPart}${normalizedFraction ? `.${normalizedFraction}` : ""}`,
|
||||
)} ${money.currency === "RUB" ? "₽" : money.currency}`;
|
||||
}
|
||||
|
||||
function formatDate(value: string): string {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
export { bindIconAnimation } from "./bind-icon-animation";
|
||||
export {
|
||||
formatDate,
|
||||
formatDecimal,
|
||||
|
||||
@@ -18,56 +18,192 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.portfolioIcon {
|
||||
color: var(--mantine-color-blue-7);
|
||||
}
|
||||
|
||||
.cardsIcon {
|
||||
color: var(--mantine-color-grape-7);
|
||||
|
||||
& svg {
|
||||
overflow: visible;
|
||||
}
|
||||
}
|
||||
|
||||
.rubles {
|
||||
pointer-events: none;
|
||||
color: var(--mantine-color-green-8);
|
||||
stroke: currentColor;
|
||||
|
||||
& path {
|
||||
opacity: 0;
|
||||
--flight-x: -7px;
|
||||
--flight-rotation: -20deg;
|
||||
--flight-delay: 0ms;
|
||||
}
|
||||
|
||||
& path:nth-child(2) {
|
||||
--flight-x: 0px;
|
||||
--flight-rotation: 8deg;
|
||||
--flight-delay: 120ms;
|
||||
}
|
||||
|
||||
& path:nth-child(3) {
|
||||
--flight-x: 7px;
|
||||
--flight-rotation: 24deg;
|
||||
--flight-delay: 240ms;
|
||||
}
|
||||
}
|
||||
|
||||
.stocksIcon {
|
||||
color: var(--mantine-color-green-8);
|
||||
}
|
||||
|
||||
.bondsIcon {
|
||||
color: var(--mantine-color-orange-8);
|
||||
}
|
||||
|
||||
.settingsIcon {
|
||||
color: var(--mantine-color-gray-7);
|
||||
}
|
||||
|
||||
.portfolioRuble {
|
||||
stroke: var(--mantine-color-green-8);
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.stockArrow {
|
||||
transform-origin: 21px 5px;
|
||||
}
|
||||
|
||||
.topSlider,
|
||||
.bottomSlider {
|
||||
fill: var(--mantine-color-body);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.drawStroke {
|
||||
.navLink {
|
||||
transition: background-color 180ms ease-in-out;
|
||||
}
|
||||
|
||||
.drawStroke,
|
||||
.couponLines path {
|
||||
stroke-dasharray: 1;
|
||||
}
|
||||
|
||||
.topSlider {
|
||||
--slider-offset: -3px;
|
||||
--slider-offset: 3px;
|
||||
--slider-delay: 0ms;
|
||||
}
|
||||
|
||||
.bottomSlider {
|
||||
--slider-offset: 3px;
|
||||
--slider-offset: -3px;
|
||||
--slider-delay: 160ms;
|
||||
}
|
||||
|
||||
.navLink:focus-visible {
|
||||
.portfolioIcon {
|
||||
animation: portfolio-sway 650ms ease-in-out;
|
||||
.couponLines path:nth-child(2) {
|
||||
--line-delay: 140ms;
|
||||
}
|
||||
|
||||
.couponLines path:nth-child(3) {
|
||||
--line-delay: 280ms;
|
||||
}
|
||||
|
||||
svg[data-icon-animating] {
|
||||
.rubles path {
|
||||
animation: ruble-fly 800ms ease-out var(--flight-delay) both;
|
||||
}
|
||||
.portfolioHandle {
|
||||
animation: handle-lift 1200ms ease-in-out;
|
||||
}
|
||||
.portfolioLid {
|
||||
animation: lid-open 1200ms ease-in-out;
|
||||
}
|
||||
.portfolioRuble {
|
||||
animation: portfolio-ruble-reveal 1200ms ease-in-out;
|
||||
}
|
||||
.stockArrow {
|
||||
animation: arrow-pop 300ms ease-out 400ms both;
|
||||
}
|
||||
.couponLines path {
|
||||
animation: stroke-draw 300ms ease-out var(--line-delay, 0ms) both;
|
||||
}
|
||||
.drawStroke {
|
||||
animation: stroke-draw 650ms ease-in-out;
|
||||
animation: stroke-draw 450ms ease-out;
|
||||
}
|
||||
:is(.topSlider, .bottomSlider) {
|
||||
animation: slider-slide 650ms ease-in-out;
|
||||
}
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.navLink:hover {
|
||||
.portfolioIcon {
|
||||
animation: portfolio-sway 650ms ease-in-out;
|
||||
}
|
||||
.drawStroke {
|
||||
animation: stroke-draw 650ms ease-in-out;
|
||||
}
|
||||
:is(.topSlider, .bottomSlider) {
|
||||
animation: slider-slide 650ms ease-in-out;
|
||||
}
|
||||
animation: slider-slide 650ms ease-in-out var(--slider-delay) both;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes portfolio-sway {
|
||||
@keyframes ruble-fly {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translate(0, 4px);
|
||||
}
|
||||
20%,
|
||||
50% {
|
||||
opacity: 1;
|
||||
}
|
||||
100% {
|
||||
opacity: 0;
|
||||
transform: translate(var(--flight-x), -10px) rotate(var(--flight-rotation));
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes handle-lift {
|
||||
0%,
|
||||
100% {
|
||||
transform: rotate(0);
|
||||
transform: translateY(0);
|
||||
}
|
||||
30% {
|
||||
transform: translateY(-1px) rotate(-10deg);
|
||||
20% {
|
||||
transform: translateY(-3px);
|
||||
}
|
||||
65% {
|
||||
transform: rotate(7deg);
|
||||
40%,
|
||||
75% {
|
||||
transform: translateY(-3px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes lid-open {
|
||||
0%,
|
||||
15%,
|
||||
100% {
|
||||
transform: translateY(0);
|
||||
}
|
||||
40%,
|
||||
75% {
|
||||
transform: translateY(-3px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes portfolio-ruble-reveal {
|
||||
0%,
|
||||
25%,
|
||||
100% {
|
||||
opacity: 0;
|
||||
transform: translateY(2px);
|
||||
}
|
||||
40%,
|
||||
75% {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes arrow-pop {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: scale(0.7);
|
||||
}
|
||||
60% {
|
||||
opacity: 1;
|
||||
transform: scale(1.2);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,7 +234,14 @@
|
||||
display: flex;
|
||||
justify-content: space-around;
|
||||
left: 0;
|
||||
padding: var(--mantine-spacing-sm);
|
||||
padding: var(--mantine-spacing-xs) 2px;
|
||||
gap: 2px;
|
||||
font-size: 11px;
|
||||
& a {
|
||||
min-width: 0;
|
||||
padding: 8px 2px;
|
||||
text-align: center;
|
||||
}
|
||||
position: fixed;
|
||||
right: 0;
|
||||
z-index: 200;
|
||||
|
||||
+42
-12
@@ -2,6 +2,7 @@ import { AppShell as MantineAppShell, NavLink, Text } from "@mantine/core";
|
||||
import type { FC, ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Outlet, NavLink as RouterNavLink, useLocation } from "react-router";
|
||||
import { bindIconAnimation } from "../lib";
|
||||
import classes from "./AppShell.module.css";
|
||||
|
||||
type AppShellProps = {
|
||||
@@ -18,47 +19,75 @@ const AppShell: FC<AppShellProps> = (props) => {
|
||||
label: t("navigation.accounts"),
|
||||
iconClassName: classes.portfolioIcon,
|
||||
icon: (
|
||||
<path d="M8 6V4h8v2M3 10h18M9 10v3h6v-3M5 6h14a2 2 0 0 1 2 2v11H3V8a2 2 0 0 1 2-2Z" />
|
||||
<>
|
||||
<path d="M3 10v9h18v-9" />
|
||||
<path className={classes.portfolioHandle} d="M8 6V4h8v2" />
|
||||
<path
|
||||
className={classes.portfolioLid}
|
||||
d="M3 10V8a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v2H3Zm6 0v3h6v-3"
|
||||
/>
|
||||
<path
|
||||
className={classes.portfolioRuble}
|
||||
d="M10 18v-7h3a2 2 0 0 1 0 4H9m0 1.5h4"
|
||||
/>
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
to: "/cards",
|
||||
label: t("navigation.cards"),
|
||||
iconClassName: classes.cardsIcon,
|
||||
icon: (
|
||||
<>
|
||||
<path d="M3 5h18v14H3V5Zm0 4h18M6 15h4" />
|
||||
<g className={classes.rubles}>
|
||||
<path d="M10 12V4h3a2 2 0 0 1 0 4H9m0 2h4" />
|
||||
<path d="M10 12V4h3a2 2 0 0 1 0 4H9m0 2h4" />
|
||||
<path d="M10 12V4h3a2 2 0 0 1 0 4H9m0 2h4" />
|
||||
</g>
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
to: "/stocks",
|
||||
label: t("navigation.stocks"),
|
||||
iconClassName: classes.stocksIcon,
|
||||
icon: (
|
||||
<>
|
||||
<path d="M3 3v18h18" />
|
||||
<path
|
||||
className={classes.drawStroke}
|
||||
pathLength={1}
|
||||
d="M7 14l5-5 4 3 5-7M16 5h5v5"
|
||||
d="M7 14l5-5 4 3 5-7"
|
||||
/>
|
||||
<path className={classes.stockArrow} d="M16 5h5v5" />
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
to: "/bonds",
|
||||
label: t("navigation.bonds"),
|
||||
iconClassName: classes.bondsIcon,
|
||||
icon: (
|
||||
<>
|
||||
<path d="M6 3h12v18l-3-2-3 2-3-2-3 2V3Z" />
|
||||
<path
|
||||
className={classes.drawStroke}
|
||||
pathLength={1}
|
||||
d="M9 7h6M9 11h6M9 15h3"
|
||||
/>
|
||||
<g className={classes.couponLines}>
|
||||
<path pathLength={1} d="M9 7h6" />
|
||||
<path pathLength={1} d="M9 11h6" />
|
||||
<path pathLength={1} d="M9 15h3" />
|
||||
</g>
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
to: "/settings",
|
||||
label: t("navigation.settings"),
|
||||
iconClassName: classes.settingsIcon,
|
||||
icon: (
|
||||
<>
|
||||
<path className={classes.topSlider} d="M4 7h9m4 0h3M13 4v6h4V4h-4Z" />
|
||||
<path
|
||||
className={classes.bottomSlider}
|
||||
d="M4 17h3m4 0h9M7 14v6h4v-6H7Z"
|
||||
/>
|
||||
<path d="M4 7h16M4 17h16" />
|
||||
<path className={classes.topSlider} d="M10 4v6h4V4h-4Z" />
|
||||
<path className={classes.bottomSlider} d="M10 14v6h4v-6h-4Z" />
|
||||
</>
|
||||
),
|
||||
},
|
||||
@@ -86,6 +115,7 @@ const AppShell: FC<AppShellProps> = (props) => {
|
||||
className={`${classes.navIcon} ${item.iconClassName ?? ""}`}
|
||||
>
|
||||
<svg
|
||||
ref={bindIconAnimation}
|
||||
width={20}
|
||||
height={20}
|
||||
viewBox="0 0 24 24"
|
||||
|
||||
@@ -40,3 +40,56 @@
|
||||
text-align: left;
|
||||
}
|
||||
}
|
||||
|
||||
.valueFooter {
|
||||
display: grid;
|
||||
align-items: center;
|
||||
justify-items: end;
|
||||
min-height: 28px;
|
||||
}
|
||||
.valueLabel,
|
||||
.actions {
|
||||
grid-area: 1 / 1;
|
||||
transition: opacity 180ms ease;
|
||||
}
|
||||
.valueLabel {
|
||||
opacity: 0;
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
}
|
||||
@media (hover: hover) and (pointer: fine) {
|
||||
.valueLabel {
|
||||
opacity: 1;
|
||||
}
|
||||
.actions {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
.row:hover .actions,
|
||||
.row:focus-within .actions {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.row:hover .valueLabel,
|
||||
.row:focus-within .valueLabel {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
@media (max-width: 36em) {
|
||||
.valueFooter {
|
||||
justify-items: start;
|
||||
}
|
||||
}
|
||||
@media (pointer: coarse) {
|
||||
.actions button {
|
||||
min-width: 36px;
|
||||
min-height: 36px;
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.valueLabel,
|
||||
.actions {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,10 @@ type EntryCardProps = {
|
||||
title: string;
|
||||
metadata: string;
|
||||
details?: ReactNode;
|
||||
actions?: ReactNode;
|
||||
initial: string;
|
||||
icon?: ReactNode;
|
||||
color?: string;
|
||||
imageSrc?: string | null;
|
||||
value: string;
|
||||
valueLabel: string;
|
||||
@@ -16,7 +19,17 @@ type EntryCardProps = {
|
||||
const EntryCard: FC<EntryCardProps> = (props) => {
|
||||
const [imageFailed, setImageFailed] = useState(false);
|
||||
return (
|
||||
<Paper className={classes.row} withBorder>
|
||||
<Paper
|
||||
className={classes.row}
|
||||
withBorder
|
||||
style={
|
||||
props.color
|
||||
? {
|
||||
background: `color-mix(in srgb, var(--mantine-color-${props.color}-0) 45%, white)`,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<Avatar
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
@@ -25,7 +38,7 @@ const EntryCard: FC<EntryCardProps> = (props) => {
|
||||
src={imageFailed ? null : props.imageSrc}
|
||||
onError={() => setImageFailed(true)}
|
||||
>
|
||||
{props.initial}
|
||||
{props.icon ?? props.initial}
|
||||
</Avatar>
|
||||
<Stack className={classes.identity} gap={2}>
|
||||
<Text fw={700} lineClamp={1}>
|
||||
@@ -40,9 +53,17 @@ const EntryCard: FC<EntryCardProps> = (props) => {
|
||||
<Text className={classes[props.tone]} fw={700}>
|
||||
{props.value}
|
||||
</Text>
|
||||
<Text className={classes[props.tone]} size="sm">
|
||||
{props.valueLabel}
|
||||
</Text>
|
||||
<div className={props.actions ? classes.valueFooter : undefined}>
|
||||
<Text
|
||||
className={`${classes[props.tone]} ${props.actions ? classes.valueLabel : ""}`}
|
||||
size="sm"
|
||||
>
|
||||
{props.valueLabel}
|
||||
</Text>
|
||||
{props.actions && (
|
||||
<div className={classes.actions}>{props.actions}</div>
|
||||
)}
|
||||
</div>
|
||||
</Stack>
|
||||
</Paper>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user