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:
@@ -1,9 +1,11 @@
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import { HttpResponse, http } from "msw";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { apiClient, configureAuthClient } from "@/shared/api";
|
||||
import { createQueryWrapper } from "@/test/query";
|
||||
import { server } from "@/test/server";
|
||||
|
||||
import { useBankMutations } from "./mutations";
|
||||
import {
|
||||
type BankCard,
|
||||
@@ -17,32 +19,34 @@ import {
|
||||
useBankSummary,
|
||||
} from "./queries";
|
||||
|
||||
const card: BankCard = {
|
||||
id: "a",
|
||||
name: "Daily",
|
||||
bankName: null,
|
||||
lastFour: null,
|
||||
paymentSystem: null,
|
||||
openingBalance: { currency: "RUB", value: "100" },
|
||||
openingDate: "2026-09-01",
|
||||
balance: { currency: "RUB", value: "100" },
|
||||
archivedAt: null,
|
||||
version: 1,
|
||||
};
|
||||
const card: BankCard = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
archivedAt: null,
|
||||
balance: { currency: "RUB", value: "100" },
|
||||
bankName: null,
|
||||
id: "a",
|
||||
lastFour: null,
|
||||
name: "Daily",
|
||||
openingBalance: { currency: "RUB", value: "100" },
|
||||
openingDate: "2026-09-01",
|
||||
paymentSystem: null,
|
||||
version: 1,
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
const transfer: CreateBankOperation = {
|
||||
amount: { currency: "RUB", value: "90071992547409.93" },
|
||||
cardId: "a",
|
||||
date: "2026-09-12",
|
||||
id: "4e6caa65-dd52-4629-81e2-ce8a139a0612",
|
||||
kind: "transfer",
|
||||
cardId: "a",
|
||||
targetCardId: "b",
|
||||
amount: { currency: "RUB", value: "90071992547409.93" },
|
||||
date: "2026-09-12",
|
||||
};
|
||||
|
||||
function authenticate() {
|
||||
configureAuthClient({
|
||||
accessToken: () => "token",
|
||||
refresh: async () => true,
|
||||
clear: vi.fn(),
|
||||
refresh: () => Promise.resolve(true),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -59,30 +63,28 @@ function readHandlers(counts: Map<string, number>, categoryName = "Food") {
|
||||
counts.set(key, (counts.get(key) ?? 0) + 1);
|
||||
if (url.pathname.endsWith("/categories"))
|
||||
return HttpResponse.json([
|
||||
{ id: "food", name: categoryName, isDefault: true, version: 1 },
|
||||
{ id: "food", isDefault: true, name: categoryName, version: 1 },
|
||||
]);
|
||||
if (url.pathname.endsWith("/summary"))
|
||||
return HttpResponse.json({
|
||||
month: url.searchParams.get("month"),
|
||||
cardId: url.searchParams.get("cardId"),
|
||||
expenses: { currency: "RUB", value: "0" },
|
||||
refunds: { currency: "RUB", value: "0" },
|
||||
net: { currency: "RUB", value: "0" },
|
||||
categories: [],
|
||||
expenses: { currency: "RUB", value: "0" },
|
||||
month: url.searchParams.get("month"),
|
||||
net: { currency: "RUB", value: "0" },
|
||||
refunds: { currency: "RUB", value: "0" },
|
||||
});
|
||||
if (
|
||||
url.pathname.endsWith("/operations") ||
|
||||
url.pathname.endsWith("/expenses")
|
||||
url.pathname.endsWith("/operations")
|
||||
|| url.pathname.endsWith("/expenses")
|
||||
)
|
||||
return HttpResponse.json({
|
||||
hasNext: false,
|
||||
items: [],
|
||||
page: 1,
|
||||
total: 0,
|
||||
hasNext: false,
|
||||
});
|
||||
if (url.pathname.includes("/operations/"))
|
||||
return HttpResponse.json({ ...transfer, version: 1 });
|
||||
return HttpResponse.json({ ...card, id: url.pathname.split("/").at(-1) });
|
||||
return url.pathname.includes("/operations/") ? HttpResponse.json({ ...transfer, version: 1 }) : HttpResponse.json({ ...card, id: url.pathname.split("/").at(-1) });
|
||||
}),
|
||||
];
|
||||
}
|
||||
@@ -93,15 +95,16 @@ function useReadModels() {
|
||||
const b = useBankCard("b");
|
||||
const categories = useBankCategories();
|
||||
const history = useBankOperations("a", {
|
||||
limit: 20,
|
||||
month: "2026-09",
|
||||
page: 2,
|
||||
limit: 20,
|
||||
});
|
||||
const expenses = useBankExpenses("a", { page: 1 });
|
||||
const september = useBankSummary("2026-09");
|
||||
const august = useBankSummary("2026-08", "b");
|
||||
const original = useBankOperation("original");
|
||||
return {
|
||||
mutations: useBankMutations(),
|
||||
reads: [
|
||||
cards,
|
||||
a,
|
||||
@@ -113,7 +116,6 @@ function useReadModels() {
|
||||
august,
|
||||
original,
|
||||
],
|
||||
mutations: useBankMutations(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -122,7 +124,7 @@ describe("banking API", () => {
|
||||
|
||||
it("loads every page for all mode and fails without exposing partial results", async () => {
|
||||
const pages: number[] = [];
|
||||
let fail = false;
|
||||
let isFail = false;
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/a/operations", ({ request }) => {
|
||||
const url = new URL(request.url);
|
||||
@@ -130,33 +132,33 @@ describe("banking API", () => {
|
||||
pages.push(page);
|
||||
expect(url.searchParams.get("limit")).toBe("100");
|
||||
expect(url.searchParams.get("month")).toBe("2026-09");
|
||||
if (fail && page === 2)
|
||||
if (isFail && page === 2)
|
||||
return HttpResponse.json({ code: "FAILED" }, { status: 500 });
|
||||
return HttpResponse.json({
|
||||
items: [{ ...transfer, id: String(page) }],
|
||||
total: 2,
|
||||
page,
|
||||
hasNext: page === 1,
|
||||
items: [{ ...transfer, id: String(page) }],
|
||||
page,
|
||||
total: 2,
|
||||
});
|
||||
}),
|
||||
);
|
||||
const { result } = renderHook(
|
||||
() => useBankOperations("a", { month: "2026-09", page: 1, limit: "all" }),
|
||||
() => 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([
|
||||
expect(result.current.data?.items.map(item => item.id)).toEqual([
|
||||
"1",
|
||||
"2",
|
||||
]);
|
||||
fail = true;
|
||||
const failed = renderHook(
|
||||
() => useBankOperations("a", { month: "2026-09", page: 1, limit: "all" }),
|
||||
isFail = true;
|
||||
const { result: failedResult } = renderHook(
|
||||
() => useBankOperations("a", { limit: "all", month: "2026-09", page: 1 }),
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
await waitFor(() => expect(failed.result.current.isError).toBe(true));
|
||||
expect(failed.result.current.data).toBeUndefined();
|
||||
await waitFor(() => expect(failedResult.current.isError).toBe(true));
|
||||
expect(failedResult.current.data).toBeUndefined();
|
||||
});
|
||||
|
||||
it("uses session-aware banking endpoints and explicit month/page without T-Bank", async () => {
|
||||
@@ -166,29 +168,29 @@ describe("banking API", () => {
|
||||
wrapper: createQueryWrapper().wrapper,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current.reads.every((read) => read.isSuccess)).toBe(true),
|
||||
expect(result.current.reads.every(read => read.isSuccess)).toBe(true),
|
||||
);
|
||||
expect([...counts.keys()]).toContain(
|
||||
expect(counts.keys()).toContain(
|
||||
"/api/v1/bank-cards?includeArchived=true",
|
||||
);
|
||||
expect([...counts.keys()]).toContain(
|
||||
"/api/v1/bank-cards/a/operations?month=2026-09&page=2&limit=20",
|
||||
expect(counts.keys()).toContain(
|
||||
"/api/v1/bank-cards/a/operations?limit=20&month=2026-09&page=2",
|
||||
);
|
||||
expect([...counts.keys()]).toContain(
|
||||
"/api/v1/bank-cards/summary?month=2026-08&cardId=b",
|
||||
expect(counts.keys()).toContain(
|
||||
"/api/v1/bank-cards/summary?cardId=b&month=2026-08",
|
||||
);
|
||||
expect(counts.size).toBe(9);
|
||||
});
|
||||
|
||||
it("replays the exact UUID and large Money string once across shared auth refresh", async () => {
|
||||
let token = "expired";
|
||||
const refresh = vi.fn(async () => {
|
||||
const refresh = vi.fn(() => {
|
||||
token = "renewed";
|
||||
return true;
|
||||
return Promise.resolve(true);
|
||||
});
|
||||
configureAuthClient({ accessToken: () => token, refresh, clear: vi.fn() });
|
||||
configureAuthClient({ accessToken: () => token, clear: vi.fn(), refresh });
|
||||
const bodies: unknown[] = [];
|
||||
const headers: (string | null)[] = [];
|
||||
const headers: (null | string)[] = [];
|
||||
server.use(
|
||||
http.post("*/api/v1/bank-cards/operations", async ({ request }) => {
|
||||
bodies.push(await request.json());
|
||||
@@ -232,10 +234,8 @@ describe("banking API", () => {
|
||||
|
||||
it("keeps the confirmed balance while a mutation is pending or fails, and on refetch failure", async () => {
|
||||
server.use(...readHandlers(new Map()));
|
||||
let finish: () => void = () => {};
|
||||
const pending = new Promise<void>((resolve) => {
|
||||
finish = resolve;
|
||||
});
|
||||
|
||||
const { promise: pending, resolve: finish } = Promise.withResolvers<void>();
|
||||
server.use(
|
||||
http.post("*/api/v1/bank-cards/operations", async () => {
|
||||
await pending;
|
||||
@@ -243,7 +243,7 @@ describe("banking API", () => {
|
||||
}),
|
||||
);
|
||||
const { result } = renderHook(
|
||||
() => ({ query: useBankCard("a"), mutations: useBankMutations() }),
|
||||
() => ({ mutations: useBankMutations(), query: useBankCard("a") }),
|
||||
{ wrapper: createQueryWrapper().wrapper },
|
||||
);
|
||||
await waitFor(() => expect(result.current.query.isSuccess).toBe(true));
|
||||
@@ -251,7 +251,8 @@ describe("banking API", () => {
|
||||
act(() => {
|
||||
saving = result.current.mutations.createOperation
|
||||
.mutateAsync(transfer)
|
||||
.catch(() => undefined);
|
||||
// eslint-disable-next-line unicorn/prefer-await -- Attach the handler immediately and retain the pending promise for queue/race ordering.
|
||||
.catch(() => {});
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current.mutations.createOperation.isPending).toBe(true),
|
||||
@@ -280,17 +281,18 @@ describe("banking API", () => {
|
||||
HttpResponse.json({ ...transfer, version: 1 }),
|
||||
),
|
||||
);
|
||||
const { wrapper, queryClient } = createQueryWrapper();
|
||||
const { queryClient, wrapper } = createQueryWrapper();
|
||||
const brokerKey = ["get", "/api/v1/brokerage-accounts"];
|
||||
queryClient.setQueryData(brokerKey, []);
|
||||
const { result } = renderHook(useReadModels, { wrapper });
|
||||
await waitFor(() =>
|
||||
expect(result.current.reads.every((read) => read.isSuccess)).toBe(true),
|
||||
expect(result.current.reads.every(read => read.isSuccess)).toBe(true),
|
||||
);
|
||||
await act(() =>
|
||||
result.current.mutations.createOperation.mutateAsync(transfer),
|
||||
);
|
||||
expect([...counts.values()]).toEqual(Array(9).fill(2));
|
||||
expect(counts.size).toBe(9);
|
||||
for (const count of counts.values()) expect(count).toBe(2);
|
||||
expect(queryClient.getQueryState(brokerKey)?.isInvalidated).toBe(false);
|
||||
});
|
||||
|
||||
@@ -316,8 +318,8 @@ describe("banking API", () => {
|
||||
await act(async () => {
|
||||
await expect(
|
||||
result.current.mutations.updateCard.mutateAsync({
|
||||
id: "a",
|
||||
body: { name: "changed", version: 1 },
|
||||
id: "a",
|
||||
}),
|
||||
).rejects.toEqual({ code });
|
||||
});
|
||||
@@ -329,7 +331,7 @@ describe("banking API", () => {
|
||||
let name = "Food";
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/categories", () =>
|
||||
HttpResponse.json([{ id: "food", name, isDefault: true, version: 1 }]),
|
||||
HttpResponse.json([{ id: "food", isDefault: true, name, version: 1 }]),
|
||||
),
|
||||
http.patch("*/api/v1/bank-cards/categories/food", async ({ request }) => {
|
||||
const body = await request.json();
|
||||
@@ -337,8 +339,8 @@ describe("banking API", () => {
|
||||
name = "Groceries";
|
||||
return HttpResponse.json({
|
||||
id: "food",
|
||||
name,
|
||||
isDefault: true,
|
||||
name,
|
||||
version: 2,
|
||||
});
|
||||
}),
|
||||
@@ -366,8 +368,8 @@ describe("banking API", () => {
|
||||
);
|
||||
await act(() =>
|
||||
result.current.mutations.updateCategory.mutateAsync({
|
||||
id: "food",
|
||||
body: { name: "Groceries", version: 1 },
|
||||
id: "food",
|
||||
}),
|
||||
);
|
||||
await waitFor(() =>
|
||||
@@ -375,8 +377,8 @@ describe("banking API", () => {
|
||||
);
|
||||
await act(() =>
|
||||
result.current.mutations.updateOperation.mutateAsync({
|
||||
id: "original",
|
||||
body: { description: "corrected", version: 1 },
|
||||
id: "original",
|
||||
}),
|
||||
);
|
||||
await act(() =>
|
||||
@@ -403,8 +405,8 @@ describe("banking API", () => {
|
||||
}),
|
||||
),
|
||||
);
|
||||
const { wrapper, queryClient } = createQueryWrapper();
|
||||
const { result, rerender } = renderHook(() => useBankCard("a"), {
|
||||
const { queryClient, wrapper } = createQueryWrapper();
|
||||
const { rerender, result } = renderHook(() => useBankCard("a"), {
|
||||
wrapper,
|
||||
});
|
||||
await waitFor(() => expect(result.current.data?.balance.value).toBe("100"));
|
||||
@@ -413,7 +415,7 @@ describe("banking API", () => {
|
||||
});
|
||||
expect(result.current.data?.balance.value).toBe("100");
|
||||
act(() => {
|
||||
configureAuthClient(null);
|
||||
configureAuthClient();
|
||||
queryClient.clear();
|
||||
});
|
||||
rerender();
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiClient, apiErrorCode } from "@/shared/api";
|
||||
|
||||
import type {
|
||||
CreateBankCard,
|
||||
CreateBankOperation,
|
||||
@@ -22,59 +24,61 @@ function useBankMutations() {
|
||||
const queryClient = useQueryClient();
|
||||
const invalidate = () =>
|
||||
queryClient.invalidateQueries({
|
||||
predicate: ({ queryKey: [method, path] }) =>
|
||||
method === "get" &&
|
||||
typeof path === "string" &&
|
||||
(path === "/api/v1/bank-cards" ||
|
||||
path.startsWith("/api/v1/bank-cards/")),
|
||||
predicate: ({ queryKey }) => {
|
||||
const [method, path] = queryKey;
|
||||
return method === "get"
|
||||
&& typeof path === "string"
|
||||
&& (path === "/api/v1/bank-cards"
|
||||
|| path.startsWith("/api/v1/bank-cards/"));
|
||||
},
|
||||
});
|
||||
const options = {
|
||||
retry: false,
|
||||
onSuccess: invalidate,
|
||||
onError: (error: unknown) => {
|
||||
if (
|
||||
[
|
||||
"BANK_VERSION_CONFLICT",
|
||||
"BANK_WRITE_CONFLICT",
|
||||
"BANK_DEPENDENT_REFUNDS",
|
||||
"BANK_INTENT_CONFLICT",
|
||||
"BANK_REFUND_LIMIT",
|
||||
"BANK_DEPENDENT_REFUNDS",
|
||||
"BANK_VERSION_CONFLICT",
|
||||
"BANK_WRITE_CONFLICT",
|
||||
].includes(apiErrorCode(error) ?? "")
|
||||
)
|
||||
return invalidate();
|
||||
},
|
||||
onSuccess: invalidate,
|
||||
retry: false,
|
||||
} as const;
|
||||
const createCard = useMutation({
|
||||
const cardCreation = useMutation({
|
||||
...options,
|
||||
mutationFn: (body: CreateBankCard) =>
|
||||
mutationData(apiClient.POST("/api/v1/bank-cards", { body })),
|
||||
});
|
||||
const updateCard = useMutation({
|
||||
...options,
|
||||
mutationFn: ({ id, body }: { id: string; body: UpdateBankCard }) =>
|
||||
mutationFn: ({ body, id }: { body: UpdateBankCard; id: string }) =>
|
||||
mutationData(
|
||||
apiClient.PATCH("/api/v1/bank-cards/{id}", {
|
||||
params: { path: { id } },
|
||||
body,
|
||||
params: { path: { id } },
|
||||
}),
|
||||
),
|
||||
});
|
||||
const createOperation = useMutation({
|
||||
const operationCreation = useMutation({
|
||||
...options,
|
||||
mutationFn: (body: CreateBankOperation) =>
|
||||
mutationData(apiClient.POST("/api/v1/bank-cards/operations", { body })),
|
||||
});
|
||||
const updateOperation = useMutation({
|
||||
...options,
|
||||
mutationFn: ({ id, body }: { id: string; body: UpdateBankOperation }) =>
|
||||
mutationFn: ({ body, id }: { body: UpdateBankOperation; id: string }) =>
|
||||
mutationData(
|
||||
apiClient.PATCH("/api/v1/bank-cards/operations/{id}", {
|
||||
params: { path: { id } },
|
||||
body,
|
||||
params: { path: { id } },
|
||||
}),
|
||||
),
|
||||
});
|
||||
const deleteOperation = useMutation({
|
||||
const operationDeletion = useMutation({
|
||||
...options,
|
||||
mutationFn: ({ id, version }: { id: string; version: number }) =>
|
||||
mutationData(
|
||||
@@ -83,29 +87,29 @@ function useBankMutations() {
|
||||
}),
|
||||
),
|
||||
});
|
||||
const createCategory = useMutation({
|
||||
const categoryCreation = useMutation({
|
||||
...options,
|
||||
mutationFn: (body: CreateExpenseCategory) =>
|
||||
mutationData(apiClient.POST("/api/v1/bank-cards/categories", { body })),
|
||||
});
|
||||
const updateCategory = useMutation({
|
||||
...options,
|
||||
mutationFn: ({ id, body }: { id: string; body: UpdateExpenseCategory }) =>
|
||||
mutationFn: ({ body, id }: { body: UpdateExpenseCategory; id: string }) =>
|
||||
mutationData(
|
||||
apiClient.PATCH("/api/v1/bank-cards/categories/{id}", {
|
||||
params: { path: { id } },
|
||||
body,
|
||||
params: { path: { id } },
|
||||
}),
|
||||
),
|
||||
});
|
||||
return {
|
||||
createCard,
|
||||
createCard: cardCreation,
|
||||
createCategory: categoryCreation,
|
||||
createOperation: operationCreation,
|
||||
deleteOperation: operationDeletion,
|
||||
updateCard,
|
||||
createOperation,
|
||||
updateOperation,
|
||||
deleteOperation,
|
||||
createCategory,
|
||||
updateCategory,
|
||||
updateOperation,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -7,39 +7,43 @@ import {
|
||||
|
||||
import { moneyCents } from "../model/form-validation";
|
||||
|
||||
type BankCard =
|
||||
paths["/api/v1/bank-cards/{id}"]["get"]["responses"][200]["content"]["application/json"];
|
||||
type BankOperation =
|
||||
paths["/api/v1/bank-cards/operations/{id}"]["get"]["responses"][200]["content"]["application/json"];
|
||||
type BankOperations =
|
||||
paths["/api/v1/bank-cards/{id}/operations"]["get"]["responses"][200]["content"]["application/json"];
|
||||
type BankSummary =
|
||||
paths["/api/v1/bank-cards/summary"]["get"]["responses"][200]["content"]["application/json"];
|
||||
type ExpenseCategory =
|
||||
paths["/api/v1/bank-cards/categories"]["get"]["responses"][200]["content"]["application/json"][number];
|
||||
type CreateBankCard =
|
||||
paths["/api/v1/bank-cards"]["post"]["requestBody"]["content"]["application/json"];
|
||||
type UpdateBankCard =
|
||||
paths["/api/v1/bank-cards/{id}"]["patch"]["requestBody"]["content"]["application/json"];
|
||||
type CreateBankOperation =
|
||||
paths["/api/v1/bank-cards/operations"]["post"]["requestBody"]["content"]["application/json"];
|
||||
type UpdateBankOperation =
|
||||
paths["/api/v1/bank-cards/operations/{id}"]["patch"]["requestBody"]["content"]["application/json"];
|
||||
type CreateExpenseCategory =
|
||||
paths["/api/v1/bank-cards/categories"]["post"]["requestBody"]["content"]["application/json"];
|
||||
type UpdateExpenseCategory =
|
||||
paths["/api/v1/bank-cards/categories/{id}"]["patch"]["requestBody"]["content"]["application/json"];
|
||||
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"];
|
||||
|
||||
const OPERATIONS_PAGE_SIZE = 100;
|
||||
|
||||
function useBankCards(includeArchived = false) {
|
||||
return useAuthenticatedQuery(
|
||||
apiQueryClient.queryOptions("get", "/api/v1/bank-cards", {
|
||||
params: {
|
||||
query: { includeArchived: includeArchived ? "true" : "false" },
|
||||
},
|
||||
function sortBankSummary(data: BankSummary): BankSummary {
|
||||
return {
|
||||
...data,
|
||||
categories: data.categories.toSorted((a, b) => {
|
||||
const left = moneyCents(a.net.value);
|
||||
const right = moneyCents(b.net.value);
|
||||
if (left === null || right === null)
|
||||
throw new Error("Invalid bank summary amount");
|
||||
if (left > right) return -1;
|
||||
return left < right ? 1 : 0;
|
||||
}),
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
function useBankCard(id: string | undefined) {
|
||||
@@ -51,79 +55,25 @@ function useBankCard(id: string | undefined) {
|
||||
});
|
||||
}
|
||||
|
||||
function useBankCards(isIncludeArchived = false) {
|
||||
return useAuthenticatedQuery(
|
||||
apiQueryClient.queryOptions("get", "/api/v1/bank-cards", {
|
||||
params: {
|
||||
query: { includeArchived: isIncludeArchived ? "true" : "false" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function useBankCategories() {
|
||||
return useAuthenticatedQuery(
|
||||
apiQueryClient.queryOptions("get", "/api/v1/bank-cards/categories"),
|
||||
);
|
||||
}
|
||||
|
||||
function useBankOperations(
|
||||
id: string | undefined,
|
||||
query: {
|
||||
month?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
page: number;
|
||||
limit?: number | "all";
|
||||
},
|
||||
) {
|
||||
const all = query.limit === "all";
|
||||
const params = {
|
||||
path: { id: id ?? "" },
|
||||
query: {
|
||||
...query,
|
||||
page: all ? 1 : query.page,
|
||||
limit: query.limit === "all" ? OPERATIONS_PAGE_SIZE : query.limit,
|
||||
},
|
||||
};
|
||||
const options = apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/bank-cards/{id}/operations",
|
||||
{ params },
|
||||
);
|
||||
// eslint-disable-next-line @tanstack/query/exhaustive-deps -- Generated options.queryKey already contains params; retain the shared cache identity.
|
||||
return useAuthenticatedQuery({
|
||||
queryKey: all ? ([...options.queryKey, "all"] as const) : options.queryKey,
|
||||
placeholderData: (
|
||||
previousData: BankOperations | undefined,
|
||||
previousQuery,
|
||||
) => {
|
||||
const previous = previousQuery?.queryKey[2]?.params;
|
||||
return !all &&
|
||||
previousQuery?.queryKey.length === options.queryKey.length &&
|
||||
previous?.path?.id === id &&
|
||||
previous?.query?.month === query.month &&
|
||||
previous?.query?.from === query.from &&
|
||||
previous?.query?.to === query.to &&
|
||||
previous?.query?.limit === query.limit
|
||||
? previousData
|
||||
: undefined;
|
||||
},
|
||||
queryFn: async ({ signal }) => {
|
||||
const items: BankOperation[] = [];
|
||||
for (let page = params.query.page; ; page++) {
|
||||
const { data, error } = await apiClient.GET(
|
||||
"/api/v1/bank-cards/{id}/operations",
|
||||
{
|
||||
params: { ...params, query: { ...params.query, page } },
|
||||
signal,
|
||||
},
|
||||
);
|
||||
// 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");
|
||||
if (!all) return data;
|
||||
items.push(...data.items);
|
||||
if (!data.hasNext) return { ...data, items, page: 1, hasNext: false };
|
||||
}
|
||||
},
|
||||
enabled: Boolean(id && (query.month || (query.from && query.to))),
|
||||
});
|
||||
}
|
||||
|
||||
function useBankExpenses(
|
||||
id: string | undefined,
|
||||
query: { page: number; limit?: number },
|
||||
query: { limit?: number; page: number },
|
||||
) {
|
||||
return useAuthenticatedQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bank-cards/{id}/expenses", {
|
||||
@@ -133,36 +83,6 @@ function useBankExpenses(
|
||||
});
|
||||
}
|
||||
|
||||
function sortBankSummary(data: BankSummary): BankSummary {
|
||||
return {
|
||||
...data,
|
||||
categories: data.categories.toSorted((a, b) => {
|
||||
const left = moneyCents(a.net.value);
|
||||
const right = moneyCents(b.net.value);
|
||||
if (left === null || right === null)
|
||||
throw new Error("Invalid bank summary amount");
|
||||
return left > right ? -1 : left < right ? 1 : 0;
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function useBankSummary(
|
||||
period: string | { from: string; to: string },
|
||||
cardId?: string,
|
||||
) {
|
||||
const query =
|
||||
typeof period === "string"
|
||||
? { month: period, cardId }
|
||||
: { ...period, cardId };
|
||||
return useAuthenticatedQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bank-cards/summary", {
|
||||
params: { query },
|
||||
}),
|
||||
select: sortBankSummary,
|
||||
enabled: Boolean(period),
|
||||
});
|
||||
}
|
||||
|
||||
function useBankOperation(id: string | undefined) {
|
||||
return useAuthenticatedQuery({
|
||||
...apiQueryClient.queryOptions(
|
||||
@@ -174,6 +94,87 @@ function useBankOperation(id: string | undefined) {
|
||||
});
|
||||
}
|
||||
|
||||
function useBankOperations(
|
||||
id: string | undefined,
|
||||
query: {
|
||||
from?: string;
|
||||
limit?: "all" | number;
|
||||
month?: string;
|
||||
page: number;
|
||||
to?: string;
|
||||
},
|
||||
) {
|
||||
const isAll = query.limit === "all";
|
||||
const parameters = {
|
||||
path: { id: id ?? "" },
|
||||
query: {
|
||||
...query,
|
||||
limit: query.limit === "all" ? OPERATIONS_PAGE_SIZE : query.limit,
|
||||
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))),
|
||||
placeholderData: (
|
||||
previousData: BankOperations | undefined,
|
||||
previousQuery,
|
||||
) => {
|
||||
const previous = previousQuery?.queryKey[2]?.params;
|
||||
return !isAll
|
||||
&& previousQuery?.queryKey.length === options.queryKey.length
|
||||
&& previous?.path?.id === id
|
||||
&& previous?.query?.month === query.month
|
||||
&& previous?.query?.from === query.from
|
||||
&& previous?.query?.to === query.to
|
||||
&& previous?.query?.limit === query.limit
|
||||
? previousData
|
||||
: undefined;
|
||||
},
|
||||
queryFn: async ({ signal }) => {
|
||||
const items: BankOperation[] = [];
|
||||
for (let page = parameters.query.page; ; page++) {
|
||||
const { data, error } = await apiClient.GET(
|
||||
"/api/v1/bank-cards/{id}/operations",
|
||||
{
|
||||
params: { ...parameters, query: { ...parameters.query, page } },
|
||||
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");
|
||||
if (!isAll) return data;
|
||||
items.push(...data.items);
|
||||
if (!data.hasNext) return { ...data, hasNext: false, items, page: 1 };
|
||||
}
|
||||
},
|
||||
queryKey: isAll ? ([...options.queryKey, "all"] as const) : options.queryKey,
|
||||
});
|
||||
}
|
||||
|
||||
function useBankSummary(
|
||||
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 },
|
||||
}),
|
||||
enabled: Boolean(period),
|
||||
select: sortBankSummary,
|
||||
});
|
||||
}
|
||||
|
||||
export {
|
||||
type BankCard,
|
||||
type BankOperation,
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { type BankSummary, sortBankSummary } from "./queries";
|
||||
|
||||
const money = (value: string) => ({ currency: "RUB", value });
|
||||
|
||||
it("orders displayed expenses descending, preserving cents, ties and source data", () => {
|
||||
const values = [
|
||||
"-10",
|
||||
@@ -10,23 +13,23 @@ it("orders displayed expenses descending, preserving cents, ties and source data
|
||||
"-2",
|
||||
"0",
|
||||
];
|
||||
const money = (value: string) => ({ currency: "RUB", value });
|
||||
|
||||
const data: BankSummary = {
|
||||
month: "2026-09",
|
||||
cardId: "a",
|
||||
expenses: money("0"),
|
||||
refunds: money("0"),
|
||||
net: money("0"),
|
||||
categories: values.map((value, index) => ({
|
||||
categoryId: String(index),
|
||||
categoryName: String(index),
|
||||
expenses: money("100"),
|
||||
refunds: money("0"),
|
||||
net: money(value),
|
||||
refunds: money("0"),
|
||||
})),
|
||||
expenses: money("0"),
|
||||
month: "2026-09",
|
||||
net: money("0"),
|
||||
refunds: money("0"),
|
||||
};
|
||||
expect(sortBankSummary(data).categories.map((row) => row.categoryId)).toEqual(
|
||||
expect(sortBankSummary(data).categories.map(row => row.categoryId)).toEqual(
|
||||
["3", "1", "2", "5", "4", "0"],
|
||||
);
|
||||
expect(data.categories.map((row) => row.net.value)).toEqual(values);
|
||||
expect(data.categories.map(row => row.net.value)).toEqual(values);
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
bankCardSchema,
|
||||
bankDateInputValue,
|
||||
@@ -27,9 +28,9 @@ describe("bank form input", () => {
|
||||
}
|
||||
expect(bankMoneyValue(" -00010,20 ")).toBe("-10.20");
|
||||
const values = {
|
||||
name: "A",
|
||||
bankName: "",
|
||||
lastFour: "",
|
||||
name: "A",
|
||||
openingBalance: "-92233720368547758.08",
|
||||
openingDate: "2026-01-01",
|
||||
};
|
||||
|
||||
@@ -1,38 +1,43 @@
|
||||
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 bankToday() {
|
||||
return new Intl.DateTimeFormat("en-CA", {
|
||||
timeZone: "Europe/Moscow",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
}).format(new Date());
|
||||
}
|
||||
function bankDateInputValue(value: string) {
|
||||
return value.replace(/^(\d{2})\.(\d{2})\.(\d{4})$/, "$3-$2-$1");
|
||||
}
|
||||
function bankMonth(value: string | null) {
|
||||
return value && value >= "0001-01" && /^\d{4}-(0[1-9]|1[0-2])$/.test(value)
|
||||
? value
|
||||
: bankToday().slice(0, ISO_MONTH_LENGTH);
|
||||
}
|
||||
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",
|
||||
month: "2-digit",
|
||||
timeZone: "Europe/Moscow",
|
||||
year: "numeric",
|
||||
}).format(new Date());
|
||||
}
|
||||
function moneyCents(value: string): bigint | null {
|
||||
const normalized = value.trim().replace(",", ".");
|
||||
if (!/^-?\d+(\.\d{1,2})?$/.test(normalized)) return null;
|
||||
const [whole, fraction = ""] = normalized.replace("-", "").split(".");
|
||||
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);
|
||||
return (
|
||||
BigInt(`${whole}${fraction.padEnd(2, "0")}`) *
|
||||
(normalized.startsWith("-") ? -1n : 1n)
|
||||
BigInt(`${whole}${fraction.padEnd(CENTS_PRECISION, "0")}`)
|
||||
* (normalized.startsWith("-") ? -1n : 1n)
|
||||
);
|
||||
}
|
||||
const MIN_BALANCE_KOPECKS = -9_223_372_036_854_775_808n;
|
||||
@@ -42,9 +47,9 @@ const moneySchema = z.string().refine(
|
||||
(value) => {
|
||||
const cents = moneyCents(value);
|
||||
return (
|
||||
cents !== null &&
|
||||
cents >= MIN_BALANCE_KOPECKS &&
|
||||
cents <= MAX_BALANCE_KOPECKS
|
||||
cents !== null
|
||||
&& cents >= MIN_BALANCE_KOPECKS
|
||||
&& cents <= MAX_BALANCE_KOPECKS
|
||||
);
|
||||
},
|
||||
{ error: validationMessage("bank.validation.money") },
|
||||
@@ -59,15 +64,25 @@ const positiveMoneySchema = moneySchema.refine(
|
||||
const bankDateSchema = z
|
||||
.string()
|
||||
.refine(
|
||||
(value) =>
|
||||
/^\d{4}-\d{2}-\d{2}$/.test(value) &&
|
||||
value >= "0001-01-01" &&
|
||||
!Number.isNaN(Date.parse(`${value}T00:00:00Z`)) &&
|
||||
new Date(`${value}T00:00:00Z`).toISOString().slice(0, 10) === value &&
|
||||
value <= bankToday(),
|
||||
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()
|
||||
@@ -76,29 +91,19 @@ const bankCardSchema = z.object({
|
||||
MAX_CARD_NAME_LENGTH,
|
||||
validationMessage("bank.validation.name")(undefined),
|
||||
),
|
||||
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"),
|
||||
}),
|
||||
openingBalance: moneySchema,
|
||||
openingDate: bankDateSchema,
|
||||
paymentSystem: z
|
||||
.enum(["", "mir", "visa", "mastercard"], {
|
||||
error: validationMessage("bank.validation.paymentSystem"),
|
||||
})
|
||||
.optional(),
|
||||
openingBalance: moneySchema,
|
||||
openingDate: bankDateSchema,
|
||||
});
|
||||
type BankCardValues = z.infer<typeof bankCardSchema>;
|
||||
|
||||
export {
|
||||
type BankCardValues,
|
||||
bankCardSchema,
|
||||
type BankCardValues,
|
||||
bankDateInputValue,
|
||||
bankDateSchema,
|
||||
bankMoneyValue,
|
||||
|
||||
@@ -1,140 +1,137 @@
|
||||
import type { BankOperation } from "../api/queries";
|
||||
|
||||
type OperationIcon = { path: string; color: string; animation?: string };
|
||||
type OperationIcon = { animation?: string; color: string; path: string };
|
||||
|
||||
const categoryIcons: Record<string, OperationIcon> = {
|
||||
алкоголь: {
|
||||
"алкоголь": {
|
||||
animation: "wine",
|
||||
path: "M7 3h10v5a5 5 0 0 1-10 0V3Z M7 7h10v1a5 5 0 0 1-10 0V7Z M12 13v8 M8 21h8",
|
||||
color: "grape",
|
||||
path: "M7 3h10v5a5 5 0 0 1-10 0V3Z M7 7h10v1a5 5 0 0 1-10 0V7Z M12 13v8 M8 21h8",
|
||||
},
|
||||
вклады: {
|
||||
"вклады": {
|
||||
animation: "deposit",
|
||||
path: "M6 9a6 6 0 1 0 12 0a6 6 0 1 0-12 0 M10.5 12V6h2a1.5 1.5 0 0 1 0 3h-3m0 1.5h3 M4 16c0 4 16 4 16 0 M4 19c0 4 16 4 16 0",
|
||||
color: "green",
|
||||
path: "M6 9a6 6 0 1 0 12 0a6 6 0 1 0-12 0 M10.5 12V6h2a1.5 1.5 0 0 1 0 3h-3m0 1.5h3 M4 16c0 4 16 4 16 0 M4 19c0 4 16 4 16 0",
|
||||
},
|
||||
"жилье": { color: "orange", path: "M3 11l9-8 9 8 M5 10v11h14V10 M9 21v-8h6v8" },
|
||||
"здоровье": { color: "red", path: "M9 3h6v6h6v6h-6v6H9v-6H3V9h6V3Z" },
|
||||
"инвестиции и накопления": {
|
||||
animation: "growth",
|
||||
path: "M3 3v18h18 M6 15l5-5 4 3 6-8 M16 5h5v5",
|
||||
color: "green",
|
||||
path: "M3 3v18h18 M6 15l5-5 4 3 6-8 M16 5h5v5",
|
||||
},
|
||||
образование: {
|
||||
"кафе": {
|
||||
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",
|
||||
},
|
||||
"образование": {
|
||||
color: "blue",
|
||||
path: "M2 8l10-5 10 5-10 5L2 8Z M6 10v7c4 3 8 3 12 0v-7 M22 8v9",
|
||||
color: "blue",
|
||||
},
|
||||
переводы: {
|
||||
"переводы": {
|
||||
animation: "transfer",
|
||||
path: "M3 7h18l-4-4 M21 17H3l4 4",
|
||||
color: "blue",
|
||||
path: "M3 7h18l-4-4 M21 17H3l4 4",
|
||||
},
|
||||
"погашение кредита": {
|
||||
animation: "repayment",
|
||||
path: "M3 5h18v14H3V5Z M3 9h18 M10 18v-7h3a2 2 0 0 1 0 4H9m0 1.5h4",
|
||||
color: "orange",
|
||||
path: "M3 5h18v14H3V5Z M3 9h18 M10 18v-7h3a2 2 0 0 1 0 4H9m0 1.5h4",
|
||||
},
|
||||
подписки: {
|
||||
path: "M4 10a8 8 0 0 1 13-6l3 3 M20 3v4h-4 M20 14a8 8 0 0 1-13 6l-3-3 M4 21v-4h4",
|
||||
"подписки": {
|
||||
color: "grape",
|
||||
path: "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",
|
||||
},
|
||||
путешествия: {
|
||||
path: "M10 3h4v7l7 5v3l-7-3v5l2 1v1l-4-1-4 1v-1l2-1v-5l-7 3v-3l7-5V3Z",
|
||||
"покупки": {
|
||||
color: "grape",
|
||||
path: "M5 7h14l2 14H3L5 7Z M8 8V6a4 4 0 0 1 8 0v2",
|
||||
},
|
||||
"продукты": {
|
||||
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",
|
||||
},
|
||||
"путешествия": {
|
||||
color: "blue",
|
||||
path: "M10 3h4v7l7 5v3l-7-3v5l2 1v1l-4-1-4 1v-1l2-1v-5l-7 3v-3l7-5V3Z",
|
||||
},
|
||||
"развлечения": {
|
||||
color: "grape",
|
||||
path: "M9 5v14a3 3 0 1 1-3-3h3 M9 5l11-2v14a3 3 0 1 1-3-3h3 M9 9l11-2",
|
||||
},
|
||||
"связь и интернет": {
|
||||
animation: "wifi",
|
||||
path: "M3 7a14 14 0 0 1 18 0 M6 11a9 9 0 0 1 12 0 M9 15a4 4 0 0 1 6 0 M12 19h.01",
|
||||
color: "blue",
|
||||
path: "M3 7a14 14 0 0 1 18 0 M6 11a9 9 0 0 1 12 0 M9 15a4 4 0 0 1 6 0 M12 19h.01",
|
||||
},
|
||||
"снятие наличных": {
|
||||
color: "green",
|
||||
path: "M4 10V3h16v7 M7 7h10v14H7V7Z M7 11h10 M10 16h4",
|
||||
color: "green",
|
||||
},
|
||||
ставки: {
|
||||
path: "M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2Z M7 7h.01 M17 7h.01 M12 12h.01 M7 17h.01 M17 17h.01",
|
||||
"ставки": {
|
||||
color: "grape",
|
||||
path: "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",
|
||||
},
|
||||
страхование: {
|
||||
path: "M12 2l8 4v6c0 5-8 10-8 10S4 17 4 12V6l8-4Z M8 12l3 3 5-6",
|
||||
"страхование": {
|
||||
color: "green",
|
||||
path: "M12 2l8 4v6c0 5-8 10-8 10S4 17 4 12V6l8-4Z M8 12l3 3 5-6",
|
||||
},
|
||||
табак: {
|
||||
path: "M3 14h18v5H3v-5Z M16 14v5 M8 10V8c0-2 3-2 3-4V2 M15 10V8c0-2 3-2 3-4",
|
||||
"табак": {
|
||||
color: "orange",
|
||||
path: "M3 14h18v5H3v-5Z M16 14v5 M8 10V8c0-2 3-2 3-4V2 M15 10V8c0-2 3-2 3-4",
|
||||
},
|
||||
"такси": {
|
||||
color: "yellow",
|
||||
path: "M4 10l2-6h12l2 6 M3 10h18v8H3v-8Z M6 18v3 M18 18v3 M6 14h2 M16 14h2 M10 4V2h4v2",
|
||||
},
|
||||
"транспорт": {
|
||||
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",
|
||||
},
|
||||
"хостинг и ии-сервисы": {
|
||||
animation: "server",
|
||||
path: "M3 3h18v7H3V3Z M3 14h18v7H3v-7Z M7 6.5h.01 M7 17.5h.01 M15 6.5h3 M15 17.5h3",
|
||||
color: "grape",
|
||||
path: "M3 3h18v7H3V3Z M3 14h18v7H3v-7Z M7 6.5h.01 M7 17.5h.01 M15 6.5h3 M15 17.5h3",
|
||||
},
|
||||
"цифровые покупки": {
|
||||
color: "blue",
|
||||
path: "M3 3h18v13H3V3Z M8 21h8 M12 16v5 M12 6v7 M9 10l3 3 3-3",
|
||||
color: "blue",
|
||||
},
|
||||
продукты: {
|
||||
animation: "basket",
|
||||
path: "M3 9h18l-2 11H5L3 9Z M8 9l4-6 4 6 M9 13v3 M15 13v3 M10 6a2 2 0 1 0 4 0a2 2 0 1 0-4 0",
|
||||
color: "green",
|
||||
},
|
||||
кафе: {
|
||||
animation: "coffee",
|
||||
path: "M4 8h12v7a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4V8Z M16 9h2a3 3 0 0 1 0 6h-2 M8 6c-2-1 2-2 0-4 M12 6c-2-1 2-2 0-4 M3 22h15",
|
||||
color: "orange",
|
||||
},
|
||||
такси: {
|
||||
path: "M4 10l2-6h12l2 6 M3 10h18v8H3v-8Z M6 18v3 M18 18v3 M6 14h2 M16 14h2 M10 4V2h4v2",
|
||||
color: "yellow",
|
||||
},
|
||||
транспорт: {
|
||||
animation: "car",
|
||||
path: "M4 16H2v-4l3-1 3-4h6l4 4 4 1v4h-2 M8 16h8 M6 11h12m-6-4v4 M4 16a2 2 0 1 0 4 0a2 2 0 1 0-4 0m2-2v4m-2-2h4 M16 16a2 2 0 1 0 4 0a2 2 0 1 0-4 0m2-2v4m-2-2h4",
|
||||
color: "blue",
|
||||
},
|
||||
жилье: { path: "M3 11l9-8 9 8 M5 10v11h14V10 M9 21v-8h6v8", color: "orange" },
|
||||
здоровье: { path: "M9 3h6v6h6v6h-6v6H9v-6H3V9h6V3Z", color: "red" },
|
||||
покупки: {
|
||||
path: "M5 7h14l2 14H3L5 7Z M8 8V6a4 4 0 0 1 8 0v2",
|
||||
color: "grape",
|
||||
},
|
||||
развлечения: {
|
||||
path: "M9 5v14a3 3 0 1 1-3-3h3 M9 5l11-2v14a3 3 0 1 1-3-3h3 M9 9l11-2",
|
||||
color: "grape",
|
||||
},
|
||||
};
|
||||
const otherIcon: OperationIcon = {
|
||||
animation: "grid",
|
||||
path: "M4 4h6v6H4V4Z M14 4h6v6h-6V4Z M4 14h6v6H4v-6Z M14 14h6v6h-6v-6Z",
|
||||
color: "gray",
|
||||
path: "M4 4h6v6H4V4Z M14 4h6v6h-6V4Z M4 14h6v6H4v-6Z M14 14h6v6h-6v-6Z",
|
||||
};
|
||||
const operationIcons: Record<
|
||||
Exclude<BankOperation["kind"], "expense">,
|
||||
OperationIcon
|
||||
> = {
|
||||
refund: { color: "teal", path: "M8 4L3 9l5 5 M3 9h11a7 7 0 0 1 0 14" },
|
||||
topup: {
|
||||
animation: "topup",
|
||||
path: "M20 8V5H5a2 2 0 0 1 0-4h13v4 M3 3v16a2 2 0 0 0 2 2h15V8H5 M16 12v5m-2.5-2.5h5",
|
||||
color: "green",
|
||||
path: "M20 8V5H5a2 2 0 0 1 0-4h13v4 M3 3v16a2 2 0 0 0 2 2h15V8H5 M16 12v5m-2.5-2.5h5",
|
||||
},
|
||||
transfer: {
|
||||
animation: "transfer",
|
||||
path: "M3 7h18l-4-4 M21 17H3l4 4",
|
||||
color: "blue",
|
||||
path: "M3 7h18l-4-4 M21 17H3l4 4",
|
||||
},
|
||||
refund: { path: "M8 4L3 9l5 5 M3 9h11a7 7 0 0 1 0 14", color: "teal" },
|
||||
};
|
||||
|
||||
function bankOperationAppearance(
|
||||
kind: BankOperation["kind"],
|
||||
categoryName?: string | null,
|
||||
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];
|
||||
const name = categoryName
|
||||
?.trim()
|
||||
.toLocaleLowerCase("ru-RU")
|
||||
.replaceAll("ё", "е");
|
||||
return kind === "expense"
|
||||
? name && Object.hasOwn(categoryIcons, name)
|
||||
? categoryIcons[name]
|
||||
: otherIcon
|
||||
: operationIcons[kind];
|
||||
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;
|
||||
}
|
||||
|
||||
export { bankOperationAppearance };
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
|
||||
import { bankPeriod } from "./period";
|
||||
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { bankMonth } from "./form-validation";
|
||||
|
||||
const calendarDate = z.string().date();
|
||||
const calendarDate = z.iso.date();
|
||||
const ISO_DATE_LENGTH = 10;
|
||||
function bankPeriod(params: URLSearchParams) {
|
||||
const month = bankMonth(params.get("month"));
|
||||
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 = params.get("from");
|
||||
const to = params.get("to");
|
||||
return from &&
|
||||
to &&
|
||||
calendarDate.safeParse(from).success &&
|
||||
calendarDate.safeParse(to).success &&
|
||||
from >= "0001-01-01" &&
|
||||
from <= to
|
||||
const from = parameters.get("from");
|
||||
const to = parameters.get("to");
|
||||
return from
|
||||
&& to
|
||||
&& calendarDate.safeParse(from).success
|
||||
&& calendarDate.safeParse(to).success
|
||||
&& from >= "0001-01-01"
|
||||
&& from <= to
|
||||
? { from, to }
|
||||
: {
|
||||
from: `${month}-01`,
|
||||
|
||||
@@ -1,67 +1,75 @@
|
||||
import { SimpleGrid } from "@mantine/core";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
|
||||
import { SimpleGrid } from "@mantine/core";
|
||||
|
||||
import { BankCardFace } from "./BankCardFace";
|
||||
|
||||
const meta = {
|
||||
title: "Product/BankCards/CardAppearance",
|
||||
component: BankCardFace,
|
||||
tags: ["autodocs"],
|
||||
const meta = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
args: {
|
||||
card: {
|
||||
id: "fictional",
|
||||
name: "Для повседневных покупок",
|
||||
bankName: "Сбербанк",
|
||||
lastFour: "4829",
|
||||
paymentSystem: "mir",
|
||||
openingBalance: { value: "0", currency: "RUB" },
|
||||
openingDate: "2026-01-01",
|
||||
balance: { value: "128450.75", currency: "RUB" },
|
||||
archivedAt: null,
|
||||
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,
|
||||
},
|
||||
},
|
||||
} satisfies Meta<typeof BankCardFace>;
|
||||
component: BankCardFace,
|
||||
tags: ["autodocs"],
|
||||
title: "Product/BankCards/CardAppearance",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */) satisfies Meta<typeof BankCardFace>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
export const Banks: Story = {
|
||||
render: (args) => (
|
||||
render: arguments_ => (
|
||||
<SimpleGrid cols={{ base: 1, sm: 2 }} maw={920}>
|
||||
{["Сбербанк", "Т-Банк", "Альфа-Банк", "ВТБ", null].map(
|
||||
{["Сбербанк", "Т-Банк", "Альфа-Банк", "ВТБ", /* 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]
|
||||
?? null,
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */)}
|
||||
key={bankName ?? "unknown"}
|
||||
card={{
|
||||
...args.card,
|
||||
bankName,
|
||||
paymentSystem:
|
||||
(["mir", "mastercard", "visa", "mir", null] as const)[index] ??
|
||||
null,
|
||||
}}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</SimpleGrid>
|
||||
),
|
||||
};
|
||||
export const MissingDetails: Story = {
|
||||
args: {
|
||||
card: {
|
||||
...meta.args.card,
|
||||
bankName: null,
|
||||
lastFour: null,
|
||||
paymentSystem: null,
|
||||
export const MissingDetails: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
args: {
|
||||
card: {
|
||||
...meta.args.card,
|
||||
bankName: null,
|
||||
lastFour: null,
|
||||
paymentSystem: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
export const LongArchived: Story = {
|
||||
args: {
|
||||
card: {
|
||||
...meta.args.card,
|
||||
name: "Карта с очень длинным пользовательским названием для повседневных покупок",
|
||||
bankName: "Банк с очень длинным названием без пробелов".repeat(2),
|
||||
archivedAt: "2026-09-12",
|
||||
balance: { currency: "RUB", value: "184467440737095516.14" },
|
||||
bankName: "Банк с очень длинным названием без пробелов".repeat(2),
|
||||
name: "Карта с очень длинным пользовательским названием для повседневных покупок",
|
||||
paymentSystem: "mastercard",
|
||||
balance: { value: "184467440737095516.14", currency: "RUB" },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { formatMoney } from "@/shared/lib";
|
||||
|
||||
import type { BankCard } from "../../api/queries";
|
||||
|
||||
import classes from "./BankCardFace.module.css";
|
||||
|
||||
type BankCardFaceProps = { card: BankCard };
|
||||
@@ -9,15 +13,7 @@ const BankCardFace: FC<BankCardFaceProps> = (props) => {
|
||||
const { card } = props;
|
||||
const { t } = useTranslation();
|
||||
const bank = card.bankName?.toLocaleLowerCase("ru") ?? "";
|
||||
const tone = /сбер|sber/.test(bank)
|
||||
? "green"
|
||||
: /тинькофф|т[ -]?банк|t[ -]?bank|tinkoff/.test(bank)
|
||||
? "yellow"
|
||||
: /альфа|alfa/.test(bank)
|
||||
? "red"
|
||||
: /втб|vtb|газпром|gazprom/.test(bank)
|
||||
? "blue"
|
||||
: "graphite";
|
||||
const tone = bankTone(bank);
|
||||
return (
|
||||
<div className={classes.face} data-tone={tone}>
|
||||
<div className={classes.top}>
|
||||
@@ -26,26 +22,28 @@ const BankCardFace: FC<BankCardFaceProps> = (props) => {
|
||||
<span className={classes.archive}>{t("bank.archived")}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className={classes.hardware} aria-hidden="true">
|
||||
<div aria-hidden="true" className={classes.hardware}>
|
||||
<span className={classes.chip} />
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
width="24"
|
||||
fill="none"
|
||||
height="30"
|
||||
viewBox="0 0 24 30"
|
||||
fill="none"
|
||||
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"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeWidth="2"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div
|
||||
className={classes.number}
|
||||
>{`•••• •••• •••• ${card.lastFour || "••••"}`}</div>
|
||||
>
|
||||
{`•••• •••• •••• ${card.lastFour || "••••"}`}
|
||||
</div>
|
||||
<div className={classes.bottom}>
|
||||
<div className={classes.details}>
|
||||
<div className={classes.name}>{card.name}</div>
|
||||
@@ -54,7 +52,7 @@ const BankCardFace: FC<BankCardFaceProps> = (props) => {
|
||||
{card.paymentSystem && (
|
||||
<span className={classes.network} data-network={card.paymentSystem}>
|
||||
{card.paymentSystem === "mastercard" && (
|
||||
<span className={classes.circles} aria-hidden="true" />
|
||||
<span aria-hidden="true" className={classes.circles} />
|
||||
)}
|
||||
{t(`bank.paymentSystems.${card.paymentSystem}`)}
|
||||
</span>
|
||||
@@ -64,4 +62,11 @@ const BankCardFace: FC<BankCardFaceProps> = (props) => {
|
||||
);
|
||||
};
|
||||
|
||||
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";
|
||||
}
|
||||
|
||||
export { BankCardFace };
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
|
||||
import type { BankCardValues } from "../../model/form-validation";
|
||||
|
||||
import { BankCardFields } from "./BankCardForm.view";
|
||||
|
||||
const meta = {
|
||||
title: "Product/BankCards/CardFields",
|
||||
component: BankCardFields,
|
||||
tags: ["autodocs"],
|
||||
args: { archived: false },
|
||||
component: BankCardFields,
|
||||
decorators: [
|
||||
(Story) => {
|
||||
const methods = useForm<BankCardValues>({
|
||||
defaultValues: {
|
||||
name: "Учебная повседневная карта",
|
||||
bankName: "Вымышленный банк",
|
||||
lastFour: "1234",
|
||||
name: "Учебная повседневная карта",
|
||||
openingBalance: "-92233720368547758.08",
|
||||
openingDate: "2026-08-01",
|
||||
},
|
||||
@@ -34,11 +35,13 @@ 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 = {
|
||||
name: "Финансовые поля архивной карты",
|
||||
args: { archived: true },
|
||||
name: "Финансовые поля архивной карты",
|
||||
};
|
||||
|
||||
@@ -1,31 +1,36 @@
|
||||
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 { http, HttpResponse } from "msw";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createTestQueryClient } from "@/test/query";
|
||||
import { server } from "@/test/server";
|
||||
|
||||
import type { BankCard } from "../../api/queries";
|
||||
|
||||
import { BankCardForm } from "./BankCardForm";
|
||||
|
||||
const card: BankCard = {
|
||||
id: "a",
|
||||
name: "Основная",
|
||||
bankName: "Банк",
|
||||
lastFour: "1234",
|
||||
paymentSystem: null,
|
||||
openingBalance: { currency: "RUB", value: "100" },
|
||||
balance: { currency: "RUB", value: "50" },
|
||||
openingDate: "2026-01-01",
|
||||
archivedAt: null,
|
||||
version: 1,
|
||||
};
|
||||
const card: BankCard = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
archivedAt: null,
|
||||
balance: { currency: "RUB", value: "50" },
|
||||
bankName: "Банк",
|
||||
id: "a",
|
||||
lastFour: "1234",
|
||||
name: "Основная",
|
||||
openingBalance: { currency: "RUB", value: "100" },
|
||||
openingDate: "2026-01-01",
|
||||
paymentSystem: null,
|
||||
version: 1,
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
function setup(value: BankCard) {
|
||||
configureAuthClient({
|
||||
accessToken: () => "test",
|
||||
refresh: async () => false,
|
||||
clear: () => {},
|
||||
refresh: () => Promise.resolve(false),
|
||||
});
|
||||
server.use(http.get("*/api/v1/bank-cards/a", () => HttpResponse.json(value)));
|
||||
const close = vi.fn();
|
||||
@@ -64,13 +69,15 @@ describe("BankCardForm", () => {
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||
expect(body).toEqual({
|
||||
version: 1,
|
||||
name: "Основная",
|
||||
bankName: null,
|
||||
lastFour: null,
|
||||
paymentSystem: null,
|
||||
});
|
||||
expect(body).toEqual((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
bankName: null,
|
||||
lastFour: null,
|
||||
name: "Основная",
|
||||
paymentSystem: null,
|
||||
version: 1,
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */));
|
||||
});
|
||||
it("loads and saves the selected payment system", async () => {
|
||||
const close = setup({ ...card, paymentSystem: "mir" });
|
||||
@@ -146,6 +153,6 @@ describe("BankCardForm", () => {
|
||||
fireEvent.click(adopt);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||
expect(bodies.map((b) => b.version)).toEqual([1, 2]);
|
||||
expect(bodies.map(b => b.version)).toEqual([1, 2]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,12 +3,14 @@ import { Button, Group, Modal, Stack, Text } from "@mantine/core";
|
||||
import { type FC, useState } from "react";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { formatDate } from "@/shared/lib";
|
||||
|
||||
import { useBankMutations } from "../../api/mutations";
|
||||
import { type BankCard, useBankCard } from "../../api/queries";
|
||||
import {
|
||||
type BankCardValues,
|
||||
bankCardSchema,
|
||||
type BankCardValues,
|
||||
bankMoneyValue,
|
||||
bankToday,
|
||||
} from "../../model/form-validation";
|
||||
@@ -29,29 +31,29 @@ const BankCardForm: FC<BankCardFormProps> = (props) => {
|
||||
const fresh = useBankCard(props.card?.id);
|
||||
const mutation = useBankMutations();
|
||||
const methods = useForm<BankCardValues>({
|
||||
resolver: zodResolver(bankCardSchema),
|
||||
defaultValues: {
|
||||
name: props.card?.name ?? "",
|
||||
bankName: props.card?.bankName ?? "",
|
||||
lastFour: props.card?.lastFour ?? "",
|
||||
paymentSystem: props.card?.paymentSystem ?? "",
|
||||
name: props.card?.name ?? "",
|
||||
openingBalance: props.card?.openingBalance.value ?? "0",
|
||||
openingDate: props.card?.openingDate ?? bankToday(),
|
||||
paymentSystem: props.card?.paymentSystem ?? "",
|
||||
},
|
||||
resolver: zodResolver(bankCardSchema),
|
||||
});
|
||||
const pending =
|
||||
!opened ||
|
||||
methods.formState.isSubmitting ||
|
||||
(fresh.isFetching && Boolean(error));
|
||||
const isPending
|
||||
= !opened
|
||||
|| methods.formState.isSubmitting
|
||||
|| (fresh.isFetching && Boolean(error));
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
closeButtonProps={{ "aria-label": t("bank.close"), "disabled": isPending }}
|
||||
closeOnClickOutside={!isPending}
|
||||
closeOnEscape={!isPending}
|
||||
onClose={() => !isPending && setOpened(false)}
|
||||
onExitTransitionEnd={props.onClose}
|
||||
onClose={() => !pending && setOpened(false)}
|
||||
opened={opened}
|
||||
title={t(props.card ? "bank.editCard" : "bank.addCard")}
|
||||
closeButtonProps={{ "aria-label": t("bank.close"), disabled: pending }}
|
||||
closeOnClickOutside={!pending}
|
||||
closeOnEscape={!pending}
|
||||
>
|
||||
<FormProvider {...methods}>
|
||||
<form
|
||||
@@ -59,10 +61,10 @@ const BankCardForm: FC<BankCardFormProps> = (props) => {
|
||||
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,
|
||||
bankName: values.bankName || null,
|
||||
lastFour: values.lastFour || null,
|
||||
paymentSystem: values.paymentSystem || null,
|
||||
paymentSystem: values.paymentSystem || /* eslint-disable-line unicorn/no-null -- PATCH uses null to clear these optional card fields. */ null,
|
||||
};
|
||||
const financial = {
|
||||
openingBalance: {
|
||||
@@ -73,12 +75,12 @@ const BankCardForm: FC<BankCardFormProps> = (props) => {
|
||||
};
|
||||
if (props.card)
|
||||
await mutation.updateCard.mutateAsync({
|
||||
id: props.card.id,
|
||||
body: {
|
||||
...metadata,
|
||||
...(!props.card.archivedAt ? financial : {}),
|
||||
...(!props.card.archivedAt && financial),
|
||||
version,
|
||||
},
|
||||
id: props.card.id,
|
||||
});
|
||||
else
|
||||
await mutation.createCard.mutateAsync({
|
||||
@@ -87,32 +89,33 @@ const BankCardForm: FC<BankCardFormProps> = (props) => {
|
||||
...financial,
|
||||
});
|
||||
setOpened(false);
|
||||
} catch (failure) {
|
||||
setError(failure);
|
||||
}
|
||||
catch (error_) {
|
||||
setError(error_);
|
||||
}
|
||||
})}
|
||||
>
|
||||
<fieldset className={classes.fieldset} disabled={pending}>
|
||||
<fieldset className={classes.fieldset} disabled={isPending}>
|
||||
<Stack>
|
||||
<BankCardFields archived={Boolean(props.card?.archivedAt)} />
|
||||
{error ? (
|
||||
{!!(error) && ((
|
||||
<>
|
||||
<BankFeedback error={error} />
|
||||
{props.card && (
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={async () => {
|
||||
const response = await fresh.refetch();
|
||||
if (response.data && !response.error)
|
||||
setLatest(response.data);
|
||||
else setError(response.error);
|
||||
}}
|
||||
variant="default"
|
||||
>
|
||||
{t("bank.reloadRecord")}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
))}
|
||||
{latest && (
|
||||
<>
|
||||
<Text>
|
||||
@@ -121,22 +124,22 @@ const BankCardForm: FC<BankCardFormProps> = (props) => {
|
||||
})}
|
||||
</Text>
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={() => {
|
||||
setVersion(latest.version);
|
||||
setLatest(undefined);
|
||||
setError(undefined);
|
||||
}}
|
||||
variant="default"
|
||||
>
|
||||
{t("bank.adoptVersion", { version: latest.version })}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Group>
|
||||
<Button type="submit" loading={pending}>
|
||||
<Button loading={isPending} type="submit">
|
||||
{t("bank.save")}
|
||||
</Button>
|
||||
<Button variant="default" onClick={() => setOpened(false)}>
|
||||
<Button onClick={() => setOpened(false)} variant="default">
|
||||
{t("bank.cancel")}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { Select, Stack, Text, TextInput } from "@mantine/core";
|
||||
import { DateInput } from "@mantine/dates";
|
||||
import type { FC } from "react";
|
||||
import { Controller, useFormContext } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import {
|
||||
type BankCardValues,
|
||||
bankDateInputValue,
|
||||
@@ -14,8 +16,8 @@ type BankCardFieldsProps = { archived: boolean };
|
||||
const BankCardFields: FC<BankCardFieldsProps> = (props) => {
|
||||
const {
|
||||
control,
|
||||
register,
|
||||
formState: { errors },
|
||||
register,
|
||||
} = useFormContext<BankCardValues>();
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
@@ -32,8 +34,8 @@ const BankCardFields: FC<BankCardFieldsProps> = (props) => {
|
||||
error={errors.bankName?.message}
|
||||
/>
|
||||
<TextInput
|
||||
label={t("bank.lastFour")}
|
||||
inputMode="numeric"
|
||||
label={t("bank.lastFour")}
|
||||
{...register("lastFour")}
|
||||
error={errors.lastFour?.message}
|
||||
/>
|
||||
@@ -43,25 +45,25 @@ const BankCardFields: FC<BankCardFieldsProps> = (props) => {
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
{...field}
|
||||
value={field.value || null}
|
||||
onChange={(value) => field.onChange(value ?? "")}
|
||||
label={t("bank.paymentSystem")}
|
||||
placeholder={t("bank.paymentSystemUnknown")}
|
||||
clearable
|
||||
data={["mir", "visa", "mastercard"].map((value) => ({
|
||||
value,
|
||||
label: t(`bank.paymentSystems.${value}`),
|
||||
}))}
|
||||
comboboxProps={{ withinPortal: false }}
|
||||
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}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<TextInput
|
||||
label={t("bank.openingBalance")}
|
||||
required
|
||||
inputMode="decimal"
|
||||
label={t("bank.openingBalance")}
|
||||
readOnly={props.archived}
|
||||
required
|
||||
{...register("openingBalance")}
|
||||
error={errors.openingBalance?.message}
|
||||
/>
|
||||
@@ -71,37 +73,35 @@ const BankCardFields: FC<BankCardFieldsProps> = (props) => {
|
||||
render={({ field }) => (
|
||||
<DateInput
|
||||
{...field}
|
||||
label={t("bank.openingDate")}
|
||||
required
|
||||
valueFormat="DD.MM.YYYY"
|
||||
value={
|
||||
bankDateSchema.safeParse(field.value).success ? field.value : null
|
||||
}
|
||||
dateParser={(value) =>
|
||||
dateParser={value =>
|
||||
bankDateSchema.safeParse(bankDateInputValue(value)).success
|
||||
? bankDateInputValue(value)
|
||||
: null
|
||||
}
|
||||
: /* eslint-disable-line unicorn/no-null -- Mantine represents an empty controlled field as null. */ null}
|
||||
error={errors.openingDate?.message}
|
||||
fixOnBlur={false}
|
||||
onInput={(event) =>
|
||||
field.onChange(bankDateInputValue(event.currentTarget.value))
|
||||
}
|
||||
onChange={(value) => field.onChange(value ?? "")}
|
||||
label={t("bank.openingDate")}
|
||||
maxDate={bankToday()}
|
||||
onBlur={(event) => {
|
||||
field.onChange(bankDateInputValue(event.currentTarget.value));
|
||||
field.onBlur();
|
||||
}}
|
||||
maxDate={bankToday()}
|
||||
onChange={value => field.onChange(value ?? "")}
|
||||
onInput={event =>
|
||||
field.onChange(bankDateInputValue(event.currentTarget.value))}
|
||||
popoverProps={{
|
||||
withinPortal: false,
|
||||
middlewares: { shift: { crossAxis: true } },
|
||||
withinPortal: false,
|
||||
}}
|
||||
readOnly={props.archived}
|
||||
error={errors.openingDate?.message}
|
||||
required
|
||||
value={
|
||||
(bankDateSchema.safeParse(field.value).success) ? (field.value) : undefined
|
||||
}
|
||||
valueFormat="DD.MM.YYYY"
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Text size="sm" c="dimmed">
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("bank.openingHint")}
|
||||
</Text>
|
||||
{props.archived && <Text>{t("bank.archiveHint")}</Text>}
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { Alert, Button, Group, Text } from "@mantine/core";
|
||||
import type { FC } from "react";
|
||||
|
||||
import { Alert, Button, Group, Text } from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { apiErrorCode } from "@/shared/api";
|
||||
|
||||
type BankFeedbackProps = {
|
||||
error: unknown;
|
||||
retry?: () => void;
|
||||
cached?: boolean;
|
||||
error: unknown;
|
||||
loadingError?: boolean;
|
||||
retry?: () => void;
|
||||
};
|
||||
const BankFeedback: FC<BankFeedbackProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
@@ -25,7 +27,7 @@ const BankFeedback: FC<BankFeedbackProps> = (props) => {
|
||||
})}
|
||||
</Text>
|
||||
{props.retry && (
|
||||
<Button variant="default" onClick={props.retry}>
|
||||
<Button onClick={props.retry} variant="default">
|
||||
{t("bank.retry")}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { Stack } from "@mantine/core";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
|
||||
import { Stack } from "@mantine/core";
|
||||
import { EntryCard } from "@wealthledger/ui";
|
||||
|
||||
import { BankOperationIcon } from "./BankOperationIcon";
|
||||
|
||||
const meta = {
|
||||
title: "Product/BankCards/OperationIcons",
|
||||
args: { categoryName: "Продукты", kind: "expense" },
|
||||
component: BankOperationIcon,
|
||||
tags: ["autodocs"],
|
||||
args: { kind: "expense", categoryName: "Продукты" },
|
||||
title: "Product/BankCards/OperationIcons",
|
||||
} satisfies Meta<typeof BankOperationIcon>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
@@ -40,28 +42,28 @@ export const Categories: Story = {
|
||||
"Хостинг и ИИ-сервисы",
|
||||
"Цифровые покупки",
|
||||
"Моя категория",
|
||||
].map((name) => (
|
||||
].map(name => (
|
||||
<EntryCard
|
||||
key={name}
|
||||
title="Расход"
|
||||
metadata={`12.09.2026 · ${name}`}
|
||||
initial="Р"
|
||||
color="red"
|
||||
icon={<BankOperationIcon kind="expense" categoryName={name} />}
|
||||
icon={<BankOperationIcon categoryName={name} kind="expense" />}
|
||||
initial="Р"
|
||||
key={name}
|
||||
metadata={`12.09.2026 · ${name}`}
|
||||
title="Расход"
|
||||
tone="negative"
|
||||
value="−1 250,00 ₽"
|
||||
valueLabel="Расход"
|
||||
tone="negative"
|
||||
/>
|
||||
))}
|
||||
<EntryCard
|
||||
title="Пополнение"
|
||||
metadata="12.09.2026"
|
||||
initial="П"
|
||||
color="green"
|
||||
icon={<BankOperationIcon kind="topup" />}
|
||||
initial="П"
|
||||
metadata="12.09.2026"
|
||||
title="Пополнение"
|
||||
tone="positive"
|
||||
value="+15 000,00 ₽"
|
||||
valueLabel="Пополнение"
|
||||
tone="positive"
|
||||
/>
|
||||
</Stack>
|
||||
),
|
||||
|
||||
@@ -1,36 +1,40 @@
|
||||
import { render } from "@testing-library/react";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { BankOperationIcon } from "./BankOperationIcon";
|
||||
|
||||
it("matches normalized category names, falls back after renaming and distinguishes operation kinds", () => {
|
||||
const { container, rerender } = render(
|
||||
<BankOperationIcon kind="expense" categoryName="Жильё" />,
|
||||
<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();
|
||||
rerender(<BankOperationIcon kind="expense" categoryName=" ЖИЛЬЕ " />);
|
||||
rerender(<BankOperationIcon categoryName=" ЖИЛЬЕ " kind="expense" />);
|
||||
expect(path()).toBe(housing);
|
||||
rerender(<BankOperationIcon kind="expense" categoryName="Другое" />);
|
||||
rerender(<BankOperationIcon categoryName="Другое" kind="expense" />);
|
||||
const fallback = path();
|
||||
expect(fallback).not.toBe(housing);
|
||||
for (const categoryName of ["Моя категория", "constructor", null]) {
|
||||
rerender(<BankOperationIcon kind="expense" categoryName={categoryName} />);
|
||||
for (const categoryName of ["Моя категория", "constructor", /* eslint-disable-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 kind={kind} categoryName="Жильё" />);
|
||||
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");
|
||||
});
|
||||
|
||||
it("provides a distinct icon for every existing named category", () => {
|
||||
const { container, rerender } = render(
|
||||
<BankOperationIcon kind="expense" categoryName="Другое" />,
|
||||
<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 [
|
||||
"Алкоголь",
|
||||
@@ -57,7 +61,8 @@ it("provides a distinct icon for every existing named category", () => {
|
||||
"Хостинг и ИИ-сервисы",
|
||||
"Цифровые покупки",
|
||||
]) {
|
||||
rerender(<BankOperationIcon kind="expense" categoryName={categoryName} />);
|
||||
rerender(<BankOperationIcon categoryName={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");
|
||||
expect(path).toBeTruthy();
|
||||
expect(paths.has(path), categoryName).toBe(false);
|
||||
|
||||
@@ -1,34 +1,36 @@
|
||||
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"];
|
||||
categoryName?: string | null;
|
||||
};
|
||||
const BankOperationIcon: FC<BankOperationIconProps> = (props) => {
|
||||
const icon = bankOperationAppearance(props.kind, props.categoryName);
|
||||
return (
|
||||
<svg
|
||||
ref={bindIconAnimation}
|
||||
aria-hidden="true"
|
||||
className={`${classes.icon} ${icon.animation ? classes[icon.animation] : ""}`}
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
focusable="false"
|
||||
height="24"
|
||||
ref={bindIconAnimation}
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.6"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
style={{ flexShrink: 0, color: `var(--mantine-color-${icon.color}-7)` }}
|
||||
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 key={part} d={index ? `M${part}` : part} pathLength={1} />
|
||||
<path d={index ? `M${part}` : part} key={part} pathLength={1} />
|
||||
))}
|
||||
</svg>
|
||||
);
|
||||
|
||||
@@ -3,34 +3,34 @@ import { type FC, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
type BankPeriodPickerProps = {
|
||||
onChange: (value: [null | string, null | string]) => void;
|
||||
period: { from: string; to: string };
|
||||
onChange: (value: [string | null, string | null]) => void;
|
||||
};
|
||||
const BankPeriodPicker: FC<BankPeriodPickerProps> = (props) => {
|
||||
const { period, onChange } = props;
|
||||
const { onChange, period } = props;
|
||||
const { t } = useTranslation();
|
||||
const scope = `${period.from}-${period.to}`;
|
||||
const [draft, setDraft] = useState<{
|
||||
scope: string;
|
||||
value: [string | null, string | null];
|
||||
value: [null | string, null | string];
|
||||
}>();
|
||||
const value: [string | null, string | null] =
|
||||
draft?.scope === scope ? draft.value : [period.from, period.to];
|
||||
const value: [null | string, null | string]
|
||||
= draft?.scope === scope ? draft.value : [period.from, period.to];
|
||||
return (
|
||||
<DatePickerInput
|
||||
type="range"
|
||||
allowSingleDateInRange
|
||||
label={t("bank.period")}
|
||||
valueFormat="DD.MM.YYYY"
|
||||
value={value}
|
||||
onChange={(next) => {
|
||||
setDraft({ scope, value: next });
|
||||
onChange(next);
|
||||
}}
|
||||
popoverProps={{
|
||||
returnFocus: true,
|
||||
middlewares: { shift: { crossAxis: true } },
|
||||
returnFocus: true,
|
||||
}}
|
||||
type="range"
|
||||
value={value}
|
||||
valueFormat="DD.MM.YYYY"
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,11 +1,54 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
|
||||
import { BankSummaryView } from "./BankSummary.view";
|
||||
|
||||
const money = (value: string) => ({ currency: "RUB", value });
|
||||
const meta = {
|
||||
title: "Product/BankCards/Summary",
|
||||
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"),
|
||||
},
|
||||
error: false,
|
||||
fetching: false,
|
||||
loading: false,
|
||||
retry: () => {},
|
||||
},
|
||||
component: BankSummaryView,
|
||||
tags: ["autodocs"],
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
@@ -14,118 +57,84 @@ const meta = {
|
||||
},
|
||||
},
|
||||
},
|
||||
args: {
|
||||
loading: false,
|
||||
error: false,
|
||||
fetching: false,
|
||||
retry: () => {},
|
||||
data: {
|
||||
month: "2026-09",
|
||||
cardId: null,
|
||||
expenses: money("8500"),
|
||||
refunds: money("1000"),
|
||||
net: money("7500"),
|
||||
categories: [
|
||||
{
|
||||
categoryId: "food",
|
||||
categoryName: "Продукты",
|
||||
expenses: money("3500"),
|
||||
refunds: money("1000"),
|
||||
net: money("2500"),
|
||||
},
|
||||
{
|
||||
categoryId: "cafe",
|
||||
categoryName: "Кафе",
|
||||
expenses: money("2200"),
|
||||
refunds: money("0"),
|
||||
net: money("2200"),
|
||||
},
|
||||
{
|
||||
categoryId: "taxi",
|
||||
categoryName: "Такси",
|
||||
expenses: money("1800"),
|
||||
refunds: money("0"),
|
||||
net: money("1800"),
|
||||
},
|
||||
{
|
||||
categoryId: "health",
|
||||
categoryName: "Здоровье",
|
||||
expenses: money("1000"),
|
||||
refunds: money("0"),
|
||||
net: money("1000"),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
} satisfies Meta<typeof BankSummaryView>;
|
||||
tags: ["autodocs"],
|
||||
title: "Product/BankCards/Summary",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */) satisfies Meta<typeof BankSummaryView>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
export const Loaded: Story = { name: "Расходы по категориям" };
|
||||
export const RefundMonth: Story = {
|
||||
name: "Возврат покупки прошлого месяца",
|
||||
args: {
|
||||
data: {
|
||||
month: "2026-09",
|
||||
cardId: null,
|
||||
expenses: money("0"),
|
||||
refunds: money("600"),
|
||||
net: money("-600"),
|
||||
categories: [
|
||||
{
|
||||
categoryId: "shopping",
|
||||
categoryName:
|
||||
export const RefundMonth: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
args: {
|
||||
data: {
|
||||
cardId: null,
|
||||
categories: [
|
||||
{
|
||||
categoryId: "shopping",
|
||||
categoryName:
|
||||
"Покупки с длинным пользовательским названием категории",
|
||||
expenses: money("0"),
|
||||
refunds: money("600"),
|
||||
net: money("-600"),
|
||||
},
|
||||
],
|
||||
expenses: money("0"),
|
||||
net: money("-600"),
|
||||
refunds: money("600"),
|
||||
},
|
||||
],
|
||||
expenses: money("0"),
|
||||
month: "2026-09",
|
||||
net: money("-600"),
|
||||
refunds: money("600"),
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
export const Empty: Story = {
|
||||
name: "Известные нули",
|
||||
args: {
|
||||
data: {
|
||||
month: "2026-09",
|
||||
cardId: null,
|
||||
expenses: money("0"),
|
||||
refunds: money("0"),
|
||||
net: money("0"),
|
||||
categories: [],
|
||||
name: "Возврат покупки прошлого месяца",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
export const Empty: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
args: {
|
||||
data: {
|
||||
cardId: null,
|
||||
categories: [],
|
||||
expenses: money("0"),
|
||||
month: "2026-09",
|
||||
net: money("0"),
|
||||
refunds: money("0"),
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
name: "Известные нули",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
export const Loading: Story = {
|
||||
name: "Начальная загрузка",
|
||||
args: { data: undefined, loading: true },
|
||||
name: "Начальная загрузка",
|
||||
};
|
||||
export const Failed: Story = {
|
||||
name: "Ошибка без данных",
|
||||
args: { data: undefined, error: true },
|
||||
name: "Ошибка без данных",
|
||||
};
|
||||
export const CachedError: Story = {
|
||||
name: "Сохранённые суммы при ошибке обновления",
|
||||
args: { error: true },
|
||||
name: "Сохранённые суммы при ошибке обновления",
|
||||
};
|
||||
export const LongAmounts: Story = {
|
||||
name: "Точный итог длиннее предела отдельного ввода",
|
||||
args: {
|
||||
data: {
|
||||
month: "2026-09",
|
||||
cardId: null,
|
||||
expenses: money("184467440737095516.14"),
|
||||
refunds: money("0"),
|
||||
net: money("184467440737095516.14"),
|
||||
categories: [
|
||||
{
|
||||
categoryId: "shopping",
|
||||
categoryName: "Покупки",
|
||||
expenses: money("184467440737095516.14"),
|
||||
refunds: money("0"),
|
||||
net: money("184467440737095516.14"),
|
||||
},
|
||||
],
|
||||
export const LongAmounts: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
args: {
|
||||
data: {
|
||||
cardId: null,
|
||||
categories: [
|
||||
{
|
||||
categoryId: "shopping",
|
||||
categoryName: "Покупки",
|
||||
expenses: money("184467440737095516.14"),
|
||||
net: money("184467440737095516.14"),
|
||||
refunds: money("0"),
|
||||
},
|
||||
],
|
||||
expenses: money("184467440737095516.14"),
|
||||
month: "2026-09",
|
||||
net: money("184467440737095516.14"),
|
||||
refunds: money("0"),
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
name: "Точный итог длиннее предела отдельного ввода",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
|
||||
@@ -1,24 +1,78 @@
|
||||
import type { CSSProperties, FC } from "react";
|
||||
|
||||
import { Button, Group, Skeleton, Stack, Text, Title } from "@mantine/core";
|
||||
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||
import type { CSSProperties, FC } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { formatMoney } from "@/shared/lib";
|
||||
|
||||
import type { BankSummary } from "../../api/queries";
|
||||
|
||||
import { BankOperationIcon } from "../BankOperationIcon/BankOperationIcon";
|
||||
import classes from "./BankSummary.module.css";
|
||||
|
||||
const CATEGORY_COLUMNS = 2;
|
||||
|
||||
type BankSummaryViewProps = {
|
||||
all?: boolean;
|
||||
data?: BankSummary;
|
||||
loading: boolean;
|
||||
error: boolean;
|
||||
fetching: boolean;
|
||||
loading: boolean;
|
||||
retry: () => void;
|
||||
all?: boolean;
|
||||
};
|
||||
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 gap="md" aria-busy={props.loading || props.fetching}>
|
||||
<Stack aria-busy={props.loading || props.fetching} gap="md">
|
||||
<div className={classes.header}>
|
||||
<Title order={2}>
|
||||
{t(props.all ? "bank.allSummary" : "bank.summary")}
|
||||
@@ -29,49 +83,11 @@ const BankSummaryView: FC<BankSummaryViewProps> = (props) => {
|
||||
</Text>
|
||||
)}
|
||||
</div>
|
||||
{props.data ? (
|
||||
props.data.categories.length ? (
|
||||
<dl
|
||||
className={classes.categories}
|
||||
style={
|
||||
{
|
||||
"--category-rows": Math.ceil(props.data.categories.length / 2),
|
||||
} as CSSProperties
|
||||
}
|
||||
>
|
||||
{props.data.categories.map((category) => (
|
||||
<div className={classes.category} key={category.categoryId}>
|
||||
<dt className={classes.label}>
|
||||
<BankOperationIcon
|
||||
kind="expense"
|
||||
categoryName={category.categoryName}
|
||||
/>
|
||||
<span>{category.categoryName}</span>
|
||||
</dt>
|
||||
<dd className={classes.amount}>
|
||||
{formatMoney(category.net, { withZeroCents: true })}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
) : (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("bank.noExpenses")}
|
||||
</Text>
|
||||
)
|
||||
) : props.loading ? (
|
||||
<LoadingSkeleton label={t("bank.loading")}>
|
||||
<Stack gap="sm">
|
||||
<Skeleton h={32} w="35%" />
|
||||
<Skeleton h={40} />
|
||||
<Skeleton h={40} />
|
||||
</Stack>
|
||||
</LoadingSkeleton>
|
||||
) : null}
|
||||
{renderCategories()}
|
||||
{props.error && (
|
||||
<Group role="alert">
|
||||
<Text>{t(props.data ? "bank.refreshError" : "bank.error")}</Text>
|
||||
<Button variant="default" onClick={props.retry}>
|
||||
<Button onClick={props.retry} variant="default">
|
||||
{t("bank.retry")}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
@@ -7,36 +7,36 @@ import {
|
||||
screen,
|
||||
waitFor,
|
||||
} from "@testing-library/react";
|
||||
import { HttpResponse, http } from "msw";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createTestQueryClient } from "@/test/query";
|
||||
import { server } from "@/test/server";
|
||||
|
||||
import { CategoryManager } from "./CategoryManager";
|
||||
|
||||
describe("CategoryManager", () => {
|
||||
it("ignores a late reload for A while editing B and submits B's draft and version", async () => {
|
||||
configureAuthClient({
|
||||
accessToken: () => "test",
|
||||
refresh: async () => false,
|
||||
clear: () => {},
|
||||
refresh: () => Promise.resolve(false),
|
||||
});
|
||||
const categories = [
|
||||
{ id: "a", name: "Первая", isDefault: false, version: 1 },
|
||||
{ id: "b", name: "Вторая", isDefault: false, version: 4 },
|
||||
{ id: "a", isDefault: false, name: "Первая", version: 1 },
|
||||
{ id: "b", isDefault: false, name: "Вторая", version: 4 },
|
||||
];
|
||||
let reads = 0;
|
||||
let release = () => {};
|
||||
const reloaded = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const patches: { id: unknown; body: unknown }[] = [];
|
||||
|
||||
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) =>
|
||||
categories.map(category =>
|
||||
category.id === "a" && reads > 1
|
||||
? {
|
||||
...category,
|
||||
@@ -49,8 +49,8 @@ describe("CategoryManager", () => {
|
||||
}),
|
||||
http.patch(
|
||||
"*/api/v1/bank-cards/categories/:id",
|
||||
async ({ request, params }) => {
|
||||
patches.push({ id: params.id, body: await request.json() });
|
||||
async ({ params, request }) => {
|
||||
patches.push({ body: await request.json(), id: params.id });
|
||||
return patches.length === 1
|
||||
? HttpResponse.json(
|
||||
{ code: "BANK_VERSION_CONFLICT" },
|
||||
@@ -67,9 +67,8 @@ describe("CategoryManager", () => {
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
fireEvent.click(
|
||||
(await screen.findAllByRole("button", { name: "Переименовать" }))[0],
|
||||
);
|
||||
const renameButtons = await screen.findAllByRole("button", { name: "Переименовать" });
|
||||
fireEvent.click(renameButtons[0]);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
fireEvent.click(
|
||||
await screen.findByRole("button", { name: "Перечитать запись" }),
|
||||
@@ -99,8 +98,8 @@ describe("CategoryManager", () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await waitFor(() =>
|
||||
expect(patches).toEqual([
|
||||
{ id: "a", body: { name: "Первая", version: 1 } },
|
||||
{ id: "b", body: { name: "Новая вторая", version: 4 } },
|
||||
{ body: { name: "Первая", version: 1 }, id: "a" },
|
||||
{ body: { name: "Новая вторая", version: 4 }, id: "b" },
|
||||
]),
|
||||
);
|
||||
});
|
||||
@@ -110,15 +109,15 @@ describe("CategoryManager", () => {
|
||||
async (action) => {
|
||||
configureAuthClient({
|
||||
accessToken: () => "test",
|
||||
refresh: async () => false,
|
||||
clear: () => {},
|
||||
refresh: () => Promise.resolve(false),
|
||||
});
|
||||
let version = 1;
|
||||
let writes = 0;
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/categories", () =>
|
||||
HttpResponse.json([
|
||||
{ id: "a", name: "Первая", isDefault: false, version },
|
||||
{ id: "a", isDefault: false, name: "Первая", version },
|
||||
]),
|
||||
),
|
||||
http.patch("*/api/v1/bank-cards/categories/a", () => {
|
||||
@@ -161,13 +160,13 @@ describe("CategoryManager", () => {
|
||||
it("rejects duplicate case-insensitive and too long names then renames default identity", async () => {
|
||||
configureAuthClient({
|
||||
accessToken: () => "test",
|
||||
refresh: async () => false,
|
||||
clear: () => {},
|
||||
refresh: () => Promise.resolve(false),
|
||||
});
|
||||
let category = {
|
||||
id: "default",
|
||||
name: "Другое",
|
||||
isDefault: true,
|
||||
name: "Другое",
|
||||
version: 1,
|
||||
};
|
||||
let creates = 0;
|
||||
|
||||
@@ -17,7 +17,9 @@ import {
|
||||
} from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { z } from "zod";
|
||||
|
||||
import { validationMessage } from "@/shared/i18n";
|
||||
|
||||
import { useBankMutations } from "../../api/mutations";
|
||||
import { type ExpenseCategory, useBankCategories } from "../../api/queries";
|
||||
import { BankFeedback } from "../BankFeedback";
|
||||
@@ -60,44 +62,40 @@ const CategoryManager: FC<CategoryManagerProps> = (props) => {
|
||||
const categories = useBankCategories();
|
||||
const mutation = useBankMutations();
|
||||
const [editing, setEditing] = useState<ExpenseCategory>();
|
||||
const editSession = useRef(0);
|
||||
const editSessionRef = useRef(0);
|
||||
const [error, setError] = useState<unknown>();
|
||||
const [latest, setLatest] = useState<ExpenseCategory>();
|
||||
const methods = useForm<CategoryValues>({
|
||||
resolver: zodResolver(
|
||||
z.object({
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.refine(
|
||||
(value) =>
|
||||
value.length > 0 && value.length <= 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 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"),
|
||||
),
|
||||
}),
|
||||
),
|
||||
defaultValues: { name: "" },
|
||||
{ error: validationMessage("bank.validation.duplicate") },
|
||||
),
|
||||
});
|
||||
const pending = !opened || methods.formState.isSubmitting;
|
||||
const methods = useForm<CategoryValues>({ defaultValues: { name: "" }, resolver: zodResolver(schema) });
|
||||
const isPending = !opened || methods.formState.isSubmitting;
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
closeButtonProps={{ "aria-label": t("bank.close"), "disabled": isPending }}
|
||||
closeOnClickOutside={!isPending}
|
||||
closeOnEscape={!isPending}
|
||||
onClose={() => !isPending && setOpened(false)}
|
||||
onExitTransitionEnd={props.onClose}
|
||||
onClose={() => !pending && setOpened(false)}
|
||||
opened={opened}
|
||||
title={t("bank.categories")}
|
||||
closeOnClickOutside={!pending}
|
||||
closeOnEscape={!pending}
|
||||
closeButtonProps={{ "aria-label": t("bank.close"), disabled: pending }}
|
||||
>
|
||||
<FormProvider {...methods}>
|
||||
<form
|
||||
@@ -107,8 +105,8 @@ const CategoryManager: FC<CategoryManagerProps> = (props) => {
|
||||
try {
|
||||
if (editing)
|
||||
await mutation.updateCategory.mutateAsync({
|
||||
id: editing.id,
|
||||
body: { name: values.name, version: editing.version },
|
||||
id: editing.id,
|
||||
});
|
||||
else {
|
||||
const result = await mutation.createCategory.mutateAsync({
|
||||
@@ -116,24 +114,25 @@ const CategoryManager: FC<CategoryManagerProps> = (props) => {
|
||||
});
|
||||
if (result) props.onCreated?.(result.id);
|
||||
}
|
||||
editSession.current++;
|
||||
editSessionRef.current++;
|
||||
setEditing(undefined);
|
||||
setLatest(undefined);
|
||||
methods.reset({ name: "" });
|
||||
} catch (failure) {
|
||||
setError(failure);
|
||||
}
|
||||
catch (error_) {
|
||||
setError(error_);
|
||||
}
|
||||
})(event);
|
||||
}}
|
||||
>
|
||||
<fieldset disabled={pending} className={classes.fieldset}>
|
||||
<fieldset className={classes.fieldset} disabled={isPending}>
|
||||
<Stack>
|
||||
{categories.data?.map((category) => (
|
||||
{categories.data?.map(category => (
|
||||
<Group justify="space-between" key={category.id}>
|
||||
<Group gap="xs">
|
||||
<BankOperationIcon
|
||||
kind="expense"
|
||||
categoryName={category.name}
|
||||
kind="expense"
|
||||
/>
|
||||
<Text>{category.name}</Text>
|
||||
{category.isDefault && (
|
||||
@@ -141,14 +140,14 @@ const CategoryManager: FC<CategoryManagerProps> = (props) => {
|
||||
)}
|
||||
</Group>
|
||||
<Button
|
||||
variant="subtle"
|
||||
onClick={() => {
|
||||
editSession.current++;
|
||||
editSessionRef.current++;
|
||||
setEditing(category);
|
||||
methods.reset({ name: category.name });
|
||||
setError(undefined);
|
||||
setLatest(undefined);
|
||||
}}
|
||||
variant="subtle"
|
||||
>
|
||||
{t("bank.rename")}
|
||||
</Button>
|
||||
@@ -159,35 +158,35 @@ const CategoryManager: FC<CategoryManagerProps> = (props) => {
|
||||
)}
|
||||
{categories.isError && (
|
||||
<BankFeedback
|
||||
loadingError
|
||||
error={categories.error}
|
||||
cached={Boolean(categories.data)}
|
||||
error={categories.error}
|
||||
loadingError
|
||||
retry={() => void categories.refetch()}
|
||||
/>
|
||||
)}
|
||||
<CategoryFields />
|
||||
{error ? (
|
||||
{!!(error) && ((
|
||||
<>
|
||||
<BankFeedback error={error} />
|
||||
{editing && (
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={async () => {
|
||||
const session = editSession.current;
|
||||
const session = editSessionRef.current;
|
||||
const response = await categories.refetch();
|
||||
if (session !== editSession.current) return;
|
||||
if (session !== editSessionRef.current) return;
|
||||
if (response.error) setError(response.error);
|
||||
else
|
||||
setLatest(
|
||||
response.data?.find((c) => c.id === editing.id),
|
||||
response.data?.find(c => c.id === editing.id),
|
||||
);
|
||||
}}
|
||||
variant="default"
|
||||
>
|
||||
{t("bank.reloadRecord")}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
))}
|
||||
{latest && latest.id === editing?.id && (
|
||||
<>
|
||||
<Text>{t("bank.versionHint", { details: latest.name })}</Text>
|
||||
@@ -203,24 +202,24 @@ const CategoryManager: FC<CategoryManagerProps> = (props) => {
|
||||
</>
|
||||
)}
|
||||
<Group>
|
||||
<Button type="submit" loading={pending}>
|
||||
<Button loading={isPending} type="submit">
|
||||
{t(editing ? "bank.save" : "bank.addCategory")}
|
||||
</Button>
|
||||
{editing && (
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={() => {
|
||||
editSession.current++;
|
||||
editSessionRef.current++;
|
||||
setEditing(undefined);
|
||||
setLatest(undefined);
|
||||
methods.reset({ name: "" });
|
||||
setError(undefined);
|
||||
}}
|
||||
variant="default"
|
||||
>
|
||||
{t("bank.cancel")}
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="default" onClick={() => setOpened(false)}>
|
||||
<Button onClick={() => setOpened(false)} variant="default">
|
||||
{t("bank.close")}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
|
||||
|
||||
const MIN_BOND_SEARCH_LENGTH = 2;
|
||||
|
||||
type BondPeriod = NonNullable<
|
||||
NonNullable<
|
||||
paths["/api/v1/bonds/{uid}/candles"]["get"]["parameters"]["query"]
|
||||
@@ -8,15 +10,6 @@ type BondPeriod = NonNullable<
|
||||
|
||||
const BOND_STALE_TIME_MS = 30_000;
|
||||
|
||||
function useBondSearch(query: string) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds", {
|
||||
params: { query: { query } },
|
||||
}),
|
||||
enabled: query.length >= 2,
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
function bondQueryOptions(uid: string) {
|
||||
return {
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}", {
|
||||
@@ -25,10 +18,9 @@ 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(
|
||||
const isUid
|
||||
= /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
|
||||
identifier,
|
||||
);
|
||||
|
||||
@@ -45,24 +37,7 @@ function useBond(identifier: string) {
|
||||
});
|
||||
return isUid ? byUid : byTicker;
|
||||
}
|
||||
function useBondMetrics(uid: string) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/metrics", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
enabled: Boolean(uid),
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
function useBondQuote(uid: string) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/quote", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
enabled: Boolean(uid),
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
|
||||
function useBondCandles(uid: string, period: BondPeriod) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/candles", {
|
||||
@@ -72,16 +47,6 @@ function useBondCandles(uid: string, period: BondPeriod) {
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
function useBondPosition(uid: string) {
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/position", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
enabled: Boolean(uid),
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
function useBondCoupons(uid: string) {
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
@@ -92,9 +57,46 @@ function useBondCoupons(uid: string) {
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
function useBondMetrics(uid: string) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/metrics", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
enabled: Boolean(uid),
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
function useBondPosition(uid: string) {
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/position", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
enabled: Boolean(uid),
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
function useBondQuote(uid: string) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds/{uid}/quote", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
enabled: Boolean(uid),
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
function useBondSearch(query: string) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/bonds", {
|
||||
params: { query: { query } },
|
||||
}),
|
||||
enabled: query.length >= MIN_BOND_SEARCH_LENGTH,
|
||||
staleTime: BOND_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
|
||||
export {
|
||||
type BondPeriod,
|
||||
export { type BondPeriod,
|
||||
MIN_BOND_SEARCH_LENGTH,
|
||||
useBond,
|
||||
useBondCandles,
|
||||
useBondCoupons,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export {
|
||||
type BondPeriod,
|
||||
export { type BondPeriod,
|
||||
MIN_BOND_SEARCH_LENGTH,
|
||||
useBond,
|
||||
useBondCandles,
|
||||
useBondCoupons,
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { renderHook, waitFor } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createQueryWrapper } from "@/test/query";
|
||||
|
||||
import {
|
||||
brokerageOperationsQueryParams,
|
||||
brokerageOperationsQueryParams as brokerageOperationsQueryParameters,
|
||||
useBrokerageOperations,
|
||||
} from "./useBrokerageOperations";
|
||||
|
||||
@@ -11,11 +13,11 @@ describe("useBrokerageOperations", () => {
|
||||
it("normalizes categories, preserves the cursor and loads a page", async () => {
|
||||
configureAuthClient({
|
||||
accessToken: () => "token",
|
||||
refresh: async () => true,
|
||||
clear: vi.fn(),
|
||||
refresh: () => Promise.resolve(true),
|
||||
});
|
||||
expect(
|
||||
brokerageOperationsQueryParams({
|
||||
brokerageOperationsQueryParameters({
|
||||
categories: ["tax", "income"],
|
||||
cursor: "next",
|
||||
}),
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
|
||||
|
||||
type OperationsEndpoint =
|
||||
paths["/api/v1/brokerage-accounts/{accountId}/operations"]["get"];
|
||||
|
||||
type BrokerageOperation = NonNullable<
|
||||
OperationsEndpoint["responses"][200]["content"]["application/json"]["data"]
|
||||
>["items"][number];
|
||||
|
||||
type BrokerageOperationsQuery = Omit<
|
||||
NonNullable<OperationsEndpoint["parameters"]["query"]>,
|
||||
"sync"
|
||||
>;
|
||||
type OperationCategory = BrokerageOperation["category"];
|
||||
type OperationsEndpoint
|
||||
= paths["/api/v1/brokerage-accounts/{accountId}/operations"]["get"];
|
||||
|
||||
const operationCategories = [
|
||||
"trade",
|
||||
@@ -21,19 +21,6 @@ const operationCategories = [
|
||||
"other",
|
||||
] as const satisfies readonly OperationCategory[];
|
||||
|
||||
function brokerageOperationsQueryParams(query: BrokerageOperationsQuery) {
|
||||
return {
|
||||
...(query.instrumentUid ? { instrumentUid: query.instrumentUid } : {}),
|
||||
...(query.from ? { from: query.from } : {}),
|
||||
...(query.to ? { to: query.to } : {}),
|
||||
...(query.categories?.length
|
||||
? { categories: [...query.categories].sort() }
|
||||
: {}),
|
||||
...(query.cursor ? { cursor: query.cursor } : {}),
|
||||
...(query.limit ? { limit: query.limit } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function brokerageOperationsQueryOptions(
|
||||
accountId: string | undefined,
|
||||
query: BrokerageOperationsQuery = {},
|
||||
@@ -44,12 +31,23 @@ function brokerageOperationsQueryOptions(
|
||||
{
|
||||
params: {
|
||||
path: { accountId: accountId ?? "" },
|
||||
query: brokerageOperationsQueryParams(query),
|
||||
query: brokerageOperationsQueryParameters(query),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function brokerageOperationsQueryParameters(query: BrokerageOperationsQuery) {
|
||||
return {
|
||||
...(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.cursor && { cursor: query.cursor }),
|
||||
...(query.limit && { limit: query.limit }),
|
||||
};
|
||||
}
|
||||
|
||||
function useBrokerageOperations(
|
||||
accountId: string | undefined,
|
||||
query: BrokerageOperationsQuery = {},
|
||||
@@ -65,8 +63,8 @@ function useBrokerageOperations(
|
||||
export {
|
||||
type BrokerageOperation,
|
||||
brokerageOperationsQueryOptions,
|
||||
brokerageOperationsQueryParams,
|
||||
type OperationCategory,
|
||||
brokerageOperationsQueryParameters as brokerageOperationsQueryParams,
|
||||
operationCategories,
|
||||
type OperationCategory,
|
||||
useBrokerageOperations,
|
||||
};
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
export {
|
||||
type BrokerageOperation,
|
||||
brokerageOperationsQueryOptions,
|
||||
type OperationCategory,
|
||||
operationCategories,
|
||||
type OperationCategory,
|
||||
useBrokerageOperations,
|
||||
} from "./api/useBrokerageOperations";
|
||||
export { LedgerEntryRow } from "./ui/LedgerEntryRow";
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { formatMoney } from "@/shared/lib";
|
||||
|
||||
import type { BrokerageOperation } from "../api/useBrokerageOperations";
|
||||
|
||||
type PaymentPresentation = {
|
||||
amount: string;
|
||||
label: string;
|
||||
tone: "positive" | "negative" | "neutral";
|
||||
tone: "negative" | "neutral" | "positive";
|
||||
};
|
||||
|
||||
function entryLabelKey(operation: BrokerageOperation): string {
|
||||
@@ -15,6 +16,44 @@ function entryLabelKey(operation: BrokerageOperation): string {
|
||||
return `ledger.category.${operation.category}`;
|
||||
}
|
||||
|
||||
function isZeroDecimal(value: string): boolean {
|
||||
return /^-?0$|^-?0\.0+$/.test(value);
|
||||
}
|
||||
|
||||
function operationLabelKey(type: string): string {
|
||||
if (
|
||||
[
|
||||
"OPERATION_TYPE_BUY",
|
||||
"OPERATION_TYPE_BUY_CARD",
|
||||
"OPERATION_TYPE_BUY_MARGIN",
|
||||
].includes(type)
|
||||
)
|
||||
return "ledger.operationType.buy";
|
||||
if (
|
||||
[
|
||||
"OPERATION_TYPE_SELL",
|
||||
"OPERATION_TYPE_SELL_CARD",
|
||||
"OPERATION_TYPE_SELL_MARGIN",
|
||||
].includes(type)
|
||||
)
|
||||
return "ledger.operationType.sell";
|
||||
if (
|
||||
[
|
||||
"OPERATION_TYPE_DIV_EXT",
|
||||
"OPERATION_TYPE_DIVIDEND",
|
||||
"OPERATION_TYPE_DIVIDEND_TRANSFER",
|
||||
].includes(type)
|
||||
)
|
||||
return "ledger.operationType.dividend";
|
||||
if (type.includes("TAX")) return "ledger.operationType.tax";
|
||||
if (type.includes("FEE")) return "ledger.operationType.fee";
|
||||
if (type === "OPERATION_TYPE_INPUT_SECURITIES")
|
||||
return "ledger.operationType.input";
|
||||
if (type === "OPERATION_TYPE_OUTPUT_SECURITIES")
|
||||
return "ledger.operationType.output";
|
||||
return type.startsWith("OPERATION_TYPE_TRANS_") ? "ledger.operationType.transfer" : "ledger.operationType.other";
|
||||
}
|
||||
|
||||
function paymentPresentation(
|
||||
operation: BrokerageOperation,
|
||||
): PaymentPresentation {
|
||||
@@ -46,44 +85,4 @@ function paymentPresentation(
|
||||
};
|
||||
}
|
||||
|
||||
function isZeroDecimal(value: string): boolean {
|
||||
return /^-?0(?:\.0+)?$/.test(value);
|
||||
}
|
||||
|
||||
function operationLabelKey(type: string): string {
|
||||
if (
|
||||
[
|
||||
"OPERATION_TYPE_BUY",
|
||||
"OPERATION_TYPE_BUY_CARD",
|
||||
"OPERATION_TYPE_BUY_MARGIN",
|
||||
].includes(type)
|
||||
)
|
||||
return "ledger.operationType.buy";
|
||||
if (
|
||||
[
|
||||
"OPERATION_TYPE_SELL",
|
||||
"OPERATION_TYPE_SELL_CARD",
|
||||
"OPERATION_TYPE_SELL_MARGIN",
|
||||
].includes(type)
|
||||
)
|
||||
return "ledger.operationType.sell";
|
||||
if (
|
||||
[
|
||||
"OPERATION_TYPE_DIVIDEND",
|
||||
"OPERATION_TYPE_DIV_EXT",
|
||||
"OPERATION_TYPE_DIVIDEND_TRANSFER",
|
||||
].includes(type)
|
||||
)
|
||||
return "ledger.operationType.dividend";
|
||||
if (type.includes("TAX")) return "ledger.operationType.tax";
|
||||
if (type.includes("FEE")) return "ledger.operationType.fee";
|
||||
if (type === "OPERATION_TYPE_INPUT_SECURITIES")
|
||||
return "ledger.operationType.input";
|
||||
if (type === "OPERATION_TYPE_OUTPUT_SECURITIES")
|
||||
return "ledger.operationType.output";
|
||||
if (type.startsWith("OPERATION_TYPE_TRANS_"))
|
||||
return "ledger.operationType.transfer";
|
||||
return "ledger.operationType.other";
|
||||
}
|
||||
|
||||
export { operationLabelKey, paymentPresentation };
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { Anchor, Group, Text } from "@mantine/core";
|
||||
import { EntryCard } from "@wealthledger/ui";
|
||||
import type { FC } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
|
||||
import {
|
||||
formatDecimal,
|
||||
formatMoney,
|
||||
formatSnapshotTime,
|
||||
instrumentLogoUrl,
|
||||
} from "@/shared/lib";
|
||||
|
||||
import type { BrokerageOperation } from "../api/useBrokerageOperations";
|
||||
|
||||
import { operationLabelKey, paymentPresentation } from "../model/display";
|
||||
|
||||
type LedgerEntryRowProps = {
|
||||
@@ -20,55 +24,57 @@ type LedgerEntryRowProps = {
|
||||
const LedgerEntryRow: FC<LedgerEntryRowProps> = (props) => {
|
||||
const { operation } = props;
|
||||
const { t } = useTranslation();
|
||||
const instrument =
|
||||
operation.ticker ?? operation.instrumentType ?? t("ledger.noInstrument");
|
||||
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 ? null : operation.account?.name,
|
||||
props.withDetails ? /* eslint-disable-line unicorn/no-null -- Preserve the nullable domain value consumed by this view model. */ null : operation.account?.name,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
|
||||
return (
|
||||
<EntryCard
|
||||
title={operation.description || t(operationLabelKey(operation.type))}
|
||||
metadata={metadata}
|
||||
details={
|
||||
props.withDetails ? (
|
||||
<>
|
||||
<Group gap="sm">
|
||||
{operation.quantity != null ? (
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("ledger.quantity", {
|
||||
value: formatDecimal(operation.quantity),
|
||||
})}
|
||||
</Text>
|
||||
) : null}
|
||||
{operation.price ? (
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("ledger.price", { value: formatMoney(operation.price) })}
|
||||
</Text>
|
||||
) : null}
|
||||
</Group>
|
||||
{operation.account ? (
|
||||
<Anchor
|
||||
component={Link}
|
||||
size="sm"
|
||||
to={`/accounts/${encodeURIComponent(operation.account.id)}`}
|
||||
>
|
||||
{operation.account.name}
|
||||
</Anchor>
|
||||
) : null}
|
||||
</>
|
||||
) : undefined
|
||||
(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
|
||||
}
|
||||
initial={(instrument.trim()[0] ?? "?").toUpperCase()}
|
||||
imageSrc={instrumentLogoUrl(operation.logoName)}
|
||||
initial={(instrument.trim()[0] ?? "?").toUpperCase()}
|
||||
metadata={metadata}
|
||||
title={operation.description || t(operationLabelKey(operation.type))}
|
||||
tone={payment.tone}
|
||||
value={payment.amount}
|
||||
valueLabel={t(payment.label)}
|
||||
tone={payment.tone}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
import { renderHook, waitFor } from "@testing-library/react";
|
||||
import { HttpResponse, http } from "msw";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createQueryWrapper } from "@/test/query";
|
||||
import { resource } from "@/test/resource";
|
||||
import { server } from "@/test/server";
|
||||
|
||||
import { useBrokerageAccounts } from "./useBrokerageAccounts";
|
||||
|
||||
describe("useBrokerageAccounts", () => {
|
||||
it("loads accounts through the authenticated query seam", async () => {
|
||||
configureAuthClient({
|
||||
accessToken: () => "token",
|
||||
refresh: async () => true,
|
||||
clear: vi.fn(),
|
||||
refresh: () => Promise.resolve(true),
|
||||
});
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", () =>
|
||||
@@ -21,8 +23,8 @@ describe("useBrokerageAccounts", () => {
|
||||
{
|
||||
id: "account-1",
|
||||
name: "Основной",
|
||||
type: "BROKERAGE",
|
||||
openedOn: "2024-08-13",
|
||||
type: "BROKERAGE",
|
||||
},
|
||||
]),
|
||||
),
|
||||
@@ -38,8 +40,8 @@ describe("useBrokerageAccounts", () => {
|
||||
{
|
||||
id: "account-1",
|
||||
name: "Основной",
|
||||
type: "BROKERAGE",
|
||||
openedOn: "2024-08-13",
|
||||
type: "BROKERAGE",
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -47,8 +49,8 @@ describe("useBrokerageAccounts", () => {
|
||||
it("keeps the current connection snapshot after a background refetch error", async () => {
|
||||
configureAuthClient({
|
||||
accessToken: () => "token",
|
||||
refresh: async () => true,
|
||||
clear: vi.fn(),
|
||||
refresh: () => Promise.resolve(true),
|
||||
});
|
||||
let calls = 0;
|
||||
server.use(
|
||||
@@ -60,8 +62,8 @@ describe("useBrokerageAccounts", () => {
|
||||
{
|
||||
id: "account-1",
|
||||
name: "Основной",
|
||||
type: "BROKERAGE",
|
||||
openedOn: "2024-08-13",
|
||||
type: "BROKERAGE",
|
||||
},
|
||||
]),
|
||||
)
|
||||
|
||||
@@ -3,24 +3,26 @@ import type {
|
||||
useBrokerageAccounts,
|
||||
} from "../api/useBrokerageAccounts";
|
||||
|
||||
type Money = NonNullable<
|
||||
BrokerageAccount["portfolioSummary"]
|
||||
>["totalsByCurrency"][number];
|
||||
const VISIBLE_CURRENCY_LIMIT = 2;
|
||||
|
||||
type BrokerageAccountCard = {
|
||||
account: BrokerageAccount;
|
||||
positionCounts: null | { bonds: number; stocks: number };
|
||||
source?: NonNullable<
|
||||
ReturnType<typeof useBrokerageAccounts>["meta"]
|
||||
>["dependencies"] extends (infer T)[] | undefined
|
||||
? T
|
||||
: never;
|
||||
account: BrokerageAccount;
|
||||
positionCounts: { stocks: number; bonds: number } | null;
|
||||
summary:
|
||||
| { state: "unavailable" }
|
||||
| { remainingCurrencyCount: number; state: "available"; totals: Money[] }
|
||||
| { state: "empty" }
|
||||
| { state: "available"; totals: Money[]; remainingCurrencyCount: number };
|
||||
| { state: "unavailable" };
|
||||
};
|
||||
|
||||
type Money = NonNullable<
|
||||
BrokerageAccount["portfolioSummary"]
|
||||
>["totalsByCurrency"][number];
|
||||
|
||||
function accountTypeKey(type: BrokerageAccount["type"]) {
|
||||
return `accounts.types.${type}` as const;
|
||||
}
|
||||
@@ -33,34 +35,34 @@ function brokerageAccountCards(
|
||||
): BrokerageAccountCard[] {
|
||||
return accounts.map((account) => {
|
||||
const source = dependencies.find(
|
||||
(item) =>
|
||||
item =>
|
||||
item.resourceKey === `portfolio/${encodeURIComponent(account.id)}`,
|
||||
);
|
||||
const summary = account.portfolioSummary;
|
||||
if (!summary)
|
||||
return {
|
||||
source,
|
||||
account,
|
||||
positionCounts: null,
|
||||
positionCounts: /* eslint-disable-line unicorn/no-null -- The existing formatter contract uses null for unavailable data. */ null,
|
||||
source,
|
||||
summary: { state: "unavailable" },
|
||||
};
|
||||
const positionCounts = {
|
||||
stocks: summary.stockPositionCount,
|
||||
bonds: summary.bondPositionCount,
|
||||
stocks: summary.stockPositionCount,
|
||||
};
|
||||
if (!summary.totalsByCurrency.length)
|
||||
return { source, account, positionCounts, summary: { state: "empty" } };
|
||||
if (summary.totalsByCurrency.length === 0)
|
||||
return { account, positionCounts, source, summary: { state: "empty" } };
|
||||
return {
|
||||
source,
|
||||
account,
|
||||
positionCounts,
|
||||
source,
|
||||
summary: {
|
||||
state: "available",
|
||||
totals: summary.totalsByCurrency.slice(0, 2),
|
||||
remainingCurrencyCount: Math.max(
|
||||
summary.totalsByCurrency.length - 2,
|
||||
summary.totalsByCurrency.length - VISIBLE_CURRENCY_LIMIT,
|
||||
0,
|
||||
),
|
||||
state: "available",
|
||||
totals: summary.totalsByCurrency.slice(0, VISIBLE_CURRENCY_LIMIT),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
+82
-75
@@ -1,34 +1,36 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
|
||||
import { MemoryRouter } from "react-router";
|
||||
|
||||
import type { BrokerageAccount } from "../../api/useBrokerageAccounts";
|
||||
|
||||
import { brokerageAccountCards } from "../../model/display";
|
||||
import { BrokerageAccountList } from "./BrokerageAccountList";
|
||||
|
||||
const syntheticAccount = {
|
||||
id: "storybook-account",
|
||||
name: "Учебный брокерский счёт",
|
||||
type: "BROKERAGE",
|
||||
openedOn: "2025-03-15",
|
||||
portfolioSummary: {
|
||||
stockPositionCount: 5,
|
||||
bondPositionCount: 12,
|
||||
stockPositionCount: 5,
|
||||
totalsByCurrency: [
|
||||
{ currency: "RUB", value: "125000.50" },
|
||||
{ currency: "USD", value: "320" },
|
||||
{ currency: "EUR", value: "210" },
|
||||
],
|
||||
},
|
||||
type: "BROKERAGE",
|
||||
} satisfies BrokerageAccount;
|
||||
|
||||
const meta = {
|
||||
title: "Product/BrokerageAccountList",
|
||||
component: BrokerageAccountList,
|
||||
tags: ["autodocs"],
|
||||
args: { accounts: brokerageAccountCards([syntheticAccount]) },
|
||||
argTypes: {
|
||||
accounts: { control: false },
|
||||
},
|
||||
component: BrokerageAccountList,
|
||||
decorators: [
|
||||
(Story) => (
|
||||
Story => (
|
||||
<MemoryRouter initialEntries={["/accounts"]}>
|
||||
<Story />
|
||||
</MemoryRouter>
|
||||
@@ -42,7 +44,8 @@ const meta = {
|
||||
},
|
||||
},
|
||||
},
|
||||
args: { accounts: brokerageAccountCards([syntheticAccount]) },
|
||||
tags: ["autodocs"],
|
||||
title: "Product/BrokerageAccountList",
|
||||
} satisfies Meta<typeof BrokerageAccountList>;
|
||||
|
||||
export default meta;
|
||||
@@ -61,37 +64,39 @@ export const Available: Story = {
|
||||
},
|
||||
};
|
||||
|
||||
export const Unavailable: Story = {
|
||||
name: "Сводка недоступна",
|
||||
args: {
|
||||
accounts: brokerageAccountCards([
|
||||
{ ...syntheticAccount, portfolioSummary: null, openedOn: null },
|
||||
]),
|
||||
},
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story:
|
||||
export const Unavailable: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
args: {
|
||||
accounts: brokerageAccountCards([
|
||||
{ ...syntheticAccount, openedOn: null, portfolioSummary: null },
|
||||
]),
|
||||
},
|
||||
name: "Сводка недоступна",
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story:
|
||||
"Счёт остаётся доступен для открытия, даже если сводка временно недоступна. Неизвестные суммы не заменяются нулём; отсутствующая дата открытия не отображается.",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
|
||||
export const Empty: Story = {
|
||||
name: "Нет текущих сумм",
|
||||
args: {
|
||||
accounts: brokerageAccountCards([
|
||||
{
|
||||
...syntheticAccount,
|
||||
portfolioSummary: {
|
||||
totalsByCurrency: [],
|
||||
stockPositionCount: 0,
|
||||
bondPositionCount: 0,
|
||||
stockPositionCount: 0,
|
||||
totalsByCurrency: [],
|
||||
},
|
||||
},
|
||||
]),
|
||||
},
|
||||
name: "Нет текущих сумм",
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
@@ -103,7 +108,6 @@ export const Empty: Story = {
|
||||
};
|
||||
|
||||
export const LongName: Story = {
|
||||
name: "Длинное название счёта",
|
||||
args: {
|
||||
accounts: brokerageAccountCards([
|
||||
{
|
||||
@@ -113,6 +117,7 @@ export const LongName: Story = {
|
||||
},
|
||||
]),
|
||||
},
|
||||
name: "Длинное название счёта",
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
@@ -124,105 +129,107 @@ export const LongName: Story = {
|
||||
};
|
||||
|
||||
export const AccountGrid: Story = {
|
||||
name: "Несколько счетов",
|
||||
args: {
|
||||
accounts: brokerageAccountCards([
|
||||
{
|
||||
...syntheticAccount,
|
||||
name: "Основной",
|
||||
portfolioSummary: {
|
||||
totalsByCurrency: [{ currency: "RUB", value: "1256430.50" }],
|
||||
stockPositionCount: 8,
|
||||
bondPositionCount: 14,
|
||||
stockPositionCount: 8,
|
||||
totalsByCurrency: [{ currency: "RUB", value: "1256430.50" }],
|
||||
},
|
||||
},
|
||||
{
|
||||
...syntheticAccount,
|
||||
id: "storybook-iis",
|
||||
name: "Долгосрочные инвестиции",
|
||||
type: "INDIVIDUAL_INVESTMENT",
|
||||
portfolioSummary: {
|
||||
totalsByCurrency: [{ currency: "RUB", value: "480250" }],
|
||||
stockPositionCount: 0,
|
||||
bondPositionCount: 6,
|
||||
stockPositionCount: 0,
|
||||
totalsByCurrency: [{ currency: "RUB", value: "480250" }],
|
||||
},
|
||||
type: "INDIVIDUAL_INVESTMENT",
|
||||
},
|
||||
]),
|
||||
},
|
||||
name: "Несколько счетов",
|
||||
};
|
||||
|
||||
export const UnvaluedPositions: Story = {
|
||||
name: "Бумаги без текущей оценки",
|
||||
args: {
|
||||
accounts: brokerageAccountCards([
|
||||
{
|
||||
...syntheticAccount,
|
||||
portfolioSummary: {
|
||||
totalsByCurrency: [],
|
||||
stockPositionCount: 2,
|
||||
bondPositionCount: 1,
|
||||
stockPositionCount: 2,
|
||||
totalsByCurrency: [],
|
||||
},
|
||||
},
|
||||
]),
|
||||
},
|
||||
name: "Бумаги без текущей оценки",
|
||||
};
|
||||
|
||||
export const LargeValues: Story = {
|
||||
name: "Длинные суммы",
|
||||
args: {
|
||||
accounts: brokerageAccountCards([
|
||||
{
|
||||
...syntheticAccount,
|
||||
portfolioSummary: {
|
||||
bondPositionCount: 105,
|
||||
stockPositionCount: 21,
|
||||
totalsByCurrency: [
|
||||
{ currency: "RUB", value: "1234567890123456789.50" },
|
||||
{ currency: "USD", value: "-9876543210987654321.50" },
|
||||
],
|
||||
stockPositionCount: 21,
|
||||
bondPositionCount: 105,
|
||||
},
|
||||
},
|
||||
]),
|
||||
},
|
||||
name: "Длинные суммы",
|
||||
};
|
||||
|
||||
export const IndependentFreshness: Story = {
|
||||
name: "Независимая свежесть и ошибка сводок",
|
||||
args: {
|
||||
accounts: brokerageAccountCards(
|
||||
[
|
||||
syntheticAccount,
|
||||
{
|
||||
...syntheticAccount,
|
||||
id: "waiting",
|
||||
name: "Новый счёт",
|
||||
portfolioSummary: null,
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
resourceKey: "portfolio/storybook-account",
|
||||
dataRevision: "1",
|
||||
stateVersion: "failed",
|
||||
availability: "complete",
|
||||
freshness: "stale",
|
||||
lastSuccessfulAt: "2026-09-24T10:30:00Z",
|
||||
sync: {
|
||||
id: "failed",
|
||||
state: "failed",
|
||||
errorCode: "TBANK_UNAVAILABLE",
|
||||
export const IndependentFreshness: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
args: {
|
||||
accounts: brokerageAccountCards(
|
||||
[
|
||||
syntheticAccount,
|
||||
{
|
||||
...syntheticAccount,
|
||||
id: "waiting",
|
||||
name: "Новый счёт",
|
||||
portfolioSummary: null,
|
||||
},
|
||||
},
|
||||
{
|
||||
resourceKey: "portfolio/waiting",
|
||||
dataRevision: "0",
|
||||
stateVersion: "waiting",
|
||||
availability: "missing",
|
||||
freshness: "unknown",
|
||||
lastSuccessfulAt: null,
|
||||
sync: { id: "waiting", state: "running", errorCode: null },
|
||||
},
|
||||
],
|
||||
),
|
||||
},
|
||||
};
|
||||
],
|
||||
[
|
||||
{
|
||||
availability: "complete",
|
||||
dataRevision: "1",
|
||||
freshness: "stale",
|
||||
lastSuccessfulAt: "2026-09-24T10:30:00Z",
|
||||
resourceKey: "portfolio/storybook-account",
|
||||
stateVersion: "failed",
|
||||
sync: {
|
||||
errorCode: "TBANK_UNAVAILABLE",
|
||||
id: "failed",
|
||||
state: "failed",
|
||||
},
|
||||
},
|
||||
{
|
||||
availability: "missing",
|
||||
dataRevision: "0",
|
||||
freshness: "unknown",
|
||||
lastSuccessfulAt: null,
|
||||
resourceKey: "portfolio/waiting",
|
||||
stateVersion: "waiting",
|
||||
sync: { errorCode: null, id: "waiting", state: "running" },
|
||||
},
|
||||
],
|
||||
),
|
||||
},
|
||||
name: "Независимая свежесть и ошибка сводок",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
|
||||
+44
-36
@@ -2,7 +2,9 @@ import { MantineProvider } from "@mantine/core";
|
||||
import { render, screen, within } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resource } from "@/test/resource";
|
||||
|
||||
import { brokerageAccountCards } from "../../model/display";
|
||||
import { BrokerageAccountList } from "./BrokerageAccountList";
|
||||
|
||||
@@ -16,36 +18,40 @@ describe("BrokerageAccountList", () => {
|
||||
{
|
||||
id: "account-1",
|
||||
name: "Основной",
|
||||
type: "BROKERAGE",
|
||||
openedOn: "2024-08-13",
|
||||
portfolioSummary: {
|
||||
stockPositionCount: 5,
|
||||
bondPositionCount: 12,
|
||||
stockPositionCount: 5,
|
||||
totalsByCurrency: [
|
||||
{ currency: "RUB", value: "1500" },
|
||||
{ currency: "USD", value: "20" },
|
||||
{ currency: "EUR", value: "5" },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "account-2",
|
||||
name: "Недоступный",
|
||||
type: "BROKERAGE",
|
||||
openedOn: null,
|
||||
portfolioSummary: null,
|
||||
},
|
||||
{
|
||||
id: "account-3",
|
||||
name: "Пустой",
|
||||
type: "BROKERAGE",
|
||||
openedOn: null,
|
||||
portfolioSummary: {
|
||||
totalsByCurrency: [],
|
||||
stockPositionCount: 2,
|
||||
bondPositionCount: 0,
|
||||
},
|
||||
},
|
||||
(/* 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>
|
||||
@@ -65,18 +71,18 @@ describe("BrokerageAccountList", () => {
|
||||
expect(screen.getByText("Нет текущих сумм")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("Открыть счет")).toHaveLength(3);
|
||||
const available = within(screen.getByRole("link", { name: /Основной/ }));
|
||||
expect(available.getByText("Акции").nextElementSibling).toHaveTextContent(
|
||||
expect(available.getAllByRole("definition")[0]).toHaveTextContent(
|
||||
"5",
|
||||
);
|
||||
expect(
|
||||
available.getByText("Облигации").nextElementSibling,
|
||||
available.getAllByRole("definition")[1],
|
||||
).toHaveTextContent("12");
|
||||
const unvalued = within(screen.getByRole("link", { name: /Пустой/ }));
|
||||
expect(unvalued.getByText("Акции").nextElementSibling).toHaveTextContent(
|
||||
expect(unvalued.getAllByRole("definition")[0]).toHaveTextContent(
|
||||
"2",
|
||||
);
|
||||
expect(
|
||||
unvalued.getByText("Облигации").nextElementSibling,
|
||||
unvalued.getAllByRole("definition")[1],
|
||||
).toHaveTextContent("0");
|
||||
expect(
|
||||
within(screen.getByRole("link", { name: /Недоступный/ })).queryByText(
|
||||
@@ -88,21 +94,23 @@ describe("BrokerageAccountList", () => {
|
||||
|
||||
it("shows portfolio summary freshness independently for each account", () => {
|
||||
const accounts = brokerageAccountCards(
|
||||
["fresh", "stale"].map((id) => ({
|
||||
id,
|
||||
name: id,
|
||||
type: "BROKERAGE" as const,
|
||||
openedOn: null,
|
||||
portfolioSummary: {
|
||||
stockPositionCount: 1,
|
||||
bondPositionCount: 0,
|
||||
totalsByCurrency: [{ currency: "RUB", value: "10" }],
|
||||
},
|
||||
})),
|
||||
["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 */))),
|
||||
[
|
||||
resource(null, { resourceKey: "portfolio/fresh", freshness: "fresh" })
|
||||
resource(null, { freshness: "fresh", resourceKey: "portfolio/fresh" })
|
||||
.meta,
|
||||
resource(null, { resourceKey: "portfolio/stale", freshness: "stale" })
|
||||
resource(null, { freshness: "stale", resourceKey: "portfolio/stale" })
|
||||
.meta,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { Card, Group, SimpleGrid, Stack, Text } from "@mantine/core";
|
||||
import type { FC } from "react";
|
||||
|
||||
import { Card, Group, SimpleGrid, Stack, Text } from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
|
||||
import { formatDate, formatMoney, formatSnapshotTime } from "@/shared/lib";
|
||||
|
||||
import type { BrokerageAccountCard } from "../../model/display";
|
||||
|
||||
import { accountTypeKey } from "../../model/display";
|
||||
import classes from "./BrokerageAccountList.module.css";
|
||||
|
||||
@@ -31,18 +35,18 @@ const BrokerageAccountSummary: FC<BrokerageAccountSummaryProps> = (props) => {
|
||||
|
||||
return (
|
||||
<Stack className={classes.summary} gap={4}>
|
||||
{summary.totals.map((total) => (
|
||||
{summary.totals.map(total => (
|
||||
<Text className={classes.total} fw={700} key={total.currency}>
|
||||
{formatMoney(total)}
|
||||
</Text>
|
||||
))}
|
||||
{summary.remainingCurrencyCount ? (
|
||||
{!!(summary.remainingCurrencyCount) && ((
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("accounts.remainingCurrencies", {
|
||||
count: summary.remainingCurrencyCount,
|
||||
})}
|
||||
</Text>
|
||||
) : null}
|
||||
))}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
@@ -53,37 +57,37 @@ const BrokerageAccountList: FC<BrokerageAccountListProps> = (props) => {
|
||||
|
||||
return (
|
||||
<SimpleGrid className={classes.list} cols={1} spacing="lg">
|
||||
{accounts.map(({ account, summary, positionCounts, source }) => (
|
||||
{accounts.map(({ account, positionCounts, source, summary }) => (
|
||||
<Card
|
||||
component={Link}
|
||||
to={`/accounts/${account.id}`}
|
||||
key={account.id}
|
||||
className={classes.card}
|
||||
component={Link}
|
||||
key={account.id}
|
||||
padding="xl"
|
||||
radius="lg"
|
||||
to={`/accounts/${account.id}`}
|
||||
withBorder
|
||||
>
|
||||
<Stack className={classes.identity} gap="sm">
|
||||
<Group justify="space-between" wrap="nowrap" gap="sm">
|
||||
<Text className={classes.kicker} size="xs" fw={700}>
|
||||
<Group gap="sm" justify="space-between" wrap="nowrap">
|
||||
<Text className={classes.kicker} fw={700} size="xs">
|
||||
{t(accountTypeKey(account.type))}
|
||||
</Text>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
className={classes.accountIcon}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
focusable="false"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
strokeWidth="1.5"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<rect x="3" y="5" width="18" height="15" rx="3" />
|
||||
<rect height="15" rx="3" width="18" x="3" y="5" />
|
||||
<path d="M3 9h18M7 15h3M14 5V3H7a4 4 0 0 0-4 4" />
|
||||
</svg>
|
||||
</Group>
|
||||
<Text component="h2" className={classes.name} fw={700}>
|
||||
<Text className={classes.name} component="h2" fw={700}>
|
||||
{account.name}
|
||||
</Text>
|
||||
</Stack>
|
||||
@@ -92,27 +96,27 @@ const BrokerageAccountList: FC<BrokerageAccountListProps> = (props) => {
|
||||
{t("accounts.currentValue")}
|
||||
</Text>
|
||||
<BrokerageAccountSummary summary={summary} />
|
||||
{source?.lastSuccessfulAt ? (
|
||||
<Text size="xs" c="dimmed">
|
||||
{!!(source?.lastSuccessfulAt) && ((
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("investment.sourceTime", {
|
||||
date: formatSnapshotTime(source.lastSuccessfulAt),
|
||||
})}
|
||||
</Text>
|
||||
) : null}
|
||||
{source?.sync.state === "running" ||
|
||||
source?.sync.state === "queued" ? (
|
||||
<Text size="xs" role="status">
|
||||
))}
|
||||
{(source?.sync.state === "running"
|
||||
|| source?.sync.state === "queued") && ((
|
||||
<Text role="status" size="xs">
|
||||
{t("accounts.refreshing")}
|
||||
</Text>
|
||||
) : null}
|
||||
{source?.sync.state === "failed" ? (
|
||||
))}
|
||||
{(source?.sync.state === "failed") && ((
|
||||
<Text size="xs">{t("accounts.refreshError")}</Text>
|
||||
) : null}
|
||||
{source?.freshness === "stale" ? (
|
||||
))}
|
||||
{(source?.freshness === "stale") && ((
|
||||
<Text size="xs">{t("investment.stale")}</Text>
|
||||
) : null}
|
||||
))}
|
||||
</Stack>
|
||||
{positionCounts ? (
|
||||
{!!(positionCounts) && ((
|
||||
<dl className={classes.positions}>
|
||||
<div className={classes.stocks}>
|
||||
<dt>{t("accounts.stocks")}</dt>
|
||||
@@ -127,18 +131,18 @@ const BrokerageAccountList: FC<BrokerageAccountListProps> = (props) => {
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
) : null}
|
||||
<Group className={classes.footer} justify="space-between" gap="sm">
|
||||
{account.openedOn ? (
|
||||
))}
|
||||
<Group className={classes.footer} gap="sm" justify="space-between">
|
||||
{!!(account.openedOn) && ((
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("accounts.openedOn", {
|
||||
date: formatDate(account.openedOn),
|
||||
})}
|
||||
</Text>
|
||||
) : null}
|
||||
<Text component="span" className={classes.open} size="sm" fw={600}>
|
||||
))}
|
||||
<Text className={classes.open} component="span" fw={600} size="sm">
|
||||
{t("accounts.openAccount")}
|
||||
<span className={classes.arrow} aria-hidden="true">
|
||||
<span aria-hidden="true" className={classes.arrow}>
|
||||
→
|
||||
</span>
|
||||
</Text>
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
import { renderHook, waitFor } from "@testing-library/react";
|
||||
import { HttpResponse, http } from "msw";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createQueryWrapper } from "@/test/query";
|
||||
import { resource } from "@/test/resource";
|
||||
import { server } from "@/test/server";
|
||||
|
||||
import { useBrokerageEvents } from "./useBrokerageEvents";
|
||||
|
||||
describe("useBrokerageEvents", () => {
|
||||
it("does not fetch events without an account ID", async () => {
|
||||
configureAuthClient({
|
||||
accessToken: () => "token",
|
||||
refresh: async () => true,
|
||||
clear: vi.fn(),
|
||||
refresh: () => Promise.resolve(true),
|
||||
});
|
||||
const requested = vi.fn(() => HttpResponse.json({ events: [] }));
|
||||
server.use(
|
||||
@@ -27,29 +29,31 @@ describe("useBrokerageEvents", () => {
|
||||
it("loads future cash events through the authenticated query seam", async () => {
|
||||
configureAuthClient({
|
||||
accessToken: () => "token",
|
||||
refresh: async () => true,
|
||||
clear: vi.fn(),
|
||||
refresh: () => Promise.resolve(true),
|
||||
});
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts/account-1/events", () =>
|
||||
HttpResponse.json(
|
||||
resource({
|
||||
accountId: "account-1",
|
||||
calculatedAt: "2026-08-14T00:00:00Z",
|
||||
events: [
|
||||
{
|
||||
type: "dividend",
|
||||
date: "2026-09-01",
|
||||
dateKind: "registry",
|
||||
figi: "figi-1",
|
||||
instrumentUid: null,
|
||||
ticker: "SBER",
|
||||
displayName: "Сбер",
|
||||
logoName: "sber3.png",
|
||||
projectedAmount: { currency: "RUB", value: "12.34" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
accountId: "account-1",
|
||||
calculatedAt: "2026-08-14T00:00:00Z",
|
||||
events: [
|
||||
{
|
||||
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 */)),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -60,17 +64,19 @@ describe("useBrokerageEvents", () => {
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
expect(result.current.data?.events).toEqual([
|
||||
{
|
||||
type: "dividend",
|
||||
date: "2026-09-01",
|
||||
dateKind: "registry",
|
||||
figi: "figi-1",
|
||||
instrumentUid: null,
|
||||
ticker: "SBER",
|
||||
displayName: "Сбер",
|
||||
logoName: "sber3.png",
|
||||
projectedAmount: { currency: "RUB", value: "12.34" },
|
||||
},
|
||||
(/* 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 */),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
|
||||
|
||||
type EventsEndpoint =
|
||||
paths["/api/v1/brokerage-accounts/{accountId}/events"]["get"];
|
||||
type BrokerageEvent = NonNullable<
|
||||
EventsEndpoint["responses"][200]["content"]["application/json"]["data"]
|
||||
>["events"][number];
|
||||
type EventsEndpoint
|
||||
= paths["/api/v1/brokerage-accounts/{accountId}/events"]["get"];
|
||||
|
||||
function useBrokerageEvents(
|
||||
accountId: string | undefined,
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { EntryCard } from "@wealthledger/ui";
|
||||
import type { FC } from "react";
|
||||
|
||||
import { EntryCard } from "@wealthledger/ui";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { formatDate, formatMoney, instrumentLogoUrl } from "@/shared/lib";
|
||||
|
||||
import type { BrokerageEvent } from "../api/useBrokerageEvents";
|
||||
|
||||
type BrokerageEventCardProps = { event: BrokerageEvent };
|
||||
@@ -14,7 +17,7 @@ const BrokerageEventCard: FC<BrokerageEventCardProps> = (props) => {
|
||||
|
||||
const metadata = [
|
||||
date,
|
||||
event.dateKind === "registry" ? t("events.dateKind.registry") : null,
|
||||
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.isin,
|
||||
event.account?.name,
|
||||
]
|
||||
@@ -23,19 +26,19 @@ const BrokerageEventCard: FC<BrokerageEventCardProps> = (props) => {
|
||||
|
||||
return (
|
||||
<EntryCard
|
||||
title={`${t(`events.type.${event.type}`)} · ${event.displayName}`}
|
||||
metadata={metadata}
|
||||
imageSrc={instrumentLogoUrl(event.logoName)}
|
||||
initial={(
|
||||
(event.ticker ?? event.displayName).trim()[0] ?? "?"
|
||||
).toUpperCase()}
|
||||
imageSrc={instrumentLogoUrl(event.logoName)}
|
||||
metadata={metadata}
|
||||
title={[t(`events.type.${event.type}`), event.displayName].join(" · ")}
|
||||
tone="neutral"
|
||||
value={
|
||||
event.projectedAmount
|
||||
? formatMoney(event.projectedAmount)
|
||||
: t("events.noAmount")
|
||||
}
|
||||
valueLabel={t("events.projectedAmount")}
|
||||
tone="neutral"
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
+73
-64
@@ -1,32 +1,53 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
|
||||
import { MemoryRouter } from "react-router";
|
||||
|
||||
import type { BrokerageEvent } from "../../api/useBrokerageEvents";
|
||||
|
||||
import { BrokerageEventsPreview } from "./BrokerageEventsPreview";
|
||||
|
||||
const syntheticEvent = {
|
||||
type: "coupon",
|
||||
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,
|
||||
ticker: "DEMO",
|
||||
displayName: "Учебные облигации",
|
||||
logoName: null,
|
||||
isin: "RU000A0JX0J2",
|
||||
logoName: null,
|
||||
projectedAmount: { currency: "RUB", value: "850.50" },
|
||||
} satisfies BrokerageEvent;
|
||||
ticker: "DEMO",
|
||||
type: "coupon",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */) satisfies BrokerageEvent;
|
||||
|
||||
const eventsPath = "/accounts/storybook-account/events";
|
||||
|
||||
const meta = {
|
||||
title: "Product/RecentEvents",
|
||||
component: BrokerageEventsPreview,
|
||||
tags: ["autodocs"],
|
||||
args: {
|
||||
events: {
|
||||
items: [
|
||||
syntheticEvent,
|
||||
{
|
||||
...syntheticEvent,
|
||||
date: "2026-11-01",
|
||||
dateKind: "registry",
|
||||
displayName: "Учебные технологии",
|
||||
projectedAmount: { currency: "RUB", value: "1200" },
|
||||
ticker: "EXAMPLE",
|
||||
type: "dividend",
|
||||
},
|
||||
],
|
||||
state: "loaded",
|
||||
to: eventsPath,
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
events: { control: false },
|
||||
},
|
||||
component: BrokerageEventsPreview,
|
||||
decorators: [
|
||||
(Story) => (
|
||||
Story => (
|
||||
<MemoryRouter initialEntries={["/accounts/storybook-account"]}>
|
||||
<Story />
|
||||
</MemoryRouter>
|
||||
@@ -40,24 +61,8 @@ const meta = {
|
||||
},
|
||||
},
|
||||
},
|
||||
args: {
|
||||
events: {
|
||||
state: "loaded",
|
||||
to: eventsPath,
|
||||
items: [
|
||||
syntheticEvent,
|
||||
{
|
||||
...syntheticEvent,
|
||||
type: "dividend",
|
||||
date: "2026-11-01",
|
||||
dateKind: "registry",
|
||||
ticker: "EXAMPLE",
|
||||
displayName: "Учебные технологии",
|
||||
projectedAmount: { currency: "RUB", value: "1200" },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
tags: ["autodocs"],
|
||||
title: "Product/RecentEvents",
|
||||
} satisfies Meta<typeof BrokerageEventsPreview>;
|
||||
|
||||
export default meta;
|
||||
@@ -77,8 +82,8 @@ export const Loaded: Story = {
|
||||
};
|
||||
|
||||
export const Loading: Story = {
|
||||
name: "Загрузка раздела",
|
||||
args: { events: { state: "loading", to: eventsPath } },
|
||||
name: "Загрузка раздела",
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
@@ -90,8 +95,8 @@ export const Loading: Story = {
|
||||
};
|
||||
|
||||
export const Failed: Story = {
|
||||
name: "Ошибка получения событий",
|
||||
args: { events: { state: "error", to: eventsPath } },
|
||||
name: "Ошибка получения событий",
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
@@ -103,8 +108,8 @@ export const Failed: Story = {
|
||||
};
|
||||
|
||||
export const Empty: Story = {
|
||||
name: "Нет ближайших событий",
|
||||
args: { events: { state: "empty", to: eventsPath } },
|
||||
name: "Нет ближайших событий",
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
@@ -115,40 +120,44 @@ export const Empty: Story = {
|
||||
},
|
||||
};
|
||||
|
||||
export const MissingAmount: Story = {
|
||||
name: "Событие без ожидаемой суммы",
|
||||
args: {
|
||||
events: {
|
||||
state: "loaded",
|
||||
to: eventsPath,
|
||||
items: [{ ...syntheticEvent, projectedAmount: null }],
|
||||
},
|
||||
},
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story:
|
||||
"Событие остаётся видимым при неизвестной ожидаемой сумме. Отсутствие оценки не подменяется нулевой выплатой.",
|
||||
export const MissingAmount: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
args: {
|
||||
events: {
|
||||
items: [{ ...syntheticEvent, projectedAmount: null }],
|
||||
state: "loaded",
|
||||
to: eventsPath,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const LongEvent: Story = {
|
||||
name: "Длинное название на узком экране",
|
||||
args: {
|
||||
events: {
|
||||
state: "loaded",
|
||||
to: eventsPath,
|
||||
items: [
|
||||
{
|
||||
...syntheticEvent,
|
||||
type: "offer",
|
||||
displayName:
|
||||
"Учебные облигации компании с очень длинным названием инструмента",
|
||||
projectedAmount: null,
|
||||
name: "Событие без ожидаемой суммы",
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story:
|
||||
"Событие остаётся видимым при неизвестной ожидаемой сумме. Отсутствие оценки не подменяется нулевой выплатой.",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
|
||||
export const LongEvent: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
args: {
|
||||
events: {
|
||||
items: [
|
||||
{
|
||||
...syntheticEvent,
|
||||
displayName:
|
||||
"Учебные облигации компании с очень длинным названием инструмента",
|
||||
projectedAmount: null,
|
||||
type: "offer",
|
||||
},
|
||||
],
|
||||
state: "loaded",
|
||||
to: eventsPath,
|
||||
},
|
||||
},
|
||||
name: "Длинное название на узком экране",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
|
||||
@@ -1,26 +1,30 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { Alert, Button, Skeleton, Stack, Text } from "@mantine/core";
|
||||
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||
import type { FC } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
|
||||
import { formatSnapshotTime } from "@/shared/lib";
|
||||
|
||||
import type { BrokerageEvent } from "../../api/useBrokerageEvents";
|
||||
|
||||
import { BrokerageEventCard } from "../BrokerageEventCard";
|
||||
|
||||
type BrokerageEventsPreviewProps = {
|
||||
events: BrokerageEventsPreviewState;
|
||||
};
|
||||
|
||||
type BrokerageEventsPreviewState =
|
||||
| { state: "loading" | "error" | "empty"; to: string }
|
||||
| {
|
||||
state: "loaded" | "partial";
|
||||
to: string;
|
||||
lastSuccessfulAt?: string | null;
|
||||
stale?: boolean;
|
||||
refreshError?: boolean;
|
||||
items: BrokerageEvent[];
|
||||
};
|
||||
type BrokerageEventsPreviewState
|
||||
= | {
|
||||
items: BrokerageEvent[];
|
||||
lastSuccessfulAt?: null | string;
|
||||
refreshError?: boolean;
|
||||
stale?: boolean;
|
||||
state: "loaded" | "partial";
|
||||
to: string;
|
||||
}
|
||||
| { state: "empty" | "error" | "loading"; to: string };
|
||||
|
||||
const BrokerageEventsPreview: FC<BrokerageEventsPreviewProps> = (props) => {
|
||||
const { events } = props;
|
||||
@@ -28,53 +32,51 @@ const BrokerageEventsPreview: FC<BrokerageEventsPreviewProps> = (props) => {
|
||||
|
||||
return (
|
||||
<Stack gap="sm">
|
||||
{events.state === "loaded" ? (
|
||||
{(events.state === "loaded") && ((
|
||||
<>
|
||||
{events.lastSuccessfulAt ? (
|
||||
<Text size="xs" c="dimmed">
|
||||
{!!(events.lastSuccessfulAt) && ((
|
||||
<Text c="dimmed" size="xs">
|
||||
{t("investment.sourceTime", {
|
||||
date: formatSnapshotTime(events.lastSuccessfulAt),
|
||||
})}
|
||||
</Text>
|
||||
) : null}
|
||||
{events.stale ? <Text size="xs">{t("investment.stale")}</Text> : null}
|
||||
{events.refreshError ? (
|
||||
))}
|
||||
{!!(events.stale) && (<Text size="xs">{t("investment.stale")}</Text>)}
|
||||
{!!(events.refreshError) && ((
|
||||
<Text role="status">{t("accounts.refreshError")}</Text>
|
||||
) : null}
|
||||
))}
|
||||
</>
|
||||
) : null}
|
||||
{events.state === "loading" ? (
|
||||
))}
|
||||
{(events.state === "loading") && ((
|
||||
<LoadingSkeleton label={t("events.recentLoading")}>
|
||||
{[0, 1, 2].map((index) => (
|
||||
<Skeleton key={index} height={48} radius="sm" />
|
||||
{["first", "second", "third"].map(placeholder => (
|
||||
<Skeleton height={48} key={placeholder} radius="sm" />
|
||||
))}
|
||||
</LoadingSkeleton>
|
||||
) : null}
|
||||
{events.state === "error" ? (
|
||||
))}
|
||||
{(events.state === "error") && ((
|
||||
<Alert color="red">{t("events.recentError")}</Alert>
|
||||
) : null}
|
||||
{events.state === "empty" ? (
|
||||
))}
|
||||
{(events.state === "empty") && ((
|
||||
<Text c="dimmed">{t("events.recentEmpty")}</Text>
|
||||
) : null}
|
||||
{events.state === "partial" ? (
|
||||
))}
|
||||
{(events.state === "partial") && ((
|
||||
<Text role="status">{t("investment.partial")}</Text>
|
||||
) : null}
|
||||
{events.state === "loaded" || events.state === "partial"
|
||||
? events.items.map((event) => (
|
||||
<BrokerageEventCard
|
||||
key={JSON.stringify([
|
||||
event.account?.id,
|
||||
event.type,
|
||||
event.date,
|
||||
event.instrumentUid,
|
||||
event.figi,
|
||||
event.ticker,
|
||||
event.logoName,
|
||||
])}
|
||||
event={event}
|
||||
/>
|
||||
))
|
||||
: null}
|
||||
))}
|
||||
{(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>
|
||||
|
||||
@@ -1,24 +1,11 @@
|
||||
import { apiQueryClient, type paths, useResourceQuery } from "@/shared/api";
|
||||
|
||||
type IncomeSummary = NonNullable<
|
||||
paths["/api/v1/brokerage-accounts/{accountId}/income-summary"]["get"]["responses"][200]["content"]["application/json"]["data"]
|
||||
>;
|
||||
type IncomeAnalytics = NonNullable<
|
||||
paths["/api/v1/brokerage-accounts/{accountId}/income-analytics"]["get"]["responses"][200]["content"]["application/json"]["data"]
|
||||
>;
|
||||
|
||||
function useIncomeSummary(accountId: string | undefined) {
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/brokerage-accounts/{accountId}/income-summary",
|
||||
{ params: { path: { accountId: accountId ?? "" } } },
|
||||
),
|
||||
enabled: Boolean(accountId),
|
||||
staleTime: 30_000,
|
||||
});
|
||||
}
|
||||
type IncomeSummary = NonNullable<
|
||||
paths["/api/v1/brokerage-accounts/{accountId}/income-summary"]["get"]["responses"][200]["content"]["application/json"]["data"]
|
||||
>;
|
||||
|
||||
function useIncomeAnalytics(
|
||||
accountId: string | undefined,
|
||||
@@ -41,6 +28,19 @@ function useIncomeAnalytics(
|
||||
});
|
||||
}
|
||||
|
||||
function useIncomeSummary(accountId: string | undefined) {
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...apiQueryClient.queryOptions(
|
||||
"get",
|
||||
"/api/v1/brokerage-accounts/{accountId}/income-summary",
|
||||
{ params: { path: { accountId: accountId ?? "" } } },
|
||||
),
|
||||
enabled: Boolean(accountId),
|
||||
staleTime: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
export {
|
||||
type IncomeAnalytics,
|
||||
type IncomeSummary,
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import { HttpResponse, http } from "msw";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { apiClient, configureAuthClient } from "@/shared/api";
|
||||
import { createQueryWrapper } from "@/test/query";
|
||||
import { resource } from "@/test/resource";
|
||||
import { server } from "@/test/server";
|
||||
|
||||
import {
|
||||
type Portfolio,
|
||||
portfolioQueryOptions,
|
||||
@@ -12,25 +14,25 @@ import {
|
||||
} from "./usePortfolio";
|
||||
|
||||
const snapshot: Portfolio = {
|
||||
positions: [],
|
||||
totalsByCurrency: [{ currency: "RUB", value: "123.000000001" }],
|
||||
cashBalances: [],
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
lastSuccessfulAt: "2026-08-14T00:00:00Z",
|
||||
isStale: false,
|
||||
lastSuccessfulAt: "2026-08-14T00:00:00Z",
|
||||
positions: [],
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
totalsByCurrency: [{ currency: "RUB", value: "123.000000001" }],
|
||||
};
|
||||
function auth() {
|
||||
configureAuthClient({
|
||||
accessToken: () => "synthetic",
|
||||
refresh: async () => true,
|
||||
clear: vi.fn(),
|
||||
refresh: () => Promise.resolve(true),
|
||||
});
|
||||
}
|
||||
|
||||
describe("persistent resource query lifecycle", () => {
|
||||
it("observes into the canonical cache and rejects an old notified state before accepting the current one", async () => {
|
||||
auth();
|
||||
const modes: (string | null)[] = [];
|
||||
const modes: (null | string)[] = [];
|
||||
let observations = 0;
|
||||
server.use(
|
||||
http.get(
|
||||
@@ -47,16 +49,17 @@ describe("persistent resource query lifecycle", () => {
|
||||
},
|
||||
),
|
||||
);
|
||||
const { wrapper, queryClient } = createQueryWrapper();
|
||||
const { queryClient, wrapper } = createQueryWrapper();
|
||||
const { result } = renderHook(() => usePortfolio("a"), { wrapper });
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
await act(() => result.current.observe("new"));
|
||||
await waitFor(() => expect(result.current.meta?.stateVersion).toBe("new"));
|
||||
// eslint-disable-next-line unicorn/no-null -- Preserve the API/DOM null sentinel in the expected response.
|
||||
expect(modes).toEqual([null, "observe", "observe"]);
|
||||
expect(queryClient.getQueryCache().getAll()).toHaveLength(1);
|
||||
expect(
|
||||
queryClient.getQueryData(portfolioQueryOptions("a").queryKey),
|
||||
).toMatchObject({ meta: { stateVersion: "new" }, data: snapshot });
|
||||
).toMatchObject({ data: snapshot, meta: { stateVersion: "new" } });
|
||||
});
|
||||
it("does not convert missing or failed source data to empty financial success", async () => {
|
||||
auth();
|
||||
@@ -65,9 +68,9 @@ describe("persistent resource query lifecycle", () => {
|
||||
HttpResponse.json(
|
||||
resource(null, {
|
||||
sync: {
|
||||
errorCode: "TBANK_UNAVAILABLE",
|
||||
id: "work",
|
||||
state: "failed",
|
||||
errorCode: "TBANK_UNAVAILABLE",
|
||||
},
|
||||
}),
|
||||
),
|
||||
@@ -82,20 +85,22 @@ describe("persistent resource query lifecycle", () => {
|
||||
expect(result.current.status).toBe("pending");
|
||||
expect(result.current.isPending).toBe(true);
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
expect(result.current.transport).toEqual({
|
||||
status: "success",
|
||||
fetchStatus: "idle",
|
||||
error: null,
|
||||
});
|
||||
expect(result.current.transport).toEqual((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
error: null,
|
||||
fetchStatus: "idle",
|
||||
status: "success",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */));
|
||||
expect(result.current.meta?.availability).toBe("missing");
|
||||
});
|
||||
it("keeps the refetch envelope while exposing the refreshed resource payload", async () => {
|
||||
auth();
|
||||
let ready = false;
|
||||
let isReady = false;
|
||||
const refreshed = resource(snapshot, { stateVersion: "ready" });
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts/:accountId/portfolio", () =>
|
||||
HttpResponse.json(ready ? refreshed : resource(null)),
|
||||
HttpResponse.json(isReady ? refreshed : resource(null)),
|
||||
),
|
||||
);
|
||||
const { result } = renderHook(() => usePortfolio("a"), {
|
||||
@@ -109,7 +114,7 @@ describe("persistent resource query lifecycle", () => {
|
||||
expect(missing.status).toBe("success");
|
||||
expect(missing.data).toEqual(resource(null));
|
||||
expect(missing.data?.data).toBeNull();
|
||||
ready = true;
|
||||
isReady = true;
|
||||
const loaded = await result.current.refetch();
|
||||
expect(loaded.data).toEqual(refreshed);
|
||||
expect(loaded.data?.data?.totalsByCurrency).toEqual(
|
||||
@@ -124,10 +129,8 @@ describe("persistent resource query lifecycle", () => {
|
||||
});
|
||||
it("rejects a late ordinary response when an observe response for that resource arrived first", async () => {
|
||||
auth();
|
||||
let release!: () => void;
|
||||
const blocked = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
|
||||
const { promise: blocked, resolve: release } = Promise.withResolvers<void>();
|
||||
server.use(
|
||||
http.get(
|
||||
"*/api/v1/brokerage-accounts/:accountId/portfolio",
|
||||
@@ -151,19 +154,15 @@ describe("persistent resource query lifecycle", () => {
|
||||
});
|
||||
it("clears private snapshots on confirmed access loss and fences another pending success", async () => {
|
||||
auth();
|
||||
let denied = false;
|
||||
let release!: () => void;
|
||||
const blocked = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
let isDenied = false;
|
||||
|
||||
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;
|
||||
if (params.accountId === "a" && denied)
|
||||
return HttpResponse.json({ code: "NOT_FOUND" }, { status: 404 });
|
||||
return HttpResponse.json(resource(snapshot));
|
||||
return isDenied && params.accountId === "a" ? HttpResponse.json({ code: "NOT_FOUND" }, { status: 404 }) : HttpResponse.json(resource(snapshot));
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -173,7 +172,7 @@ describe("persistent resource query lifecycle", () => {
|
||||
{ wrapper },
|
||||
);
|
||||
await waitFor(() => expect(result.current.a.data).toEqual(snapshot));
|
||||
denied = true;
|
||||
isDenied = true;
|
||||
await act(() => result.current.a.refetch());
|
||||
await waitFor(() => expect(result.current.a.data).toBeUndefined());
|
||||
await act(async () => {
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
import { renderHook, waitFor } from "@testing-library/react";
|
||||
import { HttpResponse, http } from "msw";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { configureAuthClient } from "@/shared/api";
|
||||
import { createQueryWrapper } from "@/test/query";
|
||||
import { resource } from "@/test/resource";
|
||||
import { server } from "@/test/server";
|
||||
|
||||
import { usePortfolio } from "./usePortfolio";
|
||||
|
||||
describe("usePortfolio", () => {
|
||||
it("loads the account portfolio", async () => {
|
||||
configureAuthClient({
|
||||
accessToken: () => "token",
|
||||
refresh: async () => true,
|
||||
clear: vi.fn(),
|
||||
refresh: () => Promise.resolve(true),
|
||||
});
|
||||
const { result } = renderHook(() => usePortfolio("account-1"), {
|
||||
wrapper: createQueryWrapper().wrapper,
|
||||
@@ -25,8 +27,8 @@ describe("usePortfolio", () => {
|
||||
it("keeps the current connection snapshot after a background refetch error", async () => {
|
||||
configureAuthClient({
|
||||
accessToken: () => "token",
|
||||
refresh: async () => true,
|
||||
clear: vi.fn(),
|
||||
refresh: () => Promise.resolve(true),
|
||||
});
|
||||
let calls = 0;
|
||||
server.use(
|
||||
@@ -35,12 +37,12 @@ describe("usePortfolio", () => {
|
||||
return calls === 1
|
||||
? HttpResponse.json(
|
||||
resource({
|
||||
lastSuccessfulAt: "2026-08-14T00:00:00Z",
|
||||
cashBalances: [],
|
||||
isStale: false,
|
||||
totalsByCurrency: [],
|
||||
lastSuccessfulAt: "2026-08-14T00:00:00Z",
|
||||
positions: [],
|
||||
structure: { currencies: [], unvaluedCategories: [] },
|
||||
cashBalances: [],
|
||||
totalsByCurrency: [],
|
||||
}),
|
||||
)
|
||||
: HttpResponse.json({ code: "TBANK_UNAVAILABLE" }, { status: 503 });
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { formatShare } from "./display";
|
||||
|
||||
describe("portfolio display helpers", () => {
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import type { Portfolio } from "../api/usePortfolio";
|
||||
|
||||
const PERCENT_SCALE = 100;
|
||||
|
||||
type Money = Portfolio["totalsByCurrency"][number];
|
||||
|
||||
function formatShare(
|
||||
numerator: Money | null,
|
||||
denominator: Money | null,
|
||||
): string | null {
|
||||
if (!numerator || !denominator) return null;
|
||||
): null | string {
|
||||
if (!numerator || !denominator) return /* eslint-disable-line unicorn/no-null -- The existing formatter contract uses null for unavailable data. */ null;
|
||||
const total = Number(denominator.value);
|
||||
if (!Number.isFinite(total) || total <= 0) return null;
|
||||
// biome-ignore lint/style/noMagicNumbers: obvious conversion of a ratio to percent.
|
||||
const percent = (Number(numerator.value) / total) * 100;
|
||||
if (!Number.isFinite(percent)) return null;
|
||||
if (!Number.isFinite(total) || total <= 0) return /* eslint-disable-line unicorn/no-null -- The existing formatter contract uses null for unavailable data. */ 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;
|
||||
const rounded = new Intl.NumberFormat("ru-RU", {
|
||||
maximumFractionDigits: 1,
|
||||
}).format(percent);
|
||||
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
useResourceQuery,
|
||||
} from "@/shared/api";
|
||||
|
||||
const MIN_STOCK_SEARCH_LENGTH = 2;
|
||||
|
||||
type StockPeriod = NonNullable<
|
||||
NonNullable<
|
||||
paths["/api/v1/stocks/{uid}/candles"]["get"]["parameters"]["query"]
|
||||
@@ -14,15 +16,6 @@ type StockPeriod = NonNullable<
|
||||
|
||||
const STOCK_STALE_TIME_MS = 30_000;
|
||||
|
||||
function useStockSearch(query: string) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks", {
|
||||
params: { query: { query } },
|
||||
}),
|
||||
enabled: query.length >= 2,
|
||||
staleTime: STOCK_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
function stockQueryOptions(uid: string) {
|
||||
return {
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}", {
|
||||
@@ -31,21 +24,9 @@ function stockQueryOptions(uid: string) {
|
||||
staleTime: STOCK_STALE_TIME_MS,
|
||||
};
|
||||
}
|
||||
|
||||
function useStocks(uids: string[]) {
|
||||
const uniqueUids = [...new Set(uids)];
|
||||
const queries = useAuthenticatedQueries(uniqueUids.map(stockQueryOptions));
|
||||
return new Map(
|
||||
queries.map((query, index) => [
|
||||
uniqueUids[index],
|
||||
unwrapResourceResult(query).data,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
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(
|
||||
const isUid
|
||||
= /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
|
||||
identifier,
|
||||
);
|
||||
|
||||
@@ -62,15 +43,7 @@ function useStock(identifier: string) {
|
||||
});
|
||||
return isUid ? byUid : byTicker;
|
||||
}
|
||||
function useStockQuote(uid: string) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/quote", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
enabled: Boolean(uid),
|
||||
staleTime: STOCK_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
|
||||
function useStockCandles(uid: string, period: StockPeriod) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/candles", {
|
||||
@@ -80,16 +53,7 @@ function useStockCandles(uid: string, period: StockPeriod) {
|
||||
staleTime: STOCK_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
function useStockPosition(uid: string) {
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/position", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
enabled: Boolean(uid),
|
||||
staleTime: STOCK_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
|
||||
function useStockCompany(uid: string) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/company", {
|
||||
@@ -109,8 +73,46 @@ function useStockDividends(uid: string) {
|
||||
staleTime: STOCK_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
function useStockPosition(uid: string) {
|
||||
return useResourceQuery({
|
||||
meta: { accessGroup: "brokerage" },
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/position", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
enabled: Boolean(uid),
|
||||
staleTime: STOCK_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
function useStockQuote(uid: string) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks/{uid}/quote", {
|
||||
params: { path: { uid } },
|
||||
}),
|
||||
enabled: Boolean(uid),
|
||||
staleTime: STOCK_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
function useStocks(uids: string[]) {
|
||||
const uniqueUids = [...new Set(uids)];
|
||||
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],
|
||||
unwrapResourceResult(query).data,
|
||||
]),
|
||||
);
|
||||
}
|
||||
function useStockSearch(query: string) {
|
||||
return useResourceQuery({
|
||||
...apiQueryClient.queryOptions("get", "/api/v1/stocks", {
|
||||
params: { query: { query } },
|
||||
}),
|
||||
enabled: query.length >= MIN_STOCK_SEARCH_LENGTH,
|
||||
staleTime: STOCK_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
|
||||
export {
|
||||
export { MIN_STOCK_SEARCH_LENGTH,
|
||||
type StockPeriod,
|
||||
useStock,
|
||||
useStockCandles,
|
||||
@@ -118,6 +120,6 @@ export {
|
||||
useStockDividends,
|
||||
useStockPosition,
|
||||
useStockQuote,
|
||||
useStockSearch,
|
||||
useStocks,
|
||||
useStockSearch,
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export {
|
||||
export { MIN_STOCK_SEARCH_LENGTH,
|
||||
type StockPeriod,
|
||||
useStock,
|
||||
useStockCandles,
|
||||
@@ -6,6 +6,6 @@ export {
|
||||
useStockDividends,
|
||||
useStockPosition,
|
||||
useStockQuote,
|
||||
useStockSearch,
|
||||
useStocks,
|
||||
useStockSearch,
|
||||
} from "./api/queries";
|
||||
|
||||
Reference in New Issue
Block a user