refactor: enforce frontend view model boundaries
This commit is contained in:
@@ -28,8 +28,11 @@ const accounts = [
|
||||
{ id: "a", name: "Основной" },
|
||||
{ id: "b", name: "ИИС" },
|
||||
];
|
||||
const position: Portfolio["positions"][number] = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
const position: Portfolio["positions"][number]
|
||||
= {
|
||||
absoluteReturn: null,
|
||||
averagePurchasePrice: null,
|
||||
currentValue: { currency: "RUB", value: "600" },
|
||||
@@ -40,8 +43,9 @@ const position: Portfolio["positions"][number] = (/* eslint-disable unicorn/no-n
|
||||
quantity: "2",
|
||||
ticker: "SBER",
|
||||
type: "STOCK",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
};
|
||||
|
||||
/* eslint-enable unicorn/no-null */
|
||||
const portfolio: Portfolio = {
|
||||
cashBalances: [],
|
||||
isStale: false,
|
||||
@@ -50,8 +54,11 @@ const portfolio: Portfolio = {
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
totalsByCurrency: [{ currency: "RUB", value: "1200" }],
|
||||
};
|
||||
const receipt: BrokerageOperation = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
const receipt: BrokerageOperation
|
||||
= {
|
||||
accruedInterest: null,
|
||||
category: "income",
|
||||
commission: null,
|
||||
@@ -67,11 +74,15 @@ const receipt: BrokerageOperation = (/* eslint-disable unicorn/no-null -- Fixtur
|
||||
quantity: null,
|
||||
ticker: "BOND",
|
||||
type: "OPERATION_TYPE_COUPON",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
};
|
||||
|
||||
/* eslint-enable unicorn/no-null */
|
||||
const items = accounts.map(account => ({ ...receipt, account }));
|
||||
const analytics: IncomeAnalytics = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
const analytics: IncomeAnalytics
|
||||
= {
|
||||
accountId: "all",
|
||||
bucketGranularity: "day",
|
||||
buckets: [],
|
||||
@@ -105,17 +116,21 @@ const analytics: IncomeAnalytics = (/* eslint-disable unicorn/no-null -- Fixture
|
||||
},
|
||||
],
|
||||
yearComparison: null,
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
};
|
||||
|
||||
/* eslint-enable unicorn/no-null */
|
||||
const CurrentLocation: FC = () => {
|
||||
const location = useLocation();
|
||||
|
||||
return (
|
||||
<output aria-label="Текущий путь">
|
||||
{location.pathname}
|
||||
|
||||
{location.search}
|
||||
</output>
|
||||
);
|
||||
};
|
||||
|
||||
function renderPage(path: string) {
|
||||
const client = createTestQueryClient();
|
||||
render(
|
||||
@@ -124,12 +139,14 @@ function renderPage(path: string) {
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
<AuthProvider>
|
||||
<AppRoutes />
|
||||
|
||||
<CurrentLocation />
|
||||
</AuthProvider>
|
||||
</MemoryRouter>
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
@@ -144,14 +161,17 @@ beforeEach(() => {
|
||||
http.get("*/api/v1/brokerage-accounts", () =>
|
||||
HttpResponse.json(
|
||||
resource(
|
||||
accounts.map(account => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
...account,
|
||||
openedOn: null,
|
||||
portfolioSummary: null,
|
||||
type: "BROKERAGE",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */))),
|
||||
accounts.map(
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
account =>
|
||||
({
|
||||
...account,
|
||||
openedOn: null,
|
||||
portfolioSummary: null,
|
||||
type: "BROKERAGE",
|
||||
}),
|
||||
/* eslint-enable unicorn/no-null */
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -162,15 +182,17 @@ beforeEach(() => {
|
||||
"*/api/v1/brokerage-accounts/:accountId/operations",
|
||||
({ params }) =>
|
||||
HttpResponse.json(
|
||||
resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
resource(
|
||||
{
|
||||
accountId: params.accountId,
|
||||
hasNext: false,
|
||||
items,
|
||||
nextCursor: null,
|
||||
observedAt: receipt.occurredAt,
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */)),
|
||||
},
|
||||
/* eslint-enable unicorn/no-null */
|
||||
),
|
||||
),
|
||||
),
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/income-analytics", () =>
|
||||
@@ -181,21 +203,24 @@ beforeEach(() => {
|
||||
resource({
|
||||
accountId: "all",
|
||||
calculatedAt: receipt.occurredAt,
|
||||
events: accounts.map(account => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
account,
|
||||
date: "2026-09-15",
|
||||
dateKind: "event",
|
||||
displayName: "Облигация",
|
||||
figi: null,
|
||||
instrumentUid: null,
|
||||
isin: null,
|
||||
logoName: null,
|
||||
projectedAmount: { currency: "RUB", value: "2" },
|
||||
ticker: "BOND",
|
||||
type: "coupon",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */))),
|
||||
events: accounts.map(
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
account =>
|
||||
({
|
||||
account,
|
||||
date: "2026-09-15",
|
||||
dateKind: "event",
|
||||
displayName: "Облигация",
|
||||
figi: null,
|
||||
instrumentUid: null,
|
||||
isin: null,
|
||||
logoName: null,
|
||||
projectedAmount: { currency: "RUB", value: "2" },
|
||||
ticker: "BOND",
|
||||
type: "coupon",
|
||||
}),
|
||||
/* eslint-enable unicorn/no-null */
|
||||
),
|
||||
incomeTotalsByCurrency: [],
|
||||
}),
|
||||
),
|
||||
@@ -235,7 +260,11 @@ describe("All accounts routes", () => {
|
||||
);
|
||||
for (const suffix of ["operations", "income", "events"])
|
||||
expect(
|
||||
screen.getAllByRole("link").find(link => link.getAttribute("href") === `/accounts/all/${suffix}`),
|
||||
screen
|
||||
.getAllByRole("link")
|
||||
.find(
|
||||
link => link.getAttribute("href") === `/accounts/all/${suffix}`,
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -247,8 +276,10 @@ describe("All accounts routes", () => {
|
||||
({ params, request }) => {
|
||||
const url = new URL(request.url);
|
||||
requests.push(url);
|
||||
|
||||
return HttpResponse.json(
|
||||
resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
resource(
|
||||
{
|
||||
accountId: params.accountId,
|
||||
hasNext: !url.searchParams.has("cursor"),
|
||||
@@ -262,8 +293,9 @@ describe("All accounts routes", () => {
|
||||
],
|
||||
nextCursor: url.searchParams.has("cursor") ? null : "next",
|
||||
observedAt: receipt.occurredAt,
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */)),
|
||||
},
|
||||
/* eslint-enable unicorn/no-null */
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
@@ -281,9 +313,11 @@ describe("All accounts routes", () => {
|
||||
requests.some(url => url.pathname.includes("/b/operations")),
|
||||
).toBe(true),
|
||||
);
|
||||
|
||||
const selected = requests.find(url =>
|
||||
url.pathname.includes("/b/operations"),
|
||||
);
|
||||
|
||||
expect(selected?.searchParams.get("from")).toBe("2026-08-01T00:00:00.000Z");
|
||||
expect(selected?.searchParams.get("to")).toBe("2026-08-31T23:59:59.999Z");
|
||||
expect(selected?.searchParams.get("categories")).toBe("income");
|
||||
|
||||
@@ -62,6 +62,7 @@ describe("AppRoutes", () => {
|
||||
server.use(
|
||||
http.post("*/api/v1/auth/login", async ({ request }) => {
|
||||
credentials = await request.json();
|
||||
|
||||
return HttpResponse.json({
|
||||
accessToken: "login-token",
|
||||
user: { email: "user@example.com", id: "user-1" },
|
||||
@@ -103,7 +104,8 @@ describe("AppRoutes", () => {
|
||||
),
|
||||
http.get("*/api/v1/bank-cards", () => HttpResponse.json([])),
|
||||
http.get("*/api/v1/bank-cards/summary", () =>
|
||||
HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
HttpResponse.json(
|
||||
{
|
||||
cardId: null,
|
||||
categories: [],
|
||||
@@ -111,8 +113,9 @@ describe("AppRoutes", () => {
|
||||
month: "2026-08",
|
||||
net: { currency: "RUB", value: "0" },
|
||||
refunds: { currency: "RUB", value: "0" },
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */)),
|
||||
},
|
||||
/* eslint-enable unicorn/no-null */
|
||||
),
|
||||
),
|
||||
);
|
||||
renderRoutes("/cards?month=2026-08");
|
||||
|
||||
@@ -8,72 +8,104 @@ 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 };
|
||||
});
|
||||
|
||||
const BondsPage = lazy(async () => {
|
||||
const { BondsPage } = await import("@/pages/bonds");
|
||||
|
||||
return { default: BondsPage };
|
||||
});
|
||||
|
||||
const StockPage = lazy(async () => {
|
||||
const { StockPage } = await import("@/pages/stock");
|
||||
|
||||
return { default: StockPage };
|
||||
});
|
||||
|
||||
const StocksPage = lazy(async () => {
|
||||
const { StocksPage } = await import("@/pages/stocks");
|
||||
|
||||
return { default: StocksPage };
|
||||
});
|
||||
|
||||
const AccountPage = lazy(async () => {
|
||||
const { AccountPage } = await import("@/pages/account");
|
||||
|
||||
return { default: AccountPage };
|
||||
});
|
||||
|
||||
const AccountEventsPage = lazy(async () => {
|
||||
const { AccountEventsPage } = await import("@/pages/account-events");
|
||||
|
||||
return { default: AccountEventsPage };
|
||||
});
|
||||
|
||||
const AccountOperationsPage = lazy(async () => {
|
||||
const { AccountOperationsPage } = await import("@/pages/account-operations");
|
||||
|
||||
return { default: AccountOperationsPage };
|
||||
});
|
||||
|
||||
const AccountIncomePage = lazy(async () => {
|
||||
const { AccountIncomePage } = await import("@/pages/account-income");
|
||||
|
||||
return { default: AccountIncomePage };
|
||||
});
|
||||
|
||||
const AccountsPage = lazy(async () => {
|
||||
const { AccountsPage } = await import("@/pages/accounts");
|
||||
|
||||
return { default: AccountsPage };
|
||||
});
|
||||
|
||||
const LoginPage = lazy(async () => {
|
||||
const { LoginPage } = await import("@/pages/login");
|
||||
|
||||
return { default: LoginPage };
|
||||
});
|
||||
|
||||
const NotFoundPage = lazy(async () => {
|
||||
const { NotFoundPage } = await import("@/pages/not-found");
|
||||
|
||||
return { default: NotFoundPage };
|
||||
});
|
||||
|
||||
const RegisterPage = lazy(async () => {
|
||||
const { RegisterPage } = await import("@/pages/register");
|
||||
|
||||
return { default: RegisterPage };
|
||||
});
|
||||
|
||||
const SettingsPage = lazy(async () => {
|
||||
const { SettingsPage } = await import("@/pages/settings");
|
||||
|
||||
return { default: SettingsPage };
|
||||
});
|
||||
|
||||
const ProtectedLayout = lazy(async () => {
|
||||
const { ProtectedLayout } = await import("../ProtectedLayout");
|
||||
|
||||
return { default: ProtectedLayout };
|
||||
});
|
||||
|
||||
const AppRoutes: FC = () => (
|
||||
<Routes>
|
||||
<Route element={<Navigate replace to="/accounts" />} path="/" />
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<Public>
|
||||
@@ -84,6 +116,7 @@ const AppRoutes: FC = () => (
|
||||
)}
|
||||
path="/login"
|
||||
/>
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<Public>
|
||||
@@ -94,6 +127,7 @@ const AppRoutes: FC = () => (
|
||||
)}
|
||||
path="/register"
|
||||
/>
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<Protected>
|
||||
@@ -111,6 +145,7 @@ const AppRoutes: FC = () => (
|
||||
)}
|
||||
path="/cards/:cardId"
|
||||
/>
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<LazyPage variant="content">
|
||||
@@ -119,6 +154,7 @@ const AppRoutes: FC = () => (
|
||||
)}
|
||||
path="/cards"
|
||||
/>
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<LazyPage variant="content">
|
||||
@@ -127,6 +163,7 @@ const AppRoutes: FC = () => (
|
||||
)}
|
||||
path="/bonds"
|
||||
/>
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<LazyPage variant="content">
|
||||
@@ -135,6 +172,7 @@ const AppRoutes: FC = () => (
|
||||
)}
|
||||
path="/bonds/:bondId"
|
||||
/>
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<LazyPage variant="content">
|
||||
@@ -143,6 +181,7 @@ const AppRoutes: FC = () => (
|
||||
)}
|
||||
path="/stocks"
|
||||
/>
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<LazyPage variant="content">
|
||||
@@ -151,6 +190,7 @@ const AppRoutes: FC = () => (
|
||||
)}
|
||||
path="/stocks/:stockId"
|
||||
/>
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<LazyPage variant="content">
|
||||
@@ -159,6 +199,7 @@ const AppRoutes: FC = () => (
|
||||
)}
|
||||
path="/accounts"
|
||||
/>
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<LazyPage variant="content">
|
||||
@@ -167,6 +208,7 @@ const AppRoutes: FC = () => (
|
||||
)}
|
||||
path="/accounts/all"
|
||||
/>
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<LazyPage variant="content">
|
||||
@@ -175,6 +217,7 @@ const AppRoutes: FC = () => (
|
||||
)}
|
||||
path="/accounts/all/operations"
|
||||
/>
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<LazyPage variant="content">
|
||||
@@ -183,6 +226,7 @@ const AppRoutes: FC = () => (
|
||||
)}
|
||||
path="/accounts/all/income"
|
||||
/>
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<LazyPage variant="content">
|
||||
@@ -191,6 +235,7 @@ const AppRoutes: FC = () => (
|
||||
)}
|
||||
path="/accounts/all/events"
|
||||
/>
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<LazyPage variant="content">
|
||||
@@ -199,6 +244,7 @@ const AppRoutes: FC = () => (
|
||||
)}
|
||||
path="/accounts/:accountId"
|
||||
/>
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<LazyPage variant="content">
|
||||
@@ -207,6 +253,7 @@ const AppRoutes: FC = () => (
|
||||
)}
|
||||
path="/accounts/:accountId/events"
|
||||
/>
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<LazyPage variant="content">
|
||||
@@ -215,6 +262,7 @@ const AppRoutes: FC = () => (
|
||||
)}
|
||||
path="/accounts/:accountId/income"
|
||||
/>
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<LazyPage variant="content">
|
||||
@@ -223,6 +271,7 @@ const AppRoutes: FC = () => (
|
||||
)}
|
||||
path="/accounts/:accountId/operations"
|
||||
/>
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<LazyPage variant="content">
|
||||
@@ -232,6 +281,7 @@ const AppRoutes: FC = () => (
|
||||
path="/settings"
|
||||
/>
|
||||
</Route>
|
||||
|
||||
<Route
|
||||
element={(
|
||||
<LazyPage variant="content">
|
||||
|
||||
@@ -21,11 +21,13 @@ import { ProtectedDocumentTitle } from "./DocumentTitle";
|
||||
|
||||
const Navigation: FC = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
return (
|
||||
<>
|
||||
<button onClick={() => navigate("/accounts/all/income")} type="button">
|
||||
Все счета
|
||||
</button>
|
||||
|
||||
<button onClick={() => navigate(-1)} type="button">
|
||||
Назад
|
||||
</button>
|
||||
@@ -39,6 +41,7 @@ const renderTitle = (path: string) =>
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
<AuthProvider>
|
||||
<ProtectedDocumentTitle />
|
||||
|
||||
<Navigation />
|
||||
</AuthProvider>
|
||||
</MemoryRouter>
|
||||
@@ -59,10 +62,13 @@ beforeEach(() => {
|
||||
|
||||
describe("document titles", () => {
|
||||
it("updates a loading account name and follows account scope and history", async () => {
|
||||
const { promise: accountsReady, resolve: resolveAccounts } = Promise.withResolvers<void>();
|
||||
const { promise: accountsReady, resolve: resolveAccounts }
|
||||
= Promise.withResolvers<void>();
|
||||
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", async () => {
|
||||
await accountsReady;
|
||||
|
||||
return HttpResponse.json(resource([{ id: "a", name: "ИИС" }]));
|
||||
}),
|
||||
);
|
||||
@@ -102,6 +108,7 @@ describe("document titles", () => {
|
||||
server.use(
|
||||
http.get("*/api/v1/stocks/by-ticker/:ticker", () => {
|
||||
isRequested = true;
|
||||
|
||||
return HttpResponse.json({ code: "NOT_FOUND" }, { status: 404 });
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -24,29 +24,36 @@ type AccountDocumentTitleProps = {
|
||||
const AccountDocumentTitle: FC<AccountDocumentTitleProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
const { data } = useBrokerageAccounts();
|
||||
|
||||
const accountName
|
||||
= props.accountId === "all"
|
||||
? t("accounts.all")
|
||||
: (data?.find(account => account.id === props.accountId)?.name
|
||||
?? t("account.title"));
|
||||
|
||||
let section = t("portfolio.title");
|
||||
|
||||
switch (props.section ?? "") {
|
||||
case "income": {
|
||||
section = t("income.title");
|
||||
break;
|
||||
}
|
||||
|
||||
case "operations": {
|
||||
section = t("ledger.title");
|
||||
break;
|
||||
}
|
||||
|
||||
case "events": {
|
||||
section = t("events.title");
|
||||
break;
|
||||
}
|
||||
|
||||
default: {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return <DocumentTitle title={`${section} — ${accountName}`} />;
|
||||
};
|
||||
|
||||
@@ -55,18 +62,21 @@ type InstrumentDocumentTitleProps = { identifier: string };
|
||||
const BondDocumentTitle: FC<InstrumentDocumentTitleProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
const { data } = useBond(props.identifier);
|
||||
|
||||
return <DocumentTitle title={data?.name ?? t("bond.instrument")} />;
|
||||
};
|
||||
|
||||
const StockDocumentTitle: FC<InstrumentDocumentTitleProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
const { data } = useStock(props.identifier);
|
||||
|
||||
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")} />;
|
||||
};
|
||||
|
||||
@@ -94,7 +104,14 @@ const ProtectedDocumentTitle: FC = () => {
|
||||
if (cards) return <DocumentTitle title={t("navigation.cards")} />;
|
||||
if (bonds) return <DocumentTitle title={t("navigation.bonds")} />;
|
||||
if (stocks) return <DocumentTitle title={t("navigation.stocks")} />;
|
||||
return settings ? <DocumentTitle title={t("navigation.settings")} /> : <DocumentTitle title={t("navigation.accounts")} />;
|
||||
|
||||
return settings
|
||||
? (
|
||||
<DocumentTitle title={t("navigation.settings")} />
|
||||
)
|
||||
: (
|
||||
<DocumentTitle title={t("navigation.accounts")} />
|
||||
);
|
||||
};
|
||||
|
||||
export { ProtectedDocumentTitle };
|
||||
|
||||
@@ -8,6 +8,7 @@ const ProtectedLayout: FC = () => {
|
||||
return (
|
||||
<>
|
||||
<ProtectedDocumentTitle />
|
||||
|
||||
<AppShell contentAboveOutlet={<AppBreadcrumbs />} />
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -8,9 +8,10 @@ import { RouteErrorBoundary } from "./RouteErrorBoundary";
|
||||
|
||||
const session = { isAuthenticated: false };
|
||||
vi.mock("@/features/auth", () => ({
|
||||
useAuth: () => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{ user: session.isAuthenticated ? {} : null }
|
||||
/* eslint-enable unicorn/no-null */)),
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
useAuth: () =>
|
||||
({ user: session.isAuthenticated ? {} : null }),
|
||||
/* eslint-enable unicorn/no-null */
|
||||
}));
|
||||
|
||||
const ThrowingRoute: FC = () => {
|
||||
@@ -39,6 +40,7 @@ const RouteHarness: FC = () => {
|
||||
<button onClick={() => navigate("/healthy")} type="button">
|
||||
go healthy
|
||||
</button>
|
||||
|
||||
<RouteErrorBoundary>
|
||||
<HealthyRoute />
|
||||
</RouteErrorBoundary>
|
||||
@@ -62,10 +64,13 @@ describe("RouteErrorBoundary", () => {
|
||||
async (path) => {
|
||||
session.isAuthenticated = path === "/accounts";
|
||||
let isFailing = true;
|
||||
|
||||
const RecoverableRoute: FC = () => {
|
||||
if (isFailing) throw new Error("temporary failure");
|
||||
|
||||
return <div>recovered route</div>;
|
||||
};
|
||||
|
||||
render(
|
||||
<MantineProvider>
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
@@ -116,10 +121,12 @@ describe("RouteErrorBoundary", () => {
|
||||
expect(reload).toHaveAttribute("href", "/login");
|
||||
// Cancel browser navigation in JSDOM only after proving React Router did not intercept it.
|
||||
let isIntercepted = true;
|
||||
|
||||
const preventNavigation = (event: MouseEvent) => {
|
||||
isIntercepted = event.defaultPrevented;
|
||||
event.preventDefault();
|
||||
};
|
||||
|
||||
document.addEventListener("click", preventNavigation, { once: true });
|
||||
fireEvent.click(reload);
|
||||
expect(isIntercepted).toBe(false);
|
||||
|
||||
@@ -33,7 +33,13 @@ class Boundary extends Component<BoundaryProps, State> {
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.state.hasError ? <RouteErrorFallback authenticated={this.props.authenticated} /> : this.props.children;
|
||||
return this.state.hasError
|
||||
? (
|
||||
<RouteErrorFallback authenticated={this.props.authenticated} />
|
||||
)
|
||||
: (
|
||||
this.props.children
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,10 +52,13 @@ const RouteErrorFallback: FC<RouteErrorFallbackProps> = (props) => {
|
||||
return (
|
||||
<Stack>
|
||||
<Title order={1}>{t("routeError.title")}</Title>
|
||||
|
||||
<Text>{t("routeError.text")}</Text>
|
||||
|
||||
<Button component={Link} to={to}>
|
||||
{t("routeError.action")}
|
||||
</Button>
|
||||
|
||||
<Button component="a" href={to} variant="default">
|
||||
{t("routeError.reload")}
|
||||
</Button>
|
||||
|
||||
@@ -7,7 +7,10 @@ import { useTranslation } from "react-i18next";
|
||||
import { RouteTransition } from "./RouteTransition";
|
||||
|
||||
type LazyPageProps = PropsWithChildren<{ variant: RouteSkeletonVariant }>;
|
||||
type RouteSkeletonVariant = "auth" | "content" | "shell";
|
||||
|
||||
type RouteSkeletonVariant = "auth"
|
||||
| "content"
|
||||
| "shell";
|
||||
|
||||
const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => {
|
||||
const { variant } = props;
|
||||
@@ -22,8 +25,11 @@ const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => {
|
||||
role="status"
|
||||
>
|
||||
<Skeleton height={32} width="45%" />
|
||||
|
||||
<Skeleton height={48} radius="sm" />
|
||||
|
||||
<Skeleton height={48} radius="sm" />
|
||||
|
||||
<Skeleton height={36} radius="sm" />
|
||||
</Stack>
|
||||
</Container>
|
||||
@@ -39,12 +45,16 @@ const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => {
|
||||
>
|
||||
<Group justify="space-between" p="md">
|
||||
<Skeleton height={28} width={160} />
|
||||
|
||||
<Skeleton height={28} width={96} />
|
||||
</Group>
|
||||
|
||||
<Container fluid p="md">
|
||||
<Skeleton height={20} width="30%" />
|
||||
|
||||
<Stack mt="lg">
|
||||
<Skeleton height={32} width="30%" />
|
||||
|
||||
<Skeleton height={160} radius="md" />
|
||||
</Stack>
|
||||
</Container>
|
||||
@@ -54,6 +64,7 @@ const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => {
|
||||
return (
|
||||
<Stack aria-busy="true" aria-label={t("states.loadingTitle")} role="status">
|
||||
<Skeleton height={32} width="30%" />
|
||||
|
||||
<Skeleton height={160} radius="md" />
|
||||
</Stack>
|
||||
);
|
||||
@@ -61,6 +72,7 @@ const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => {
|
||||
|
||||
const LazyPage: FC<LazyPageProps> = (props) => {
|
||||
const { children, variant } = props;
|
||||
|
||||
return (
|
||||
<Suspense fallback={<RouteSkeleton variant={variant} />}>
|
||||
{variant === "shell"
|
||||
|
||||
@@ -11,6 +11,7 @@ const Protected: FC<PropsWithChildren> = (props) => {
|
||||
const { ready, user } = useAuth();
|
||||
const location = useLocation();
|
||||
if (!ready) return <RouteSkeleton variant="shell" />;
|
||||
|
||||
return user
|
||||
? (
|
||||
<>{children}</>
|
||||
@@ -30,13 +31,17 @@ const Public: FC<PropsWithChildren> = (props) => {
|
||||
const location = useLocation();
|
||||
|
||||
if (!ready) return <RouteSkeleton variant="shell" />;
|
||||
const requested = (location.state as null | { returnTo?: string })?.returnTo;
|
||||
|
||||
const requested = (location.state as null
|
||||
| { returnTo?: string })?.returnTo;
|
||||
|
||||
const returnTo
|
||||
= typeof requested === "string"
|
||||
&& requested.startsWith("/")
|
||||
&& !requested.startsWith("//")
|
||||
? requested
|
||||
: "/accounts";
|
||||
|
||||
return user ? <Navigate replace to={returnTo} /> : <>{children}</>;
|
||||
};
|
||||
|
||||
|
||||
@@ -11,16 +11,18 @@ const RouteTransition: FC<PropsWithChildren> = (props) => {
|
||||
const { pathname } = useLocation();
|
||||
const reduceMotion = useReducedMotion();
|
||||
|
||||
const transition = {
|
||||
duration: reduceMotion ? 0 : TRANSITION_DURATION_SECONDS,
|
||||
ease: "easeOut" as const,
|
||||
};
|
||||
|
||||
return (
|
||||
<LazyMotion features={domAnimation}>
|
||||
<m.div
|
||||
animate={{ opacity: 1 }}
|
||||
initial={!reduceMotion && { opacity: 0 }}
|
||||
key={pathname}
|
||||
transition={{
|
||||
duration: reduceMotion ? 0 : TRANSITION_DURATION_SECONDS,
|
||||
ease: "easeOut",
|
||||
}}
|
||||
transition={transition}
|
||||
>
|
||||
{children}
|
||||
</m.div>
|
||||
|
||||
@@ -8,19 +8,24 @@ import { BreadcrumbTrail } from "./BreadcrumbTrail";
|
||||
|
||||
type AccountBreadcrumbsProps = {
|
||||
accountId: string;
|
||||
section?: "events" | "income" | "operations";
|
||||
section?: "events"
|
||||
| "income"
|
||||
| "operations";
|
||||
};
|
||||
|
||||
const AccountBreadcrumbs: FC<AccountBreadcrumbsProps> = (props) => {
|
||||
const { accountId, section } = props;
|
||||
const { data: accounts } = useBrokerageAccounts();
|
||||
const { t } = useTranslation();
|
||||
|
||||
const accountName
|
||||
= accountId === "all"
|
||||
? t("accounts.all")
|
||||
: (accounts?.find(account => account.id === accountId)?.name
|
||||
?? t("breadcrumbs.accountFallback"));
|
||||
|
||||
const accountPath = `/accounts/${accountId}`;
|
||||
|
||||
const items = [
|
||||
{ label: t("breadcrumbs.accounts"), to: "/accounts" },
|
||||
section ? { label: accountName, to: accountPath } : { label: accountName },
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { Select } from "@mantine/core";
|
||||
|
||||
import { useAccountScopeSwitchVm } from "./AccountScopeSwitch.vm";
|
||||
|
||||
type AccountScopeSwitchProps = { accountId: string; section?: string };
|
||||
|
||||
const AccountScopeSwitch: FC<AccountScopeSwitchProps> = (props) => {
|
||||
const { accountId, data, onChange, t } = useAccountScopeSwitchVm(props);
|
||||
|
||||
return (
|
||||
<Select
|
||||
allowDeselect={false}
|
||||
data={data}
|
||||
label={t("accounts.scope")}
|
||||
maw={360}
|
||||
onChange={onChange}
|
||||
value={accountId}
|
||||
w="100%"
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export { AccountScopeSwitch };
|
||||
+19
-25
@@ -1,6 +1,3 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { Select } from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useLocation, useNavigate } from "react-router";
|
||||
|
||||
@@ -8,12 +5,13 @@ import { useBrokerageAccounts } from "@/entities/brokerage-account";
|
||||
|
||||
type AccountScopeSwitchProps = { accountId: string; section?: string };
|
||||
|
||||
const AccountScopeSwitch: FC<AccountScopeSwitchProps> = (props) => {
|
||||
function useAccountScopeSwitchVm(props: AccountScopeSwitchProps) {
|
||||
const { accountId, section } = props;
|
||||
const { data: accounts } = useBrokerageAccounts();
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const { search } = useLocation();
|
||||
|
||||
const data = [
|
||||
{ label: t("accounts.all"), value: "all" },
|
||||
...(accounts ?? []).map(account => ({
|
||||
@@ -21,27 +19,23 @@ const AccountScopeSwitch: FC<AccountScopeSwitchProps> = (props) => {
|
||||
value: account.id,
|
||||
})),
|
||||
];
|
||||
|
||||
if (data.every(item => item.value !== accountId))
|
||||
data.push({ label: t("breadcrumbs.accountFallback"), value: accountId });
|
||||
return (
|
||||
<Select
|
||||
allowDeselect={false}
|
||||
data={data}
|
||||
label={t("accounts.scope")}
|
||||
maw={360}
|
||||
onChange={(value) => {
|
||||
if (!value || value === accountId) return;
|
||||
const filters = new URLSearchParams(search);
|
||||
filters.delete("cursor");
|
||||
void navigate({
|
||||
pathname: ["/accounts", encodeURIComponent(value), section].filter(Boolean).join("/"),
|
||||
search: filters.toString(),
|
||||
});
|
||||
}}
|
||||
value={accountId}
|
||||
w="100%"
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export { AccountScopeSwitch };
|
||||
const onChange: (value: null | string) => void = (value) => {
|
||||
if (!value || value === accountId) return;
|
||||
const filters = new URLSearchParams(search);
|
||||
filters.delete("cursor");
|
||||
void navigate({
|
||||
pathname: ["/accounts", encodeURIComponent(value), section]
|
||||
.filter(Boolean)
|
||||
.join("/"),
|
||||
search: filters.toString(),
|
||||
});
|
||||
};
|
||||
|
||||
return { accountId, data, onChange, t };
|
||||
}
|
||||
|
||||
export { useAccountScopeSwitchVm };
|
||||
@@ -16,6 +16,7 @@ function renderBreadcrumbs(
|
||||
accounts?: { id: string; name: string }[],
|
||||
) {
|
||||
useBrokerageAccounts.mockReturnValue({ data: accounts });
|
||||
|
||||
return render(
|
||||
<MantineProvider>
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
@@ -70,6 +71,7 @@ describe("AppBreadcrumbs", () => {
|
||||
"page",
|
||||
);
|
||||
expect(screen.getByRole("navigation")).toHaveAttribute("data-depth", "3");
|
||||
|
||||
for (const separator of screen.getAllByText("→")) {
|
||||
expect(separator).toHaveAttribute("aria-hidden", "true");
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { useMatch } from "react-router";
|
||||
|
||||
import { AccountBreadcrumbs } from "./AccountBreadcrumbs";
|
||||
import { AccountScopeSwitch } from "./AccountScopeSwitch";
|
||||
import { AccountScopeSwitch } from "./AccountScopeSwitch/AccountScopeSwitch";
|
||||
import { BondBreadcrumbs } from "./BondBreadcrumbs";
|
||||
import { BreadcrumbTrail } from "./BreadcrumbTrail";
|
||||
import { CardBreadcrumbs } from "./CardBreadcrumbs";
|
||||
@@ -13,10 +13,12 @@ import { StockBreadcrumbs } from "./StockBreadcrumbs";
|
||||
|
||||
const AppBreadcrumbs: FC = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const operations = useMatch({
|
||||
end: true,
|
||||
path: "/accounts/:accountId/operations",
|
||||
});
|
||||
|
||||
const events = useMatch({ end: true, path: "/accounts/:accountId/events" });
|
||||
const income = useMatch({ end: true, path: "/accounts/:accountId/income" });
|
||||
const account = useMatch({ end: true, path: "/accounts/:accountId" });
|
||||
@@ -37,6 +39,7 @@ const AppBreadcrumbs: FC = () => {
|
||||
accountId={operations.params.accountId ?? ""}
|
||||
section="operations"
|
||||
/>
|
||||
|
||||
<AccountScopeSwitch
|
||||
accountId={operations.params.accountId ?? ""}
|
||||
section="operations"
|
||||
@@ -50,6 +53,7 @@ const AppBreadcrumbs: FC = () => {
|
||||
accountId={events.params.accountId ?? ""}
|
||||
section="events"
|
||||
/>
|
||||
|
||||
<AccountScopeSwitch
|
||||
accountId={events.params.accountId ?? ""}
|
||||
section="events"
|
||||
@@ -63,6 +67,7 @@ const AppBreadcrumbs: FC = () => {
|
||||
accountId={income.params.accountId ?? ""}
|
||||
section="income"
|
||||
/>
|
||||
|
||||
<AccountScopeSwitch
|
||||
accountId={income.params.accountId ?? ""}
|
||||
section="income"
|
||||
@@ -73,6 +78,7 @@ const AppBreadcrumbs: FC = () => {
|
||||
return (
|
||||
<Stack gap={0} mb="md">
|
||||
<AccountBreadcrumbs accountId={account.params.accountId ?? ""} />
|
||||
|
||||
<AccountScopeSwitch accountId={account.params.accountId ?? ""} />
|
||||
</Stack>
|
||||
);
|
||||
@@ -80,7 +86,12 @@ const AppBreadcrumbs: FC = () => {
|
||||
if (cards) return <BreadcrumbTrail items={[{ label: t("bank.title") }]} />;
|
||||
if (accounts)
|
||||
return <BreadcrumbTrail items={[{ label: t("breadcrumbs.accounts") }]} />;
|
||||
return settings ? <BreadcrumbTrail items={[{ label: t("breadcrumbs.settings") }]} /> : undefined;
|
||||
|
||||
return settings
|
||||
? (
|
||||
<BreadcrumbTrail items={[{ label: t("breadcrumbs.settings") }]} />
|
||||
)
|
||||
: undefined;
|
||||
};
|
||||
|
||||
export { AppBreadcrumbs };
|
||||
|
||||
@@ -7,9 +7,11 @@ import { useBond } from "@/entities/bond";
|
||||
import { BreadcrumbTrail } from "./BreadcrumbTrail";
|
||||
|
||||
type BondBreadcrumbsProps = { identifier: string };
|
||||
|
||||
const BondBreadcrumbs: FC<BondBreadcrumbsProps> = (props) => {
|
||||
const { data } = useBond(props.identifier);
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<BreadcrumbTrail
|
||||
items={[
|
||||
|
||||
@@ -7,11 +7,13 @@ import { Link } from "react-router";
|
||||
import classes from "./AppBreadcrumbs.module.css";
|
||||
|
||||
type BreadcrumbTrailProps = { items: Crumb[] };
|
||||
|
||||
type Crumb = { label: string; to?: string };
|
||||
|
||||
const BreadcrumbTrail: FC<BreadcrumbTrailProps> = (props) => {
|
||||
const { items } = props;
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Breadcrumbs
|
||||
aria-label={t("breadcrumbs.label")}
|
||||
|
||||
@@ -7,9 +7,11 @@ 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={[
|
||||
|
||||
@@ -7,9 +7,11 @@ import { useStock } from "@/entities/stock";
|
||||
import { BreadcrumbTrail } from "./BreadcrumbTrail";
|
||||
|
||||
type StockBreadcrumbsProps = { identifier: string };
|
||||
|
||||
const StockBreadcrumbs: FC<StockBreadcrumbsProps> = (props) => {
|
||||
const { data } = useStock(props.identifier);
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<BreadcrumbTrail
|
||||
items={[
|
||||
|
||||
@@ -30,31 +30,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
.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);
|
||||
}
|
||||
@@ -67,163 +42,10 @@
|
||||
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) {
|
||||
.navLink {
|
||||
transition: background-color 180ms ease-in-out;
|
||||
}
|
||||
|
||||
.drawStroke,
|
||||
.couponLines path {
|
||||
stroke-dasharray: 1;
|
||||
}
|
||||
|
||||
.topSlider {
|
||||
--slider-offset: 3px;
|
||||
--slider-delay: 0ms;
|
||||
}
|
||||
|
||||
.bottomSlider {
|
||||
--slider-offset: -3px;
|
||||
--slider-delay: 160ms;
|
||||
}
|
||||
|
||||
.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 450ms ease-out;
|
||||
}
|
||||
:is(.topSlider, .bottomSlider) {
|
||||
animation: slider-slide 650ms ease-in-out var(--slider-delay) both;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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: translateY(0);
|
||||
}
|
||||
20% {
|
||||
transform: translateY(-3px);
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes stroke-draw {
|
||||
0% {
|
||||
stroke-dashoffset: 1;
|
||||
}
|
||||
100% {
|
||||
stroke-dashoffset: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes slider-slide {
|
||||
0%,
|
||||
100% {
|
||||
transform: translateX(0);
|
||||
}
|
||||
50% {
|
||||
transform: translateX(var(--slider-offset));
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 47.99375em) {
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
import type { FC, ReactNode } from "react";
|
||||
|
||||
import { AppShell as MantineAppShell, NavLink, Text } from "@mantine/core";
|
||||
import {
|
||||
BondsIcon,
|
||||
CardsIcon,
|
||||
PortfolioIcon,
|
||||
SettingsIcon,
|
||||
StocksIcon,
|
||||
} from "@wealthledger/icons";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Outlet, NavLink as RouterNavLink, useLocation } from "react-router";
|
||||
|
||||
import { bindIconAnimation } from "@/shared/lib";
|
||||
|
||||
import classes from "./AppShell.module.css";
|
||||
|
||||
type AppShellProps = {
|
||||
@@ -16,80 +21,34 @@ const AppShell: FC<AppShellProps> = (props) => {
|
||||
const { contentAboveOutlet } = props;
|
||||
const { t } = useTranslation();
|
||||
const { pathname } = useLocation();
|
||||
|
||||
const items = [
|
||||
{
|
||||
icon: (
|
||||
<>
|
||||
<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"
|
||||
/>
|
||||
</>
|
||||
),
|
||||
icon: <PortfolioIcon size={20} />,
|
||||
iconClassName: classes.portfolioIcon,
|
||||
label: t("navigation.accounts"),
|
||||
to: "/accounts",
|
||||
},
|
||||
{
|
||||
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>
|
||||
</>
|
||||
),
|
||||
icon: <CardsIcon size={20} />,
|
||||
iconClassName: classes.cardsIcon,
|
||||
label: t("navigation.cards"),
|
||||
to: "/cards",
|
||||
},
|
||||
{
|
||||
icon: (
|
||||
<>
|
||||
<path d="M3 3v18h18" />
|
||||
<path
|
||||
className={classes.drawStroke}
|
||||
d="M7 14l5-5 4 3 5-7"
|
||||
pathLength={1}
|
||||
/>
|
||||
<path className={classes.stockArrow} d="M16 5h5v5" />
|
||||
</>
|
||||
),
|
||||
icon: <StocksIcon size={20} />,
|
||||
iconClassName: classes.stocksIcon,
|
||||
label: t("navigation.stocks"),
|
||||
to: "/stocks",
|
||||
},
|
||||
{
|
||||
icon: (
|
||||
<>
|
||||
<path d="M6 3h12v18l-3-2-3 2-3-2-3 2V3Z" />
|
||||
<g className={classes.couponLines}>
|
||||
<path d="M9 7h6" pathLength={1} />
|
||||
<path d="M9 11h6" pathLength={1} />
|
||||
<path d="M9 15h3" pathLength={1} />
|
||||
</g>
|
||||
</>
|
||||
),
|
||||
icon: <BondsIcon size={20} />,
|
||||
iconClassName: classes.bondsIcon,
|
||||
label: t("navigation.bonds"),
|
||||
to: "/bonds",
|
||||
},
|
||||
{
|
||||
icon: (
|
||||
<>
|
||||
<path d="M4 7h16M4 17h16" />
|
||||
<path className={classes.topSlider} d="M10 4v6h4V4h-4Z" />
|
||||
<path className={classes.bottomSlider} d="M10 14v6h4v-6h-4Z" />
|
||||
</>
|
||||
),
|
||||
icon: <SettingsIcon size={20} />,
|
||||
iconClassName: classes.settingsIcon,
|
||||
label: t("navigation.settings"),
|
||||
to: "/settings",
|
||||
@@ -105,6 +64,7 @@ const AppShell: FC<AppShellProps> = (props) => {
|
||||
<MantineAppShell.Header className={classes.header}>
|
||||
<Text fw={700}>{t("appName")}</Text>
|
||||
</MantineAppShell.Header>
|
||||
|
||||
<MantineAppShell.Navbar p="sm">
|
||||
{items.map(item => (
|
||||
<NavLink
|
||||
@@ -117,45 +77,38 @@ const AppShell: FC<AppShellProps> = (props) => {
|
||||
<span
|
||||
className={`${classes.navIcon} ${item.iconClassName ?? ""}`}
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
fill="none"
|
||||
focusable="false"
|
||||
height={20}
|
||||
ref={bindIconAnimation}
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="1.5"
|
||||
viewBox="0 0 24 24"
|
||||
width={20}
|
||||
>
|
||||
{item.icon}
|
||||
</svg>
|
||||
{item.icon}
|
||||
</span>
|
||||
)}
|
||||
to={item.to}
|
||||
/>
|
||||
))}
|
||||
</MantineAppShell.Navbar>
|
||||
|
||||
<MantineAppShell.Main className={classes.main}>
|
||||
<div className={classes.content}>
|
||||
{contentAboveOutlet}
|
||||
|
||||
<Outlet />
|
||||
</div>
|
||||
</MantineAppShell.Main>
|
||||
|
||||
<nav aria-label={t("appName")} className={classes.bottomNav}>
|
||||
{items.map(item => (
|
||||
<RouterNavLink
|
||||
className={
|
||||
(pathname.startsWith(item.to)) ? (classes.active) : undefined
|
||||
}
|
||||
key={item.to}
|
||||
to={item.to}
|
||||
>
|
||||
{item.label}
|
||||
</RouterNavLink>
|
||||
))}
|
||||
{items.map((item) => {
|
||||
const appearanceClass = pathname.startsWith(item.to)
|
||||
? classes.active
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<RouterNavLink
|
||||
className={appearanceClass}
|
||||
key={item.to}
|
||||
to={item.to}
|
||||
>
|
||||
{item.label}
|
||||
</RouterNavLink>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
</MantineAppShell>
|
||||
);
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 4.0 KiB |
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 8.5 KiB |
@@ -19,8 +19,10 @@ import {
|
||||
useBankSummary,
|
||||
} from "./queries";
|
||||
|
||||
const card: BankCard = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
const card: BankCard
|
||||
= {
|
||||
archivedAt: null,
|
||||
balance: { currency: "RUB", value: "100" },
|
||||
bankName: null,
|
||||
@@ -31,8 +33,9 @@ const card: BankCard = (/* eslint-disable unicorn/no-null -- Fixture preserves t
|
||||
openingDate: "2026-09-01",
|
||||
paymentSystem: null,
|
||||
version: 1,
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
};
|
||||
|
||||
/* eslint-enable unicorn/no-null */
|
||||
const transfer: CreateBankOperation = {
|
||||
amount: { currency: "RUB", value: "90071992547409.93" },
|
||||
cardId: "a",
|
||||
@@ -55,6 +58,7 @@ function readHandlers(counts: Map<string, number>, categoryName = "Food") {
|
||||
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 }) => {
|
||||
@@ -84,7 +88,10 @@ function readHandlers(counts: Map<string, number>, categoryName = "Food") {
|
||||
page: 1,
|
||||
total: 0,
|
||||
});
|
||||
return url.pathname.includes("/operations/") ? HttpResponse.json({ ...transfer, version: 1 }) : HttpResponse.json({ ...card, id: url.pathname.split("/").at(-1) });
|
||||
|
||||
return url.pathname.includes("/operations/")
|
||||
? HttpResponse.json({ ...transfer, version: 1 })
|
||||
: HttpResponse.json({ ...card, id: url.pathname.split("/").at(-1) });
|
||||
}),
|
||||
];
|
||||
}
|
||||
@@ -94,15 +101,18 @@ function useReadModels() {
|
||||
const a = useBankCard("a");
|
||||
const b = useBankCard("b");
|
||||
const categories = useBankCategories();
|
||||
|
||||
const history = useBankOperations("a", {
|
||||
limit: 20,
|
||||
month: "2026-09",
|
||||
page: 2,
|
||||
});
|
||||
|
||||
const expenses = useBankExpenses("a", { page: 1 });
|
||||
const september = useBankSummary("2026-09");
|
||||
const august = useBankSummary("2026-08", "b");
|
||||
const original = useBankOperation("original");
|
||||
|
||||
return {
|
||||
mutations: useBankMutations(),
|
||||
reads: [
|
||||
@@ -134,6 +144,7 @@ describe("banking API", () => {
|
||||
expect(url.searchParams.get("month")).toBe("2026-09");
|
||||
if (isFail && page === 2)
|
||||
return HttpResponse.json({ code: "FAILED" }, { status: 500 });
|
||||
|
||||
return HttpResponse.json({
|
||||
hasNext: page === 1,
|
||||
items: [{ ...transfer, id: String(page) }],
|
||||
@@ -142,10 +153,12 @@ describe("banking API", () => {
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useBankOperations("a", { limit: "all", month: "2026-09", page: 1 }),
|
||||
{ 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([
|
||||
@@ -153,10 +166,12 @@ describe("banking API", () => {
|
||||
"2",
|
||||
]);
|
||||
isFail = true;
|
||||
|
||||
const { result: failedResult } = renderHook(
|
||||
() => useBankOperations("a", { limit: "all", month: "2026-09", page: 1 }),
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
|
||||
await waitFor(() => expect(failedResult.current.isError).toBe(true));
|
||||
expect(failedResult.current.data).toBeUndefined();
|
||||
});
|
||||
@@ -164,15 +179,15 @@ describe("banking API", () => {
|
||||
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?includeArchived=true");
|
||||
expect(counts.keys()).toContain(
|
||||
"/api/v1/bank-cards/a/operations?limit=20&month=2026-09&page=2",
|
||||
);
|
||||
@@ -184,10 +199,13 @@ describe("banking API", () => {
|
||||
|
||||
it("replays the exact UUID and large Money string once across shared auth refresh", async () => {
|
||||
let token = "expired";
|
||||
|
||||
const refresh = vi.fn(() => {
|
||||
token = "renewed";
|
||||
|
||||
return Promise.resolve(true);
|
||||
});
|
||||
|
||||
configureAuthClient({ accessToken: () => token, clear: vi.fn(), refresh });
|
||||
const bodies: unknown[] = [];
|
||||
const headers: (null | string)[] = [];
|
||||
@@ -195,14 +213,17 @@ describe("banking API", () => {
|
||||
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"]);
|
||||
@@ -214,14 +235,17 @@ describe("banking API", () => {
|
||||
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),
|
||||
@@ -239,13 +263,16 @@ describe("banking API", () => {
|
||||
server.use(
|
||||
http.post("*/api/v1/bank-cards/operations", async () => {
|
||||
await pending;
|
||||
|
||||
return HttpResponse.json({ code: "INTERNAL_ERROR" }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(
|
||||
() => ({ mutations: useBankMutations(), query: useBankCard("a") }),
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
|
||||
await waitFor(() => expect(result.current.query.isSuccess).toBe(true));
|
||||
let saving: Promise<unknown>;
|
||||
act(() => {
|
||||
@@ -310,10 +337,12 @@ describe("banking API", () => {
|
||||
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(
|
||||
@@ -337,6 +366,7 @@ describe("banking API", () => {
|
||||
const body = await request.json();
|
||||
requests.push(body);
|
||||
name = "Groceries";
|
||||
|
||||
return HttpResponse.json({
|
||||
id: "food",
|
||||
isDefault: true,
|
||||
@@ -348,14 +378,17 @@ describe("banking API", () => {
|
||||
"*/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(),
|
||||
@@ -363,6 +396,7 @@ describe("banking API", () => {
|
||||
}),
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.categories.data?.[0].name).toBe("Food"),
|
||||
);
|
||||
@@ -406,9 +440,11 @@ describe("banking API", () => {
|
||||
),
|
||||
);
|
||||
const { queryClient, wrapper } = createQueryWrapper();
|
||||
|
||||
const { rerender, result } = renderHook(() => useBankCard("a"), {
|
||||
wrapper,
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.data?.balance.value).toBe("100"));
|
||||
await apiClient.PUT("/api/v1/tbank-connection", {
|
||||
body: { token: "synthetic" },
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiClient, ApiErrorCode, apiErrorCode, isApiErrorCode } from "@/shared/api";
|
||||
import {
|
||||
apiClient,
|
||||
ApiErrorCode,
|
||||
apiErrorCode,
|
||||
isApiErrorCode,
|
||||
} from "@/shared/api";
|
||||
|
||||
import type {
|
||||
CreateBankCard,
|
||||
@@ -17,21 +22,27 @@ async function mutationData<T>(
|
||||
const { data, error } = await request;
|
||||
// eslint-disable-next-line @typescript-eslint/only-throw-error -- Preserve generated ProblemDetails for apiErrorCode and field-error consumers.
|
||||
if (error) throw error;
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
function useBankMutations() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const invalidate = () =>
|
||||
queryClient.invalidateQueries({
|
||||
predicate: ({ queryKey }) => {
|
||||
const [method, path] = queryKey;
|
||||
return method === "get"
|
||||
|
||||
return (
|
||||
method === "get"
|
||||
&& typeof path === "string"
|
||||
&& (path === "/api/v1/bank-cards"
|
||||
|| path.startsWith("/api/v1/bank-cards/"));
|
||||
|| path.startsWith("/api/v1/bank-cards/"))
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const options = {
|
||||
onError: (error: unknown) => {
|
||||
const errorCode = apiErrorCode(error);
|
||||
@@ -49,11 +60,13 @@ function useBankMutations() {
|
||||
onSuccess: invalidate,
|
||||
retry: false,
|
||||
} as const;
|
||||
|
||||
const cardCreation = useMutation({
|
||||
...options,
|
||||
mutationFn: (body: CreateBankCard) =>
|
||||
mutationData(apiClient.POST("/api/v1/bank-cards", { body })),
|
||||
});
|
||||
|
||||
const updateCard = useMutation({
|
||||
...options,
|
||||
mutationFn: ({ body, id }: { body: UpdateBankCard; id: string }) =>
|
||||
@@ -64,11 +77,13 @@ function useBankMutations() {
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const operationCreation = useMutation({
|
||||
...options,
|
||||
mutationFn: (body: CreateBankOperation) =>
|
||||
mutationData(apiClient.POST("/api/v1/bank-cards/operations", { body })),
|
||||
});
|
||||
|
||||
const updateOperation = useMutation({
|
||||
...options,
|
||||
mutationFn: ({ body, id }: { body: UpdateBankOperation; id: string }) =>
|
||||
@@ -79,6 +94,7 @@ function useBankMutations() {
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const operationDeletion = useMutation({
|
||||
...options,
|
||||
mutationFn: ({ id, version }: { id: string; version: number }) =>
|
||||
@@ -88,11 +104,13 @@ function useBankMutations() {
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const categoryCreation = useMutation({
|
||||
...options,
|
||||
mutationFn: (body: CreateExpenseCategory) =>
|
||||
mutationData(apiClient.POST("/api/v1/bank-cards/categories", { body })),
|
||||
});
|
||||
|
||||
const updateCategory = useMutation({
|
||||
...options,
|
||||
mutationFn: ({ body, id }: { body: UpdateExpenseCategory; id: string }) =>
|
||||
@@ -103,6 +121,7 @@ function useBankMutations() {
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
return {
|
||||
createCard: cardCreation,
|
||||
createCategory: categoryCreation,
|
||||
|
||||
@@ -9,24 +9,34 @@ 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 CreateBankCard
|
||||
= paths["/api/v1/bank-cards"]["post"]["requestBody"]["content"]["application/json"];
|
||||
|
||||
type CreateBankOperation
|
||||
= paths["/api/v1/bank-cards/operations"]["post"]["requestBody"]["content"]["application/json"];
|
||||
|
||||
type CreateExpenseCategory
|
||||
= paths["/api/v1/bank-cards/categories"]["post"]["requestBody"]["content"]["application/json"];
|
||||
|
||||
type ExpenseCategory
|
||||
= paths["/api/v1/bank-cards/categories"]["get"]["responses"][200]["content"]["application/json"][number];
|
||||
|
||||
type UpdateBankCard
|
||||
= paths["/api/v1/bank-cards/{id}"]["patch"]["requestBody"]["content"]["application/json"];
|
||||
|
||||
type UpdateBankOperation
|
||||
= paths["/api/v1/bank-cards/operations/{id}"]["patch"]["requestBody"]["content"]["application/json"];
|
||||
|
||||
type UpdateExpenseCategory
|
||||
= paths["/api/v1/bank-cards/categories/{id}"]["patch"]["requestBody"]["content"]["application/json"];
|
||||
|
||||
@@ -41,12 +51,13 @@ function sortBankSummary(data: BankSummary): BankSummary {
|
||||
if (left === null || right === null)
|
||||
throw new Error("Invalid bank summary amount");
|
||||
if (left > right) return -1;
|
||||
|
||||
return left < right ? 1 : 0;
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function useBankCard(id: string | undefined) {
|
||||
function useBankCard(id?: string) {
|
||||
return useAuthenticatedQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bank-cards/{id}", {
|
||||
params: { path: { id: id ?? "" } },
|
||||
@@ -83,7 +94,7 @@ function useBankExpenses(
|
||||
});
|
||||
}
|
||||
|
||||
function useBankOperation(id: string | undefined) {
|
||||
function useBankOperation(id?: string) {
|
||||
return useAuthenticatedQuery({
|
||||
...apiQueryClient.queryOptions(
|
||||
"get",
|
||||
@@ -105,6 +116,7 @@ function useBankOperations(
|
||||
},
|
||||
) {
|
||||
const isAll = query.limit === "all";
|
||||
|
||||
const parameters = {
|
||||
path: { id: id ?? "" },
|
||||
query: {
|
||||
@@ -113,11 +125,13 @@ function useBankOperations(
|
||||
page: isAll ? 1 : query.page,
|
||||
},
|
||||
};
|
||||
|
||||
const options = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/bank-cards/{id}/operations",
|
||||
{ params: parameters },
|
||||
);
|
||||
|
||||
// eslint-disable-next-line @tanstack/query/exhaustive-deps -- Generated options.queryKey already contains params; retain the shared cache identity.
|
||||
return useAuthenticatedQuery({
|
||||
enabled: Boolean(id && (query.month || (query.from && query.to))),
|
||||
@@ -126,6 +140,7 @@ function useBankOperations(
|
||||
previousQuery,
|
||||
) => {
|
||||
const previous = previousQuery?.queryKey[2]?.params;
|
||||
|
||||
return !isAll
|
||||
&& previousQuery?.queryKey.length === options.queryKey.length
|
||||
&& previous?.path?.id === id
|
||||
@@ -138,6 +153,7 @@ function useBankOperations(
|
||||
},
|
||||
queryFn: async ({ signal }) => {
|
||||
const items: BankOperation[] = [];
|
||||
|
||||
for (let page = parameters.query.page; ; page++) {
|
||||
const { data, error } = await apiClient.GET(
|
||||
"/api/v1/bank-cards/{id}/operations",
|
||||
@@ -146,6 +162,7 @@ function useBankOperations(
|
||||
signal,
|
||||
},
|
||||
);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/only-throw-error -- Preserve generated ProblemDetails for apiErrorCode and field-error consumers.
|
||||
if (error) throw error;
|
||||
if (!data) throw new Error("Missing bank operations response");
|
||||
@@ -154,18 +171,22 @@ function useBankOperations(
|
||||
if (!data.hasNext) return { ...data, hasNext: false, items, page: 1 };
|
||||
}
|
||||
},
|
||||
queryKey: isAll ? ([...options.queryKey, "all"] as const) : options.queryKey,
|
||||
queryKey: isAll
|
||||
? ([...options.queryKey, "all"] as const)
|
||||
: options.queryKey,
|
||||
});
|
||||
}
|
||||
|
||||
function useBankSummary(
|
||||
period: string | { from: string; to: string },
|
||||
period: string
|
||||
| { from: string; to: string },
|
||||
cardId?: string,
|
||||
) {
|
||||
const query
|
||||
= typeof period === "string"
|
||||
? { cardId, month: period }
|
||||
: { ...period, cardId };
|
||||
|
||||
return useAuthenticatedQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bank-cards/summary", {
|
||||
params: { query },
|
||||
|
||||
@@ -28,6 +28,7 @@ it("orders displayed expenses descending, preserving cents, ties and source data
|
||||
net: money("0"),
|
||||
refunds: money("0"),
|
||||
};
|
||||
|
||||
expect(sortBankSummary(data).categories.map(row => row.categoryId)).toEqual(
|
||||
["3", "1", "2", "5", "4", "0"],
|
||||
);
|
||||
|
||||
@@ -10,21 +10,16 @@ export {
|
||||
useBankOperations,
|
||||
useBankSummary,
|
||||
} from "./api/queries";
|
||||
export {
|
||||
bankDateInputValue,
|
||||
bankDateSchema,
|
||||
bankMoneyValue,
|
||||
bankToday,
|
||||
moneyCents,
|
||||
positiveMoneySchema,
|
||||
} from "./model/form-validation";
|
||||
export { bankDateInputValue, bankMoneyValue, bankToday, moneyCents } from "./model/form-validation";
|
||||
export { bankDateSchema, positiveMoneySchema } from "./model/form.schema";
|
||||
|
||||
export { bankOperationAppearance } from "./model/operation-appearance";
|
||||
export { bankOperationKinds } from "./model/operation-kinds";
|
||||
export { bankPeriod } from "./model/period";
|
||||
export { BankCardFace } from "./ui/BankCardFace/BankCardFace";
|
||||
export { BankCardForm } from "./ui/BankCardForm/BankCardForm";
|
||||
export { BankFeedback } from "./ui/BankFeedback";
|
||||
export { BankOperationIcon } from "./ui/BankOperationIcon/BankOperationIcon";
|
||||
export { BankPeriodPicker } from "./ui/BankPeriodPicker";
|
||||
export { BankPeriodPicker } from "./ui/BankPeriodPicker/BankPeriodPicker";
|
||||
export { BankSummaryView } from "./ui/BankSummary/BankSummary.view";
|
||||
export { CategoryManager } from "./ui/CategoryManager/CategoryManager";
|
||||
export { useBankFormFocus } from "./ui/useBankFormFocus";
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { validationMessage } from "@/shared/i18n";
|
||||
|
||||
import type { ExpenseCategory } from "../api/queries";
|
||||
const MAX_CATEGORY_NAME_LENGTH = 80;
|
||||
|
||||
function categorySchema(categories?: ExpenseCategory[], editingId?: string) {
|
||||
return z.object({
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.refine(
|
||||
value => value.length > 0 && value.length <= MAX_CATEGORY_NAME_LENGTH,
|
||||
{ error: validationMessage("bank.validation.category") },
|
||||
)
|
||||
.refine(
|
||||
value =>
|
||||
!categories?.some(
|
||||
c =>
|
||||
c.id !== editingId
|
||||
&& c.name.toLocaleLowerCase("ru-RU")
|
||||
=== value.toLocaleLowerCase("ru-RU"),
|
||||
),
|
||||
{ error: validationMessage("bank.validation.duplicate") },
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export { categorySchema };
|
||||
@@ -1,14 +1,7 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
bankCardSchema,
|
||||
bankDateInputValue,
|
||||
bankDateSchema,
|
||||
bankMoneyValue,
|
||||
bankMonth,
|
||||
bankToday,
|
||||
positiveMoneySchema,
|
||||
} from "./form-validation";
|
||||
import { bankDateInputValue, bankMoneyValue, bankMonth, bankToday } from "./form-validation";
|
||||
import { bankCardSchema, bankDateSchema, positiveMoneySchema } from "./form.schema";
|
||||
|
||||
afterEach(() => vi.useRealTimers());
|
||||
describe("bank form input", () => {
|
||||
@@ -16,6 +9,7 @@ describe("bank form input", () => {
|
||||
expect(positiveMoneySchema.safeParse("92233720368547758.07").success).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
for (const invalid of [
|
||||
"92233720368547758.08",
|
||||
"1.001",
|
||||
@@ -26,7 +20,9 @@ describe("bank form input", () => {
|
||||
]) {
|
||||
expect(positiveMoneySchema.safeParse(invalid).success).toBe(false);
|
||||
}
|
||||
|
||||
expect(bankMoneyValue(" -00010,20 ")).toBe("-10.20");
|
||||
|
||||
const values = {
|
||||
bankName: "",
|
||||
lastFour: "",
|
||||
@@ -34,6 +30,7 @@ describe("bank form input", () => {
|
||||
openingBalance: "-92233720368547758.08",
|
||||
openingDate: "2026-01-01",
|
||||
};
|
||||
|
||||
expect(bankCardSchema.safeParse(values).success).toBe(true);
|
||||
expect(
|
||||
bankCardSchema.safeParse({
|
||||
@@ -62,6 +59,7 @@ it("converts local date input without accepting impossible or unfinished dates",
|
||||
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,
|
||||
|
||||
@@ -1,28 +1,25 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { validationMessage } from "@/shared/i18n";
|
||||
|
||||
const DECIMAL_PART_COUNT = 2;
|
||||
const CENTS_PRECISION = 2;
|
||||
const ISO_DATE_LENGTH = 10;
|
||||
|
||||
const ISO_MONTH_LENGTH = 7;
|
||||
const MAX_CARD_NAME_LENGTH = 100;
|
||||
|
||||
function bankDateInputValue(value: string) {
|
||||
return value.replace(/^(\d{2})\.(\d{2})\.(\d{4})$/, "$3-$2-$1");
|
||||
}
|
||||
|
||||
function bankMoneyValue(value: string) {
|
||||
return value
|
||||
.trim()
|
||||
.replace(",", ".")
|
||||
.replace(/^(-?)0+(?=\d)/, "$1");
|
||||
}
|
||||
|
||||
function bankMonth(value: null | string) {
|
||||
return value && value >= "0001-01" && /^\d{4}-(?:0[1-9]|1[0-2])$/.test(value)
|
||||
? value
|
||||
: bankToday().slice(0, ISO_MONTH_LENGTH);
|
||||
}
|
||||
|
||||
function bankToday() {
|
||||
return new Intl.DateTimeFormat("en-CA", {
|
||||
day: "2-digit",
|
||||
@@ -31,84 +28,21 @@ function bankToday() {
|
||||
year: "numeric",
|
||||
}).format(new Date());
|
||||
}
|
||||
|
||||
function moneyCents(value: string): bigint | null {
|
||||
const normalized = value.trim().replace(",", ".");
|
||||
if (!/^-?\d+$|^-?\d+\.\d{1,2}$/.test(normalized)) return /* eslint-disable-line unicorn/no-null -- The money parser’s callers distinguish invalid input with null. */ null;
|
||||
const [whole, fraction = ""] = normalized.replace("-", "").split(".", DECIMAL_PART_COUNT);
|
||||
if (!/^-?\d+$|^-?\d+\.\d{1,2}$/.test(normalized))
|
||||
// eslint-disable-next-line unicorn/no-null -- The money parser’s callers distinguish invalid input with null.
|
||||
return null;
|
||||
|
||||
const [whole, fraction = ""] = normalized
|
||||
.replace("-", "")
|
||||
.split(".", DECIMAL_PART_COUNT);
|
||||
|
||||
return (
|
||||
BigInt(`${whole}${fraction.padEnd(CENTS_PRECISION, "0")}`)
|
||||
* (normalized.startsWith("-") ? -1n : 1n)
|
||||
);
|
||||
}
|
||||
const MIN_BALANCE_KOPECKS = -9_223_372_036_854_775_808n;
|
||||
const MAX_BALANCE_KOPECKS = 9_223_372_036_854_775_807n;
|
||||
|
||||
const moneySchema = z.string().refine(
|
||||
(value) => {
|
||||
const cents = moneyCents(value);
|
||||
return (
|
||||
cents !== null
|
||||
&& cents >= MIN_BALANCE_KOPECKS
|
||||
&& cents <= MAX_BALANCE_KOPECKS
|
||||
);
|
||||
},
|
||||
{ error: validationMessage("bank.validation.money") },
|
||||
);
|
||||
const positiveMoneySchema = moneySchema.refine(
|
||||
(value) => {
|
||||
const cents = moneyCents(value);
|
||||
return cents === null || cents > 0n;
|
||||
},
|
||||
{ error: 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, ISO_DATE_LENGTH) === value
|
||||
&& value <= bankToday(),
|
||||
{ error: validationMessage("bank.validation.date") },
|
||||
);
|
||||
const bankCardSchema = z.object({
|
||||
bankName: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(
|
||||
MAX_CARD_NAME_LENGTH,
|
||||
validationMessage("bank.validation.bankName")(undefined),
|
||||
),
|
||||
lastFour: z.string().refine(value => !value || /^\d{4}$/.test(value), {
|
||||
error: validationMessage("bank.validation.lastFour"),
|
||||
}),
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, validationMessage("bank.validation.name")(undefined))
|
||||
.max(
|
||||
MAX_CARD_NAME_LENGTH,
|
||||
validationMessage("bank.validation.name")(undefined),
|
||||
),
|
||||
openingBalance: moneySchema,
|
||||
openingDate: bankDateSchema,
|
||||
paymentSystem: z
|
||||
.enum(["", "mir", "visa", "mastercard"], {
|
||||
error: validationMessage("bank.validation.paymentSystem"),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
type BankCardValues = z.infer<typeof bankCardSchema>;
|
||||
|
||||
export {
|
||||
bankCardSchema,
|
||||
type BankCardValues,
|
||||
bankDateInputValue,
|
||||
bankDateSchema,
|
||||
bankMoneyValue,
|
||||
bankMonth,
|
||||
bankToday,
|
||||
moneyCents,
|
||||
positiveMoneySchema,
|
||||
};
|
||||
export { bankDateInputValue, bankMoneyValue, bankMonth, bankToday, moneyCents };
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { validationMessage } from "@/shared/i18n";
|
||||
|
||||
import { bankToday, moneyCents } from "./form-validation";
|
||||
const ISO_DATE_LENGTH = 10;
|
||||
const MAX_CARD_NAME_LENGTH = 100;
|
||||
const MIN_BALANCE_KOPECKS = -9_223_372_036_854_775_808n;
|
||||
const MAX_BALANCE_KOPECKS = 9_223_372_036_854_775_807n;
|
||||
|
||||
const moneySchema = z.string().refine(
|
||||
(value) => {
|
||||
const cents = moneyCents(value);
|
||||
|
||||
return (
|
||||
cents !== null
|
||||
&& cents >= MIN_BALANCE_KOPECKS
|
||||
&& cents <= MAX_BALANCE_KOPECKS
|
||||
);
|
||||
},
|
||||
{ error: validationMessage("bank.validation.money") },
|
||||
);
|
||||
|
||||
const positiveMoneySchema = moneySchema.refine(
|
||||
(value) => {
|
||||
const cents = moneyCents(value);
|
||||
|
||||
return cents === null || cents > 0n;
|
||||
},
|
||||
{ error: 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, ISO_DATE_LENGTH)
|
||||
=== value
|
||||
&& value <= bankToday(),
|
||||
{ error: validationMessage("bank.validation.date") },
|
||||
);
|
||||
|
||||
const bankCardSchema = z.object({
|
||||
bankName: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(
|
||||
MAX_CARD_NAME_LENGTH,
|
||||
validationMessage("bank.validation.bankName")(undefined),
|
||||
),
|
||||
lastFour: z.string().refine(value => !value || /^\d{4}$/.test(value), {
|
||||
error: validationMessage("bank.validation.lastFour"),
|
||||
}),
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, validationMessage("bank.validation.name")(undefined))
|
||||
.max(
|
||||
MAX_CARD_NAME_LENGTH,
|
||||
validationMessage("bank.validation.name")(undefined),
|
||||
),
|
||||
openingBalance: moneySchema,
|
||||
openingDate: bankDateSchema,
|
||||
paymentSystem: z
|
||||
.enum(["", "mir", "visa", "mastercard"], {
|
||||
error: validationMessage("bank.validation.paymentSystem"),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
|
||||
type BankCardValues = z.infer<typeof bankCardSchema>;
|
||||
|
||||
export {
|
||||
bankCardSchema,
|
||||
type BankCardValues,
|
||||
bankDateSchema,
|
||||
positiveMoneySchema,
|
||||
};
|
||||
@@ -1,124 +1,132 @@
|
||||
import type { OperationIconProps } from "@wealthledger/icons";
|
||||
|
||||
import type { BankOperation } from "../api/queries";
|
||||
|
||||
type OperationIcon = { animation?: string; color: string; path: string };
|
||||
type OperationIcon = {
|
||||
animation?: string;
|
||||
color: string;
|
||||
variant: OperationIconProps["variant"];
|
||||
};
|
||||
|
||||
const categoryIcons: Record<string, OperationIcon> = {
|
||||
"алкоголь": {
|
||||
animation: "wine",
|
||||
color: "grape",
|
||||
path: "M7 3h10v5a5 5 0 0 1-10 0V3Z M7 7h10v1a5 5 0 0 1-10 0V7Z M12 13v8 M8 21h8",
|
||||
variant: "wine",
|
||||
},
|
||||
"вклады": {
|
||||
animation: "deposit",
|
||||
color: "green",
|
||||
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",
|
||||
variant: "deposit",
|
||||
},
|
||||
"жилье": { color: "orange", path: "M3 11l9-8 9 8 M5 10v11h14V10 M9 21v-8h6v8" },
|
||||
"здоровье": { color: "red", path: "M9 3h6v6h6v6h-6v6H9v-6H3V9h6V3Z" },
|
||||
"жилье": { color: "orange", variant: "home" },
|
||||
"здоровье": { color: "red", variant: "medical" },
|
||||
"инвестиции и накопления": {
|
||||
animation: "growth",
|
||||
color: "green",
|
||||
path: "M3 3v18h18 M6 15l5-5 4 3 6-8 M16 5h5v5",
|
||||
variant: "growth",
|
||||
},
|
||||
"кафе": {
|
||||
animation: "coffee",
|
||||
color: "orange",
|
||||
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",
|
||||
variant: "coffee",
|
||||
},
|
||||
"образование": {
|
||||
color: "blue",
|
||||
path: "M2 8l10-5 10 5-10 5L2 8Z M6 10v7c4 3 8 3 12 0v-7 M22 8v9",
|
||||
variant: "education",
|
||||
},
|
||||
"переводы": {
|
||||
animation: "transfer",
|
||||
color: "blue",
|
||||
path: "M3 7h18l-4-4 M21 17H3l4 4",
|
||||
variant: "transfer",
|
||||
},
|
||||
"погашение кредита": {
|
||||
animation: "repayment",
|
||||
color: "orange",
|
||||
path: "M3 5h18v14H3V5Z M3 9h18 M10 18v-7h3a2 2 0 0 1 0 4H9m0 1.5h4",
|
||||
variant: "repayment",
|
||||
},
|
||||
"подписки": {
|
||||
color: "grape",
|
||||
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",
|
||||
variant: "subscriptions",
|
||||
},
|
||||
"покупки": {
|
||||
color: "grape",
|
||||
path: "M5 7h14l2 14H3L5 7Z M8 8V6a4 4 0 0 1 8 0v2",
|
||||
variant: "shopping",
|
||||
},
|
||||
"продукты": {
|
||||
animation: "basket",
|
||||
color: "green",
|
||||
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",
|
||||
variant: "basket",
|
||||
},
|
||||
"путешествия": {
|
||||
color: "blue",
|
||||
path: "M10 3h4v7l7 5v3l-7-3v5l2 1v1l-4-1-4 1v-1l2-1v-5l-7 3v-3l7-5V3Z",
|
||||
variant: "travel",
|
||||
},
|
||||
"развлечения": {
|
||||
color: "grape",
|
||||
path: "M9 5v14a3 3 0 1 1-3-3h3 M9 5l11-2v14a3 3 0 1 1-3-3h3 M9 9l11-2",
|
||||
variant: "music",
|
||||
},
|
||||
"связь и интернет": {
|
||||
animation: "wifi",
|
||||
color: "blue",
|
||||
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",
|
||||
variant: "wifi",
|
||||
},
|
||||
"снятие наличных": {
|
||||
color: "green",
|
||||
path: "M4 10V3h16v7 M7 7h10v14H7V7Z M7 11h10 M10 16h4",
|
||||
variant: "cashWithdrawal",
|
||||
},
|
||||
"ставки": {
|
||||
color: "grape",
|
||||
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",
|
||||
variant: "dice",
|
||||
},
|
||||
"страхование": {
|
||||
color: "green",
|
||||
path: "M12 2l8 4v6c0 5-8 10-8 10S4 17 4 12V6l8-4Z M8 12l3 3 5-6",
|
||||
variant: "shield",
|
||||
},
|
||||
"табак": {
|
||||
color: "orange",
|
||||
path: "M3 14h18v5H3v-5Z M16 14v5 M8 10V8c0-2 3-2 3-4V2 M15 10V8c0-2 3-2 3-4",
|
||||
variant: "smoking",
|
||||
},
|
||||
"такси": {
|
||||
color: "yellow",
|
||||
path: "M4 10l2-6h12l2 6 M3 10h18v8H3v-8Z M6 18v3 M18 18v3 M6 14h2 M16 14h2 M10 4V2h4v2",
|
||||
variant: "taxi",
|
||||
},
|
||||
"транспорт": {
|
||||
animation: "car",
|
||||
color: "blue",
|
||||
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",
|
||||
variant: "car",
|
||||
},
|
||||
"хостинг и ии-сервисы": {
|
||||
animation: "server",
|
||||
color: "grape",
|
||||
path: "M3 3h18v7H3V3Z M3 14h18v7H3v-7Z M7 6.5h.01 M7 17.5h.01 M15 6.5h3 M15 17.5h3",
|
||||
variant: "server",
|
||||
},
|
||||
"цифровые покупки": {
|
||||
color: "blue",
|
||||
path: "M3 3h18v13H3V3Z M8 21h8 M12 16v5 M12 6v7 M9 10l3 3 3-3",
|
||||
variant: "download",
|
||||
},
|
||||
};
|
||||
|
||||
const otherIcon: OperationIcon = {
|
||||
animation: "grid",
|
||||
color: "gray",
|
||||
path: "M4 4h6v6H4V4Z M14 4h6v6h-6V4Z M4 14h6v6H4v-6Z M14 14h6v6h-6v-6Z",
|
||||
variant: "grid",
|
||||
};
|
||||
|
||||
const operationIcons: Record<
|
||||
Exclude<BankOperation["kind"], "expense">,
|
||||
OperationIcon
|
||||
> = {
|
||||
refund: { color: "teal", path: "M8 4L3 9l5 5 M3 9h11a7 7 0 0 1 0 14" },
|
||||
refund: { color: "teal", variant: "refund" },
|
||||
topup: {
|
||||
animation: "topup",
|
||||
color: "green",
|
||||
path: "M20 8V5H5a2 2 0 0 1 0-4h13v4 M3 3v16a2 2 0 0 0 2 2h15V8H5 M16 12v5m-2.5-2.5h5",
|
||||
variant: "topup",
|
||||
},
|
||||
transfer: {
|
||||
animation: "transfer",
|
||||
color: "blue",
|
||||
path: "M3 7h18l-4-4 M21 17H3l4 4",
|
||||
variant: "transfer",
|
||||
},
|
||||
};
|
||||
|
||||
@@ -126,12 +134,18 @@ function bankOperationAppearance(
|
||||
kind: BankOperation["kind"],
|
||||
categoryName?: null | string,
|
||||
) {
|
||||
if (kind !== "expense") return /* eslint-disable-line security/detect-object-injection -- Operation kinds are finite; category names are guarded by Object.hasOwn. */ operationIcons[kind];
|
||||
if (kind !== "expense")
|
||||
// eslint-disable-next-line security/detect-object-injection -- Operation kinds are finite; category names are guarded by Object.hasOwn.
|
||||
return operationIcons[kind];
|
||||
|
||||
const name = categoryName
|
||||
?.trim()
|
||||
.toLocaleLowerCase("ru-RU")
|
||||
.replaceAll("ё", "е");
|
||||
return name && Object.hasOwn(categoryIcons, name) ? /* eslint-disable-line security/detect-object-injection -- Operation kinds are finite; category names are guarded by Object.hasOwn. */ categoryIcons[name] : otherIcon;
|
||||
|
||||
return name && Object.hasOwn(categoryIcons, name)
|
||||
? categoryIcons[name] // eslint-disable-line security/detect-object-injection -- Operation kinds are finite; category names are guarded by Object.hasOwn.
|
||||
: otherIcon;
|
||||
}
|
||||
|
||||
export { bankOperationAppearance };
|
||||
|
||||
@@ -17,6 +17,7 @@ it.each([
|
||||
it("rejects zero year consistently in legacy and explicit periods", () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-09-27T10:00:00Z"));
|
||||
|
||||
for (const query of ["month=0000-01", "from=0000-01-01&to=0000-01-31"]) {
|
||||
expect(bankPeriod(new URLSearchParams(query))).toEqual({
|
||||
from: "2026-09-01",
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import { z } from "zod";
|
||||
import { calendarDate } from "@/shared/lib";
|
||||
|
||||
import { bankMonth } from "./form-validation";
|
||||
|
||||
const calendarDate = z.iso.date();
|
||||
const ISO_DATE_LENGTH = 10;
|
||||
|
||||
function bankPeriod(parameters: URLSearchParams) {
|
||||
const month = bankMonth(parameters.get("month"));
|
||||
const monthEnd = new Date(`${month}-01T00:00:00Z`);
|
||||
monthEnd.setUTCMonth(monthEnd.getUTCMonth() + 1, 0);
|
||||
const from = parameters.get("from");
|
||||
const to = parameters.get("to");
|
||||
|
||||
return from
|
||||
&& to
|
||||
&& calendarDate.safeParse(from).success
|
||||
|
||||
@@ -4,53 +4,66 @@ import { SimpleGrid } from "@mantine/core";
|
||||
|
||||
import { BankCardFace } from "./BankCardFace";
|
||||
|
||||
const meta = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
args: {
|
||||
card: {
|
||||
archivedAt: null,
|
||||
balance: { currency: "RUB", value: "128450.75" },
|
||||
bankName: "Сбербанк",
|
||||
id: "fictional",
|
||||
lastFour: "4829",
|
||||
name: "Для повседневных покупок",
|
||||
openingBalance: { currency: "RUB", value: "0" },
|
||||
openingDate: "2026-01-01",
|
||||
paymentSystem: "mir",
|
||||
version: 1,
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
const meta
|
||||
= {
|
||||
args: {
|
||||
card: {
|
||||
archivedAt: null,
|
||||
balance: { currency: "RUB", value: "128450.75" },
|
||||
bankName: "Сбербанк",
|
||||
id: "fictional",
|
||||
lastFour: "4829",
|
||||
name: "Для повседневных покупок",
|
||||
openingBalance: { currency: "RUB", value: "0" },
|
||||
openingDate: "2026-01-01",
|
||||
paymentSystem: "mir",
|
||||
version: 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
component: BankCardFace,
|
||||
tags: ["autodocs"],
|
||||
title: "Product/BankCards/CardAppearance",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */) satisfies Meta<typeof BankCardFace>;
|
||||
component: BankCardFace,
|
||||
tags: ["autodocs"],
|
||||
title: "Product/BankCards/CardAppearance",
|
||||
} satisfies /* eslint-enable unicorn/no-null */ Meta<typeof BankCardFace>;
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Banks: Story = {
|
||||
render: arguments_ => (
|
||||
<SimpleGrid cols={{ base: 1, sm: 2 }} maw={920}>
|
||||
{["Сбербанк", "Т-Банк", "Альфа-Банк", "ВТБ", /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null].map(
|
||||
(bankName, index) => (
|
||||
<BankCardFace
|
||||
card={(/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
...arguments_.card,
|
||||
bankName,
|
||||
paymentSystem:
|
||||
/* eslint-disable-line security/detect-object-injection -- This is a positional index into the local array, not a user-supplied object key. */ (["mir", "mastercard", "visa", "mir", null] as const)[index]
|
||||
{[
|
||||
"Сбербанк",
|
||||
"Т-Банк",
|
||||
"Альфа-Банк",
|
||||
"ВТБ",
|
||||
// eslint-disable-next-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
|
||||
null,
|
||||
].map((bankName, index) => (
|
||||
<BankCardFace
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
card={
|
||||
{
|
||||
...arguments_.card,
|
||||
bankName,
|
||||
paymentSystem:
|
||||
// eslint-disable-next-line security/detect-object-injection -- This is a positional index into the local array, not a user-supplied object key.
|
||||
(["mir", "mastercard", "visa", "mir", null] as const)[index]
|
||||
?? null,
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */)}
|
||||
key={bankName ?? "unknown"}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */
|
||||
}
|
||||
key={bankName ?? "unknown"}
|
||||
/>
|
||||
))}
|
||||
</SimpleGrid>
|
||||
),
|
||||
};
|
||||
export const MissingDetails: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
export const MissingDetails: Story
|
||||
= {
|
||||
args: {
|
||||
card: {
|
||||
...meta.args.card,
|
||||
@@ -59,8 +72,8 @@ export const MissingDetails: Story = (/* eslint-disable unicorn/no-null -- Fixtu
|
||||
paymentSystem: null,
|
||||
},
|
||||
},
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
};
|
||||
/* eslint-enable unicorn/no-null */
|
||||
export const LongArchived: Story = {
|
||||
args: {
|
||||
card: {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { ContactlessIcon } from "@wealthledger/icons";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { formatMoney } from "@/shared/lib";
|
||||
@@ -9,51 +10,46 @@ 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 = bankTone(bank);
|
||||
|
||||
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 aria-hidden="true" className={classes.hardware}>
|
||||
<span className={classes.chip} />
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
fill="none"
|
||||
height="30"
|
||||
viewBox="0 0 24 30"
|
||||
width="24"
|
||||
>
|
||||
<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"
|
||||
strokeLinecap="round"
|
||||
strokeWidth="2"
|
||||
/>
|
||||
</svg>
|
||||
|
||||
<ContactlessIcon height="30" viewBox="0 0 24 30" />
|
||||
</div>
|
||||
<div
|
||||
className={classes.number}
|
||||
>
|
||||
|
||||
<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 aria-hidden="true" className={classes.circles} />
|
||||
)}
|
||||
|
||||
{t(`bank.paymentSystems.${card.paymentSystem}`)}
|
||||
</span>
|
||||
)}
|
||||
@@ -66,6 +62,7 @@ function bankTone(bank: string) {
|
||||
if (/сбер|sber/.test(bank)) return "green";
|
||||
if (/тинькофф|т[ -]?банк|t[ -]?bank|tinkoff/.test(bank)) return "yellow";
|
||||
if (/альфа|alfa/.test(bank)) return "red";
|
||||
|
||||
return /втб|vtb|газпром|gazprom/.test(bank) ? "blue" : "graphite";
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { ComponentProps } from "react";
|
||||
|
||||
import { DateInput } from "@mantine/dates";
|
||||
import { useController, useFormContext } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { bankDateInputValue } from "../../model/form-validation";
|
||||
import { type BankCardValues, bankDateSchema } from "../../model/form.schema";
|
||||
|
||||
function useBankCardFieldsVm() {
|
||||
const {
|
||||
control,
|
||||
formState: { errors },
|
||||
register,
|
||||
} = useFormContext<BankCardValues>();
|
||||
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { field: paymentSystemField } = useController({
|
||||
control,
|
||||
name: "paymentSystem",
|
||||
});
|
||||
|
||||
const { field: openingDateField } = useController({
|
||||
control,
|
||||
name: "openingDate",
|
||||
});
|
||||
|
||||
const paymentSystems = ["mir", "visa", "mastercard"].map(value => ({
|
||||
label: t(`bank.paymentSystems.${value}`),
|
||||
value,
|
||||
}));
|
||||
|
||||
const onPaymentSystemChange: (value: null | string) => void = value =>
|
||||
paymentSystemField.onChange(value ?? "");
|
||||
|
||||
const dateParser: ComponentProps<typeof DateInput>["dateParser"] = value =>
|
||||
bankDateSchema.safeParse(bankDateInputValue(value)).success
|
||||
? bankDateInputValue(value)
|
||||
: null; // eslint-disable-line unicorn/no-null -- Mantine represents an empty controlled openingDateField as null.
|
||||
|
||||
const onOpeningDateBlur: ComponentProps<typeof DateInput>["onBlur"] = (
|
||||
event,
|
||||
) => {
|
||||
openingDateField.onChange(bankDateInputValue(event.currentTarget.value));
|
||||
openingDateField.onBlur();
|
||||
};
|
||||
|
||||
const onOpeningDateChange: (value: null | string) => void = value =>
|
||||
openingDateField.onChange(value ?? "");
|
||||
|
||||
const onOpeningDateInput: ComponentProps<typeof DateInput>["onInput"] = event =>
|
||||
openingDateField.onChange(bankDateInputValue(event.currentTarget.value));
|
||||
|
||||
const openingDateValue = bankDateSchema.safeParse(openingDateField.value)
|
||||
.success
|
||||
? openingDateField.value
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
dateParser,
|
||||
errors,
|
||||
onOpeningDateBlur,
|
||||
onOpeningDateChange,
|
||||
onOpeningDateInput,
|
||||
onPaymentSystemChange,
|
||||
openingDateField,
|
||||
openingDateValue,
|
||||
paymentSystemField,
|
||||
paymentSystems,
|
||||
register,
|
||||
t,
|
||||
};
|
||||
}
|
||||
|
||||
export { useBankCardFieldsVm };
|
||||
@@ -2,7 +2,7 @@ import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
|
||||
import type { BankCardValues } from "../../model/form-validation";
|
||||
import type { BankCardValues } from "../../model/form.schema";
|
||||
|
||||
import { BankCardFields } from "./BankCardForm.view";
|
||||
|
||||
@@ -20,6 +20,7 @@ const meta = {
|
||||
openingDate: "2026-08-01",
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<FormProvider {...methods}>
|
||||
<Story />
|
||||
@@ -38,8 +39,11 @@ const meta = {
|
||||
tags: ["autodocs"],
|
||||
title: "Product/BankCards/CardFields",
|
||||
} satisfies Meta<typeof BankCardFields>;
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Active: Story = { name: "Независимая карта в рублях" };
|
||||
export const Archived: Story = {
|
||||
args: { archived: true },
|
||||
|
||||
@@ -12,8 +12,10 @@ import type { BankCard } from "../../api/queries";
|
||||
|
||||
import { BankCardForm } from "./BankCardForm";
|
||||
|
||||
const card: BankCard = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
const card: BankCard
|
||||
= {
|
||||
archivedAt: null,
|
||||
balance: { currency: "RUB", value: "50" },
|
||||
bankName: "Банк",
|
||||
@@ -24,8 +26,9 @@ const card: BankCard = (/* eslint-disable unicorn/no-null -- Fixture preserves t
|
||||
openingDate: "2026-01-01",
|
||||
paymentSystem: null,
|
||||
version: 1,
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
};
|
||||
|
||||
/* eslint-enable unicorn/no-null */
|
||||
function setup(value: BankCard) {
|
||||
configureAuthClient({
|
||||
accessToken: () => "test",
|
||||
@@ -41,8 +44,10 @@ function setup(value: BankCard) {
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
|
||||
return close;
|
||||
}
|
||||
|
||||
describe("BankCardForm", () => {
|
||||
it("waits for the exit transition before notifying the parent", async () => {
|
||||
const close = setup(card);
|
||||
@@ -64,20 +69,23 @@ describe("BankCardForm", () => {
|
||||
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((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
expect(body).toEqual(
|
||||
{
|
||||
bankName: null,
|
||||
lastFour: null,
|
||||
name: "Основная",
|
||||
paymentSystem: null,
|
||||
version: 1,
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */));
|
||||
},
|
||||
/* eslint-enable unicorn/no-null */
|
||||
);
|
||||
});
|
||||
it("loads and saves the selected payment system", async () => {
|
||||
const close = setup({ ...card, paymentSystem: "mir" });
|
||||
@@ -92,6 +100,7 @@ describe("BankCardForm", () => {
|
||||
server.use(
|
||||
http.patch("*/api/v1/bank-cards/a", async ({ request }) => {
|
||||
body = await request.json();
|
||||
|
||||
return HttpResponse.json({ ...card, paymentSystem: "visa" });
|
||||
}),
|
||||
);
|
||||
@@ -132,6 +141,7 @@ describe("BankCardForm", () => {
|
||||
const body = (await request.json()) as Record<string, unknown>;
|
||||
bodies.push(body);
|
||||
version = 2;
|
||||
|
||||
return body.version === 1
|
||||
? HttpResponse.json(
|
||||
{ code: "BANK_VERSION_CONFLICT" },
|
||||
@@ -146,9 +156,11 @@ describe("BankCardForm", () => {
|
||||
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: "Сохранить" }));
|
||||
|
||||
@@ -1,121 +1,61 @@
|
||||
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 { type FC } from "react";
|
||||
import { FormProvider } from "react-hook-form";
|
||||
|
||||
import { formatDate } from "@/shared/lib";
|
||||
|
||||
import { useBankMutations } from "../../api/mutations";
|
||||
import { type BankCard, useBankCard } from "../../api/queries";
|
||||
import {
|
||||
bankCardSchema,
|
||||
type BankCardValues,
|
||||
bankMoneyValue,
|
||||
bankToday,
|
||||
} from "../../model/form-validation";
|
||||
import { type BankCard } from "../../api/queries";
|
||||
import { BankFeedback } from "../BankFeedback";
|
||||
import classes from "../BankForms.module.css";
|
||||
import { useBankFormFocus } from "../useBankFormFocus";
|
||||
import { BankCardFields } from "./BankCardForm.view";
|
||||
import { useBankCardFormVm } from "./BankCardForm.vm";
|
||||
|
||||
type BankCardFormProps = { card?: BankCard; onClose: () => void };
|
||||
|
||||
const BankCardForm: FC<BankCardFormProps> = (props) => {
|
||||
useBankFormFocus();
|
||||
const [opened, setOpened] = useState(true);
|
||||
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>({
|
||||
defaultValues: {
|
||||
bankName: props.card?.bankName ?? "",
|
||||
lastFour: props.card?.lastFour ?? "",
|
||||
name: props.card?.name ?? "",
|
||||
openingBalance: props.card?.openingBalance.value ?? "0",
|
||||
openingDate: props.card?.openingDate ?? bankToday(),
|
||||
paymentSystem: props.card?.paymentSystem ?? "",
|
||||
},
|
||||
resolver: zodResolver(bankCardSchema),
|
||||
});
|
||||
const isPending
|
||||
= !opened
|
||||
|| methods.formState.isSubmitting
|
||||
|| (fresh.isFetching && Boolean(error));
|
||||
const {
|
||||
dialogTitle,
|
||||
error,
|
||||
isPending,
|
||||
latest,
|
||||
methods,
|
||||
onAdoptVersion,
|
||||
onCancel,
|
||||
onReloadRecord,
|
||||
onRequestClose,
|
||||
onSubmit,
|
||||
opened,
|
||||
t,
|
||||
} = useBankCardFormVm(props);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
closeButtonProps={{ "aria-label": t("bank.close"), "disabled": isPending }}
|
||||
closeOnClickOutside={!isPending}
|
||||
closeOnEscape={!isPending}
|
||||
onClose={() => !isPending && setOpened(false)}
|
||||
onClose={onRequestClose}
|
||||
onExitTransitionEnd={props.onClose}
|
||||
opened={opened}
|
||||
title={t(props.card ? "bank.editCard" : "bank.addCard")}
|
||||
title={dialogTitle}
|
||||
>
|
||||
<FormProvider {...methods}>
|
||||
<form
|
||||
onSubmit={methods.handleSubmit(async (values) => {
|
||||
setError(undefined);
|
||||
try {
|
||||
const metadata = {
|
||||
bankName: values.bankName || /* eslint-disable-line unicorn/no-null -- PATCH uses null to clear these optional card fields. */ null,
|
||||
lastFour: values.lastFour || /* eslint-disable-line unicorn/no-null -- PATCH uses null to clear these optional card fields. */ null,
|
||||
name: values.name,
|
||||
paymentSystem: values.paymentSystem || /* eslint-disable-line unicorn/no-null -- PATCH uses null to clear these optional card fields. */ null,
|
||||
};
|
||||
const financial = {
|
||||
openingBalance: {
|
||||
currency: "RUB" as const,
|
||||
value: bankMoneyValue(values.openingBalance),
|
||||
},
|
||||
openingDate: values.openingDate,
|
||||
};
|
||||
if (props.card)
|
||||
await mutation.updateCard.mutateAsync({
|
||||
body: {
|
||||
...metadata,
|
||||
...(!props.card.archivedAt && financial),
|
||||
version,
|
||||
},
|
||||
id: props.card.id,
|
||||
});
|
||||
else
|
||||
await mutation.createCard.mutateAsync({
|
||||
id: intent,
|
||||
...metadata,
|
||||
...financial,
|
||||
});
|
||||
setOpened(false);
|
||||
}
|
||||
catch (error_) {
|
||||
setError(error_);
|
||||
}
|
||||
})}
|
||||
>
|
||||
<form onSubmit={onSubmit}>
|
||||
<fieldset className={classes.fieldset} disabled={isPending}>
|
||||
<Stack>
|
||||
<BankCardFields archived={Boolean(props.card?.archivedAt)} />
|
||||
{!!(error) && ((
|
||||
|
||||
{!!error && (
|
||||
<>
|
||||
<BankFeedback error={error} />
|
||||
|
||||
{props.card && (
|
||||
<Button
|
||||
onClick={async () => {
|
||||
const response = await fresh.refetch();
|
||||
if (response.data && !response.error)
|
||||
setLatest(response.data);
|
||||
else setError(response.error);
|
||||
}}
|
||||
variant="default"
|
||||
>
|
||||
<Button onClick={onReloadRecord} variant="default">
|
||||
{t("bank.reloadRecord")}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
))}
|
||||
)}
|
||||
|
||||
{latest && (
|
||||
<>
|
||||
<Text>
|
||||
@@ -123,23 +63,19 @@ const BankCardForm: FC<BankCardFormProps> = (props) => {
|
||||
details: `${latest.name} · ${latest.openingBalance.value} RUB · ${formatDate(latest.openingDate)}`,
|
||||
})}
|
||||
</Text>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setVersion(latest.version);
|
||||
setLatest(undefined);
|
||||
setError(undefined);
|
||||
}}
|
||||
variant="default"
|
||||
>
|
||||
|
||||
<Button onClick={onAdoptVersion} variant="default">
|
||||
{t("bank.adoptVersion", { version: latest.version })}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Group>
|
||||
<Button loading={isPending} type="submit">
|
||||
{t("bank.save")}
|
||||
</Button>
|
||||
<Button onClick={() => setOpened(false)} variant="default">
|
||||
|
||||
<Button onClick={onCancel} variant="default">
|
||||
{t("bank.cancel")}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
@@ -2,24 +2,28 @@ import type { FC } from "react";
|
||||
|
||||
import { Select, Stack, Text, TextInput } from "@mantine/core";
|
||||
import { DateInput } from "@mantine/dates";
|
||||
import { Controller, useFormContext } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import {
|
||||
type BankCardValues,
|
||||
bankDateInputValue,
|
||||
bankDateSchema,
|
||||
bankToday,
|
||||
} from "../../model/form-validation";
|
||||
import { bankToday } from "../../model/form-validation";
|
||||
import { useBankCardFieldsVm } from "./BankCardFields.vm";
|
||||
|
||||
type BankCardFieldsProps = { archived: boolean };
|
||||
|
||||
const BankCardFields: FC<BankCardFieldsProps> = (props) => {
|
||||
const {
|
||||
control,
|
||||
formState: { errors },
|
||||
dateParser,
|
||||
errors,
|
||||
onOpeningDateBlur,
|
||||
onOpeningDateChange,
|
||||
onOpeningDateInput,
|
||||
onPaymentSystemChange,
|
||||
openingDateField,
|
||||
openingDateValue,
|
||||
paymentSystemField,
|
||||
paymentSystems,
|
||||
register,
|
||||
} = useFormContext<BankCardValues>();
|
||||
const { t } = useTranslation();
|
||||
t,
|
||||
} = useBankCardFieldsVm();
|
||||
|
||||
return (
|
||||
<Stack>
|
||||
<TextInput
|
||||
@@ -28,37 +32,36 @@ const BankCardFields: FC<BankCardFieldsProps> = (props) => {
|
||||
{...register("name")}
|
||||
error={errors.name?.message}
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
label={t("bank.bankName")}
|
||||
{...register("bankName")}
|
||||
error={errors.bankName?.message}
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
inputMode="numeric"
|
||||
label={t("bank.lastFour")}
|
||||
{...register("lastFour")}
|
||||
error={errors.lastFour?.message}
|
||||
/>
|
||||
<Controller
|
||||
control={control}
|
||||
name="paymentSystem"
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
{...field}
|
||||
clearable
|
||||
comboboxProps={{ withinPortal: false }}
|
||||
data={["mir", "visa", "mastercard"].map(value => ({
|
||||
label: t(`bank.paymentSystems.${value}`),
|
||||
value,
|
||||
}))}
|
||||
error={errors.paymentSystem?.message}
|
||||
label={t("bank.paymentSystem")}
|
||||
onChange={value => field.onChange(value ?? "")}
|
||||
placeholder={t("bank.paymentSystemUnknown")}
|
||||
value={field.value || /* eslint-disable-line unicorn/no-null -- Mantine represents an empty controlled field as null. */ null}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Select
|
||||
{...paymentSystemField}
|
||||
clearable
|
||||
comboboxProps={{ withinPortal: false }}
|
||||
data={paymentSystems}
|
||||
error={errors.paymentSystem?.message}
|
||||
label={t("bank.paymentSystem")}
|
||||
onChange={onPaymentSystemChange}
|
||||
placeholder={t("bank.paymentSystemUnknown")}
|
||||
value={
|
||||
paymentSystemField.value
|
||||
// eslint-disable-next-line unicorn/no-null -- Mantine represents an empty controlled paymentSystemField as null.
|
||||
|| null
|
||||
}
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
inputMode="decimal"
|
||||
label={t("bank.openingBalance")}
|
||||
@@ -67,43 +70,31 @@ const BankCardFields: FC<BankCardFieldsProps> = (props) => {
|
||||
{...register("openingBalance")}
|
||||
error={errors.openingBalance?.message}
|
||||
/>
|
||||
<Controller
|
||||
control={control}
|
||||
name="openingDate"
|
||||
render={({ field }) => (
|
||||
<DateInput
|
||||
{...field}
|
||||
dateParser={value =>
|
||||
bankDateSchema.safeParse(bankDateInputValue(value)).success
|
||||
? bankDateInputValue(value)
|
||||
: /* eslint-disable-line unicorn/no-null -- Mantine represents an empty controlled field as null. */ null}
|
||||
error={errors.openingDate?.message}
|
||||
fixOnBlur={false}
|
||||
label={t("bank.openingDate")}
|
||||
maxDate={bankToday()}
|
||||
onBlur={(event) => {
|
||||
field.onChange(bankDateInputValue(event.currentTarget.value));
|
||||
field.onBlur();
|
||||
}}
|
||||
onChange={value => field.onChange(value ?? "")}
|
||||
onInput={event =>
|
||||
field.onChange(bankDateInputValue(event.currentTarget.value))}
|
||||
popoverProps={{
|
||||
middlewares: { shift: { crossAxis: true } },
|
||||
withinPortal: false,
|
||||
}}
|
||||
readOnly={props.archived}
|
||||
required
|
||||
value={
|
||||
(bankDateSchema.safeParse(field.value).success) ? (field.value) : undefined
|
||||
}
|
||||
valueFormat="DD.MM.YYYY"
|
||||
/>
|
||||
)}
|
||||
|
||||
<DateInput
|
||||
{...openingDateField}
|
||||
dateParser={dateParser}
|
||||
error={errors.openingDate?.message}
|
||||
fixOnBlur={false}
|
||||
label={t("bank.openingDate")}
|
||||
maxDate={bankToday()}
|
||||
onBlur={onOpeningDateBlur}
|
||||
onChange={onOpeningDateChange}
|
||||
onInput={onOpeningDateInput}
|
||||
popoverProps={{
|
||||
middlewares: { shift: { crossAxis: true } },
|
||||
withinPortal: false,
|
||||
}}
|
||||
readOnly={props.archived}
|
||||
required
|
||||
value={openingDateValue}
|
||||
valueFormat="DD.MM.YYYY"
|
||||
/>
|
||||
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("bank.openingHint")}
|
||||
</Text>
|
||||
|
||||
{props.archived && <Text>{t("bank.archiveHint")}</Text>}
|
||||
</Stack>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { useBankMutations } from "../../api/mutations";
|
||||
import { type BankCard, useBankCard } from "../../api/queries";
|
||||
import { bankMoneyValue, bankToday } from "../../model/form-validation";
|
||||
import { bankCardSchema, type BankCardValues } from "../../model/form.schema";
|
||||
import { useBankFormFocus } from "../useBankFormFocus";
|
||||
|
||||
type BankCardFormProps = { card?: BankCard; onClose: () => void };
|
||||
|
||||
function useBankCardFormVm(props: BankCardFormProps) {
|
||||
useBankFormFocus();
|
||||
const [opened, setOpened] = useState(true);
|
||||
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>({
|
||||
defaultValues: {
|
||||
bankName: props.card?.bankName ?? "",
|
||||
lastFour: props.card?.lastFour ?? "",
|
||||
name: props.card?.name ?? "",
|
||||
openingBalance: props.card?.openingBalance.value ?? "0",
|
||||
openingDate: props.card?.openingDate ?? bankToday(),
|
||||
paymentSystem: props.card?.paymentSystem ?? "",
|
||||
},
|
||||
resolver: zodResolver(bankCardSchema),
|
||||
});
|
||||
|
||||
const isPending
|
||||
= !opened
|
||||
|| methods.formState.isSubmitting
|
||||
|| (fresh.isFetching && Boolean(error));
|
||||
|
||||
const onRequestClose = () => !isPending && setOpened(false);
|
||||
const dialogTitle = t(props.card ? "bank.editCard" : "bank.addCard");
|
||||
|
||||
const onSubmit = methods.handleSubmit(async (values) => {
|
||||
setError(undefined);
|
||||
|
||||
try {
|
||||
const metadata = {
|
||||
bankName:
|
||||
values.bankName
|
||||
// eslint-disable-next-line unicorn/no-null -- PATCH uses null to clear these optional card fields.
|
||||
|| null,
|
||||
lastFour:
|
||||
values.lastFour
|
||||
// eslint-disable-next-line unicorn/no-null -- PATCH uses null to clear these optional card fields.
|
||||
|| null,
|
||||
name: values.name,
|
||||
paymentSystem:
|
||||
values.paymentSystem
|
||||
// eslint-disable-next-line unicorn/no-null -- PATCH uses null to clear these optional card fields.
|
||||
|| null,
|
||||
};
|
||||
|
||||
const financial = {
|
||||
openingBalance: {
|
||||
currency: "RUB" as const,
|
||||
value: bankMoneyValue(values.openingBalance),
|
||||
},
|
||||
openingDate: values.openingDate,
|
||||
};
|
||||
|
||||
if (props.card)
|
||||
await mutation.updateCard.mutateAsync({
|
||||
body: {
|
||||
...metadata,
|
||||
...(!props.card.archivedAt && financial),
|
||||
version,
|
||||
},
|
||||
id: props.card.id,
|
||||
});
|
||||
else
|
||||
await mutation.createCard.mutateAsync({
|
||||
id: intent,
|
||||
...metadata,
|
||||
...financial,
|
||||
});
|
||||
setOpened(false);
|
||||
}
|
||||
catch (error_) {
|
||||
setError(error_);
|
||||
}
|
||||
});
|
||||
|
||||
const onReloadRecord = async () => {
|
||||
const response = await fresh.refetch();
|
||||
if (response.data && !response.error) setLatest(response.data);
|
||||
else setError(response.error);
|
||||
};
|
||||
|
||||
const onAdoptVersion = () => {
|
||||
if (!latest) return;
|
||||
setVersion(latest.version);
|
||||
setLatest(undefined);
|
||||
setError(undefined);
|
||||
};
|
||||
|
||||
const onCancel = () => setOpened(false);
|
||||
|
||||
return {
|
||||
dialogTitle,
|
||||
error,
|
||||
isPending,
|
||||
latest,
|
||||
methods,
|
||||
onAdoptVersion,
|
||||
onCancel,
|
||||
onReloadRecord,
|
||||
onRequestClose,
|
||||
onSubmit,
|
||||
opened,
|
||||
t,
|
||||
version,
|
||||
};
|
||||
}
|
||||
|
||||
export { useBankCardFormVm };
|
||||
@@ -11,9 +11,11 @@ type BankFeedbackProps = {
|
||||
loadingError?: boolean;
|
||||
retry?: () => void;
|
||||
};
|
||||
|
||||
const BankFeedback: FC<BankFeedbackProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
const code = apiErrorCode(props.error);
|
||||
|
||||
return (
|
||||
<Alert color="orange" role="alert">
|
||||
<Group>
|
||||
@@ -26,6 +28,7 @@ const BankFeedback: FC<BankFeedbackProps> = (props) => {
|
||||
),
|
||||
})}
|
||||
</Text>
|
||||
|
||||
{props.retry && (
|
||||
<Button onClick={props.retry} variant="default">
|
||||
{t("bank.retry")}
|
||||
|
||||
@@ -1,365 +0,0 @@
|
||||
.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);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,17 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
|
||||
import { Stack } from "@mantine/core";
|
||||
import { OperationIcon } from "@wealthledger/icons";
|
||||
import { EntryCard } from "@wealthledger/ui";
|
||||
|
||||
import { BankOperationIcon } from "./BankOperationIcon";
|
||||
import { bankOperationAppearance } from "../../model/operation-appearance";
|
||||
|
||||
const BankOperationIcon = (props: {
|
||||
categoryName?: null | string;
|
||||
kind: "expense" | "refund" | "topup" | "transfer";
|
||||
}) => (
|
||||
<OperationIcon {...bankOperationAppearance(props.kind, props.categoryName)} />
|
||||
);
|
||||
|
||||
const meta = {
|
||||
args: { categoryName: "Продукты", kind: "expense" },
|
||||
@@ -11,8 +19,11 @@ const meta = {
|
||||
tags: ["autodocs"],
|
||||
title: "Product/BankCards/OperationIcons",
|
||||
} satisfies Meta<typeof BankOperationIcon>;
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Categories: Story = {
|
||||
render: () => (
|
||||
<Stack maw={640}>
|
||||
@@ -55,6 +66,7 @@ export const Categories: Story = {
|
||||
valueLabel="Расход"
|
||||
/>
|
||||
))}
|
||||
|
||||
<EntryCard
|
||||
color="green"
|
||||
icon={<BankOperationIcon kind="topup" />}
|
||||
|
||||
@@ -1,12 +1,21 @@
|
||||
import { render } from "@testing-library/react";
|
||||
import { OperationIcon } from "@wealthledger/icons";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { BankOperationIcon } from "./BankOperationIcon";
|
||||
import { bankOperationAppearance } from "../../model/operation-appearance";
|
||||
|
||||
const BankOperationIcon = (props: {
|
||||
categoryName?: null | string;
|
||||
kind: "expense" | "refund" | "topup" | "transfer";
|
||||
}) => (
|
||||
<OperationIcon {...bankOperationAppearance(props.kind, props.categoryName)} />
|
||||
);
|
||||
|
||||
it("matches normalized category names, falls back after renaming and distinguishes operation kinds", () => {
|
||||
const { container, rerender } = render(
|
||||
<BankOperationIcon categoryName="Жильё" kind="expense" />,
|
||||
);
|
||||
|
||||
// eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
|
||||
const path = () => container.querySelector("path")?.getAttribute("d");
|
||||
const housing = path();
|
||||
@@ -15,16 +24,25 @@ it("matches normalized category names, falls back after renaming and distinguish
|
||||
rerender(<BankOperationIcon categoryName="Другое" kind="expense" />);
|
||||
const fallback = path();
|
||||
expect(fallback).not.toBe(housing);
|
||||
for (const categoryName of ["Моя категория", "constructor", /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null]) {
|
||||
|
||||
for (const categoryName of [
|
||||
"Моя категория",
|
||||
"constructor",
|
||||
// eslint-disable-next-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
|
||||
null,
|
||||
]) {
|
||||
rerender(<BankOperationIcon categoryName={categoryName} kind="expense" />);
|
||||
expect(path()).toBe(fallback);
|
||||
}
|
||||
|
||||
const paths = [fallback, housing];
|
||||
|
||||
for (const kind of ["topup", "transfer", "refund"] as const) {
|
||||
rerender(<BankOperationIcon categoryName="Жильё" kind={kind} />);
|
||||
expect(path()).toBeTruthy();
|
||||
paths.push(path());
|
||||
}
|
||||
|
||||
expect(new Set(paths).size).toBe(5);
|
||||
// eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
|
||||
expect(container.querySelector("svg")).toHaveAttribute("aria-hidden", "true");
|
||||
@@ -34,8 +52,10 @@ it("provides a distinct icon for every existing named category", () => {
|
||||
const { container, rerender } = render(
|
||||
<BankOperationIcon categoryName="Другое" kind="expense" />,
|
||||
);
|
||||
|
||||
// eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
|
||||
const paths = new Set([container.querySelector("path")?.getAttribute("d")]);
|
||||
|
||||
for (const categoryName of [
|
||||
"Алкоголь",
|
||||
"Вклады",
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
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 = {
|
||||
categoryName?: null | string;
|
||||
kind: BankOperation["kind"];
|
||||
};
|
||||
const BankOperationIcon: FC<BankOperationIconProps> = (props) => {
|
||||
const icon = bankOperationAppearance(props.kind, props.categoryName);
|
||||
return (
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
className={`${classes.icon} ${icon.animation ? classes[icon.animation] : ""}`}
|
||||
fill="none"
|
||||
focusable="false"
|
||||
height="24"
|
||||
ref={bindIconAnimation}
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="1.6"
|
||||
style={{ color: `var(--mantine-color-${icon.color}-7)`, flexShrink: 0 }}
|
||||
viewBox="0 0 24 24"
|
||||
width="24"
|
||||
>
|
||||
{icon.path.split(" M").map((part, index) => (
|
||||
<path d={index ? `M${part}` : part} key={part} pathLength={1} />
|
||||
))}
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export { BankOperationIcon };
|
||||
+7
-15
@@ -1,29 +1,21 @@
|
||||
import { DatePickerInput } from "@mantine/dates";
|
||||
import { type FC, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { type FC } from "react";
|
||||
|
||||
import { useBankPeriodPickerVm } from "./BankPeriodPicker.vm";
|
||||
|
||||
type BankPeriodPickerProps = {
|
||||
onChange: (value: [null | string, null | string]) => void;
|
||||
period: { from: string; to: string };
|
||||
};
|
||||
|
||||
const BankPeriodPicker: FC<BankPeriodPickerProps> = (props) => {
|
||||
const { onChange, period } = props;
|
||||
const { t } = useTranslation();
|
||||
const scope = `${period.from}-${period.to}`;
|
||||
const [draft, setDraft] = useState<{
|
||||
scope: string;
|
||||
value: [null | string, null | string];
|
||||
}>();
|
||||
const value: [null | string, null | string]
|
||||
= draft?.scope === scope ? draft.value : [period.from, period.to];
|
||||
const { onPeriodChange, t, value } = useBankPeriodPickerVm(props);
|
||||
|
||||
return (
|
||||
<DatePickerInput
|
||||
allowSingleDateInRange
|
||||
label={t("bank.period")}
|
||||
onChange={(next) => {
|
||||
setDraft({ scope, value: next });
|
||||
onChange(next);
|
||||
}}
|
||||
onChange={onPeriodChange}
|
||||
popoverProps={{
|
||||
middlewares: { shift: { crossAxis: true } },
|
||||
returnFocus: true,
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
type BankPeriodPickerProps = {
|
||||
onChange: (value: [null | string, null | string]) => void;
|
||||
period: { from: string; to: string };
|
||||
};
|
||||
|
||||
function useBankPeriodPickerVm(props: BankPeriodPickerProps) {
|
||||
const { onChange, period } = props;
|
||||
const { t } = useTranslation();
|
||||
const scope = `${period.from}-${period.to}`;
|
||||
|
||||
const [draft, setDraft] = useState<{
|
||||
scope: string;
|
||||
value: [null | string, null | string];
|
||||
}>();
|
||||
|
||||
const value: [null | string, null | string]
|
||||
= draft?.scope === scope ? draft.value : [period.from, period.to];
|
||||
|
||||
const onPeriodChange = (next: [null | string, null | string]) => {
|
||||
setDraft({ scope, value: next });
|
||||
onChange(next);
|
||||
};
|
||||
|
||||
return { onChange, onPeriodChange, t, value };
|
||||
}
|
||||
|
||||
export { useBankPeriodPickerVm };
|
||||
@@ -3,69 +3,75 @@ import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { BankSummaryView } from "./BankSummary.view";
|
||||
|
||||
const money = (value: string) => ({ currency: "RUB", value });
|
||||
const meta = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
args: {
|
||||
data: {
|
||||
cardId: null,
|
||||
categories: [
|
||||
{
|
||||
categoryId: "food",
|
||||
categoryName: "Продукты",
|
||||
expenses: money("3500"),
|
||||
net: money("2500"),
|
||||
refunds: money("1000"),
|
||||
},
|
||||
{
|
||||
categoryId: "cafe",
|
||||
categoryName: "Кафе",
|
||||
expenses: money("2200"),
|
||||
net: money("2200"),
|
||||
refunds: money("0"),
|
||||
},
|
||||
{
|
||||
categoryId: "taxi",
|
||||
categoryName: "Такси",
|
||||
expenses: money("1800"),
|
||||
net: money("1800"),
|
||||
refunds: money("0"),
|
||||
},
|
||||
{
|
||||
categoryId: "health",
|
||||
categoryName: "Здоровье",
|
||||
expenses: money("1000"),
|
||||
net: money("1000"),
|
||||
refunds: money("0"),
|
||||
},
|
||||
],
|
||||
expenses: money("8500"),
|
||||
month: "2026-09",
|
||||
net: money("7500"),
|
||||
refunds: money("1000"),
|
||||
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
const meta
|
||||
= {
|
||||
args: {
|
||||
data: {
|
||||
cardId: null,
|
||||
categories: [
|
||||
{
|
||||
categoryId: "food",
|
||||
categoryName: "Продукты",
|
||||
expenses: money("3500"),
|
||||
net: money("2500"),
|
||||
refunds: money("1000"),
|
||||
},
|
||||
{
|
||||
categoryId: "cafe",
|
||||
categoryName: "Кафе",
|
||||
expenses: money("2200"),
|
||||
net: money("2200"),
|
||||
refunds: money("0"),
|
||||
},
|
||||
{
|
||||
categoryId: "taxi",
|
||||
categoryName: "Такси",
|
||||
expenses: money("1800"),
|
||||
net: money("1800"),
|
||||
refunds: money("0"),
|
||||
},
|
||||
{
|
||||
categoryId: "health",
|
||||
categoryName: "Здоровье",
|
||||
expenses: money("1000"),
|
||||
net: money("1000"),
|
||||
refunds: money("0"),
|
||||
},
|
||||
],
|
||||
expenses: money("8500"),
|
||||
month: "2026-09",
|
||||
net: money("7500"),
|
||||
refunds: money("1000"),
|
||||
},
|
||||
error: false,
|
||||
fetching: false,
|
||||
loading: false,
|
||||
retry: () => {},
|
||||
},
|
||||
error: false,
|
||||
fetching: false,
|
||||
loading: false,
|
||||
retry: () => {},
|
||||
},
|
||||
component: BankSummaryView,
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
"Месячные расходы ручного учёта. Вымышленные суммы, без API и сохранения. Один итог с учётом возвратов и компактные строки категорий. Отрицательные суммы сохраняют знак.",
|
||||
component: BankSummaryView,
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
"Месячные расходы ручного учёта. Вымышленные суммы, без API и сохранения. Один итог с учётом возвратов и компактные строки категорий. Отрицательные суммы сохраняют знак.",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
tags: ["autodocs"],
|
||||
title: "Product/BankCards/Summary",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */) satisfies Meta<typeof BankSummaryView>;
|
||||
tags: ["autodocs"],
|
||||
title: "Product/BankCards/Summary",
|
||||
} satisfies /* eslint-enable unicorn/no-null */ Meta<typeof BankSummaryView>;
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Loaded: Story = { name: "Расходы по категориям" };
|
||||
export const RefundMonth: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
export const RefundMonth: Story
|
||||
= {
|
||||
args: {
|
||||
data: {
|
||||
cardId: null,
|
||||
@@ -73,7 +79,7 @@ export const RefundMonth: Story = (/* eslint-disable unicorn/no-null -- Fixture
|
||||
{
|
||||
categoryId: "shopping",
|
||||
categoryName:
|
||||
"Покупки с длинным пользовательским названием категории",
|
||||
"Покупки с длинным пользовательским названием категории",
|
||||
expenses: money("0"),
|
||||
net: money("-600"),
|
||||
refunds: money("600"),
|
||||
@@ -86,10 +92,11 @@ export const RefundMonth: Story = (/* eslint-disable unicorn/no-null -- Fixture
|
||||
},
|
||||
},
|
||||
name: "Возврат покупки прошлого месяца",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
export const Empty: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
};
|
||||
/* eslint-enable unicorn/no-null */
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
export const Empty: Story
|
||||
= {
|
||||
args: {
|
||||
data: {
|
||||
cardId: null,
|
||||
@@ -101,8 +108,8 @@ export const Empty: Story = (/* eslint-disable unicorn/no-null -- Fixture preser
|
||||
},
|
||||
},
|
||||
name: "Известные нули",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
};
|
||||
/* eslint-enable unicorn/no-null */
|
||||
export const Loading: Story = {
|
||||
args: { data: undefined, loading: true },
|
||||
name: "Начальная загрузка",
|
||||
@@ -115,8 +122,9 @@ export const CachedError: Story = {
|
||||
args: { error: true },
|
||||
name: "Сохранённые суммы при ошибке обновления",
|
||||
};
|
||||
export const LongAmounts: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
export const LongAmounts: Story
|
||||
= {
|
||||
args: {
|
||||
data: {
|
||||
cardId: null,
|
||||
@@ -136,5 +144,5 @@ export const LongAmounts: Story = (/* eslint-disable unicorn/no-null -- Fixture
|
||||
},
|
||||
},
|
||||
name: "Точный итог длиннее предела отдельного ввода",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
};
|
||||
/* eslint-enable unicorn/no-null */
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { CSSProperties, FC } from "react";
|
||||
|
||||
import { Button, Group, Skeleton, Stack, Text, Title } from "@mantine/core";
|
||||
import { OperationIcon } from "@wealthledger/icons";
|
||||
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@@ -8,7 +9,7 @@ import { formatMoney } from "@/shared/lib";
|
||||
|
||||
import type { BankSummary } from "../../api/queries";
|
||||
|
||||
import { BankOperationIcon } from "../BankOperationIcon/BankOperationIcon";
|
||||
import { bankOperationAppearance } from "../../model/operation-appearance";
|
||||
import classes from "./BankSummary.module.css";
|
||||
|
||||
const CATEGORY_COLUMNS = 2;
|
||||
@@ -21,77 +22,93 @@ type BankSummaryViewProps = {
|
||||
loading: boolean;
|
||||
retry: () => void;
|
||||
};
|
||||
|
||||
const BankSummaryViewCategories: FC<BankSummaryViewProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (props.data) {
|
||||
if (props.data.categories.length > 0) {
|
||||
return (
|
||||
<dl
|
||||
className={classes.categories}
|
||||
style={
|
||||
{
|
||||
"--category-rows": Math.ceil(
|
||||
props.data.categories.length / CATEGORY_COLUMNS,
|
||||
),
|
||||
} as CSSProperties
|
||||
}
|
||||
>
|
||||
{props.data.categories.map(category => (
|
||||
<div className={classes.category} key={category.categoryId}>
|
||||
<dt className={classes.label}>
|
||||
<OperationIcon
|
||||
{...bankOperationAppearance("expense", category.categoryName)}
|
||||
/>
|
||||
|
||||
<span>{category.categoryName}</span>
|
||||
</dt>
|
||||
|
||||
<dd className={classes.amount}>
|
||||
{formatMoney(category.net, { withZeroCents: true })}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("bank.noExpenses")}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.loading) {
|
||||
return (
|
||||
<LoadingSkeleton label={t("bank.loading")}>
|
||||
<Stack gap="sm">
|
||||
<Skeleton h={32} w="35%" />
|
||||
|
||||
<Skeleton h={40} />
|
||||
|
||||
<Skeleton h={40} />
|
||||
</Stack>
|
||||
</LoadingSkeleton>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const BankSummaryView: FC<BankSummaryViewProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
function renderCategories() {
|
||||
if (props.data) {
|
||||
if (props.data.categories.length > 0) {
|
||||
return (
|
||||
<dl
|
||||
className={classes.categories}
|
||||
style={
|
||||
{
|
||||
"--category-rows": Math.ceil(props.data.categories.length / CATEGORY_COLUMNS),
|
||||
} as CSSProperties
|
||||
}
|
||||
>
|
||||
{props.data.categories.map(category => (
|
||||
<div className={classes.category} key={category.categoryId}>
|
||||
<dt className={classes.label}>
|
||||
<BankOperationIcon
|
||||
categoryName={category.categoryName}
|
||||
kind="expense"
|
||||
/>
|
||||
<span>{category.categoryName}</span>
|
||||
</dt>
|
||||
<dd className={classes.amount}>
|
||||
{formatMoney(category.net, { withZeroCents: true })}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("bank.noExpenses")}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
if (props.loading) {
|
||||
return (
|
||||
<LoadingSkeleton label={t("bank.loading")}>
|
||||
<Stack gap="sm">
|
||||
<Skeleton h={32} w="35%" />
|
||||
<Skeleton h={40} />
|
||||
<Skeleton h={40} />
|
||||
</Stack>
|
||||
</LoadingSkeleton>
|
||||
);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Stack aria-busy={props.loading || props.fetching} gap="md">
|
||||
<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>
|
||||
{renderCategories()}
|
||||
|
||||
<BankSummaryViewCategories {...props} />
|
||||
|
||||
{props.error && (
|
||||
<Group role="alert">
|
||||
<Text>{t(props.data ? "bank.refreshError" : "bank.error")}</Text>
|
||||
|
||||
<Button onClick={props.retry} variant="default">
|
||||
{t("bank.retry")}
|
||||
</Button>
|
||||
</Group>
|
||||
)}
|
||||
|
||||
{props.data && props.fetching && (
|
||||
<Text role="status">{t("bank.refreshing")}</Text>
|
||||
)}
|
||||
|
||||
@@ -23,18 +23,23 @@ describe("CategoryManager", () => {
|
||||
clear: () => {},
|
||||
refresh: () => Promise.resolve(false),
|
||||
});
|
||||
|
||||
const categories = [
|
||||
{ id: "a", isDefault: false, name: "Первая", version: 1 },
|
||||
{ id: "b", isDefault: false, name: "Вторая", version: 4 },
|
||||
];
|
||||
|
||||
let reads = 0;
|
||||
|
||||
const { promise: reloaded, resolve: release } = Promise.withResolvers<void>();
|
||||
const { promise: reloaded, resolve: release }
|
||||
= Promise.withResolvers<void>();
|
||||
|
||||
const patches: { body: unknown; id: unknown }[] = [];
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/categories", async () => {
|
||||
reads++;
|
||||
if (reads === 3) await reloaded;
|
||||
|
||||
return HttpResponse.json(
|
||||
categories.map(category =>
|
||||
category.id === "a" && reads > 1
|
||||
@@ -51,6 +56,7 @@ describe("CategoryManager", () => {
|
||||
"*/api/v1/bank-cards/categories/:id",
|
||||
async ({ params, request }) => {
|
||||
patches.push({ body: await request.json(), id: params.id });
|
||||
|
||||
return patches.length === 1
|
||||
? HttpResponse.json(
|
||||
{ code: "BANK_VERSION_CONFLICT" },
|
||||
@@ -67,7 +73,11 @@ describe("CategoryManager", () => {
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
const renameButtons = await screen.findAllByRole("button", { name: "Переименовать" });
|
||||
|
||||
const renameButtons = await screen.findAllByRole("button", {
|
||||
name: "Переименовать",
|
||||
});
|
||||
|
||||
fireEvent.click(renameButtons[0]);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
fireEvent.click(
|
||||
@@ -122,6 +132,7 @@ describe("CategoryManager", () => {
|
||||
),
|
||||
http.patch("*/api/v1/bank-cards/categories/a", () => {
|
||||
version = 2;
|
||||
|
||||
return ++writes === 1
|
||||
? HttpResponse.json(
|
||||
{ code: "BANK_VERSION_CONFLICT" },
|
||||
@@ -163,12 +174,14 @@ describe("CategoryManager", () => {
|
||||
clear: () => {},
|
||||
refresh: () => Promise.resolve(false),
|
||||
});
|
||||
|
||||
let category = {
|
||||
id: "default",
|
||||
isDefault: true,
|
||||
name: "Другое",
|
||||
version: 1,
|
||||
};
|
||||
|
||||
let creates = 0;
|
||||
let body: unknown;
|
||||
server.use(
|
||||
@@ -177,6 +190,7 @@ describe("CategoryManager", () => {
|
||||
),
|
||||
http.post("*/api/v1/bank-cards/categories", () => {
|
||||
creates++;
|
||||
|
||||
return HttpResponse.json({});
|
||||
}),
|
||||
http.patch(
|
||||
@@ -184,6 +198,7 @@ describe("CategoryManager", () => {
|
||||
async ({ request }) => {
|
||||
body = await request.json();
|
||||
category = { ...category, name: "Остальное", version: 2 };
|
||||
|
||||
return HttpResponse.json(category);
|
||||
},
|
||||
),
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
@@ -8,218 +7,148 @@ import {
|
||||
Text,
|
||||
TextInput,
|
||||
} from "@mantine/core";
|
||||
import { type FC, useRef, useState } from "react";
|
||||
import {
|
||||
Controller,
|
||||
FormProvider,
|
||||
useForm,
|
||||
useFormContext,
|
||||
} from "react-hook-form";
|
||||
import { OperationIcon } from "@wealthledger/icons";
|
||||
import { type FC } from "react";
|
||||
import { FormProvider, useController, 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 { bankOperationAppearance } from "../../model/operation-appearance";
|
||||
import { BankFeedback } from "../BankFeedback";
|
||||
import classes from "../BankForms.module.css";
|
||||
import { BankOperationIcon } from "../BankOperationIcon/BankOperationIcon";
|
||||
import { useBankFormFocus } from "../useBankFormFocus";
|
||||
|
||||
const MAX_CATEGORY_NAME_LENGTH = 80;
|
||||
import { useCategoryManagerVm } from "./CategoryManager.vm";
|
||||
|
||||
type CategoryManagerProps = {
|
||||
onClose: () => void;
|
||||
onCreated?: (id: string) => void;
|
||||
};
|
||||
|
||||
type CategoryValues = { name: string };
|
||||
|
||||
const CategoryFields: FC = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const {
|
||||
control,
|
||||
formState: { errors },
|
||||
} = useFormContext<CategoryValues>();
|
||||
|
||||
const { field: nameField } = useController({ control, name: "name" });
|
||||
|
||||
return (
|
||||
<Controller
|
||||
control={control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<TextInput
|
||||
label={t("bank.categoryName")}
|
||||
required
|
||||
{...field}
|
||||
error={errors.name?.message}
|
||||
/>
|
||||
)}
|
||||
<TextInput
|
||||
label={t("bank.categoryName")}
|
||||
required
|
||||
{...nameField}
|
||||
error={errors.name?.message}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const CategoryManager: FC<CategoryManagerProps> = (props) => {
|
||||
useBankFormFocus();
|
||||
const [opened, setOpened] = useState(true);
|
||||
const { t } = useTranslation();
|
||||
const categories = useBankCategories();
|
||||
const mutation = useBankMutations();
|
||||
const [editing, setEditing] = useState<ExpenseCategory>();
|
||||
const editSessionRef = useRef(0);
|
||||
const [error, setError] = useState<unknown>();
|
||||
const [latest, setLatest] = useState<ExpenseCategory>();
|
||||
const schema = z.object({
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.refine(
|
||||
value =>
|
||||
value.length > 0 && value.length <= MAX_CATEGORY_NAME_LENGTH,
|
||||
{ error: validationMessage("bank.validation.category") },
|
||||
)
|
||||
.refine(
|
||||
value =>
|
||||
!categories.data?.some(
|
||||
c =>
|
||||
c.id !== editing?.id
|
||||
&& c.name.toLocaleLowerCase("ru-RU")
|
||||
=== value.toLocaleLowerCase("ru-RU"),
|
||||
),
|
||||
{ error: validationMessage("bank.validation.duplicate") },
|
||||
),
|
||||
});
|
||||
const methods = useForm<CategoryValues>({ defaultValues: { name: "" }, resolver: zodResolver(schema) });
|
||||
const isPending = !opened || methods.formState.isSubmitting;
|
||||
const {
|
||||
categories,
|
||||
categoryRows,
|
||||
editing,
|
||||
error,
|
||||
isPending,
|
||||
latest,
|
||||
methods,
|
||||
onAdoptVersion,
|
||||
onCancel,
|
||||
onDismiss,
|
||||
onReloadRecord,
|
||||
onRequestClose,
|
||||
onSubmit,
|
||||
opened,
|
||||
retryCategories,
|
||||
t,
|
||||
} = useCategoryManagerVm(props);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
closeButtonProps={{ "aria-label": t("bank.close"), "disabled": isPending }}
|
||||
closeOnClickOutside={!isPending}
|
||||
closeOnEscape={!isPending}
|
||||
onClose={() => !isPending && setOpened(false)}
|
||||
onClose={onRequestClose}
|
||||
onExitTransitionEnd={props.onClose}
|
||||
opened={opened}
|
||||
title={t("bank.categories")}
|
||||
>
|
||||
<FormProvider {...methods}>
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
void methods.handleSubmit(async (values) => {
|
||||
setError(undefined);
|
||||
try {
|
||||
if (editing)
|
||||
await mutation.updateCategory.mutateAsync({
|
||||
body: { name: values.name, version: editing.version },
|
||||
id: editing.id,
|
||||
});
|
||||
else {
|
||||
const result = await mutation.createCategory.mutateAsync({
|
||||
name: values.name,
|
||||
});
|
||||
if (result) props.onCreated?.(result.id);
|
||||
}
|
||||
editSessionRef.current++;
|
||||
setEditing(undefined);
|
||||
setLatest(undefined);
|
||||
methods.reset({ name: "" });
|
||||
}
|
||||
catch (error_) {
|
||||
setError(error_);
|
||||
}
|
||||
})(event);
|
||||
}}
|
||||
>
|
||||
<form onSubmit={onSubmit}>
|
||||
<fieldset className={classes.fieldset} disabled={isPending}>
|
||||
<Stack>
|
||||
{categories.data?.map(category => (
|
||||
<Group justify="space-between" key={category.id}>
|
||||
<Group gap="xs">
|
||||
<BankOperationIcon
|
||||
categoryName={category.name}
|
||||
kind="expense"
|
||||
/>
|
||||
<Text>{category.name}</Text>
|
||||
{category.isDefault && (
|
||||
<Badge>{t("bank.defaultCategory")}</Badge>
|
||||
)}
|
||||
{categoryRows?.map((category) => {
|
||||
return (
|
||||
<Group justify="space-between" key={category.id}>
|
||||
<Group gap="xs">
|
||||
<OperationIcon
|
||||
{...bankOperationAppearance("expense", category.name)}
|
||||
/>
|
||||
|
||||
<Text>{category.name}</Text>
|
||||
|
||||
{category.isDefault && (
|
||||
<Badge>{t("bank.defaultCategory")}</Badge>
|
||||
)}
|
||||
</Group>
|
||||
|
||||
<Button onClick={category.onRename} variant="subtle">
|
||||
{t("bank.rename")}
|
||||
</Button>
|
||||
</Group>
|
||||
<Button
|
||||
onClick={() => {
|
||||
editSessionRef.current++;
|
||||
setEditing(category);
|
||||
methods.reset({ name: category.name });
|
||||
setError(undefined);
|
||||
setLatest(undefined);
|
||||
}}
|
||||
variant="subtle"
|
||||
>
|
||||
{t("bank.rename")}
|
||||
</Button>
|
||||
</Group>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
|
||||
{categories.isLoading && (
|
||||
<Text role="status">{t("bank.loading")}</Text>
|
||||
)}
|
||||
|
||||
{categories.isError && (
|
||||
<BankFeedback
|
||||
cached={Boolean(categories.data)}
|
||||
error={categories.error}
|
||||
loadingError
|
||||
retry={() => void categories.refetch()}
|
||||
retry={retryCategories}
|
||||
/>
|
||||
)}
|
||||
|
||||
<CategoryFields />
|
||||
{!!(error) && ((
|
||||
|
||||
{!!error && (
|
||||
<>
|
||||
<BankFeedback error={error} />
|
||||
|
||||
{editing && (
|
||||
<Button
|
||||
onClick={async () => {
|
||||
const session = editSessionRef.current;
|
||||
const response = await categories.refetch();
|
||||
if (session !== editSessionRef.current) return;
|
||||
if (response.error) setError(response.error);
|
||||
else
|
||||
setLatest(
|
||||
response.data?.find(c => c.id === editing.id),
|
||||
);
|
||||
}}
|
||||
variant="default"
|
||||
>
|
||||
<Button onClick={onReloadRecord} variant="default">
|
||||
{t("bank.reloadRecord")}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
))}
|
||||
)}
|
||||
|
||||
{latest && latest.id === editing?.id && (
|
||||
<>
|
||||
<Text>{t("bank.versionHint", { details: latest.name })}</Text>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setEditing(latest);
|
||||
setLatest(undefined);
|
||||
setError(undefined);
|
||||
}}
|
||||
>
|
||||
|
||||
<Button onClick={onAdoptVersion}>
|
||||
{t("bank.adoptVersion", { version: latest.version })}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Group>
|
||||
<Button loading={isPending} type="submit">
|
||||
{t(editing ? "bank.save" : "bank.addCategory")}
|
||||
</Button>
|
||||
|
||||
{editing && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
editSessionRef.current++;
|
||||
setEditing(undefined);
|
||||
setLatest(undefined);
|
||||
methods.reset({ name: "" });
|
||||
setError(undefined);
|
||||
}}
|
||||
variant="default"
|
||||
>
|
||||
<Button onClick={onCancel} variant="default">
|
||||
{t("bank.cancel")}
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={() => setOpened(false)} variant="default">
|
||||
|
||||
<Button onClick={onDismiss} variant="default">
|
||||
{t("bank.close")}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import type { ComponentProps } from "react";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useRef, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { useBankMutations } from "../../api/mutations";
|
||||
import { type ExpenseCategory, useBankCategories } from "../../api/queries";
|
||||
import { categorySchema } from "../../model/category.schema";
|
||||
import { useBankFormFocus } from "../useBankFormFocus";
|
||||
|
||||
type CategoryManagerProps = {
|
||||
onClose: () => void;
|
||||
onCreated?: (id: string) => void;
|
||||
};
|
||||
|
||||
type CategoryValues = { name: string };
|
||||
|
||||
function useCategoryManagerVm(props: CategoryManagerProps) {
|
||||
useBankFormFocus();
|
||||
const [opened, setOpened] = useState(true);
|
||||
const { t } = useTranslation();
|
||||
const categories = useBankCategories();
|
||||
const mutation = useBankMutations();
|
||||
const [editing, setEditing] = useState<ExpenseCategory>();
|
||||
const editSessionRef = useRef(0);
|
||||
const [error, setError] = useState<unknown>();
|
||||
const [latest, setLatest] = useState<ExpenseCategory>();
|
||||
const schema = categorySchema(categories.data, editing?.id);
|
||||
|
||||
const methods = useForm<CategoryValues>({
|
||||
defaultValues: { name: "" },
|
||||
resolver: zodResolver(schema),
|
||||
});
|
||||
|
||||
const isPending = !opened || methods.formState.isSubmitting;
|
||||
const onRequestClose = () => !isPending && setOpened(false);
|
||||
|
||||
const onSubmit: ComponentProps<"form">["onSubmit"] = (event) => {
|
||||
void methods.handleSubmit(async (values) => {
|
||||
setError(undefined);
|
||||
|
||||
try {
|
||||
if (editing)
|
||||
await mutation.updateCategory.mutateAsync({
|
||||
body: { name: values.name, version: editing.version },
|
||||
id: editing.id,
|
||||
});
|
||||
else {
|
||||
const result = await mutation.createCategory.mutateAsync({
|
||||
name: values.name,
|
||||
});
|
||||
|
||||
if (result) props.onCreated?.(result.id);
|
||||
}
|
||||
|
||||
editSessionRef.current++;
|
||||
setEditing(undefined);
|
||||
setLatest(undefined);
|
||||
methods.reset({ name: "" });
|
||||
}
|
||||
catch (error_) {
|
||||
setError(error_);
|
||||
}
|
||||
})(event);
|
||||
};
|
||||
|
||||
const retryCategories = () => void categories.refetch();
|
||||
|
||||
const onReloadRecord = async () => {
|
||||
if (!editing) return;
|
||||
const session = editSessionRef.current;
|
||||
const response = await categories.refetch();
|
||||
if (session !== editSessionRef.current) return;
|
||||
if (response.error) setError(response.error);
|
||||
else setLatest(response.data?.find(c => c.id === editing.id));
|
||||
};
|
||||
|
||||
const onAdoptVersion = () => {
|
||||
setEditing(latest);
|
||||
setLatest(undefined);
|
||||
setError(undefined);
|
||||
};
|
||||
|
||||
const onCancel = () => {
|
||||
editSessionRef.current++;
|
||||
setEditing(undefined);
|
||||
setLatest(undefined);
|
||||
methods.reset({ name: "" });
|
||||
setError(undefined);
|
||||
};
|
||||
|
||||
const onDismiss = () => setOpened(false);
|
||||
|
||||
const categoryRows = categories.data?.map((category) => {
|
||||
const onRename = () => {
|
||||
editSessionRef.current++;
|
||||
setEditing(category);
|
||||
methods.reset({ name: category.name });
|
||||
setError(undefined);
|
||||
setLatest(undefined);
|
||||
};
|
||||
|
||||
return { ...category, onRename };
|
||||
});
|
||||
|
||||
return {
|
||||
categories,
|
||||
categoryRows,
|
||||
editing,
|
||||
error,
|
||||
isPending,
|
||||
latest,
|
||||
methods,
|
||||
onAdoptVersion,
|
||||
onCancel,
|
||||
onDismiss,
|
||||
onReloadRecord,
|
||||
onRequestClose,
|
||||
onSubmit,
|
||||
opened,
|
||||
retryCategories,
|
||||
t,
|
||||
};
|
||||
}
|
||||
|
||||
export { useCategoryManagerVm };
|
||||
@@ -18,6 +18,7 @@ function bondQueryOptions(uid: string) {
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
};
|
||||
}
|
||||
|
||||
function useBond(identifier: string) {
|
||||
const isUid
|
||||
= /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
|
||||
@@ -28,6 +29,7 @@ function useBond(identifier: string) {
|
||||
...bondQueryOptions(identifier),
|
||||
enabled: Boolean(identifier) && isUid,
|
||||
});
|
||||
|
||||
const byTicker = useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/by-ticker/{ticker}", {
|
||||
params: { path: { ticker: identifier } },
|
||||
@@ -35,6 +37,7 @@ function useBond(identifier: string) {
|
||||
enabled: Boolean(identifier) && !isUid,
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
});
|
||||
|
||||
return isUid ? byUid : byTicker;
|
||||
}
|
||||
|
||||
@@ -47,6 +50,7 @@ function useBondCandles(uid: string, period: BondPeriod) {
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
|
||||
function useBondCoupons(uid: string) {
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
@@ -57,6 +61,7 @@ function useBondCoupons(uid: string) {
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
|
||||
function useBondMetrics(uid: string) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/metrics", {
|
||||
@@ -66,6 +71,7 @@ function useBondMetrics(uid: string) {
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
|
||||
function useBondPosition(uid: string) {
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
@@ -76,6 +82,7 @@ function useBondPosition(uid: string) {
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
|
||||
function useBondQuote(uid: string) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/quote", {
|
||||
@@ -85,6 +92,7 @@ function useBondQuote(uid: string) {
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
|
||||
function useBondSearch(query: string) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds", {
|
||||
@@ -95,7 +103,8 @@ function useBondSearch(query: string) {
|
||||
});
|
||||
}
|
||||
|
||||
export { type BondPeriod,
|
||||
export {
|
||||
type BondPeriod,
|
||||
MIN_BOND_SEARCH_LENGTH,
|
||||
useBond,
|
||||
useBondCandles,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
export { type BondPeriod,
|
||||
export {
|
||||
type BondPeriod,
|
||||
MIN_BOND_SEARCH_LENGTH,
|
||||
useBond,
|
||||
useBondCandles,
|
||||
|
||||
@@ -22,6 +22,7 @@ describe("useBrokerageOperations", () => {
|
||||
cursor: "next",
|
||||
}),
|
||||
).toEqual({ categories: ["income", "tax"], cursor: "next" });
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useBrokerageOperations("account-1", { limit: 5 }),
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
|
||||
@@ -8,7 +8,9 @@ type BrokerageOperationsQuery = Omit<
|
||||
NonNullable<OperationsEndpoint["parameters"]["query"]>,
|
||||
"sync"
|
||||
>;
|
||||
|
||||
type OperationCategory = BrokerageOperation["category"];
|
||||
|
||||
type OperationsEndpoint
|
||||
= paths["/api/v1/brokerage-accounts/{accountId}/operations"]["get"];
|
||||
|
||||
@@ -42,7 +44,11 @@ function brokerageOperationsQueryParameters(query: BrokerageOperationsQuery) {
|
||||
...(query.instrumentUid && { instrumentUid: query.instrumentUid }),
|
||||
...(query.from && { from: query.from }),
|
||||
...(query.to && { to: query.to }),
|
||||
...(query.categories?.length && { categories: query.categories.toSorted((left, right) => left.localeCompare(right)) }),
|
||||
...(query.categories?.length && {
|
||||
categories: query.categories.toSorted((left, right) =>
|
||||
left.localeCompare(right),
|
||||
),
|
||||
}),
|
||||
...(query.cursor && { cursor: query.cursor }),
|
||||
...(query.limit && { limit: query.limit }),
|
||||
};
|
||||
|
||||
@@ -22,7 +22,9 @@ const operationTransferPrefix = "OPERATION_TYPE_TRANS_";
|
||||
type PaymentPresentation = {
|
||||
amount: string;
|
||||
label: string;
|
||||
tone: "negative" | "neutral" | "positive";
|
||||
tone: "negative"
|
||||
| "neutral"
|
||||
| "positive";
|
||||
};
|
||||
|
||||
function entryLabelKey(operation: BrokerageOperation): string {
|
||||
@@ -30,6 +32,7 @@ function entryLabelKey(operation: BrokerageOperation): string {
|
||||
return isOperationType(operation.type, OperationType.Coupon)
|
||||
? "ledger.entryLabel.income.coupon"
|
||||
: "ledger.entryLabel.income.dividend";
|
||||
|
||||
return `ledger.category.${operation.category}`;
|
||||
}
|
||||
|
||||
@@ -43,19 +46,15 @@ function isZeroDecimal(value: string): boolean {
|
||||
|
||||
function operationLabelKey(type: string): string {
|
||||
if (
|
||||
[
|
||||
OperationType.Buy,
|
||||
OperationType.BuyCard,
|
||||
OperationType.BuyMargin,
|
||||
].some(candidate => isOperationType(type, candidate))
|
||||
[OperationType.Buy, OperationType.BuyCard, OperationType.BuyMargin].some(
|
||||
candidate => isOperationType(type, candidate),
|
||||
)
|
||||
)
|
||||
return "ledger.operationType.buy";
|
||||
if (
|
||||
[
|
||||
OperationType.Sell,
|
||||
OperationType.SellCard,
|
||||
OperationType.SellMargin,
|
||||
].some(candidate => isOperationType(type, candidate))
|
||||
[OperationType.Sell, OperationType.SellCard, OperationType.SellMargin].some(
|
||||
candidate => isOperationType(type, candidate),
|
||||
)
|
||||
)
|
||||
return "ledger.operationType.sell";
|
||||
if (
|
||||
@@ -72,7 +71,10 @@ function operationLabelKey(type: string): string {
|
||||
return "ledger.operationType.input";
|
||||
if (isOperationType(type, OperationType.OutputSecurities))
|
||||
return "ledger.operationType.output";
|
||||
return type.startsWith(operationTransferPrefix) ? "ledger.operationType.transfer" : "ledger.operationType.other";
|
||||
|
||||
return type.startsWith(operationTransferPrefix)
|
||||
? "ledger.operationType.transfer"
|
||||
: "ledger.operationType.other";
|
||||
}
|
||||
|
||||
function paymentPresentation(
|
||||
@@ -99,6 +101,7 @@ function paymentPresentation(
|
||||
label: entryLabelKey(operation),
|
||||
tone: "negative",
|
||||
};
|
||||
|
||||
return {
|
||||
amount: `+${formatMoney(operation.payment)}`,
|
||||
label: entryLabelKey(operation),
|
||||
|
||||
@@ -24,50 +24,59 @@ type LedgerEntryRowProps = {
|
||||
const LedgerEntryRow: FC<LedgerEntryRowProps> = (props) => {
|
||||
const { operation } = props;
|
||||
const { t } = useTranslation();
|
||||
|
||||
const instrument
|
||||
= operation.ticker ?? operation.instrumentType ?? t("ledger.noInstrument");
|
||||
|
||||
const payment = paymentPresentation(operation);
|
||||
|
||||
const metadata = [
|
||||
t("ledger.occurredAt", { date: formatSnapshotTime(operation.occurredAt) }),
|
||||
instrument,
|
||||
props.withDetails ? /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null : operation.account?.name,
|
||||
props.withDetails
|
||||
? null // eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model.
|
||||
: operation.account?.name,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
|
||||
let details;
|
||||
if (props.withDetails) {
|
||||
details = (
|
||||
<>
|
||||
<Group gap="sm">
|
||||
{operation.quantity != undefined && (
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("ledger.quantity", {
|
||||
value: formatDecimal(operation.quantity),
|
||||
})}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
{!!operation.price && (
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("ledger.price", { value: formatMoney(operation.price) })}
|
||||
</Text>
|
||||
)}
|
||||
</Group>
|
||||
|
||||
{!!operation.account && (
|
||||
<Anchor
|
||||
component={Link}
|
||||
size="sm"
|
||||
to={`/accounts/${encodeURIComponent(operation.account.id)}`}
|
||||
>
|
||||
{operation.account.name}
|
||||
</Anchor>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
else details = undefined;
|
||||
|
||||
return (
|
||||
<EntryCard
|
||||
details={
|
||||
(props.withDetails)
|
||||
? ((
|
||||
<>
|
||||
<Group gap="sm">
|
||||
{operation.quantity != undefined && ((
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("ledger.quantity", {
|
||||
value: formatDecimal(operation.quantity),
|
||||
})}
|
||||
</Text>
|
||||
))}
|
||||
{!!(operation.price) && ((
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("ledger.price", { value: formatMoney(operation.price) })}
|
||||
</Text>
|
||||
))}
|
||||
</Group>
|
||||
{!!(operation.account) && ((
|
||||
<Anchor
|
||||
component={Link}
|
||||
size="sm"
|
||||
to={`/accounts/${encodeURIComponent(operation.account.id)}`}
|
||||
>
|
||||
{operation.account.name}
|
||||
</Anchor>
|
||||
))}
|
||||
</>
|
||||
))
|
||||
: undefined
|
||||
}
|
||||
details={details}
|
||||
imageSrc={instrumentLogoUrl(operation.logoName)}
|
||||
initial={(instrument.trim()[0] ?? "?").toUpperCase()}
|
||||
metadata={metadata}
|
||||
|
||||
@@ -56,6 +56,7 @@ describe("useBrokerageAccounts", () => {
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", () => {
|
||||
calls += 1;
|
||||
|
||||
return calls === 1
|
||||
? HttpResponse.json(
|
||||
resource([
|
||||
@@ -70,6 +71,7 @@ describe("useBrokerageAccounts", () => {
|
||||
: HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 });
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useBrokerageAccounts(), {
|
||||
wrapper: createQueryWrapper().wrapper,
|
||||
});
|
||||
|
||||
@@ -7,7 +7,8 @@ const VISIBLE_CURRENCY_LIMIT = 2;
|
||||
|
||||
type BrokerageAccountCard = {
|
||||
account: BrokerageAccount;
|
||||
positionCounts: null | { bonds: number; stocks: number };
|
||||
positionCounts: null
|
||||
| { bonds: number; stocks: number };
|
||||
source?: NonNullable<
|
||||
ReturnType<typeof useBrokerageAccounts>["meta"]
|
||||
>["dependencies"] extends (infer T)[] | undefined
|
||||
@@ -38,20 +39,26 @@ function brokerageAccountCards(
|
||||
item =>
|
||||
item.resourceKey === `portfolio/${encodeURIComponent(account.id)}`,
|
||||
);
|
||||
|
||||
const summary = account.portfolioSummary;
|
||||
if (!summary)
|
||||
return {
|
||||
account,
|
||||
positionCounts: /* eslint-disable-line unicorn/no-null -- The existing formatter contract uses null for unavailable data. */ null,
|
||||
positionCounts:
|
||||
// eslint-disable-next-line unicorn/no-null -- The existing formatter contract uses null for unavailable data.
|
||||
null,
|
||||
source,
|
||||
summary: { state: "unavailable" },
|
||||
};
|
||||
|
||||
const positionCounts = {
|
||||
bonds: summary.bondPositionCount,
|
||||
stocks: summary.stockPositionCount,
|
||||
};
|
||||
|
||||
if (summary.totalsByCurrency.length === 0)
|
||||
return { account, positionCounts, source, summary: { state: "empty" } };
|
||||
|
||||
return {
|
||||
account,
|
||||
positionCounts,
|
||||
|
||||
+13
-9
@@ -64,8 +64,10 @@ export const Available: Story = {
|
||||
},
|
||||
};
|
||||
|
||||
export const Unavailable: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
export const Unavailable: Story
|
||||
= {
|
||||
args: {
|
||||
accounts: brokerageAccountCards([
|
||||
{ ...syntheticAccount, openedOn: null, portfolioSummary: null },
|
||||
@@ -76,12 +78,12 @@ export const Unavailable: Story = (/* eslint-disable unicorn/no-null -- Fixture
|
||||
docs: {
|
||||
description: {
|
||||
story:
|
||||
"Счёт остаётся доступен для открытия, даже если сводка временно недоступна. Неизвестные суммы не заменяются нулём; отсутствующая дата открытия не отображается.",
|
||||
"Счёт остаётся доступен для открытия, даже если сводка временно недоступна. Неизвестные суммы не заменяются нулём; отсутствующая дата открытия не отображается.",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
};
|
||||
/* eslint-enable unicorn/no-null */
|
||||
|
||||
export const Empty: Story = {
|
||||
args: {
|
||||
@@ -191,8 +193,10 @@ export const LargeValues: Story = {
|
||||
name: "Длинные суммы",
|
||||
};
|
||||
|
||||
export const IndependentFreshness: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
export const IndependentFreshness: Story
|
||||
= {
|
||||
args: {
|
||||
accounts: brokerageAccountCards(
|
||||
[
|
||||
@@ -231,5 +235,5 @@ export const IndependentFreshness: Story = (/* eslint-disable unicorn/no-null --
|
||||
),
|
||||
},
|
||||
name: "Независимая свежесть и ошибка сводок",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
};
|
||||
/* eslint-enable unicorn/no-null */
|
||||
|
||||
+40
-47
@@ -29,29 +29,26 @@ describe("BrokerageAccountList", () => {
|
||||
],
|
||||
},
|
||||
type: "BROKERAGE",
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
},
|
||||
{
|
||||
id: "account-2",
|
||||
name: "Недоступный",
|
||||
openedOn: null,
|
||||
portfolioSummary: null,
|
||||
type: "BROKERAGE",
|
||||
},
|
||||
/* eslint-enable unicorn/no-null */ {
|
||||
id: "account-3",
|
||||
name: "Пустой",
|
||||
openedOn: null, // eslint-disable-line unicorn/no-null -- Preserve explicit null in the API fixture.
|
||||
portfolioSummary: {
|
||||
bondPositionCount: 0,
|
||||
stockPositionCount: 2,
|
||||
totalsByCurrency: [],
|
||||
},
|
||||
type: "BROKERAGE",
|
||||
},
|
||||
(/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
id: "account-2",
|
||||
name: "Недоступный",
|
||||
openedOn: null,
|
||||
portfolioSummary: null,
|
||||
type: "BROKERAGE",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */),
|
||||
(/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
id: "account-3",
|
||||
name: "Пустой",
|
||||
openedOn: null,
|
||||
portfolioSummary: {
|
||||
bondPositionCount: 0,
|
||||
stockPositionCount: 2,
|
||||
totalsByCurrency: [],
|
||||
},
|
||||
type: "BROKERAGE",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */),
|
||||
])}
|
||||
/>
|
||||
</MemoryRouter>
|
||||
@@ -71,19 +68,11 @@ describe("BrokerageAccountList", () => {
|
||||
expect(screen.getByText("Нет текущих сумм")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("Открыть счет")).toHaveLength(3);
|
||||
const available = within(screen.getByRole("link", { name: /Основной/ }));
|
||||
expect(available.getAllByRole("definition")[0]).toHaveTextContent(
|
||||
"5",
|
||||
);
|
||||
expect(
|
||||
available.getAllByRole("definition")[1],
|
||||
).toHaveTextContent("12");
|
||||
expect(available.getAllByRole("definition")[0]).toHaveTextContent("5");
|
||||
expect(available.getAllByRole("definition")[1]).toHaveTextContent("12");
|
||||
const unvalued = within(screen.getByRole("link", { name: /Пустой/ }));
|
||||
expect(unvalued.getAllByRole("definition")[0]).toHaveTextContent(
|
||||
"2",
|
||||
);
|
||||
expect(
|
||||
unvalued.getAllByRole("definition")[1],
|
||||
).toHaveTextContent("0");
|
||||
expect(unvalued.getAllByRole("definition")[0]).toHaveTextContent("2");
|
||||
expect(unvalued.getAllByRole("definition")[1]).toHaveTextContent("0");
|
||||
expect(
|
||||
within(screen.getByRole("link", { name: /Недоступный/ })).queryByText(
|
||||
"Акции",
|
||||
@@ -94,19 +83,22 @@ describe("BrokerageAccountList", () => {
|
||||
|
||||
it("shows portfolio summary freshness independently for each account", () => {
|
||||
const accounts = brokerageAccountCards(
|
||||
["fresh", "stale"].map(id => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
id,
|
||||
name: id,
|
||||
openedOn: null,
|
||||
portfolioSummary: {
|
||||
bondPositionCount: 0,
|
||||
stockPositionCount: 1,
|
||||
totalsByCurrency: [{ currency: "RUB", value: "10" }],
|
||||
},
|
||||
type: "BROKERAGE" as const,
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */))),
|
||||
["fresh", "stale"].map(
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
id =>
|
||||
({
|
||||
id,
|
||||
name: id,
|
||||
openedOn: null,
|
||||
portfolioSummary: {
|
||||
bondPositionCount: 0,
|
||||
stockPositionCount: 1,
|
||||
totalsByCurrency: [{ currency: "RUB", value: "10" }],
|
||||
},
|
||||
type: "BROKERAGE" as const,
|
||||
}),
|
||||
/* eslint-enable unicorn/no-null */
|
||||
),
|
||||
[
|
||||
resource(null, { freshness: "fresh", resourceKey: "portfolio/fresh" })
|
||||
.meta,
|
||||
@@ -114,6 +106,7 @@ it("shows portfolio summary freshness independently for each account", () => {
|
||||
.meta,
|
||||
],
|
||||
);
|
||||
|
||||
render(
|
||||
<MantineProvider>
|
||||
<MemoryRouter>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { Card, Group, SimpleGrid, Stack, Text } from "@mantine/core";
|
||||
import { WalletIcon } from "@wealthledger/icons";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
|
||||
@@ -40,13 +41,14 @@ const BrokerageAccountSummary: FC<BrokerageAccountSummaryProps> = (props) => {
|
||||
{formatMoney(total)}
|
||||
</Text>
|
||||
))}
|
||||
{!!(summary.remainingCurrencyCount) && ((
|
||||
|
||||
{!!summary.remainingCurrencyCount && (
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("accounts.remainingCurrencies", {
|
||||
count: summary.remainingCurrencyCount,
|
||||
})}
|
||||
</Text>
|
||||
))}
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
@@ -72,76 +74,78 @@ const BrokerageAccountList: FC<BrokerageAccountListProps> = (props) => {
|
||||
<Text className={classes.kicker} fw={700} size="xs">
|
||||
{t(accountTypeKey(account.type))}
|
||||
</Text>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
className={classes.accountIcon}
|
||||
fill="none"
|
||||
focusable="false"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="1.5"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<rect height="15" rx="3" width="18" x="3" y="5" />
|
||||
<path d="M3 9h18M7 15h3M14 5V3H7a4 4 0 0 0-4 4" />
|
||||
</svg>
|
||||
|
||||
<WalletIcon className={classes.accountIcon} />
|
||||
</Group>
|
||||
|
||||
<Text className={classes.name} component="h2" fw={700}>
|
||||
{account.name}
|
||||
</Text>
|
||||
</Stack>
|
||||
|
||||
<Stack className={classes.balance} gap="xs">
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("accounts.currentValue")}
|
||||
</Text>
|
||||
|
||||
<BrokerageAccountSummary summary={summary} />
|
||||
{!!(source?.lastSuccessfulAt) && ((
|
||||
|
||||
{!!source?.lastSuccessfulAt && (
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("investment.sourceTime", {
|
||||
date: formatSnapshotTime(source.lastSuccessfulAt),
|
||||
})}
|
||||
</Text>
|
||||
))}
|
||||
)}
|
||||
|
||||
{(source?.sync.state === "running"
|
||||
|| source?.sync.state === "queued") && ((
|
||||
|| source?.sync.state === "queued") && (
|
||||
<Text role="status" size="xs">
|
||||
{t("accounts.refreshing")}
|
||||
</Text>
|
||||
))}
|
||||
{(source?.sync.state === "failed") && ((
|
||||
)}
|
||||
|
||||
{source?.sync.state === "failed" && (
|
||||
<Text size="xs">{t("accounts.refreshError")}</Text>
|
||||
))}
|
||||
{(source?.freshness === "stale") && ((
|
||||
)}
|
||||
|
||||
{source?.freshness === "stale" && (
|
||||
<Text size="xs">{t("investment.stale")}</Text>
|
||||
))}
|
||||
)}
|
||||
</Stack>
|
||||
{!!(positionCounts) && ((
|
||||
|
||||
{!!positionCounts && (
|
||||
<dl className={classes.positions}>
|
||||
<div className={classes.stocks}>
|
||||
<dt>{t("accounts.stocks")}</dt>
|
||||
|
||||
<dd>
|
||||
{new Intl.NumberFormat("ru-RU").format(positionCounts.stocks)}
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
<div className={classes.bonds}>
|
||||
<dt>{t("accounts.bonds")}</dt>
|
||||
|
||||
<dd>
|
||||
{new Intl.NumberFormat("ru-RU").format(positionCounts.bonds)}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
))}
|
||||
)}
|
||||
|
||||
<Group className={classes.footer} gap="sm" justify="space-between">
|
||||
{!!(account.openedOn) && ((
|
||||
{!!account.openedOn && (
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("accounts.openedOn", {
|
||||
date: formatDate(account.openedOn),
|
||||
})}
|
||||
</Text>
|
||||
))}
|
||||
)}
|
||||
|
||||
<Text className={classes.open} component="span" fw={600} size="sm">
|
||||
{t("accounts.openAccount")}
|
||||
|
||||
<span aria-hidden="true" className={classes.arrow}>
|
||||
→
|
||||
</span>
|
||||
|
||||
@@ -20,9 +20,11 @@ describe("useBrokerageEvents", () => {
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/events", requested),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useBrokerageEvents(undefined), {
|
||||
wrapper: createQueryWrapper().wrapper,
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.fetchStatus).toBe("idle"));
|
||||
expect(requested).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -35,7 +37,8 @@ describe("useBrokerageEvents", () => {
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts/account-1/events", () =>
|
||||
HttpResponse.json(
|
||||
resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
resource(
|
||||
{
|
||||
accountId: "account-1",
|
||||
calculatedAt: "2026-08-14T00:00:00Z",
|
||||
@@ -52,8 +55,9 @@ describe("useBrokerageEvents", () => {
|
||||
type: "dividend",
|
||||
},
|
||||
],
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */)),
|
||||
},
|
||||
/* eslint-enable unicorn/no-null */
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -63,20 +67,20 @@ describe("useBrokerageEvents", () => {
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
expect(result.current.data?.events).toEqual([
|
||||
(/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
date: "2026-09-01",
|
||||
dateKind: "registry",
|
||||
displayName: "Сбер",
|
||||
figi: "figi-1",
|
||||
instrumentUid: null,
|
||||
logoName: "sber3.png",
|
||||
projectedAmount: { currency: "RUB", value: "12.34" },
|
||||
ticker: "SBER",
|
||||
type: "dividend",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */),
|
||||
{
|
||||
date: "2026-09-01",
|
||||
dateKind: "registry",
|
||||
displayName: "Сбер",
|
||||
figi: "figi-1",
|
||||
instrumentUid: null,
|
||||
logoName: "sber3.png",
|
||||
projectedAmount: { currency: "RUB", value: "12.34" },
|
||||
ticker: "SBER",
|
||||
type: "dividend",
|
||||
},
|
||||
/* eslint-enable unicorn/no-null */
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
|
||||
type BrokerageEvent = NonNullable<
|
||||
EventsEndpoint["responses"][200]["content"]["application/json"]["data"]
|
||||
>["events"][number];
|
||||
|
||||
type EventsEndpoint
|
||||
= paths["/api/v1/brokerage-accounts/{accountId}/events"]["get"];
|
||||
|
||||
|
||||
@@ -17,13 +17,19 @@ const BrokerageEventCard: FC<BrokerageEventCardProps> = (props) => {
|
||||
|
||||
const metadata = [
|
||||
date,
|
||||
event.dateKind === "registry" ? t("events.dateKind.registry") : /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null,
|
||||
event.dateKind === "registry"
|
||||
? t("events.dateKind.registry")
|
||||
: null, // eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model.
|
||||
event.isin,
|
||||
event.account?.name,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
|
||||
const projectedAmount = event.projectedAmount
|
||||
? formatMoney(event.projectedAmount)
|
||||
: t("events.noAmount");
|
||||
|
||||
return (
|
||||
<EntryCard
|
||||
imageSrc={instrumentLogoUrl(event.logoName)}
|
||||
@@ -33,11 +39,7 @@ const BrokerageEventCard: FC<BrokerageEventCardProps> = (props) => {
|
||||
metadata={metadata}
|
||||
title={[t(`events.type.${event.type}`), event.displayName].join(" · ")}
|
||||
tone="neutral"
|
||||
value={
|
||||
event.projectedAmount
|
||||
? formatMoney(event.projectedAmount)
|
||||
: t("events.noAmount")
|
||||
}
|
||||
value={projectedAmount}
|
||||
valueLabel={t("events.projectedAmount")}
|
||||
/>
|
||||
);
|
||||
|
||||
+29
-24
@@ -6,20 +6,21 @@ import type { BrokerageEvent } from "../../api/useBrokerageEvents";
|
||||
|
||||
import { BrokerageEventsPreview } from "./BrokerageEventsPreview";
|
||||
|
||||
const syntheticEvent = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
date: "2026-10-15",
|
||||
dateKind: "event",
|
||||
displayName: "Учебные облигации",
|
||||
figi: null,
|
||||
instrumentUid: null,
|
||||
isin: "RU000A0JX0J2",
|
||||
logoName: null,
|
||||
projectedAmount: { currency: "RUB", value: "850.50" },
|
||||
ticker: "DEMO",
|
||||
type: "coupon",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */) satisfies BrokerageEvent;
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
const syntheticEvent
|
||||
= {
|
||||
date: "2026-10-15",
|
||||
dateKind: "event",
|
||||
displayName: "Учебные облигации",
|
||||
figi: null,
|
||||
instrumentUid: null,
|
||||
isin: "RU000A0JX0J2",
|
||||
logoName: null,
|
||||
projectedAmount: { currency: "RUB", value: "850.50" },
|
||||
ticker: "DEMO",
|
||||
type: "coupon",
|
||||
} satisfies /* eslint-enable unicorn/no-null */ BrokerageEvent;
|
||||
|
||||
const eventsPath = "/accounts/storybook-account/events";
|
||||
|
||||
@@ -120,8 +121,10 @@ export const Empty: Story = {
|
||||
},
|
||||
};
|
||||
|
||||
export const MissingAmount: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
export const MissingAmount: Story
|
||||
= {
|
||||
args: {
|
||||
events: {
|
||||
items: [{ ...syntheticEvent, projectedAmount: null }],
|
||||
@@ -134,22 +137,24 @@ export const MissingAmount: Story = (/* eslint-disable unicorn/no-null -- Fixtur
|
||||
docs: {
|
||||
description: {
|
||||
story:
|
||||
"Событие остаётся видимым при неизвестной ожидаемой сумме. Отсутствие оценки не подменяется нулевой выплатой.",
|
||||
"Событие остаётся видимым при неизвестной ожидаемой сумме. Отсутствие оценки не подменяется нулевой выплатой.",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
};
|
||||
/* eslint-enable unicorn/no-null */
|
||||
|
||||
export const LongEvent: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
export const LongEvent: Story
|
||||
= {
|
||||
args: {
|
||||
events: {
|
||||
items: [
|
||||
{
|
||||
...syntheticEvent,
|
||||
displayName:
|
||||
"Учебные облигации компании с очень длинным названием инструмента",
|
||||
"Учебные облигации компании с очень длинным названием инструмента",
|
||||
projectedAmount: null,
|
||||
type: "offer",
|
||||
},
|
||||
@@ -159,5 +164,5 @@ export const LongEvent: Story = (/* eslint-disable unicorn/no-null -- Fixture pr
|
||||
},
|
||||
},
|
||||
name: "Длинное название на узком экране",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
};
|
||||
/* eslint-enable unicorn/no-null */
|
||||
|
||||
@@ -24,7 +24,9 @@ type BrokerageEventsPreviewState
|
||||
state: "loaded" | "partial";
|
||||
to: string;
|
||||
}
|
||||
| { state: "empty" | "error" | "loading"; to: string };
|
||||
| { state: "empty"
|
||||
| "error"
|
||||
| "loading"; to: string; };
|
||||
|
||||
const BrokerageEventsPreview: FC<BrokerageEventsPreviewProps> = (props) => {
|
||||
const { events } = props;
|
||||
@@ -32,51 +34,60 @@ const BrokerageEventsPreview: FC<BrokerageEventsPreviewProps> = (props) => {
|
||||
|
||||
return (
|
||||
<Stack gap="sm">
|
||||
{(events.state === "loaded") && ((
|
||||
{events.state === "loaded" && (
|
||||
<>
|
||||
{!!(events.lastSuccessfulAt) && ((
|
||||
{!!events.lastSuccessfulAt && (
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("investment.sourceTime", {
|
||||
date: formatSnapshotTime(events.lastSuccessfulAt),
|
||||
})}
|
||||
</Text>
|
||||
))}
|
||||
{!!(events.stale) && (<Text size="xs">{t("investment.stale")}</Text>)}
|
||||
{!!(events.refreshError) && ((
|
||||
)}
|
||||
|
||||
{!!events.stale && <Text size="xs">{t("investment.stale")}</Text>}
|
||||
|
||||
{!!events.refreshError && (
|
||||
<Text role="status">{t("accounts.refreshError")}</Text>
|
||||
))}
|
||||
)}
|
||||
</>
|
||||
))}
|
||||
{(events.state === "loading") && ((
|
||||
)}
|
||||
|
||||
{events.state === "loading" && (
|
||||
<LoadingSkeleton label={t("events.recentLoading")}>
|
||||
{["first", "second", "third"].map(placeholder => (
|
||||
<Skeleton height={48} key={placeholder} radius="sm" />
|
||||
))}
|
||||
</LoadingSkeleton>
|
||||
))}
|
||||
{(events.state === "error") && ((
|
||||
)}
|
||||
|
||||
{events.state === "error" && (
|
||||
<Alert color="red">{t("events.recentError")}</Alert>
|
||||
))}
|
||||
{(events.state === "empty") && ((
|
||||
)}
|
||||
|
||||
{events.state === "empty" && (
|
||||
<Text c="dimmed">{t("events.recentEmpty")}</Text>
|
||||
))}
|
||||
{(events.state === "partial") && ((
|
||||
)}
|
||||
|
||||
{events.state === "partial" && (
|
||||
<Text role="status">{t("investment.partial")}</Text>
|
||||
))}
|
||||
{(events.state === "loaded" || events.state === "partial") && (events.items.map(event => (
|
||||
<BrokerageEventCard
|
||||
event={event}
|
||||
key={JSON.stringify([
|
||||
event.account?.id,
|
||||
event.type,
|
||||
event.date,
|
||||
event.instrumentUid,
|
||||
event.figi,
|
||||
event.ticker,
|
||||
event.logoName,
|
||||
])}
|
||||
/>
|
||||
)))}
|
||||
)}
|
||||
|
||||
{(events.state === "loaded" || events.state === "partial")
|
||||
&& events.items.map(event => (
|
||||
<BrokerageEventCard
|
||||
event={event}
|
||||
key={JSON.stringify([
|
||||
event.account?.id,
|
||||
event.type,
|
||||
event.date,
|
||||
event.instrumentUid,
|
||||
event.figi,
|
||||
event.ticker,
|
||||
event.logoName,
|
||||
])}
|
||||
/>
|
||||
))}
|
||||
|
||||
<Button component={Link} to={events.to} variant="subtle">
|
||||
{t("events.open")}
|
||||
</Button>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
|
||||
type IncomeAnalytics = NonNullable<
|
||||
paths["/api/v1/brokerage-accounts/{accountId}/income-analytics"]["get"]["responses"][200]["content"]["application/json"]["data"]
|
||||
>;
|
||||
|
||||
type IncomeSummary = NonNullable<
|
||||
paths["/api/v1/brokerage-accounts/{accountId}/income-summary"]["get"]["responses"][200]["content"]["application/json"]["data"]
|
||||
>;
|
||||
@@ -28,7 +29,7 @@ function useIncomeAnalytics(
|
||||
});
|
||||
}
|
||||
|
||||
function useIncomeSummary(accountId: string | undefined) {
|
||||
function useIncomeSummary(accountId?: string) {
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...apiQueryClient.queryOptions(
|
||||
|
||||
@@ -21,6 +21,7 @@ const snapshot: Portfolio = {
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
totalsByCurrency: [{ currency: "RUB", value: "123.000000001" }],
|
||||
};
|
||||
|
||||
function auth() {
|
||||
configureAuthClient({
|
||||
accessToken: () => "synthetic",
|
||||
@@ -41,6 +42,7 @@ describe("persistent resource query lifecycle", () => {
|
||||
const mode = new URL(request.url).searchParams.get("sync");
|
||||
modes.push(mode);
|
||||
if (mode) observations += 1;
|
||||
|
||||
return HttpResponse.json(
|
||||
resource(snapshot, {
|
||||
stateVersion: observations > 1 ? "new" : "old",
|
||||
@@ -76,22 +78,26 @@ describe("persistent resource query lifecycle", () => {
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => usePortfolio("a"), {
|
||||
wrapper: createQueryWrapper().wrapper,
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.meta?.sync.state).toBe("failed"));
|
||||
expect(result.current.data).toBeUndefined();
|
||||
expect(result.current.isSuccess).toBe(false);
|
||||
expect(result.current.status).toBe("pending");
|
||||
expect(result.current.isPending).toBe(true);
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
expect(result.current.transport).toEqual((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
expect(result.current.transport).toEqual(
|
||||
{
|
||||
error: null,
|
||||
fetchStatus: "idle",
|
||||
status: "success",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */));
|
||||
},
|
||||
/* eslint-enable unicorn/no-null */
|
||||
);
|
||||
expect(result.current.meta?.availability).toBe("missing");
|
||||
});
|
||||
it("keeps the refetch envelope while exposing the refreshed resource payload", async () => {
|
||||
@@ -103,9 +109,11 @@ describe("persistent resource query lifecycle", () => {
|
||||
HttpResponse.json(isReady ? refreshed : resource(null)),
|
||||
),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => usePortfolio("a"), {
|
||||
wrapper: createQueryWrapper().wrapper,
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.transport.status).toBe("success"),
|
||||
);
|
||||
@@ -130,20 +138,25 @@ describe("persistent resource query lifecycle", () => {
|
||||
it("rejects a late ordinary response when an observe response for that resource arrived first", async () => {
|
||||
auth();
|
||||
|
||||
const { promise: blocked, resolve: release } = Promise.withResolvers<void>();
|
||||
const { promise: blocked, resolve: release }
|
||||
= Promise.withResolvers<void>();
|
||||
|
||||
server.use(
|
||||
http.get(
|
||||
"*/api/v1/brokerage-accounts/:accountId/portfolio",
|
||||
async ({ request }) => {
|
||||
if (!new URL(request.url).searchParams.has("sync")) await blocked;
|
||||
|
||||
return HttpResponse.json(resource(snapshot));
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
const old = apiClient.GET(
|
||||
"/api/v1/brokerage-accounts/{accountId}/portfolio",
|
||||
{ params: { path: { accountId: "a" } } },
|
||||
);
|
||||
|
||||
// eslint-disable-next-line vitest/valid-expect -- Attach rejection handling before releasing the request; the assertion is awaited below.
|
||||
const rejected = expect(old).rejects.toMatchObject({ name: "AbortError" });
|
||||
await apiClient.GET("/api/v1/brokerage-accounts/{accountId}/portfolio", {
|
||||
@@ -156,21 +169,28 @@ describe("persistent resource query lifecycle", () => {
|
||||
auth();
|
||||
let isDenied = false;
|
||||
|
||||
const { promise: blocked, resolve: release } = Promise.withResolvers<void>();
|
||||
const { promise: blocked, resolve: release }
|
||||
= Promise.withResolvers<void>();
|
||||
|
||||
server.use(
|
||||
http.get(
|
||||
"*/api/v1/brokerage-accounts/:accountId/portfolio",
|
||||
async ({ params }) => {
|
||||
if (params.accountId === "b") await blocked;
|
||||
return isDenied && params.accountId === "a" ? HttpResponse.json({ code: "NOT_FOUND" }, { status: 404 }) : HttpResponse.json(resource(snapshot));
|
||||
|
||||
return isDenied && params.accountId === "a"
|
||||
? HttpResponse.json({ code: "NOT_FOUND" }, { status: 404 })
|
||||
: HttpResponse.json(resource(snapshot));
|
||||
},
|
||||
),
|
||||
);
|
||||
const { wrapper } = createQueryWrapper();
|
||||
|
||||
const { result } = renderHook(
|
||||
() => ({ a: usePortfolio("a"), b: usePortfolio("b") }),
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
await waitFor(() => expect(result.current.a.data).toEqual(snapshot));
|
||||
isDenied = true;
|
||||
await act(() => result.current.a.refetch());
|
||||
|
||||
@@ -16,6 +16,7 @@ describe("usePortfolio", () => {
|
||||
clear: vi.fn(),
|
||||
refresh: () => Promise.resolve(true),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => usePortfolio("account-1"), {
|
||||
wrapper: createQueryWrapper().wrapper,
|
||||
});
|
||||
@@ -34,6 +35,7 @@ describe("usePortfolio", () => {
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () => {
|
||||
calls += 1;
|
||||
|
||||
return calls === 1
|
||||
? HttpResponse.json(
|
||||
resource({
|
||||
@@ -48,6 +50,7 @@ describe("usePortfolio", () => {
|
||||
: HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 });
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => usePortfolio("account-1"), {
|
||||
wrapper: createQueryWrapper().wrapper,
|
||||
});
|
||||
|
||||
@@ -8,7 +8,7 @@ type Portfolio = NonNullable<
|
||||
paths["/api/v1/brokerage-accounts/{accountId}/portfolio"]["get"]["responses"][200]["content"]["application/json"]["data"]
|
||||
>;
|
||||
|
||||
function portfolioQueryOptions(accountId: string | undefined) {
|
||||
function portfolioQueryOptions(accountId?: string) {
|
||||
return apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/brokerage-accounts/{accountId}/portfolio",
|
||||
@@ -16,7 +16,7 @@ function portfolioQueryOptions(accountId: string | undefined) {
|
||||
);
|
||||
}
|
||||
|
||||
function usePortfolio(accountId: string | undefined) {
|
||||
function usePortfolio(accountId?: string) {
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...portfolioQueryOptions(accountId),
|
||||
|
||||
@@ -8,14 +8,22 @@ function formatShare(
|
||||
numerator: Money | null,
|
||||
denominator: Money | null,
|
||||
): null | string {
|
||||
if (!numerator || !denominator) return /* eslint-disable-line unicorn/no-null -- The existing formatter contract uses null for unavailable data. */ null;
|
||||
if (!numerator || !denominator)
|
||||
// eslint-disable-next-line unicorn/no-null -- The existing formatter contract uses null for unavailable data.
|
||||
return null;
|
||||
const total = Number(denominator.value);
|
||||
if (!Number.isFinite(total) || total <= 0) return /* eslint-disable-line unicorn/no-null -- The existing formatter contract uses null for unavailable data. */ null;
|
||||
if (!Number.isFinite(total) || total <= 0)
|
||||
// eslint-disable-next-line unicorn/no-null -- The existing formatter contract uses null for unavailable data.
|
||||
return null;
|
||||
const percent = (Number(numerator.value) / total) * PERCENT_SCALE;
|
||||
if (!Number.isFinite(percent)) return /* eslint-disable-line unicorn/no-null -- The existing formatter contract uses null for unavailable data. */ null;
|
||||
if (!Number.isFinite(percent))
|
||||
// eslint-disable-next-line unicorn/no-null -- The existing formatter contract uses null for unavailable data.
|
||||
return null;
|
||||
|
||||
const rounded = new Intl.NumberFormat("ru-RU", {
|
||||
maximumFractionDigits: 1,
|
||||
}).format(percent);
|
||||
|
||||
return `${rounded} %`;
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ function stockQueryOptions(uid: string) {
|
||||
staleTime: STOCK_STALE_TIME_MS,
|
||||
};
|
||||
}
|
||||
|
||||
function useStock(identifier: string) {
|
||||
const isUid
|
||||
= /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
|
||||
@@ -34,6 +35,7 @@ function useStock(identifier: string) {
|
||||
...stockQueryOptions(identifier),
|
||||
enabled: Boolean(identifier) && isUid,
|
||||
});
|
||||
|
||||
const byTicker = useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/by-ticker/{ticker}", {
|
||||
params: { path: { ticker: identifier } },
|
||||
@@ -41,6 +43,7 @@ function useStock(identifier: string) {
|
||||
enabled: Boolean(identifier) && !isUid,
|
||||
staleTime: STOCK_STALE_TIME_MS,
|
||||
});
|
||||
|
||||
return isUid ? byUid : byTicker;
|
||||
}
|
||||
|
||||
@@ -63,6 +66,7 @@ function useStockCompany(uid: string) {
|
||||
staleTime: STOCK_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
|
||||
function useStockDividends(uid: string) {
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
@@ -73,6 +77,7 @@ function useStockDividends(uid: string) {
|
||||
staleTime: STOCK_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
|
||||
function useStockPosition(uid: string) {
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
@@ -83,6 +88,7 @@ function useStockPosition(uid: string) {
|
||||
staleTime: STOCK_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
|
||||
function useStockQuote(uid: string) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/quote", {
|
||||
@@ -92,16 +98,23 @@ function useStockQuote(uid: string) {
|
||||
staleTime: STOCK_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
|
||||
function useStocks(uids: string[]) {
|
||||
const uniqueUids = [...new Set(uids)];
|
||||
const queries = useAuthenticatedQueries(uniqueUids.map(uniqueUid => stockQueryOptions(uniqueUid)));
|
||||
|
||||
const queries = useAuthenticatedQueries(
|
||||
uniqueUids.map(uniqueUid => stockQueryOptions(uniqueUid)),
|
||||
);
|
||||
|
||||
return new Map(
|
||||
queries.map((query, index) => [
|
||||
/* eslint-disable-line security/detect-object-injection -- This is a positional index into the local array, not a user-supplied object key. */ uniqueUids[index],
|
||||
// eslint-disable-next-line security/detect-object-injection -- This is a positional index into the local array, not a user-supplied object key.
|
||||
uniqueUids[index],
|
||||
unwrapResourceResult(query).data,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
function useStockSearch(query: string) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks", {
|
||||
@@ -112,7 +125,8 @@ function useStockSearch(query: string) {
|
||||
});
|
||||
}
|
||||
|
||||
export { MIN_STOCK_SEARCH_LENGTH,
|
||||
export {
|
||||
MIN_STOCK_SEARCH_LENGTH,
|
||||
type StockPeriod,
|
||||
useStock,
|
||||
useStockCandles,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
export { MIN_STOCK_SEARCH_LENGTH,
|
||||
export {
|
||||
MIN_STOCK_SEARCH_LENGTH,
|
||||
type StockPeriod,
|
||||
useStock,
|
||||
useStockCandles,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export { AuthProvider } from "./model/auth";
|
||||
export { useAuth } from "./model/auth-context";
|
||||
export { AuthPageLayout } from "./ui/AuthPageLayout/AuthPageLayout";
|
||||
export { LoginForm } from "./ui/LoginForm";
|
||||
export { RegisterForm } from "./ui/RegisterForm";
|
||||
export { LoginForm } from "./ui/LoginForm/LoginForm";
|
||||
export { RegisterForm } from "./ui/RegisterForm/RegisterForm";
|
||||
|
||||
@@ -11,13 +11,16 @@ type AuthContextValue = {
|
||||
register: (email: string, password: string) => Promise<void>;
|
||||
user: undefined | User;
|
||||
};
|
||||
|
||||
type User
|
||||
= paths["/api/v1/auth/me"]["get"]["responses"][200]["content"]["application/json"];
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
|
||||
|
||||
function useAuth() {
|
||||
const context = use(AuthContext);
|
||||
if (!context) throw new Error("AuthProvider is required");
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ const MAX_PASSWORD_BYTES = 72;
|
||||
|
||||
function isEmailCharacterInvalid(character: string): boolean {
|
||||
const codePoint = character.codePointAt(0);
|
||||
|
||||
return (
|
||||
/\s/.test(character)
|
||||
|| (codePoint !== undefined && codePoint < ASCII_SPACE)
|
||||
@@ -31,6 +32,7 @@ const email = z
|
||||
&& value.split("").every(element => !isEmailCharacterInvalid(element)),
|
||||
{ error: validationMessage("auth.validation.invalidEmail") },
|
||||
);
|
||||
|
||||
const password = z
|
||||
.string()
|
||||
.refine(
|
||||
@@ -45,6 +47,7 @@ const loginSchema = z.object({
|
||||
password,
|
||||
passwordConfirmation: z.string().optional(),
|
||||
});
|
||||
|
||||
const registerSchema = loginSchema.refine(
|
||||
value => value.password === value.passwordConfirmation,
|
||||
{
|
||||
@@ -17,7 +17,9 @@ const bankCardsKey = apiQueryClient.queryOptions("get", "/api/v1/bank-cards", {
|
||||
params: { query: { includeArchived: "false" } },
|
||||
}).queryKey;
|
||||
|
||||
function createAuthWrapper(queryClient: ReturnType<typeof createTestQueryClient>): FC<PropsWithChildren> {
|
||||
function createAuthWrapper(
|
||||
queryClient: ReturnType<typeof createTestQueryClient>,
|
||||
): FC<PropsWithChildren> {
|
||||
return props => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AuthProvider>{props.children}</AuthProvider>
|
||||
@@ -27,7 +29,10 @@ function createAuthWrapper(queryClient: ReturnType<typeof createTestQueryClient>
|
||||
|
||||
describe("AuthProvider", () => {
|
||||
it("authorizes requests after restoring the initial session", async () => {
|
||||
let authorization: null | string = /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null;
|
||||
let authorization: null | string
|
||||
// eslint-disable-next-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
|
||||
= null;
|
||||
|
||||
server.use(
|
||||
http.post("*/api/v1/auth/refresh", () =>
|
||||
HttpResponse.json({
|
||||
@@ -37,11 +42,13 @@ describe("AuthProvider", () => {
|
||||
),
|
||||
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
|
||||
authorization = request.headers.get("Authorization");
|
||||
|
||||
return HttpResponse.json(resource([]));
|
||||
}),
|
||||
);
|
||||
const queryClient = createTestQueryClient();
|
||||
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
|
||||
|
||||
const { rerender, result } = renderHook(
|
||||
() => ({ ...useAuth(), queryClient: useQueryClient() }),
|
||||
{ wrapper },
|
||||
@@ -80,6 +87,7 @@ describe("AuthProvider", () => {
|
||||
server.use(
|
||||
http.post("*/api/v1/auth/refresh", () => {
|
||||
refreshCalls += 1;
|
||||
|
||||
return refreshCalls === 1
|
||||
? HttpResponse.json({
|
||||
accessToken: "restored-token",
|
||||
@@ -119,15 +127,18 @@ describe("AuthProvider", () => {
|
||||
),
|
||||
);
|
||||
const queryClient = createTestQueryClient();
|
||||
|
||||
const statusKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/tbank-connection",
|
||||
).queryKey;
|
||||
|
||||
const portfolioKey = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/brokerage-accounts/{accountId}/portfolio",
|
||||
{ params: { path: { accountId: "account-1" } } },
|
||||
).queryKey;
|
||||
|
||||
queryClient.setQueryData(statusKey, {
|
||||
connected: true,
|
||||
connectedAt: "2026-08-14T00:00:00Z",
|
||||
@@ -157,7 +168,9 @@ describe("AuthProvider", () => {
|
||||
])(
|
||||
"serializes late refresh (failure=%s, login=%s)",
|
||||
async (failure, loginAfterLogout) => {
|
||||
const { promise: pending, resolve: release } = Promise.withResolvers<void>();
|
||||
const { promise: pending, resolve: release }
|
||||
= Promise.withResolvers<void>();
|
||||
|
||||
let calls = 0;
|
||||
const order: string[] = [];
|
||||
server.use(
|
||||
@@ -167,6 +180,7 @@ describe("AuthProvider", () => {
|
||||
await pending;
|
||||
order.push("refresh-cookie");
|
||||
}
|
||||
|
||||
return failure && calls > 1
|
||||
? HttpResponse.error()
|
||||
: HttpResponse.json({
|
||||
@@ -176,10 +190,12 @@ describe("AuthProvider", () => {
|
||||
}),
|
||||
http.post("*/api/v1/auth/logout", () => {
|
||||
order.push("logout-cookie");
|
||||
|
||||
return new HttpResponse(null, { status: 204 });
|
||||
}),
|
||||
http.post("*/api/v1/auth/login", () => {
|
||||
order.push("login-cookie");
|
||||
|
||||
return HttpResponse.json({
|
||||
accessToken: "b",
|
||||
user: { email: "b@example.com", id: "b" },
|
||||
@@ -193,11 +209,13 @@ describe("AuthProvider", () => {
|
||||
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
|
||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||
await waitFor(() => expect(result.current.ready).toBe(true));
|
||||
|
||||
const oldRequest = apiClient
|
||||
.GET("/api/v1/brokerage-accounts")
|
||||
|
||||
// eslint-disable-next-line unicorn/prefer-await -- Attach rejection handling before releasing the deliberately pending query.
|
||||
.catch(() => {});
|
||||
|
||||
await waitFor(() => expect(order).toContain("refresh-start"));
|
||||
let logout!: Promise<void>;
|
||||
act(() => {
|
||||
@@ -214,8 +232,14 @@ describe("AuthProvider", () => {
|
||||
release();
|
||||
await Promise.all([oldRequest, logout, login]);
|
||||
});
|
||||
expect(result.current.user?.id ?? /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null).toBe(
|
||||
loginAfterLogout ? "b" : /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null,
|
||||
expect(
|
||||
result.current.user?.id
|
||||
// eslint-disable-next-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
|
||||
?? null,
|
||||
).toBe(
|
||||
loginAfterLogout
|
||||
? "b"
|
||||
: null, // eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
|
||||
);
|
||||
expect(order).toEqual([
|
||||
"refresh-start",
|
||||
@@ -244,17 +268,20 @@ describe("AuthProvider", () => {
|
||||
await act(() => result.current.refresh());
|
||||
expect(queryClient.getQueryData(bankCardsKey)).toEqual([{ id: "a-card" }]);
|
||||
let release!: (value: string) => void;
|
||||
|
||||
const pending = queryClient
|
||||
.query({
|
||||
queryFn: () => {
|
||||
const deferred = Promise.withResolvers<string>();
|
||||
release = deferred.resolve;
|
||||
|
||||
return deferred.promise;
|
||||
},
|
||||
queryKey: ["pending-finance"],
|
||||
})
|
||||
// eslint-disable-next-line unicorn/prefer-await -- Attach rejection handling before releasing the deliberately pending query.
|
||||
.catch(() => {});
|
||||
|
||||
identity = "b";
|
||||
await act(() => result.current.refresh());
|
||||
release("a-data");
|
||||
@@ -278,6 +305,7 @@ describe("AuthProvider", () => {
|
||||
);
|
||||
const queryClient = createTestQueryClient();
|
||||
const wrapper: FC<PropsWithChildren> = createAuthWrapper(queryClient);
|
||||
|
||||
const { result } = renderHook(
|
||||
() => ({
|
||||
auth: useAuth(),
|
||||
@@ -289,6 +317,7 @@ describe("AuthProvider", () => {
|
||||
}),
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.cards.data?.[0].id).toBe("a-card"),
|
||||
);
|
||||
|
||||
@@ -1,157 +1,12 @@
|
||||
import type { FC, PropsWithChildren } from "react";
|
||||
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { apiClient, configureAuthClient, type paths } from "@/shared/api";
|
||||
|
||||
import { AuthContext, type User } from "./auth-context";
|
||||
|
||||
type Authentication
|
||||
= paths["/api/v1/auth/login"]["post"]["responses"][200]["content"]["application/json"];
|
||||
type Credentials
|
||||
= paths["/api/v1/auth/login"]["post"]["requestBody"]["content"]["application/json"];
|
||||
async function request(
|
||||
path: "/api/v1/auth/login" | "/api/v1/auth/register",
|
||||
email: string,
|
||||
password: string,
|
||||
): Promise<Authentication> {
|
||||
const { data, error } = await apiClient.POST(path, {
|
||||
body: { email, password },
|
||||
} satisfies { body: Credentials });
|
||||
// eslint-disable-next-line @typescript-eslint/only-throw-error -- Preserve generated ProblemDetails for apiErrorCode and field-error consumers.
|
||||
if (error) throw error;
|
||||
return data;
|
||||
}
|
||||
import { AuthContext } from "./auth-context";
|
||||
import { useAuthProviderVm } from "./auth.vm";
|
||||
|
||||
const AuthProvider: FC<PropsWithChildren> = (props) => {
|
||||
const { children } = props;
|
||||
const queryClient = useQueryClient();
|
||||
const [user, setUser] = useState<undefined | User>(undefined);
|
||||
const [accessToken, setAccessToken] = useState<string | undefined>(undefined);
|
||||
const accessTokenRef = useRef<string | undefined>(undefined);
|
||||
const [ready, setReady] = useState(false);
|
||||
const value = useAuthProviderVm();
|
||||
|
||||
const generationRef = useRef(0);
|
||||
const userRef = useRef<undefined | User>(undefined);
|
||||
const authQueueRef = useRef<Promise<unknown>>(Promise.resolve());
|
||||
const refreshPromiseRef = useRef<Promise<boolean> | undefined>(undefined);
|
||||
// Cookie-writing requests share ordering, including across tabs with Web Locks.
|
||||
const serialize = useCallback(<T,>(run: () => Promise<T>): Promise<T> => {
|
||||
// eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering.
|
||||
const next = authQueueRef.current.then(async () =>
|
||||
"locks" in navigator
|
||||
? navigator.locks.request("wealth-ledger-refresh", run)
|
||||
: run(),
|
||||
);
|
||||
// eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering.
|
||||
authQueueRef.current = next.catch(() => {});
|
||||
return next;
|
||||
}, []);
|
||||
const applyAuthentication = useCallback(
|
||||
(authentication: Authentication) => {
|
||||
const changedIdentity
|
||||
= userRef.current && userRef.current.id !== authentication.user.id;
|
||||
accessTokenRef.current = authentication.accessToken;
|
||||
if (changedIdentity) {
|
||||
generationRef.current += 1;
|
||||
queryClient.removeQueries({ type: "inactive" });
|
||||
queryClient.getMutationCache().clear();
|
||||
void queryClient.resetQueries();
|
||||
}
|
||||
userRef.current = authentication.user;
|
||||
setUser(authentication.user);
|
||||
setAccessToken(authentication.accessToken);
|
||||
},
|
||||
[queryClient],
|
||||
);
|
||||
const clearSession = useCallback(() => {
|
||||
generationRef.current += 1;
|
||||
userRef.current = undefined;
|
||||
setUser(undefined);
|
||||
setAccessToken(undefined);
|
||||
accessTokenRef.current = undefined;
|
||||
queryClient.clear();
|
||||
}, [queryClient]);
|
||||
|
||||
const refresh = useCallback((): Promise<boolean> => {
|
||||
if (refreshPromiseRef.current) return refreshPromiseRef.current;
|
||||
const started = generationRef.current;
|
||||
const pending = serialize(async () => {
|
||||
if (started !== generationRef.current) return false;
|
||||
try {
|
||||
const { data } = await apiClient.POST("/api/v1/auth/refresh");
|
||||
if (started !== generationRef.current) return false;
|
||||
if (!data) {
|
||||
clearSession();
|
||||
return false;
|
||||
}
|
||||
applyAuthentication(data);
|
||||
return true;
|
||||
}
|
||||
catch {
|
||||
if (started === generationRef.current) clearSession();
|
||||
return false;
|
||||
}
|
||||
// eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering.
|
||||
}).finally(() => {
|
||||
if (refreshPromiseRef.current === pending) refreshPromiseRef.current = undefined;
|
||||
});
|
||||
refreshPromiseRef.current = pending;
|
||||
return pending;
|
||||
}, [applyAuthentication, clearSession, serialize]);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh().finally(() => setReady(true));
|
||||
}, [refresh]);
|
||||
|
||||
async function authenticate(
|
||||
path: "/api/v1/auth/login" | "/api/v1/auth/register",
|
||||
email: string,
|
||||
password: string,
|
||||
) {
|
||||
clearSession();
|
||||
const started = generationRef.current;
|
||||
await serialize(async () => {
|
||||
const authentication = await request(path, email, password);
|
||||
if (started === generationRef.current) applyAuthentication(authentication);
|
||||
});
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
clearSession();
|
||||
await serialize(async () => {
|
||||
await apiClient.POST("/api/v1/auth/logout");
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
configureAuthClient({
|
||||
accessToken: () => accessTokenRef.current,
|
||||
clear: clearSession,
|
||||
generation: () => generationRef.current,
|
||||
refresh,
|
||||
});
|
||||
});
|
||||
useEffect(() => () => configureAuthClient(), []);
|
||||
|
||||
return (
|
||||
<AuthContext
|
||||
value={{
|
||||
accessToken,
|
||||
login: (email, password) =>
|
||||
authenticate("/api/v1/auth/login", email, password),
|
||||
logout,
|
||||
ready,
|
||||
refresh,
|
||||
register: (email, password) =>
|
||||
authenticate("/api/v1/auth/register", email, password),
|
||||
user,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</AuthContext>
|
||||
);
|
||||
return <AuthContext value={value}>{props.children}</AuthContext>;
|
||||
};
|
||||
|
||||
export { AuthProvider };
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { apiClient, configureAuthClient, type paths } from "@/shared/api";
|
||||
|
||||
import { type User } from "./auth-context";
|
||||
|
||||
type Authentication
|
||||
= paths["/api/v1/auth/login"]["post"]["responses"][200]["content"]["application/json"];
|
||||
|
||||
type Credentials
|
||||
= paths["/api/v1/auth/login"]["post"]["requestBody"]["content"]["application/json"];
|
||||
|
||||
async function request(
|
||||
path: "/api/v1/auth/login" | "/api/v1/auth/register",
|
||||
email: string,
|
||||
password: string,
|
||||
): Promise<Authentication> {
|
||||
const { data, error } = await apiClient.POST(path, {
|
||||
body: { email, password },
|
||||
} satisfies { body: Credentials });
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/only-throw-error -- Preserve generated ProblemDetails for apiErrorCode and field-error consumers.
|
||||
if (error) throw error;
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
function useAuthProviderVm() {
|
||||
const queryClient = useQueryClient();
|
||||
const [user, setUser] = useState<undefined | User>(undefined);
|
||||
const [accessToken, setAccessToken] = useState<string | undefined>(undefined);
|
||||
const accessTokenRef = useRef<string | undefined>(undefined);
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
const generationRef = useRef(0);
|
||||
const userRef = useRef<undefined | User>(undefined);
|
||||
const authQueueRef = useRef<Promise<unknown>>(Promise.resolve());
|
||||
const refreshPromiseRef = useRef<Promise<boolean> | undefined>(undefined);
|
||||
|
||||
// Cookie-writing requests share ordering, including across tabs with Web Locks.
|
||||
const serialize = useCallback(<T>(run: () => Promise<T>): Promise<T> => {
|
||||
// eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering.
|
||||
const next = authQueueRef.current.then(async () =>
|
||||
"locks" in navigator
|
||||
? navigator.locks.request("wealth-ledger-refresh", run)
|
||||
: run(),
|
||||
);
|
||||
|
||||
// eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering.
|
||||
authQueueRef.current = next.catch(() => {});
|
||||
|
||||
return next;
|
||||
}, []);
|
||||
|
||||
const applyAuthentication = useCallback(
|
||||
(authentication: Authentication) => {
|
||||
const changedIdentity
|
||||
= userRef.current && userRef.current.id !== authentication.user.id;
|
||||
|
||||
accessTokenRef.current = authentication.accessToken;
|
||||
|
||||
if (changedIdentity) {
|
||||
generationRef.current += 1;
|
||||
queryClient.removeQueries({ type: "inactive" });
|
||||
queryClient.getMutationCache().clear();
|
||||
void queryClient.resetQueries();
|
||||
}
|
||||
|
||||
userRef.current = authentication.user;
|
||||
setUser(authentication.user);
|
||||
setAccessToken(authentication.accessToken);
|
||||
},
|
||||
[queryClient],
|
||||
);
|
||||
|
||||
const clearSession = useCallback(() => {
|
||||
generationRef.current += 1;
|
||||
userRef.current = undefined;
|
||||
setUser(undefined);
|
||||
setAccessToken(undefined);
|
||||
accessTokenRef.current = undefined;
|
||||
queryClient.clear();
|
||||
}, [queryClient]);
|
||||
|
||||
const refresh = useCallback((): Promise<boolean> => {
|
||||
if (refreshPromiseRef.current) return refreshPromiseRef.current;
|
||||
const started = generationRef.current;
|
||||
|
||||
const pending = serialize(async () => {
|
||||
if (started !== generationRef.current) return false;
|
||||
|
||||
try {
|
||||
const { data } = await apiClient.POST("/api/v1/auth/refresh");
|
||||
if (started !== generationRef.current) return false;
|
||||
|
||||
if (!data) {
|
||||
clearSession();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
applyAuthentication(data);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch {
|
||||
if (started === generationRef.current) clearSession();
|
||||
|
||||
return false;
|
||||
}
|
||||
// eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering.
|
||||
}).finally(() => {
|
||||
if (refreshPromiseRef.current === pending)
|
||||
refreshPromiseRef.current = undefined;
|
||||
});
|
||||
|
||||
refreshPromiseRef.current = pending;
|
||||
|
||||
return pending;
|
||||
}, [applyAuthentication, clearSession, serialize]);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh().finally(() => setReady(true));
|
||||
}, [refresh]);
|
||||
|
||||
async function authenticate(
|
||||
path: "/api/v1/auth/login" | "/api/v1/auth/register",
|
||||
email: string,
|
||||
password: string,
|
||||
) {
|
||||
clearSession();
|
||||
const started = generationRef.current;
|
||||
await serialize(async () => {
|
||||
const authentication = await request(path, email, password);
|
||||
if (started === generationRef.current)
|
||||
applyAuthentication(authentication);
|
||||
});
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
clearSession();
|
||||
await serialize(async () => {
|
||||
await apiClient.POST("/api/v1/auth/logout");
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
configureAuthClient({
|
||||
accessToken: () => accessTokenRef.current,
|
||||
clear: clearSession,
|
||||
generation: () => generationRef.current,
|
||||
refresh,
|
||||
});
|
||||
});
|
||||
useEffect(() => () => configureAuthClient(), []);
|
||||
|
||||
const authContextValue = {
|
||||
accessToken,
|
||||
login: (email: string, password: string) =>
|
||||
authenticate("/api/v1/auth/login", email, password),
|
||||
logout,
|
||||
ready,
|
||||
refresh,
|
||||
register: (email: string, password: string) =>
|
||||
authenticate("/api/v1/auth/register", email, password),
|
||||
user,
|
||||
};
|
||||
|
||||
return authContextValue;
|
||||
}
|
||||
|
||||
export { useAuthProviderVm };
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
type AuthFormValues,
|
||||
loginSchema,
|
||||
registerSchema,
|
||||
} from "../../model/validation";
|
||||
} from "../../model/auth.schema";
|
||||
import classes from "./AuthForm.module.css";
|
||||
|
||||
type AuthFormProps = {
|
||||
@@ -23,26 +23,33 @@ const AuthForm: FC<AuthFormProps> = (props) => {
|
||||
const { onSubmit, register } = props;
|
||||
const { t } = useTranslation();
|
||||
const schema = register ? registerSchema : loginSchema;
|
||||
|
||||
const methods = useForm<AuthFormValues>({
|
||||
resolver: zodResolver(schema) as Resolver<AuthFormValues>,
|
||||
});
|
||||
|
||||
const {
|
||||
formState: { errors, isSubmitting },
|
||||
} = methods;
|
||||
|
||||
const [submitError, setSubmitError] = useState<null | string>(null);
|
||||
|
||||
const onSubmit2 = methods.handleSubmit(async (values) => {
|
||||
setSubmitError(null);
|
||||
|
||||
try {
|
||||
await onSubmit(values.email, values.password);
|
||||
}
|
||||
catch {
|
||||
setSubmitError(t("auth.requestError"));
|
||||
}
|
||||
});
|
||||
|
||||
const to = register ? "/login" : "/register";
|
||||
|
||||
return (
|
||||
<FormProvider {...methods}>
|
||||
<form
|
||||
onSubmit={methods.handleSubmit(async (values) => {
|
||||
setSubmitError(null);
|
||||
try {
|
||||
await onSubmit(values.email, values.password);
|
||||
}
|
||||
catch {
|
||||
setSubmitError(t("auth.requestError"));
|
||||
}
|
||||
})}
|
||||
>
|
||||
<form onSubmit={onSubmit2}>
|
||||
<fieldset className={classes.fieldset} disabled={isSubmitting}>
|
||||
<Stack>
|
||||
<TextInput
|
||||
@@ -50,11 +57,13 @@ const AuthForm: FC<AuthFormProps> = (props) => {
|
||||
{...methods.register("email")}
|
||||
error={errors.email?.message as string}
|
||||
/>
|
||||
|
||||
<PasswordInput
|
||||
label={t("auth.password")}
|
||||
{...methods.register("password")}
|
||||
error={errors.password?.message as string}
|
||||
/>
|
||||
|
||||
{register && (
|
||||
<PasswordInput
|
||||
label={t("auth.passwordConfirmation")}
|
||||
@@ -62,15 +71,14 @@ const AuthForm: FC<AuthFormProps> = (props) => {
|
||||
error={errors.passwordConfirmation?.message as string}
|
||||
/>
|
||||
)}
|
||||
|
||||
{submitError && <Alert color="red">{submitError}</Alert>}
|
||||
|
||||
<Button loading={isSubmitting} type="submit">
|
||||
{t(register ? "auth.register" : "auth.login")}
|
||||
</Button>
|
||||
<Button
|
||||
component={Link}
|
||||
to={register ? "/login" : "/register"}
|
||||
variant="subtle"
|
||||
>
|
||||
|
||||
<Button component={Link} to={to} variant="subtle">
|
||||
{t(register ? "auth.haveAccount" : "auth.noAccount")}
|
||||
</Button>
|
||||
</Stack>
|
||||
|
||||
@@ -8,11 +8,13 @@ type AuthPageLayoutProps = PropsWithChildren<{ title: string }>;
|
||||
|
||||
const AuthPageLayout: FC<AuthPageLayoutProps> = (props) => {
|
||||
const { children, title } = props;
|
||||
|
||||
return (
|
||||
<main className={classes.page}>
|
||||
<Paper className={classes.card} p="xl" radius="lg" withBorder>
|
||||
<Stack gap="lg">
|
||||
<Title order={1}>{title}</Title>
|
||||
|
||||
{children}
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { useLocation, useNavigate } from "react-router";
|
||||
|
||||
import { useAuth } from "../model/auth-context";
|
||||
import { AuthForm } from "./AuthForm/AuthForm";
|
||||
|
||||
const LoginForm: FC = () => {
|
||||
const { login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const returnTo
|
||||
= (location.state as null | { returnTo?: string })?.returnTo ?? "/accounts";
|
||||
|
||||
return (
|
||||
<AuthForm
|
||||
onSubmit={async (email, password) => {
|
||||
await login(email, password);
|
||||
await navigate(returnTo, { replace: true });
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export { LoginForm };
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { AuthForm } from "../AuthForm/AuthForm";
|
||||
import { useLoginFormVm } from "./LoginForm.vm";
|
||||
|
||||
const LoginForm: FC = () => {
|
||||
const { onSubmit } = useLoginFormVm();
|
||||
|
||||
return <AuthForm onSubmit={onSubmit} />;
|
||||
};
|
||||
|
||||
export { LoginForm };
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { ComponentProps } from "react";
|
||||
|
||||
import { useLocation, useNavigate } from "react-router";
|
||||
|
||||
import { useAuth } from "../../model/auth-context";
|
||||
import { AuthForm } from "../AuthForm/AuthForm";
|
||||
|
||||
function useLoginFormVm() {
|
||||
const { login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
|
||||
const returnTo
|
||||
= (location.state as null
|
||||
| { returnTo?: string })?.returnTo ?? "/accounts";
|
||||
|
||||
const onSubmit: ComponentProps<typeof AuthForm>["onSubmit"] = async (
|
||||
email,
|
||||
password,
|
||||
) => {
|
||||
await login(email, password);
|
||||
await navigate(returnTo, { replace: true });
|
||||
};
|
||||
|
||||
return { onSubmit };
|
||||
}
|
||||
|
||||
export { useLoginFormVm };
|
||||
@@ -1,26 +0,0 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { useLocation, useNavigate } from "react-router";
|
||||
|
||||
import { useAuth } from "../model/auth-context";
|
||||
import { AuthForm } from "./AuthForm/AuthForm";
|
||||
|
||||
const RegisterForm: FC = () => {
|
||||
const { register } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const returnTo
|
||||
= (location.state as null | { returnTo?: string })?.returnTo ?? "/accounts";
|
||||
|
||||
return (
|
||||
<AuthForm
|
||||
onSubmit={async (email, password) => {
|
||||
await register(email, password);
|
||||
await navigate(returnTo, { replace: true });
|
||||
}}
|
||||
register
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export { RegisterForm };
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { AuthForm } from "../AuthForm/AuthForm";
|
||||
import { useRegisterFormVm } from "./RegisterForm.vm";
|
||||
|
||||
const RegisterForm: FC = () => {
|
||||
const { onSubmit } = useRegisterFormVm();
|
||||
|
||||
return <AuthForm onSubmit={onSubmit} register />;
|
||||
};
|
||||
|
||||
export { RegisterForm };
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { ComponentProps } from "react";
|
||||
|
||||
import { useLocation, useNavigate } from "react-router";
|
||||
|
||||
import { useAuth } from "../../model/auth-context";
|
||||
import { AuthForm } from "../AuthForm/AuthForm";
|
||||
|
||||
function useRegisterFormVm() {
|
||||
const { register } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
|
||||
const returnTo
|
||||
= (location.state as null
|
||||
| { returnTo?: string })?.returnTo ?? "/accounts";
|
||||
|
||||
const onSubmit: ComponentProps<typeof AuthForm>["onSubmit"] = async (
|
||||
email,
|
||||
password,
|
||||
) => {
|
||||
await register(email, password);
|
||||
await navigate(returnTo, { replace: true });
|
||||
};
|
||||
|
||||
return { onSubmit, register };
|
||||
}
|
||||
|
||||
export { useRegisterFormVm };
|
||||
@@ -1,6 +1,6 @@
|
||||
export { section } from "./model/section";
|
||||
export { useInstrumentOperations } from "./model/useInstrumentOperations";
|
||||
export { InstrumentChart } from "./ui/InstrumentChart.view";
|
||||
export { InstrumentChart } from "./ui/InstrumentChart/InstrumentChart.view";
|
||||
export { InstrumentEvents } from "./ui/InstrumentEvents.view";
|
||||
export { InstrumentPosition } from "./ui/InstrumentPosition.view";
|
||||
export { InstrumentSection } from "./ui/InstrumentSection.view";
|
||||
|
||||
@@ -9,6 +9,7 @@ describe("instrument source and transport presentation", () => {
|
||||
"keeps %s separate from successful transport",
|
||||
(availability) => {
|
||||
const data = availability === "missing" ? undefined : { rows: [] };
|
||||
|
||||
const state = section({
|
||||
data,
|
||||
isError: false,
|
||||
@@ -16,6 +17,7 @@ describe("instrument source and transport presentation", () => {
|
||||
meta: resource(data, { availability }).meta,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
expect(state.loading).toBe(availability === "missing");
|
||||
expect(state.partial).toBe(availability === "partial");
|
||||
expect(state.hasData).toBe(availability !== "missing");
|
||||
@@ -24,13 +26,16 @@ describe("instrument source and transport presentation", () => {
|
||||
it("preserves a full fresh source and timestamp when force fails, while offering scoped retry", () => {
|
||||
const retry = vi.fn();
|
||||
const refetch = vi.fn();
|
||||
|
||||
const meta = resource([], {
|
||||
sync: { errorCode: "TBANK_UNAVAILABLE", id: "work", state: "failed" },
|
||||
}).meta;
|
||||
|
||||
const state = section(
|
||||
{ data: [], isError: false, isFetching: false, meta, refetch },
|
||||
retry,
|
||||
);
|
||||
|
||||
expect(state).toMatchObject({
|
||||
error: true,
|
||||
hasData: true,
|
||||
@@ -43,17 +48,16 @@ describe("instrument source and transport presentation", () => {
|
||||
expect(refetch).not.toHaveBeenCalled();
|
||||
});
|
||||
it("shows source failure without a false loading or empty result", () => {
|
||||
const state = section((
|
||||
{
|
||||
data: undefined,
|
||||
isError: false,
|
||||
isFetching: false,
|
||||
meta: resource(null, {
|
||||
sync: { errorCode: "TBANK_UNAVAILABLE", id: "work", state: "failed" },
|
||||
}).meta,
|
||||
refetch: vi.fn(),
|
||||
}
|
||||
));
|
||||
const state = section({
|
||||
data: undefined,
|
||||
isError: false,
|
||||
isFetching: false,
|
||||
meta: resource(null, {
|
||||
sync: { errorCode: "TBANK_UNAVAILABLE", id: "work", state: "failed" },
|
||||
}).meta,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
expect(state).toMatchObject({
|
||||
error: true,
|
||||
hasData: false,
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { paths } from "@/shared/api";
|
||||
|
||||
type Meta
|
||||
= paths["/api/v1/tbank-sync/{id}"]["get"]["responses"][200]["content"]["application/json"]["resources"][number];
|
||||
|
||||
type SectionState = {
|
||||
error: boolean;
|
||||
hasData: boolean;
|
||||
@@ -13,6 +14,7 @@ type SectionState = {
|
||||
sourceError?: boolean;
|
||||
stale?: boolean;
|
||||
};
|
||||
|
||||
function section(
|
||||
query: {
|
||||
data: unknown;
|
||||
@@ -24,6 +26,7 @@ function section(
|
||||
retry?: () => unknown,
|
||||
): SectionState {
|
||||
const isError = query.isError || query.meta?.sync.state === "failed";
|
||||
|
||||
return {
|
||||
error: isError,
|
||||
hasData: Boolean(query.data),
|
||||
|
||||
@@ -6,7 +6,9 @@ import type { SectionState } from "./section";
|
||||
type Candles = NonNullable<
|
||||
paths["/api/v1/stocks/{uid}/candles"]["get"]["responses"][200]["content"]["application/json"]["data"]
|
||||
>;
|
||||
|
||||
type ChartRow = Candles["candles"][number] & { date: string; price: number };
|
||||
|
||||
type InstrumentChartVm = {
|
||||
averageLine: null | number;
|
||||
candles?: Candles;
|
||||
@@ -18,6 +20,7 @@ type InstrumentChartVm = {
|
||||
priceRows: ChartRow[];
|
||||
setPeriod: (value: string) => void;
|
||||
};
|
||||
|
||||
type InstrumentEventsVm = {
|
||||
eventRows: BrokerageOperation[];
|
||||
filter: string;
|
||||
@@ -28,10 +31,12 @@ type InstrumentEventsVm = {
|
||||
operationsState: SectionState;
|
||||
setFilter: (value: string) => void;
|
||||
};
|
||||
|
||||
type InstrumentPositionVm = {
|
||||
position?: Position;
|
||||
positionState: SectionState;
|
||||
};
|
||||
|
||||
type Position = NonNullable<
|
||||
paths["/api/v1/stocks/{uid}/position"]["get"]["responses"][200]["content"]["application/json"]["data"]
|
||||
>;
|
||||
|
||||
@@ -14,19 +14,28 @@ function useInstrumentOperations(
|
||||
categories: OperationCategory[],
|
||||
) {
|
||||
const scope = `${uid}:${filter}`;
|
||||
|
||||
const [pagination, setPagination] = useState<{
|
||||
cursors: string[];
|
||||
scope: string;
|
||||
}>({ cursors: [], scope });
|
||||
|
||||
const cursors = pagination.scope === scope ? pagination.cursors : [];
|
||||
const client = useQueryClient();
|
||||
const firstPage = { categories, instrumentUid: uid, limit: 20 };
|
||||
|
||||
const operations = useBrokerageOperations(uid ? "all" : undefined, {
|
||||
...firstPage,
|
||||
cursor: cursors.at(-1),
|
||||
});
|
||||
|
||||
const retry = (retryScreen: () => unknown) => {
|
||||
if (isApiErrorCode(apiErrorCode(operations.error), ApiErrorCode.InvalidOperationsCursor)) {
|
||||
if (
|
||||
isApiErrorCode(
|
||||
apiErrorCode(operations.error),
|
||||
ApiErrorCode.InvalidOperationsCursor,
|
||||
)
|
||||
) {
|
||||
setPagination({ cursors: [], scope });
|
||||
void client.invalidateQueries({
|
||||
exact: true,
|
||||
@@ -35,6 +44,7 @@ function useInstrumentOperations(
|
||||
}
|
||||
else void retryScreen();
|
||||
};
|
||||
|
||||
return {
|
||||
hasPrevious: cursors.length > 0,
|
||||
onNext: () => {
|
||||
|
||||
@@ -1,197 +0,0 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { AreaChart } from "@mantine/charts";
|
||||
import {
|
||||
Accordion,
|
||||
Badge,
|
||||
ScrollArea,
|
||||
SegmentedControl,
|
||||
Table,
|
||||
Text,
|
||||
} from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { formatDecimal, formatMoney } from "@/shared/lib";
|
||||
|
||||
import type { InstrumentChartVm } from "../model/types";
|
||||
|
||||
import classes from "./InstrumentDetails.module.css";
|
||||
import { InstrumentSection } from "./InstrumentSection.view";
|
||||
|
||||
type InstrumentChartProps = { priceUnit?: "percent"; vm: InstrumentChartVm };
|
||||
const InstrumentChart: FC<InstrumentChartProps> = (props) => {
|
||||
const { vm } = props;
|
||||
const { t } = useTranslation();
|
||||
const priceLabel = (value: string) => {
|
||||
if (props.priceUnit === "percent") return `${formatDecimal(value)} %`;
|
||||
const currency = vm.candles?.currency;
|
||||
return formatMoney(currency ? { currency, value } : undefined);
|
||||
};
|
||||
|
||||
return (
|
||||
<InstrumentSection
|
||||
controls={(
|
||||
<div className={classes.controls}>
|
||||
<SegmentedControl
|
||||
aria-label={t("stock.period")}
|
||||
data={["month", "halfYear", "year", "all"].map(value => ({
|
||||
label: t(`stock.periods.${value}`),
|
||||
value,
|
||||
}))}
|
||||
onChange={vm.setPeriod}
|
||||
value={vm.period}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
large
|
||||
state={vm.candlesState}
|
||||
title={t("stock.chart")}
|
||||
>
|
||||
{!!(vm.candles) && ((
|
||||
vm.chartData.length > 0
|
||||
? (
|
||||
<>
|
||||
<AreaChart
|
||||
areaProps={{ isAnimationActive: false }}
|
||||
aria-label={t(
|
||||
props.priceUnit === "percent"
|
||||
? "bond.chartLabel"
|
||||
: "stock.chartLabel",
|
||||
{
|
||||
currency:
|
||||
props.priceUnit === "percent"
|
||||
? t("bond.percentOfNominal")
|
||||
: (vm.candles.currency ?? ""),
|
||||
},
|
||||
)}
|
||||
curveType="linear"
|
||||
data={vm.chartData}
|
||||
dataKey="date"
|
||||
gridAxis="y"
|
||||
h={310}
|
||||
referenceLines={
|
||||
vm.averageLine === null
|
||||
? []
|
||||
: [
|
||||
{
|
||||
color: "orange.7",
|
||||
ifOverflow: "extendDomain",
|
||||
label: t("stock.averageLine"),
|
||||
y: vm.averageLine,
|
||||
},
|
||||
]
|
||||
}
|
||||
series={[
|
||||
{ color: "blue.6", label: t("stock.price"), name: "price" },
|
||||
]}
|
||||
tickLine="none"
|
||||
tooltipAnimationDuration={0}
|
||||
valueFormatter={value =>
|
||||
new Intl.NumberFormat("ru-RU", {
|
||||
maximumFractionDigits: 4,
|
||||
}).format(value)}
|
||||
withDots={vm.chartData.length === 1}
|
||||
withGradient
|
||||
yAxisProps={{ domain: ["auto", "auto"], width: 64 }}
|
||||
/>
|
||||
<Text c="dimmed" mt="sm" size="xs">
|
||||
{t(
|
||||
props.priceUnit === "percent"
|
||||
? "bond.chartNote"
|
||||
: "stock.chartNote",
|
||||
)}
|
||||
</Text>
|
||||
{!!(vm.hasIncompleteCandle) && ((
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("stock.incomplete")}
|
||||
</Text>
|
||||
))}
|
||||
{vm.averageLine !== null && ((
|
||||
<Text mt="xs" size="sm">
|
||||
{t("stock.averageLine")}
|
||||
:
|
||||
{" "}
|
||||
{formatMoney(vm.position?.averagePurchasePrice)}
|
||||
</Text>
|
||||
))}
|
||||
<Accordion
|
||||
className={classes.priceTable}
|
||||
radius="md"
|
||||
variant="contained"
|
||||
>
|
||||
<Accordion.Item value="prices">
|
||||
<Accordion.Control>
|
||||
<Text fw={600}>{t("stock.priceTable")}</Text>
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("stock.priceTableHint", { count: vm.chartData.length })}
|
||||
</Text>
|
||||
</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<ScrollArea.Autosize
|
||||
mah={360}
|
||||
type="auto"
|
||||
viewportProps={{
|
||||
"aria-label": t("stock.priceTable"),
|
||||
"role": "region",
|
||||
"tabIndex": 0,
|
||||
}}
|
||||
>
|
||||
<Table
|
||||
highlightOnHover
|
||||
horizontalSpacing="md"
|
||||
stickyHeader
|
||||
striped
|
||||
verticalSpacing="sm"
|
||||
>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th>{t("stock.date")}</Table.Th>
|
||||
<Table.Th>{t("stock.price")}</Table.Th>
|
||||
<Table.Th>{t("stock.candle")}</Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
{vm.priceRows.map(candle => (
|
||||
<Table.Tr key={candle.time}>
|
||||
<Table.Td>{candle.date}</Table.Td>
|
||||
<Table.Td>
|
||||
{priceLabel(candle.close)}
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Badge
|
||||
color={candle.isComplete ? "gray" : "blue"}
|
||||
size="sm"
|
||||
variant="light"
|
||||
>
|
||||
{t(
|
||||
candle.isComplete
|
||||
? "stock.complete"
|
||||
: "stock.forming",
|
||||
)}
|
||||
</Badge>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
))}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
</ScrollArea.Autosize>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
</>
|
||||
)
|
||||
: (
|
||||
<Text c="dimmed">
|
||||
{t(
|
||||
vm.candlesState.partial
|
||||
? "investment.partial"
|
||||
: "stock.noCandles",
|
||||
)}
|
||||
</Text>
|
||||
)
|
||||
))}
|
||||
</InstrumentSection>
|
||||
);
|
||||
};
|
||||
|
||||
export { InstrumentChart };
|
||||
@@ -0,0 +1,195 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { AreaChart } from "@mantine/charts";
|
||||
import {
|
||||
Accordion,
|
||||
Badge,
|
||||
ScrollArea,
|
||||
SegmentedControl,
|
||||
Table,
|
||||
Text,
|
||||
} from "@mantine/core";
|
||||
|
||||
import { formatMoney } from "@/shared/lib";
|
||||
|
||||
import type { InstrumentChartVm } from "../../model/types";
|
||||
|
||||
import classes from "../InstrumentDetails.module.css";
|
||||
import { InstrumentSection } from "../InstrumentSection.view";
|
||||
import { useInstrumentChartVm } from "./InstrumentChart.vm";
|
||||
|
||||
type InstrumentChartProps = { priceUnit?: "percent"; vm: InstrumentChartVm };
|
||||
|
||||
const InstrumentChart: FC<InstrumentChartProps> = (props) => {
|
||||
const {
|
||||
chartLabel,
|
||||
formatChartValue,
|
||||
periodOptions,
|
||||
priceRows,
|
||||
referenceLines,
|
||||
t,
|
||||
vm,
|
||||
} = useInstrumentChartVm(props);
|
||||
|
||||
let chartContent;
|
||||
|
||||
if (vm.candles) {
|
||||
if (vm.chartData.length > 0) {
|
||||
chartContent = (
|
||||
<>
|
||||
<AreaChart
|
||||
areaProps={{ isAnimationActive: false }}
|
||||
aria-label={chartLabel}
|
||||
curveType="linear"
|
||||
data={vm.chartData}
|
||||
dataKey="date"
|
||||
gridAxis="y"
|
||||
h={310}
|
||||
referenceLines={referenceLines}
|
||||
series={[
|
||||
{ color: "blue.6", label: t("stock.price"), name: "price" },
|
||||
]}
|
||||
tickLine="none"
|
||||
tooltipAnimationDuration={0}
|
||||
valueFormatter={formatChartValue}
|
||||
withDots={vm.chartData.length === 1}
|
||||
withGradient
|
||||
yAxisProps={{ domain: ["auto", "auto"], width: 64 }}
|
||||
/>
|
||||
|
||||
<Text c="dimmed" mt="sm" size="xs">
|
||||
{t(
|
||||
props.priceUnit === "percent"
|
||||
? "bond.chartNote"
|
||||
: "stock.chartNote",
|
||||
)}
|
||||
</Text>
|
||||
|
||||
{!!vm.hasIncompleteCandle && (
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("stock.incomplete")}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
{vm.averageLine !== null && (
|
||||
<Text mt="xs" size="sm">
|
||||
{t("stock.averageLine")}:{" "}
|
||||
{formatMoney(vm.position?.averagePurchasePrice)}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
<Accordion
|
||||
className={classes.priceTable}
|
||||
radius="md"
|
||||
variant="contained"
|
||||
>
|
||||
<Accordion.Item value="prices">
|
||||
<Accordion.Control>
|
||||
<Text fw={600}>{t("stock.priceTable")}</Text>
|
||||
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("stock.priceTableHint", { count: vm.chartData.length })}
|
||||
</Text>
|
||||
</Accordion.Control>
|
||||
|
||||
<Accordion.Panel>
|
||||
<ScrollArea.Autosize
|
||||
mah={360}
|
||||
type="auto"
|
||||
viewportProps={{
|
||||
"aria-label": t("stock.priceTable"),
|
||||
"role": "region",
|
||||
"tabIndex": 0,
|
||||
}}
|
||||
>
|
||||
<Table
|
||||
highlightOnHover
|
||||
horizontalSpacing="md"
|
||||
stickyHeader
|
||||
striped
|
||||
verticalSpacing="sm"
|
||||
>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th>{t("stock.date")}</Table.Th>
|
||||
|
||||
<Table.Th>{t("stock.price")}</Table.Th>
|
||||
|
||||
<Table.Th>{t("stock.candle")}</Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
|
||||
<Table.Tbody>
|
||||
{priceRows.map((candle) => {
|
||||
const displayColor = candle.isComplete
|
||||
? "gray"
|
||||
: "blue";
|
||||
|
||||
return (
|
||||
<Table.Tr key={candle.time}>
|
||||
<Table.Td>{candle.date}</Table.Td>
|
||||
|
||||
<Table.Td>
|
||||
{candle.price}
|
||||
</Table.Td>
|
||||
|
||||
<Table.Td>
|
||||
<Badge
|
||||
color={displayColor}
|
||||
size="sm"
|
||||
variant="light"
|
||||
>
|
||||
{t(
|
||||
candle.isComplete
|
||||
? "stock.complete"
|
||||
: "stock.forming",
|
||||
)}
|
||||
</Badge>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
);
|
||||
})}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
</ScrollArea.Autosize>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
</>
|
||||
);
|
||||
}
|
||||
else {
|
||||
chartContent = (
|
||||
<Text c="dimmed">
|
||||
{t(
|
||||
vm.candlesState.partial
|
||||
? "investment.partial"
|
||||
: "stock.noCandles",
|
||||
)}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<InstrumentSection
|
||||
controls={(
|
||||
<div className={classes.controls}>
|
||||
<SegmentedControl
|
||||
aria-label={t("stock.period")}
|
||||
data={periodOptions}
|
||||
onChange={vm.setPeriod}
|
||||
value={vm.period}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
large
|
||||
state={vm.candlesState}
|
||||
title={t("stock.chart")}
|
||||
>
|
||||
{chartContent}
|
||||
</InstrumentSection>
|
||||
);
|
||||
};
|
||||
|
||||
export { InstrumentChart };
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user