chore: finish frontend ESLint migration #18

Enable every plugin recommended preset and replace Biome with ESLint formatting.

Preserve API contracts and JSX whitespace; verify source, tests, builds and tooling.
This commit is contained in:
2026-09-28 16:36:40 +03:00
committed by ksv741
parent 57630102e4
commit 72d7835227
253 changed files with 10059 additions and 8864 deletions
@@ -1,8 +1,9 @@
import type { FC } from "react";
import { MantineProvider } from "@mantine/core";
import { QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import type { FC } from "react";
import { http, HttpResponse } from "msw";
import {
MemoryRouter,
Route,
@@ -11,6 +12,7 @@ import {
useNavigate,
} from "react-router";
import { describe, expect, it, vi } from "vitest";
import {
type BrokerageOperation,
LedgerEntryRow,
@@ -19,25 +21,28 @@ import { configureAuthClient } from "@/shared/api";
import { createTestQueryClient } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server";
import { AccountOperationsPage } from "./AccountOperationsPage";
const operation: BrokerageOperation = {
id: "operation-1",
occurredAt: "2026-08-14T10:00:00Z",
type: "OPERATION_TYPE_BUY",
category: "trade",
description: "Покупка акций",
figi: null,
instrumentUid: null,
ticker: "SBER",
instrumentType: "share",
logoName: null,
payment: null,
quantity: "2",
price: { currency: "RUB", value: "100" },
accruedInterest: null,
commission: { currency: "RUB", value: "1" },
};
const operation: BrokerageOperation = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
accruedInterest: null,
category: "trade",
commission: { currency: "RUB", value: "1" },
description: "Покупка акций",
figi: null,
id: "operation-1",
instrumentType: "share",
instrumentUid: null,
logoName: null,
occurredAt: "2026-08-14T10:00:00Z",
payment: null,
price: { currency: "RUB", value: "100" },
quantity: "2",
ticker: "SBER",
type: "OPERATION_TYPE_BUY",
}
/* eslint-enable unicorn/no-null */);
const Navigation: FC = () => {
const location = useLocation();
@@ -45,10 +50,10 @@ const Navigation: FC = () => {
return (
<>
<output aria-label="URL">{location.search}</output>
<button type="button" onClick={() => navigate(-1)}>
<button onClick={() => navigate(-1)} type="button">
History back
</button>
<button type="button" onClick={() => navigate(1)}>
<button onClick={() => navigate(1)} type="button">
History forward
</button>
</>
@@ -58,8 +63,8 @@ const Navigation: FC = () => {
function configureTestAuth() {
configureAuthClient({
accessToken: () => "token",
refresh: async () => true,
clear: vi.fn(),
refresh: () => Promise.resolve(true),
});
}
@@ -72,8 +77,8 @@ function renderPage(search = "") {
>
<Routes>
<Route
path="/accounts/:accountId/operations"
element={<AccountOperationsPage />}
path="/accounts/:accountId/operations"
/>
</Routes>
</MemoryRouter>
@@ -95,9 +100,9 @@ describe("LedgerEntryRow", () => {
expect(screen.getByText("Без движения денег")).toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "Показать детали" }),
).toBeNull();
expect(screen.queryByText("Цена: 100 ₽")).toBeNull();
expect(screen.queryByText("Количество: 2")).toBeNull();
).not.toBeInTheDocument();
expect(screen.queryByText("Цена: 100 ₽")).not.toBeInTheDocument();
expect(screen.queryByText("Количество: 2")).not.toBeInTheDocument();
});
it("labels a positive payment with its category type", () => {
@@ -125,9 +130,9 @@ describe("LedgerEntryRow", () => {
<LedgerEntryRow
operation={{
...operation,
type: "OPERATION_TYPE_COUPON",
category: "income",
payment: { currency: "RUB", value: "8" },
type: "OPERATION_TYPE_COUPON",
}}
/>
</MemoryRouter>
@@ -145,9 +150,9 @@ describe("LedgerEntryRow", () => {
<LedgerEntryRow
operation={{
...operation,
type: "OPERATION_TYPE_DIVIDEND",
category: "income",
payment: { currency: "RUB", value: "20" },
type: "OPERATION_TYPE_DIVIDEND",
}}
/>
</MemoryRouter>
@@ -165,9 +170,9 @@ describe("LedgerEntryRow", () => {
<LedgerEntryRow
operation={{
...operation,
type: "OPERATION_TYPE_SERVICE_FEE",
category: "fee",
payment: { currency: "RUB", value: "-3" },
type: "OPERATION_TYPE_SERVICE_FEE",
}}
/>
</MemoryRouter>
@@ -193,7 +198,7 @@ describe("LedgerEntryRow", () => {
);
expect(screen.getByText("Без движения денег")).toBeInTheDocument();
expect(screen.queryByText("Сделка")).toBeNull();
expect(screen.queryByText("Сделка")).not.toBeInTheDocument();
});
it("uses an instrument initial when the ledger entry has no logo", () => {
@@ -222,9 +227,9 @@ describe("AccountOperationsPage", () => {
searches.push(new URL(request.url).searchParams);
return HttpResponse.json(
resource({
hasNext: true,
items: [operation],
nextCursor: "next",
hasNext: true,
}),
);
},
@@ -234,20 +239,20 @@ describe("AccountOperationsPage", () => {
<QueryClientProvider client={createTestQueryClient()}>
<MantineProvider env="test">
<MemoryRouter
initialIndex={0}
initialEntries={[
"?from=bad&to=2026-02-28&categories=trade",
"?from=2026-02-30&categories=trade",
"?from=2026-03-01&to=2026-02-28&categories=trade",
"?from=2026-02-01&categories=trade",
"?to=2026-02-28&categories=trade",
].map((search) => `/accounts/${accountId}/operations${search}`)}
].map(search => `/accounts/${accountId}/operations${search}`)}
initialIndex={0}
>
<Navigation />
<Routes>
<Route
path="/accounts/:accountId/operations"
element={<AccountOperationsPage />}
path="/accounts/:accountId/operations"
/>
</Routes>
</MemoryRouter>
@@ -266,6 +271,7 @@ describe("AccountOperationsPage", () => {
screen.getByRole("button", { name: "History forward" }),
);
await waitFor(() =>
// eslint-disable-next-line jest-dom/prefer-to-have-text-content -- URL history requires exact equality, including empty search.
expect(screen.getByLabelText("URL").textContent).toBe(expected),
);
await screen.findByLabelText("Период");
@@ -287,11 +293,11 @@ describe("AccountOperationsPage", () => {
expect(screen.getByLabelText("Период")).toHaveTextContent("01.02.2026"),
);
expect(screen.getByRole("button", { name: "Назад" })).toBeDisabled();
expect(searches.map((query) => query.get("from"))).not.toContain(
expect(searches.map(query => query.get("from"))).not.toContain(
"badT00:00:00.000Z",
);
expect(
searches.every((query) => query.get("categories") === "trade"),
searches.every(query => query.get("categories") === "trade"),
).toBe(true);
},
);
@@ -307,7 +313,9 @@ describe("AccountOperationsPage", () => {
new URL(request.url).searchParams.has("from")
? HttpResponse.json({ code: "VALIDATION_ERROR" }, { status: 400 })
: HttpResponse.json(
resource({ items: [], hasNext: false, nextCursor: null }),
resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{ hasNext: false, items: [], nextCursor: null }
/* eslint-enable unicorn/no-null */)),
),
),
);
@@ -322,8 +330,8 @@ describe("AccountOperationsPage", () => {
<Navigation />
<Routes>
<Route
path="/accounts/:accountId/operations"
element={<AccountOperationsPage />}
path="/accounts/:accountId/operations"
/>
</Routes>
</MemoryRouter>
@@ -333,7 +341,7 @@ describe("AccountOperationsPage", () => {
await screen.findByRole("button", { name: "Повторить" });
fireEvent.click(screen.getByRole("button", { name: "Сбросить" }));
await screen.findByLabelText("Период");
expect(screen.getByLabelText("URL").textContent).toBe("");
expect(screen.getByLabelText("URL")).toBeEmptyDOMElement();
},
);
@@ -347,13 +355,15 @@ describe("AccountOperationsPage", () => {
const url = new URL(request.url);
searches.push(url.search);
return HttpResponse.json(
resource({
accountId: "account-1",
items: [operation],
nextCursor: url.searchParams.get("cursor") ? null : "next-1",
hasNext: !url.searchParams.get("cursor"),
observedAt: "2026-08-14T00:00:00Z",
}),
resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
accountId: "account-1",
hasNext: !url.searchParams.get("cursor"),
items: [operation],
nextCursor: url.searchParams.get("cursor") ? null : "next-1",
observedAt: "2026-08-14T00:00:00Z",
}
/* eslint-enable unicorn/no-null */)),
);
},
),
@@ -385,13 +395,15 @@ describe("AccountOperationsPage", () => {
const url = new URL(request.url);
searches.push(url.search);
return HttpResponse.json(
resource({
accountId: "account-1",
items: [operation],
nextCursor: null,
hasNext: false,
observedAt: "2026-08-14T00:00:00Z",
}),
resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
accountId: "account-1",
hasNext: false,
items: [operation],
nextCursor: null,
observedAt: "2026-08-14T00:00:00Z",
}
/* eslint-enable unicorn/no-null */)),
);
},
),
@@ -405,9 +417,9 @@ describe("AccountOperationsPage", () => {
const countBefore = searches.length;
fireEvent.click(screen.getByRole("combobox", { name: "Категории" }));
fireEvent.click(await screen.findByText("Налог"));
await new Promise((resolve) => setTimeout(resolve, 100));
expect(searches.length).toBe(countBefore);
expect(searches.some((s) => s.includes("categories=tax"))).toBe(false);
await new Promise(resolve => setTimeout(resolve, 100));
expect(searches).toHaveLength(countBefore);
expect(searches.some(s => s.includes("categories=tax"))).toBe(false);
});
it("reset clears filters and refetches unfiltered", async () => {
@@ -420,13 +432,15 @@ describe("AccountOperationsPage", () => {
const url = new URL(request.url);
searches.push(url.search);
return HttpResponse.json(
resource({
accountId: "account-1",
items: [operation],
nextCursor: null,
hasNext: false,
observedAt: "2026-08-14T00:00:00Z",
}),
resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
accountId: "account-1",
hasNext: false,
items: [operation],
nextCursor: null,
observedAt: "2026-08-14T00:00:00Z",
}
/* eslint-enable unicorn/no-null */)),
);
},
),
@@ -440,7 +454,7 @@ describe("AccountOperationsPage", () => {
fireEvent.click(await screen.findByText("Налог"));
fireEvent.click(screen.getByRole("button", { name: "Применить" }));
await waitFor(() =>
expect(searches.some((s) => s.includes("categories=tax"))).toBe(true),
expect(searches.some(s => s.includes("categories=tax"))).toBe(true),
);
fireEvent.click(screen.getByRole("button", { name: "Сбросить" }));
await waitFor(() => expect(searches.at(-1)).not.toContain("categories="));
@@ -471,9 +485,11 @@ it("keeps UTC operation boundaries in GET and source sync requests", async () =>
({ request }) => {
requested.push(Object.fromEntries(new URL(request.url).searchParams));
return HttpResponse.json(
resource(null, {
sync: { id: null, state: "failed", errorCode: "TBANK_UNAVAILABLE" },
}),
resource(null, (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
sync: { errorCode: "TBANK_UNAVAILABLE", id: null, state: "failed" },
}
/* eslint-enable unicorn/no-null */)),
);
},
),
@@ -486,10 +502,10 @@ it("keeps UTC operation boundaries in GET and source sync requests", async () =>
const retry = await screen.findByRole("button", { name: "Повторить" });
expect(requested).toEqual([
{
from: "2024-02-29T00:00:00.000Z",
to: "2024-03-01T23:59:59.999Z",
categories: "trade",
from: "2024-02-29T00:00:00.000Z",
limit: "100",
to: "2024-03-01T23:59:59.999Z",
},
]);
expect(syncRequests).toEqual([]);
@@ -497,12 +513,12 @@ it("keeps UTC operation boundaries in GET and source sync requests", async () =>
await waitFor(() =>
expect(syncRequests).toEqual([
{
screen: "operations",
accountId: "account-1",
from: "2024-02-29T00:00:00.000Z",
to: "2024-03-01T23:59:59.999Z",
categories: ["trade"],
from: "2024-02-29T00:00:00.000Z",
limit: 100,
screen: "operations",
to: "2024-03-01T23:59:59.999Z",
},
]),
);
@@ -514,12 +530,14 @@ it("does not label incomplete empty operations as a confirmed empty period", asy
http.get("*/api/v1/brokerage-accounts/:accountId/operations", () =>
HttpResponse.json(
resource(
{
accountId: "account-1",
items: [],
hasNext: false,
nextCursor: null,
},
(/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
accountId: "account-1",
hasNext: false,
items: [],
nextCursor: null,
}
/* eslint-enable unicorn/no-null */),
{ availability: "partial" },
),
),
@@ -537,17 +555,17 @@ it("recovers an invalid cursor at the first page without clearing applied filter
http.get(
"*/api/v1/brokerage-accounts/:accountId/operations",
({ request }) => {
const params = new URL(request.url).searchParams;
searches.push(params);
if (params.has("cursor"))
const parameters = new URL(request.url).searchParams;
searches.push(parameters);
if (parameters.has("cursor"))
return HttpResponse.json(
{ code: "INVALID_OPERATIONS_CURSOR" },
{ status: 400 },
);
return HttpResponse.json(
resource({
items: [operation],
hasNext: true,
items: [operation],
nextCursor: "old-cursor",
}),
);
@@ -557,7 +575,7 @@ it("recovers an invalid cursor at the first page without clearing applied filter
renderPage("?from=2026-08-01&to=2026-08-14&categories=trade");
fireEvent.click(await screen.findByRole("button", { name: "Далее" }));
fireEvent.click(await screen.findByRole("button", { name: "Повторить" }));
await waitFor(() => expect(searches.length).toBe(3));
await waitFor(() => expect(searches).toHaveLength(3));
expect(searches[2].get("cursor")).toBeNull();
for (const key of ["from", "to", "categories"])
expect(searches[2].get(key)).toBe(searches[0].get(key));
@@ -1,4 +1,5 @@
import type { FC } from "react";
import { useAccountOperationsPageVm } from "./AccountOperationsPage.vm";
import { AccountOperationsPageError } from "./components/AccountOperationsPageError.view";
import { AccountOperationsPageLoaded } from "./components/AccountOperationsPageLoaded.view";
@@ -13,11 +14,7 @@ const AccountOperationsPage: FC<AccountOperationsPageProps> = (props) => {
return <AccountOperationsPageLoading />;
}
if (viewModel.state === "error") {
return <AccountOperationsPageError {...viewModel} />;
}
return <AccountOperationsPageLoaded {...viewModel} />;
return viewModel.state === "error" ? <AccountOperationsPageError {...viewModel} /> : <AccountOperationsPageLoaded {...viewModel} />;
};
export { AccountOperationsPage };
@@ -2,44 +2,44 @@ import { useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { useParams, useSearchParams } from "react-router";
import { z } from "zod";
import {
type BrokerageOperation,
brokerageOperationsQueryOptions,
type OperationCategory,
operationCategories,
type OperationCategory,
useBrokerageOperations,
} from "@/entities/broker-operation";
import { useScreenSync } from "@/features/tbank-connection";
import { apiErrorCode } from "@/shared/api";
type AccountOperationsPageViewModel =
| { state: "loading" }
| { state: "error"; retry: () => void; onReset: () => void }
| {
state: "loaded";
sourceError?: boolean;
lastSuccessfulAt?: string | null;
partial?: boolean;
historyLoading?: boolean;
refreshing?: boolean;
refreshError?: boolean;
retry?: () => void;
draftFrom: string | null;
draftTo: string | null;
draftCategories: OperationCategory[];
items: BrokerageOperation[];
hasNext: boolean;
hasPrevious: boolean;
canApply: boolean;
onDraftFromChange: (value: string | null) => void;
onDraftToChange: (value: string | null) => void;
onDraftCategoriesChange: (value: OperationCategory[]) => void;
onApply: () => void;
onReset: () => void;
onNext: () => void;
onPrevious: () => void;
};
type AccountOperationsPageViewModel
= | {
canApply: boolean;
draftCategories: OperationCategory[];
draftFrom: null | string;
draftTo: null | string;
hasNext: boolean;
hasPrevious: boolean;
historyLoading?: boolean;
items: BrokerageOperation[];
lastSuccessfulAt?: null | string;
onApply: () => void;
onDraftCategoriesChange: (value: OperationCategory[]) => void;
onDraftFromChange: (value: null | string) => void;
onDraftToChange: (value: null | string) => void;
onNext: () => void;
onPrevious: () => void;
onReset: () => void;
partial?: boolean;
refreshError?: boolean;
refreshing?: boolean;
retry?: () => void;
sourceError?: boolean;
state: "loaded";
}
| { onReset: () => void; retry: () => void; state: "error" }
| { state: "loading" };
const useAccountOperationsPageVm = (
scopeId?: string,
@@ -47,19 +47,19 @@ const useAccountOperationsPageVm = (
const { accountId: routeAccountId } = useParams();
const accountId = scopeId ?? routeAccountId;
const queryClient = useQueryClient();
const [searchParams, setSearchParams] = useSearchParams();
const urlFrom = searchParams.get("from");
const urlTo = searchParams.get("to");
const validUrlPeriod = isValidPeriod(urlFrom, urlTo);
const appliedFrom = validUrlPeriod ? urlFrom : null;
const appliedTo = validUrlPeriod ? urlTo : null;
const appliedCategories = operationCategories.filter((category) =>
(searchParams.get("categories") ?? "").split(",").includes(category),
const [searchParameters, setSearchParameters] = useSearchParams();
const urlFrom = searchParameters.get("from");
const urlTo = searchParameters.get("to");
const isValidUrlPeriod = isValidPeriod(urlFrom, urlTo);
const appliedFrom = isValidUrlPeriod ? urlFrom : /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null;
const appliedTo = isValidUrlPeriod ? urlTo : /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null;
const appliedCategories = operationCategories.filter(category =>
(searchParameters.get("categories") ?? "").split(",").includes(category),
);
const [draftFrom, setDraftFrom] = useState<string | null>(appliedFrom);
const [draftTo, setDraftTo] = useState<string | null>(appliedTo);
const [draftCategories, setDraftCategories] =
useState<OperationCategory[]>(appliedCategories);
const [draftFrom, setDraftFrom] = useState<null | string>(appliedFrom);
const [draftTo, setDraftTo] = useState<null | string>(appliedTo);
const [draftCategories, setDraftCategories]
= useState<OperationCategory[]>(appliedCategories);
const scopeKey = JSON.stringify([
accountId,
urlFrom,
@@ -67,147 +67,146 @@ const useAccountOperationsPageVm = (
appliedCategories,
]);
const [pagination, setPagination] = useState<{
scopeKey: string;
cursors: string[];
}>({ scopeKey, cursors: [] });
scopeKey: string;
}>({ cursors: [], scopeKey });
const cursors = pagination.scopeKey === scopeKey ? pagination.cursors : [];
const cursor = cursors.at(-1);
if (pagination.scopeKey !== scopeKey) {
setPagination({ scopeKey, cursors: [] });
setPagination({ cursors: [], scopeKey });
}
useEffect(() => {
if (validUrlPeriod) return;
const normalized = new URLSearchParams(searchParams);
if (isValidUrlPeriod) return;
const normalized = new URLSearchParams(searchParameters);
normalized.delete("from");
normalized.delete("to");
setSearchParams(normalized, { replace: true });
}, [validUrlPeriod, searchParams, setSearchParams]);
const [previousSearch, setPreviousSearch] = useState(searchParams);
if (previousSearch !== searchParams) {
setPreviousSearch(searchParams);
setSearchParameters(normalized, { replace: true });
}, [isValidUrlPeriod, searchParameters, setSearchParameters]);
const [previousSearch, setPreviousSearch] = useState(searchParameters);
if (previousSearch !== searchParameters) {
setPreviousSearch(searchParameters);
setDraftFrom(appliedFrom);
setDraftTo(appliedTo);
setDraftCategories(
operationCategories.filter((category) =>
(searchParams.get("categories") ?? "").split(",").includes(category),
operationCategories.filter(category =>
(searchParameters.get("categories") ?? "").split(",").includes(category),
),
);
}
const firstPageQuery = {
from: dateStart(appliedFrom),
to: dateEnd(appliedTo),
...(appliedCategories.length ? { categories: appliedCategories } : {}),
...((appliedCategories.length > 0) && { categories: appliedCategories }),
limit: 100,
};
const operations = useBrokerageOperations(accountId, {
...firstPageQuery,
...(cursor ? { cursor } : {}),
...(cursor && { cursor }),
});
const sync = useScreenSync(
{ screen: "operations", accountId, ...firstPageQuery },
{ accountId, screen: "operations", ...firstPageQuery },
[operations],
);
if (operations.isLoading) return { state: "loading" };
const resetQueryKey = brokerageOperationsQueryOptions(accountId, {
limit: 100,
}).queryKey;
const resetCursors = () => setPagination({ scopeKey, cursors: [] });
const resetCursors = () => setPagination({ cursors: [], scopeKey });
const retry = () => {
if (apiErrorCode(operations.error) === "INVALID_OPERATIONS_CURSOR") {
void queryClient.invalidateQueries({
exact: true,
queryKey: brokerageOperationsQueryOptions(accountId, firstPageQuery)
.queryKey,
exact: true,
});
resetCursors();
} else void sync.retry();
}
else void sync.retry();
};
const onReset = () => {
setDraftFrom(null);
setDraftTo(null);
setDraftCategories([]);
setSearchParams({});
setSearchParameters({});
resetCursors();
void queryClient.invalidateQueries({ queryKey: resetQueryKey });
};
if (operations.isLoading) return { state: "loading" };
if (
(operations.isError || operations.meta?.sync.state === "failed") &&
(!operations.data ||
apiErrorCode(operations.error) === "INVALID_OPERATIONS_CURSOR")
(operations.isError || operations.meta?.sync.state === "failed")
&& (!operations.data
|| apiErrorCode(operations.error) === "INVALID_OPERATIONS_CURSOR")
)
return { state: "error", retry, onReset };
return { onReset, retry, state: "error" };
if (!operations.data) return { state: "loading" };
const nextCursor = operations.data.nextCursor;
const isDirty =
draftFrom !== appliedFrom ||
draftTo !== appliedTo ||
!sameCategories(draftCategories, appliedCategories);
const isDirty
= draftFrom !== appliedFrom
|| draftTo !== appliedTo
|| !isSameCategories(draftCategories, appliedCategories);
return {
state: "loaded",
sourceError: sync.sourceError,
lastSuccessfulAt: operations.meta?.lastSuccessfulAt,
partial: operations.meta?.availability !== "complete",
historyLoading:
operations.meta?.coverage?.historyState === "loading" ||
operations.meta?.coverage?.historyState === "partial",
refreshing: operations.isFetching || sync.refreshing,
refreshError: operations.isError || sync.sourceError || sync.transportError,
retry,
canApply: isDirty && isValidPeriod(draftFrom, draftTo),
draftCategories,
draftFrom,
draftTo,
draftCategories,
hasNext: Boolean(nextCursor && operations.data.hasNext),
hasPrevious: cursors.length > 0,
historyLoading:
operations.meta?.coverage?.historyState === "loading"
|| operations.meta?.coverage?.historyState === "partial",
items: operations.data.items,
hasNext: Boolean(operations.data.hasNext && nextCursor),
hasPrevious: Boolean(cursors.length),
canApply: isDirty && isValidPeriod(draftFrom, draftTo),
onDraftFromChange: setDraftFrom,
onDraftToChange: setDraftTo,
onDraftCategoriesChange: setDraftCategories,
lastSuccessfulAt: operations.meta?.lastSuccessfulAt,
onApply: () => {
if (!isValidPeriod(draftFrom, draftTo)) return;
setSearchParams({
...(draftFrom ? { from: draftFrom } : {}),
...(draftTo ? { to: draftTo } : {}),
...(draftCategories.length
? { categories: draftCategories.join(",") }
: {}),
setSearchParameters({
...(draftFrom && { from: draftFrom }),
...(draftTo && { to: draftTo }),
...((draftCategories.length > 0) && { categories: draftCategories.join(",") }),
});
resetCursors();
},
onReset,
onDraftCategoriesChange: setDraftCategories,
onDraftFromChange: setDraftFrom,
onDraftToChange: setDraftTo,
onNext: () => {
if (nextCursor)
setPagination({ scopeKey, cursors: [...cursors, nextCursor] });
setPagination({ cursors: [...cursors, nextCursor], scopeKey });
},
onPrevious: () =>
setPagination({ scopeKey, cursors: cursors.slice(0, -1) }),
setPagination({ cursors: cursors.slice(0, -1), scopeKey }),
onReset,
partial: operations.meta?.availability !== "complete",
refreshError: operations.isError || sync.sourceError || sync.transportError,
refreshing: operations.isFetching || sync.refreshing,
retry,
sourceError: sync.sourceError,
state: "loaded",
};
};
const calendarDate = z.string().date();
function isValidPeriod(from: string | null, to: string | null) {
return (
[from, to].every(
(date) => date === null || calendarDate.safeParse(date).success,
) &&
(!from || !to || from <= to)
);
}
function dateStart(value: string | null) {
return value ? `${value}T00:00:00.000Z` : undefined;
}
function dateEnd(value: string | null) {
const calendarDate = z.iso.date();
function dateEnd(value: null | string) {
return value ? `${value}T23:59:59.999Z` : undefined;
}
function sameCategories(a: OperationCategory[], b: OperationCategory[]) {
return a.length === b.length && a.every((value) => b.includes(value));
function dateStart(value: null | string) {
return value ? `${value}T00:00:00.000Z` : undefined;
}
function isSameCategories(a: OperationCategory[], b: OperationCategory[]) {
return a.length === b.length && a.every(value => b.includes(value));
}
function isValidPeriod(from: null | string, to: null | string) {
return (
[from, to].every(
date => date === null || calendarDate.safeParse(date).success,
)
&& (!from || !to || from <= to)
);
}
export { type AccountOperationsPageViewModel, useAccountOperationsPageVm };
@@ -1,7 +1,9 @@
import type { FC } from "react";
import { Button, Group } from "@mantine/core";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm";
type AccountOperationsPageErrorProps = Extract<
@@ -17,17 +19,17 @@ const AccountOperationsPageError: FC<AccountOperationsPageErrorProps> = (
return (
<StateView
error
title={t("ledger.errorTitle")}
text={t("ledger.errorText")}
action={
action={(
<Group>
<Button onClick={retry}>{t("ledger.retry")}</Button>
<Button variant="default" onClick={props.onReset}>
<Button onClick={props.onReset} variant="default">
{t("ledger.reset")}
</Button>
</Group>
}
)}
error
text={t("ledger.errorText")}
title={t("ledger.errorTitle")}
/>
);
};
@@ -1,3 +1,5 @@
import type { FC, ReactNode } from "react";
import {
Alert,
Button,
@@ -10,14 +12,15 @@ import {
} from "@mantine/core";
import { DatePickerInput } from "@mantine/dates";
import { StateView } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import {
LedgerEntryRow,
type OperationCategory,
operationCategories,
type OperationCategory,
} from "@/entities/broker-operation";
import { formatSnapshotTime } from "@/shared/lib";
import type { AccountOperationsPageViewModel } from "../AccountOperationsPage.vm";
type AccountOperationsPageLoadedProps = Extract<
@@ -54,99 +57,106 @@ const AccountOperationsPageLoaded: FC<AccountOperationsPageLoadedProps> = (
} = props;
const { t } = useTranslation();
const categoryData = operationCategories.map((category) => ({
value: category,
const categoryData = operationCategories.map(category => ({
label: t(`ledger.category.${category}`),
value: category,
}));
// eslint-disable-next-line sonarjs/function-return-type -- ReactNode deliberately includes lists, elements and empty output.
function renderOperations(): ReactNode {
if (items.length > 0) {
return items.map(operation => (
<LedgerEntryRow
key={JSON.stringify([
operation.account?.id,
operation.id,
operation.logoName,
])}
operation={operation}
/>
));
}
if (props.partial) {
return;
}
return (
<StateView
text={t("ledger.emptyText")}
title={t("ledger.emptyTitle")}
/>
);
}
return (
<Stack gap="lg">
{props.lastSuccessfulAt ? (
<Text size="xs" c="dimmed">
{!!(props.lastSuccessfulAt) && ((
<Text c="dimmed" size="xs">
{t("investment.sourceTime", {
date: formatSnapshotTime(props.lastSuccessfulAt),
})}
</Text>
) : null}
))}
<Title order={1}>{t("ledger.title")}</Title>
<Button onClick={props.retry} disabled={props.refreshing} w="fit-content">
<Button disabled={props.refreshing} onClick={props.retry} w="fit-content">
{t("investment.refresh")}
</Button>
{props.partial ? (
{!!(props.partial) && ((
<Alert role="status">{t("investment.partial")}</Alert>
) : null}
{props.historyLoading ? <Alert>{t("investment.history")}</Alert> : null}
{props.refreshing ? (
<Progress value={100} animated aria-label={t("accounts.refreshing")} />
) : null}
{props.refreshError ? (
<Alert color="yellow" role="status" aria-live="polite">
))}
{!!(props.historyLoading) && (<Alert>{t("investment.history")}</Alert>)}
{!!(props.refreshing) && ((
<Progress animated aria-label={t("accounts.refreshing")} value={100} />
))}
{!!(props.refreshError) && ((
<Alert aria-live="polite" color="yellow" role="status">
{t(
props.sourceError
? "investment.syncFailed"
: "accounts.refreshError",
)}
<Button variant="subtle" onClick={props.retry}>
<Button onClick={props.retry} variant="subtle">
{t("accounts.retry")}
</Button>
</Alert>
) : null}
))}
<Group align="end">
<DatePickerInput
type="range"
allowSingleDateInRange
clearable
clearButtonProps={{ "aria-label": t("ledger.clearPeriod") }}
label={t("ledger.period")}
value={[draftFrom, draftTo]}
onChange={([from, to]) => {
onDraftFromChange(from);
onDraftToChange(to);
}}
valueFormat="DD.MM.YYYY"
popoverProps={{
returnFocus: true,
middlewares: { shift: { crossAxis: true } },
returnFocus: true,
}}
type="range"
value={[draftFrom, draftTo]}
valueFormat="DD.MM.YYYY"
/>
</Group>
<MultiSelect
label={t("ledger.categories")}
placeholder={t("ledger.categoriesPlaceholder")}
data={categoryData}
value={draftCategories}
onChange={(value) =>
onDraftCategoriesChange(fromMultiSelectValue(value))
}
clearable
clearButtonProps={{ "aria-label": t("ledger.clearPeriod") }}
data={categoryData}
label={t("ledger.categories")}
onChange={value =>
onDraftCategoriesChange(fromMultiSelectValue(value))}
placeholder={t("ledger.categoriesPlaceholder")}
value={draftCategories}
/>
<Group>
<Button onClick={onApply} disabled={!canApply}>
<Button disabled={!canApply} onClick={onApply}>
{t("ledger.apply")}
</Button>
<Button variant="default" onClick={onReset}>
<Button onClick={onReset} variant="default">
{t("ledger.reset")}
</Button>
</Group>
{items.length ? (
items.map((operation) => (
<LedgerEntryRow
key={JSON.stringify([
operation.account?.id,
operation.id,
operation.logoName,
])}
operation={operation}
/>
))
) : !props.partial ? (
<StateView
title={t("ledger.emptyTitle")}
text={t("ledger.emptyText")}
/>
) : null}
{hasNext || hasPrevious ? (
{renderOperations()}
{!!(hasNext || hasPrevious) && ((
<Group justify="space-between">
<Button disabled={!hasPrevious} onClick={onPrevious}>
{t("ledger.previous")}
@@ -155,7 +165,7 @@ const AccountOperationsPageLoaded: FC<AccountOperationsPageLoadedProps> = (
{t("ledger.next")}
</Button>
</Group>
) : null}
))}
</Stack>
);
};
@@ -1,6 +1,7 @@
import type { FC } from "react";
import { Group, Skeleton, Stack } from "@mantine/core";
import { LoadingSkeleton } from "@wealthledger/ui";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
const skeletonRowIds = ["first", "second", "third", "fourth"];
@@ -17,12 +18,12 @@ const AccountOperationsPageLoading: FC = () => {
</Group>
<Skeleton height={48} radius="sm" />
<Group>
<Skeleton height={36} width={110} radius="sm" />
<Skeleton height={36} width={110} radius="sm" />
<Skeleton height={36} radius="sm" width={110} />
<Skeleton height={36} radius="sm" width={110} />
</Group>
<Stack gap="xs">
{skeletonRowIds.map((id) => (
<Skeleton key={id} height={64} radius="md" />
{skeletonRowIds.map(id => (
<Skeleton height={64} key={id} radius="md" />
))}
</Stack>
</LoadingSkeleton>