refactor: enforce frontend view model boundaries
This commit is contained in:
@@ -4,53 +4,66 @@ import { SimpleGrid } from "@mantine/core";
|
||||
|
||||
import { BankCardFace } from "./BankCardFace";
|
||||
|
||||
const meta = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
args: {
|
||||
card: {
|
||||
archivedAt: null,
|
||||
balance: { currency: "RUB", value: "128450.75" },
|
||||
bankName: "Сбербанк",
|
||||
id: "fictional",
|
||||
lastFour: "4829",
|
||||
name: "Для повседневных покупок",
|
||||
openingBalance: { currency: "RUB", value: "0" },
|
||||
openingDate: "2026-01-01",
|
||||
paymentSystem: "mir",
|
||||
version: 1,
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
const meta
|
||||
= {
|
||||
args: {
|
||||
card: {
|
||||
archivedAt: null,
|
||||
balance: { currency: "RUB", value: "128450.75" },
|
||||
bankName: "Сбербанк",
|
||||
id: "fictional",
|
||||
lastFour: "4829",
|
||||
name: "Для повседневных покупок",
|
||||
openingBalance: { currency: "RUB", value: "0" },
|
||||
openingDate: "2026-01-01",
|
||||
paymentSystem: "mir",
|
||||
version: 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
component: BankCardFace,
|
||||
tags: ["autodocs"],
|
||||
title: "Product/BankCards/CardAppearance",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */) satisfies Meta<typeof BankCardFace>;
|
||||
component: BankCardFace,
|
||||
tags: ["autodocs"],
|
||||
title: "Product/BankCards/CardAppearance",
|
||||
} satisfies /* eslint-enable unicorn/no-null */ Meta<typeof BankCardFace>;
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Banks: Story = {
|
||||
render: arguments_ => (
|
||||
<SimpleGrid cols={{ base: 1, sm: 2 }} maw={920}>
|
||||
{["Сбербанк", "Т-Банк", "Альфа-Банк", "ВТБ", /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null].map(
|
||||
(bankName, index) => (
|
||||
<BankCardFace
|
||||
card={(/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
...arguments_.card,
|
||||
bankName,
|
||||
paymentSystem:
|
||||
/* eslint-disable-line security/detect-object-injection -- This is a positional index into the local array, not a user-supplied object key. */ (["mir", "mastercard", "visa", "mir", null] as const)[index]
|
||||
{[
|
||||
"Сбербанк",
|
||||
"Т-Банк",
|
||||
"Альфа-Банк",
|
||||
"ВТБ",
|
||||
// eslint-disable-next-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
|
||||
null,
|
||||
].map((bankName, index) => (
|
||||
<BankCardFace
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
card={
|
||||
{
|
||||
...arguments_.card,
|
||||
bankName,
|
||||
paymentSystem:
|
||||
// eslint-disable-next-line security/detect-object-injection -- This is a positional index into the local array, not a user-supplied object key.
|
||||
(["mir", "mastercard", "visa", "mir", null] as const)[index]
|
||||
?? null,
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */)}
|
||||
key={bankName ?? "unknown"}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */
|
||||
}
|
||||
key={bankName ?? "unknown"}
|
||||
/>
|
||||
))}
|
||||
</SimpleGrid>
|
||||
),
|
||||
};
|
||||
export const MissingDetails: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
export const MissingDetails: Story
|
||||
= {
|
||||
args: {
|
||||
card: {
|
||||
...meta.args.card,
|
||||
@@ -59,8 +72,8 @@ export const MissingDetails: Story = (/* eslint-disable unicorn/no-null -- Fixtu
|
||||
paymentSystem: null,
|
||||
},
|
||||
},
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
};
|
||||
/* eslint-enable unicorn/no-null */
|
||||
export const LongArchived: Story = {
|
||||
args: {
|
||||
card: {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { ContactlessIcon } from "@wealthledger/icons";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { formatMoney } from "@/shared/lib";
|
||||
@@ -9,51 +10,46 @@ import type { BankCard } from "../../api/queries";
|
||||
import classes from "./BankCardFace.module.css";
|
||||
|
||||
type BankCardFaceProps = { card: BankCard };
|
||||
|
||||
const BankCardFace: FC<BankCardFaceProps> = (props) => {
|
||||
const { card } = props;
|
||||
const { t } = useTranslation();
|
||||
const bank = card.bankName?.toLocaleLowerCase("ru") ?? "";
|
||||
const tone = bankTone(bank);
|
||||
|
||||
return (
|
||||
<div className={classes.face} data-tone={tone}>
|
||||
<div className={classes.top}>
|
||||
<span className={classes.bank}>{card.bankName || t("bank.card")}</span>
|
||||
|
||||
{card.archivedAt && (
|
||||
<span className={classes.archive}>{t("bank.archived")}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div aria-hidden="true" className={classes.hardware}>
|
||||
<span className={classes.chip} />
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
fill="none"
|
||||
height="30"
|
||||
viewBox="0 0 24 30"
|
||||
width="24"
|
||||
>
|
||||
<path
|
||||
d="M7 11a8 8 0 0 1 0 8m5-12a15 15 0 0 1 0 16m5-20a23 23 0 0 1 0 24"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeWidth="2"
|
||||
/>
|
||||
</svg>
|
||||
|
||||
<ContactlessIcon height="30" viewBox="0 0 24 30" />
|
||||
</div>
|
||||
<div
|
||||
className={classes.number}
|
||||
>
|
||||
|
||||
<div className={classes.number}>
|
||||
{`•••• •••• •••• ${card.lastFour || "••••"}`}
|
||||
</div>
|
||||
|
||||
<div className={classes.bottom}>
|
||||
<div className={classes.details}>
|
||||
<div className={classes.name}>{card.name}</div>
|
||||
|
||||
<div className={classes.balance}>{formatMoney(card.balance)}</div>
|
||||
</div>
|
||||
|
||||
{card.paymentSystem && (
|
||||
<span className={classes.network} data-network={card.paymentSystem}>
|
||||
{card.paymentSystem === "mastercard" && (
|
||||
<span aria-hidden="true" className={classes.circles} />
|
||||
)}
|
||||
|
||||
{t(`bank.paymentSystems.${card.paymentSystem}`)}
|
||||
</span>
|
||||
)}
|
||||
@@ -66,6 +62,7 @@ function bankTone(bank: string) {
|
||||
if (/сбер|sber/.test(bank)) return "green";
|
||||
if (/тинькофф|т[ -]?банк|t[ -]?bank|tinkoff/.test(bank)) return "yellow";
|
||||
if (/альфа|alfa/.test(bank)) return "red";
|
||||
|
||||
return /втб|vtb|газпром|gazprom/.test(bank) ? "blue" : "graphite";
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { ComponentProps } from "react";
|
||||
|
||||
import { DateInput } from "@mantine/dates";
|
||||
import { useController, useFormContext } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { bankDateInputValue } from "../../model/form-validation";
|
||||
import { type BankCardValues, bankDateSchema } from "../../model/form.schema";
|
||||
|
||||
function useBankCardFieldsVm() {
|
||||
const {
|
||||
control,
|
||||
formState: { errors },
|
||||
register,
|
||||
} = useFormContext<BankCardValues>();
|
||||
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { field: paymentSystemField } = useController({
|
||||
control,
|
||||
name: "paymentSystem",
|
||||
});
|
||||
|
||||
const { field: openingDateField } = useController({
|
||||
control,
|
||||
name: "openingDate",
|
||||
});
|
||||
|
||||
const paymentSystems = ["mir", "visa", "mastercard"].map(value => ({
|
||||
label: t(`bank.paymentSystems.${value}`),
|
||||
value,
|
||||
}));
|
||||
|
||||
const onPaymentSystemChange: (value: null | string) => void = value =>
|
||||
paymentSystemField.onChange(value ?? "");
|
||||
|
||||
const dateParser: ComponentProps<typeof DateInput>["dateParser"] = value =>
|
||||
bankDateSchema.safeParse(bankDateInputValue(value)).success
|
||||
? bankDateInputValue(value)
|
||||
: null; // eslint-disable-line unicorn/no-null -- Mantine represents an empty controlled openingDateField as null.
|
||||
|
||||
const onOpeningDateBlur: ComponentProps<typeof DateInput>["onBlur"] = (
|
||||
event,
|
||||
) => {
|
||||
openingDateField.onChange(bankDateInputValue(event.currentTarget.value));
|
||||
openingDateField.onBlur();
|
||||
};
|
||||
|
||||
const onOpeningDateChange: (value: null | string) => void = value =>
|
||||
openingDateField.onChange(value ?? "");
|
||||
|
||||
const onOpeningDateInput: ComponentProps<typeof DateInput>["onInput"] = event =>
|
||||
openingDateField.onChange(bankDateInputValue(event.currentTarget.value));
|
||||
|
||||
const openingDateValue = bankDateSchema.safeParse(openingDateField.value)
|
||||
.success
|
||||
? openingDateField.value
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
dateParser,
|
||||
errors,
|
||||
onOpeningDateBlur,
|
||||
onOpeningDateChange,
|
||||
onOpeningDateInput,
|
||||
onPaymentSystemChange,
|
||||
openingDateField,
|
||||
openingDateValue,
|
||||
paymentSystemField,
|
||||
paymentSystems,
|
||||
register,
|
||||
t,
|
||||
};
|
||||
}
|
||||
|
||||
export { useBankCardFieldsVm };
|
||||
@@ -2,7 +2,7 @@ import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
|
||||
import type { BankCardValues } from "../../model/form-validation";
|
||||
import type { BankCardValues } from "../../model/form.schema";
|
||||
|
||||
import { BankCardFields } from "./BankCardForm.view";
|
||||
|
||||
@@ -20,6 +20,7 @@ const meta = {
|
||||
openingDate: "2026-08-01",
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<FormProvider {...methods}>
|
||||
<Story />
|
||||
@@ -38,8 +39,11 @@ const meta = {
|
||||
tags: ["autodocs"],
|
||||
title: "Product/BankCards/CardFields",
|
||||
} satisfies Meta<typeof BankCardFields>;
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Active: Story = { name: "Независимая карта в рублях" };
|
||||
export const Archived: Story = {
|
||||
args: { archived: true },
|
||||
|
||||
@@ -12,8 +12,10 @@ import type { BankCard } from "../../api/queries";
|
||||
|
||||
import { BankCardForm } from "./BankCardForm";
|
||||
|
||||
const card: BankCard = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
const card: BankCard
|
||||
= {
|
||||
archivedAt: null,
|
||||
balance: { currency: "RUB", value: "50" },
|
||||
bankName: "Банк",
|
||||
@@ -24,8 +26,9 @@ const card: BankCard = (/* eslint-disable unicorn/no-null -- Fixture preserves t
|
||||
openingDate: "2026-01-01",
|
||||
paymentSystem: null,
|
||||
version: 1,
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
};
|
||||
|
||||
/* eslint-enable unicorn/no-null */
|
||||
function setup(value: BankCard) {
|
||||
configureAuthClient({
|
||||
accessToken: () => "test",
|
||||
@@ -41,8 +44,10 @@ function setup(value: BankCard) {
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
|
||||
return close;
|
||||
}
|
||||
|
||||
describe("BankCardForm", () => {
|
||||
it("waits for the exit transition before notifying the parent", async () => {
|
||||
const close = setup(card);
|
||||
@@ -64,20 +69,23 @@ describe("BankCardForm", () => {
|
||||
server.use(
|
||||
http.patch("*/api/v1/bank-cards/a", async ({ request }) => {
|
||||
body = await request.json();
|
||||
|
||||
return HttpResponse.json(card);
|
||||
}),
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await waitFor(() => expect(close).toHaveBeenCalled());
|
||||
expect(body).toEqual((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
expect(body).toEqual(
|
||||
{
|
||||
bankName: null,
|
||||
lastFour: null,
|
||||
name: "Основная",
|
||||
paymentSystem: null,
|
||||
version: 1,
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */));
|
||||
},
|
||||
/* eslint-enable unicorn/no-null */
|
||||
);
|
||||
});
|
||||
it("loads and saves the selected payment system", async () => {
|
||||
const close = setup({ ...card, paymentSystem: "mir" });
|
||||
@@ -92,6 +100,7 @@ describe("BankCardForm", () => {
|
||||
server.use(
|
||||
http.patch("*/api/v1/bank-cards/a", async ({ request }) => {
|
||||
body = await request.json();
|
||||
|
||||
return HttpResponse.json({ ...card, paymentSystem: "visa" });
|
||||
}),
|
||||
);
|
||||
@@ -132,6 +141,7 @@ describe("BankCardForm", () => {
|
||||
const body = (await request.json()) as Record<string, unknown>;
|
||||
bodies.push(body);
|
||||
version = 2;
|
||||
|
||||
return body.version === 1
|
||||
? HttpResponse.json(
|
||||
{ code: "BANK_VERSION_CONFLICT" },
|
||||
@@ -146,9 +156,11 @@ describe("BankCardForm", () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
await screen.findByText(/Запись уже изменена/);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Перечитать запись" }));
|
||||
|
||||
const adopt = await screen.findByRole("button", {
|
||||
name: "Использовать актуальную версию 2",
|
||||
});
|
||||
|
||||
expect(screen.getByLabelText(/Название карты/)).toHaveValue("Мой черновик");
|
||||
fireEvent.click(adopt);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
|
||||
@@ -1,121 +1,61 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Button, Group, Modal, Stack, Text } from "@mantine/core";
|
||||
import { type FC, useState } from "react";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { type FC } from "react";
|
||||
import { FormProvider } from "react-hook-form";
|
||||
|
||||
import { formatDate } from "@/shared/lib";
|
||||
|
||||
import { useBankMutations } from "../../api/mutations";
|
||||
import { type BankCard, useBankCard } from "../../api/queries";
|
||||
import {
|
||||
bankCardSchema,
|
||||
type BankCardValues,
|
||||
bankMoneyValue,
|
||||
bankToday,
|
||||
} from "../../model/form-validation";
|
||||
import { type BankCard } from "../../api/queries";
|
||||
import { BankFeedback } from "../BankFeedback";
|
||||
import classes from "../BankForms.module.css";
|
||||
import { useBankFormFocus } from "../useBankFormFocus";
|
||||
import { BankCardFields } from "./BankCardForm.view";
|
||||
import { useBankCardFormVm } from "./BankCardForm.vm";
|
||||
|
||||
type BankCardFormProps = { card?: BankCard; onClose: () => void };
|
||||
|
||||
const BankCardForm: FC<BankCardFormProps> = (props) => {
|
||||
useBankFormFocus();
|
||||
const [opened, setOpened] = useState(true);
|
||||
const { t } = useTranslation();
|
||||
const [intent] = useState(() => crypto.randomUUID());
|
||||
const [version, setVersion] = useState(props.card?.version ?? 1);
|
||||
const [error, setError] = useState<unknown>();
|
||||
const [latest, setLatest] = useState<BankCard>();
|
||||
const fresh = useBankCard(props.card?.id);
|
||||
const mutation = useBankMutations();
|
||||
const methods = useForm<BankCardValues>({
|
||||
defaultValues: {
|
||||
bankName: props.card?.bankName ?? "",
|
||||
lastFour: props.card?.lastFour ?? "",
|
||||
name: props.card?.name ?? "",
|
||||
openingBalance: props.card?.openingBalance.value ?? "0",
|
||||
openingDate: props.card?.openingDate ?? bankToday(),
|
||||
paymentSystem: props.card?.paymentSystem ?? "",
|
||||
},
|
||||
resolver: zodResolver(bankCardSchema),
|
||||
});
|
||||
const isPending
|
||||
= !opened
|
||||
|| methods.formState.isSubmitting
|
||||
|| (fresh.isFetching && Boolean(error));
|
||||
const {
|
||||
dialogTitle,
|
||||
error,
|
||||
isPending,
|
||||
latest,
|
||||
methods,
|
||||
onAdoptVersion,
|
||||
onCancel,
|
||||
onReloadRecord,
|
||||
onRequestClose,
|
||||
onSubmit,
|
||||
opened,
|
||||
t,
|
||||
} = useBankCardFormVm(props);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
closeButtonProps={{ "aria-label": t("bank.close"), "disabled": isPending }}
|
||||
closeOnClickOutside={!isPending}
|
||||
closeOnEscape={!isPending}
|
||||
onClose={() => !isPending && setOpened(false)}
|
||||
onClose={onRequestClose}
|
||||
onExitTransitionEnd={props.onClose}
|
||||
opened={opened}
|
||||
title={t(props.card ? "bank.editCard" : "bank.addCard")}
|
||||
title={dialogTitle}
|
||||
>
|
||||
<FormProvider {...methods}>
|
||||
<form
|
||||
onSubmit={methods.handleSubmit(async (values) => {
|
||||
setError(undefined);
|
||||
try {
|
||||
const metadata = {
|
||||
bankName: values.bankName || /* eslint-disable-line unicorn/no-null -- PATCH uses null to clear these optional card fields. */ null,
|
||||
lastFour: values.lastFour || /* eslint-disable-line unicorn/no-null -- PATCH uses null to clear these optional card fields. */ null,
|
||||
name: values.name,
|
||||
paymentSystem: values.paymentSystem || /* eslint-disable-line unicorn/no-null -- PATCH uses null to clear these optional card fields. */ null,
|
||||
};
|
||||
const financial = {
|
||||
openingBalance: {
|
||||
currency: "RUB" as const,
|
||||
value: bankMoneyValue(values.openingBalance),
|
||||
},
|
||||
openingDate: values.openingDate,
|
||||
};
|
||||
if (props.card)
|
||||
await mutation.updateCard.mutateAsync({
|
||||
body: {
|
||||
...metadata,
|
||||
...(!props.card.archivedAt && financial),
|
||||
version,
|
||||
},
|
||||
id: props.card.id,
|
||||
});
|
||||
else
|
||||
await mutation.createCard.mutateAsync({
|
||||
id: intent,
|
||||
...metadata,
|
||||
...financial,
|
||||
});
|
||||
setOpened(false);
|
||||
}
|
||||
catch (error_) {
|
||||
setError(error_);
|
||||
}
|
||||
})}
|
||||
>
|
||||
<form onSubmit={onSubmit}>
|
||||
<fieldset className={classes.fieldset} disabled={isPending}>
|
||||
<Stack>
|
||||
<BankCardFields archived={Boolean(props.card?.archivedAt)} />
|
||||
{!!(error) && ((
|
||||
|
||||
{!!error && (
|
||||
<>
|
||||
<BankFeedback error={error} />
|
||||
|
||||
{props.card && (
|
||||
<Button
|
||||
onClick={async () => {
|
||||
const response = await fresh.refetch();
|
||||
if (response.data && !response.error)
|
||||
setLatest(response.data);
|
||||
else setError(response.error);
|
||||
}}
|
||||
variant="default"
|
||||
>
|
||||
<Button onClick={onReloadRecord} variant="default">
|
||||
{t("bank.reloadRecord")}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
))}
|
||||
)}
|
||||
|
||||
{latest && (
|
||||
<>
|
||||
<Text>
|
||||
@@ -123,23 +63,19 @@ const BankCardForm: FC<BankCardFormProps> = (props) => {
|
||||
details: `${latest.name} · ${latest.openingBalance.value} RUB · ${formatDate(latest.openingDate)}`,
|
||||
})}
|
||||
</Text>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setVersion(latest.version);
|
||||
setLatest(undefined);
|
||||
setError(undefined);
|
||||
}}
|
||||
variant="default"
|
||||
>
|
||||
|
||||
<Button onClick={onAdoptVersion} variant="default">
|
||||
{t("bank.adoptVersion", { version: latest.version })}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Group>
|
||||
<Button loading={isPending} type="submit">
|
||||
{t("bank.save")}
|
||||
</Button>
|
||||
<Button onClick={() => setOpened(false)} variant="default">
|
||||
|
||||
<Button onClick={onCancel} variant="default">
|
||||
{t("bank.cancel")}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
@@ -2,24 +2,28 @@ import type { FC } from "react";
|
||||
|
||||
import { Select, Stack, Text, TextInput } from "@mantine/core";
|
||||
import { DateInput } from "@mantine/dates";
|
||||
import { Controller, useFormContext } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import {
|
||||
type BankCardValues,
|
||||
bankDateInputValue,
|
||||
bankDateSchema,
|
||||
bankToday,
|
||||
} from "../../model/form-validation";
|
||||
import { bankToday } from "../../model/form-validation";
|
||||
import { useBankCardFieldsVm } from "./BankCardFields.vm";
|
||||
|
||||
type BankCardFieldsProps = { archived: boolean };
|
||||
|
||||
const BankCardFields: FC<BankCardFieldsProps> = (props) => {
|
||||
const {
|
||||
control,
|
||||
formState: { errors },
|
||||
dateParser,
|
||||
errors,
|
||||
onOpeningDateBlur,
|
||||
onOpeningDateChange,
|
||||
onOpeningDateInput,
|
||||
onPaymentSystemChange,
|
||||
openingDateField,
|
||||
openingDateValue,
|
||||
paymentSystemField,
|
||||
paymentSystems,
|
||||
register,
|
||||
} = useFormContext<BankCardValues>();
|
||||
const { t } = useTranslation();
|
||||
t,
|
||||
} = useBankCardFieldsVm();
|
||||
|
||||
return (
|
||||
<Stack>
|
||||
<TextInput
|
||||
@@ -28,37 +32,36 @@ const BankCardFields: FC<BankCardFieldsProps> = (props) => {
|
||||
{...register("name")}
|
||||
error={errors.name?.message}
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
label={t("bank.bankName")}
|
||||
{...register("bankName")}
|
||||
error={errors.bankName?.message}
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
inputMode="numeric"
|
||||
label={t("bank.lastFour")}
|
||||
{...register("lastFour")}
|
||||
error={errors.lastFour?.message}
|
||||
/>
|
||||
<Controller
|
||||
control={control}
|
||||
name="paymentSystem"
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
{...field}
|
||||
clearable
|
||||
comboboxProps={{ withinPortal: false }}
|
||||
data={["mir", "visa", "mastercard"].map(value => ({
|
||||
label: t(`bank.paymentSystems.${value}`),
|
||||
value,
|
||||
}))}
|
||||
error={errors.paymentSystem?.message}
|
||||
label={t("bank.paymentSystem")}
|
||||
onChange={value => field.onChange(value ?? "")}
|
||||
placeholder={t("bank.paymentSystemUnknown")}
|
||||
value={field.value || /* eslint-disable-line unicorn/no-null -- Mantine represents an empty controlled field as null. */ null}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Select
|
||||
{...paymentSystemField}
|
||||
clearable
|
||||
comboboxProps={{ withinPortal: false }}
|
||||
data={paymentSystems}
|
||||
error={errors.paymentSystem?.message}
|
||||
label={t("bank.paymentSystem")}
|
||||
onChange={onPaymentSystemChange}
|
||||
placeholder={t("bank.paymentSystemUnknown")}
|
||||
value={
|
||||
paymentSystemField.value
|
||||
// eslint-disable-next-line unicorn/no-null -- Mantine represents an empty controlled paymentSystemField as null.
|
||||
|| null
|
||||
}
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
inputMode="decimal"
|
||||
label={t("bank.openingBalance")}
|
||||
@@ -67,43 +70,31 @@ const BankCardFields: FC<BankCardFieldsProps> = (props) => {
|
||||
{...register("openingBalance")}
|
||||
error={errors.openingBalance?.message}
|
||||
/>
|
||||
<Controller
|
||||
control={control}
|
||||
name="openingDate"
|
||||
render={({ field }) => (
|
||||
<DateInput
|
||||
{...field}
|
||||
dateParser={value =>
|
||||
bankDateSchema.safeParse(bankDateInputValue(value)).success
|
||||
? bankDateInputValue(value)
|
||||
: /* eslint-disable-line unicorn/no-null -- Mantine represents an empty controlled field as null. */ null}
|
||||
error={errors.openingDate?.message}
|
||||
fixOnBlur={false}
|
||||
label={t("bank.openingDate")}
|
||||
maxDate={bankToday()}
|
||||
onBlur={(event) => {
|
||||
field.onChange(bankDateInputValue(event.currentTarget.value));
|
||||
field.onBlur();
|
||||
}}
|
||||
onChange={value => field.onChange(value ?? "")}
|
||||
onInput={event =>
|
||||
field.onChange(bankDateInputValue(event.currentTarget.value))}
|
||||
popoverProps={{
|
||||
middlewares: { shift: { crossAxis: true } },
|
||||
withinPortal: false,
|
||||
}}
|
||||
readOnly={props.archived}
|
||||
required
|
||||
value={
|
||||
(bankDateSchema.safeParse(field.value).success) ? (field.value) : undefined
|
||||
}
|
||||
valueFormat="DD.MM.YYYY"
|
||||
/>
|
||||
)}
|
||||
|
||||
<DateInput
|
||||
{...openingDateField}
|
||||
dateParser={dateParser}
|
||||
error={errors.openingDate?.message}
|
||||
fixOnBlur={false}
|
||||
label={t("bank.openingDate")}
|
||||
maxDate={bankToday()}
|
||||
onBlur={onOpeningDateBlur}
|
||||
onChange={onOpeningDateChange}
|
||||
onInput={onOpeningDateInput}
|
||||
popoverProps={{
|
||||
middlewares: { shift: { crossAxis: true } },
|
||||
withinPortal: false,
|
||||
}}
|
||||
readOnly={props.archived}
|
||||
required
|
||||
value={openingDateValue}
|
||||
valueFormat="DD.MM.YYYY"
|
||||
/>
|
||||
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("bank.openingHint")}
|
||||
</Text>
|
||||
|
||||
{props.archived && <Text>{t("bank.archiveHint")}</Text>}
|
||||
</Stack>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { useBankMutations } from "../../api/mutations";
|
||||
import { type BankCard, useBankCard } from "../../api/queries";
|
||||
import { bankMoneyValue, bankToday } from "../../model/form-validation";
|
||||
import { bankCardSchema, type BankCardValues } from "../../model/form.schema";
|
||||
import { useBankFormFocus } from "../useBankFormFocus";
|
||||
|
||||
type BankCardFormProps = { card?: BankCard; onClose: () => void };
|
||||
|
||||
function useBankCardFormVm(props: BankCardFormProps) {
|
||||
useBankFormFocus();
|
||||
const [opened, setOpened] = useState(true);
|
||||
const { t } = useTranslation();
|
||||
const [intent] = useState(() => crypto.randomUUID());
|
||||
const [version, setVersion] = useState(props.card?.version ?? 1);
|
||||
const [error, setError] = useState<unknown>();
|
||||
const [latest, setLatest] = useState<BankCard>();
|
||||
const fresh = useBankCard(props.card?.id);
|
||||
const mutation = useBankMutations();
|
||||
|
||||
const methods = useForm<BankCardValues>({
|
||||
defaultValues: {
|
||||
bankName: props.card?.bankName ?? "",
|
||||
lastFour: props.card?.lastFour ?? "",
|
||||
name: props.card?.name ?? "",
|
||||
openingBalance: props.card?.openingBalance.value ?? "0",
|
||||
openingDate: props.card?.openingDate ?? bankToday(),
|
||||
paymentSystem: props.card?.paymentSystem ?? "",
|
||||
},
|
||||
resolver: zodResolver(bankCardSchema),
|
||||
});
|
||||
|
||||
const isPending
|
||||
= !opened
|
||||
|| methods.formState.isSubmitting
|
||||
|| (fresh.isFetching && Boolean(error));
|
||||
|
||||
const onRequestClose = () => !isPending && setOpened(false);
|
||||
const dialogTitle = t(props.card ? "bank.editCard" : "bank.addCard");
|
||||
|
||||
const onSubmit = methods.handleSubmit(async (values) => {
|
||||
setError(undefined);
|
||||
|
||||
try {
|
||||
const metadata = {
|
||||
bankName:
|
||||
values.bankName
|
||||
// eslint-disable-next-line unicorn/no-null -- PATCH uses null to clear these optional card fields.
|
||||
|| null,
|
||||
lastFour:
|
||||
values.lastFour
|
||||
// eslint-disable-next-line unicorn/no-null -- PATCH uses null to clear these optional card fields.
|
||||
|| null,
|
||||
name: values.name,
|
||||
paymentSystem:
|
||||
values.paymentSystem
|
||||
// eslint-disable-next-line unicorn/no-null -- PATCH uses null to clear these optional card fields.
|
||||
|| null,
|
||||
};
|
||||
|
||||
const financial = {
|
||||
openingBalance: {
|
||||
currency: "RUB" as const,
|
||||
value: bankMoneyValue(values.openingBalance),
|
||||
},
|
||||
openingDate: values.openingDate,
|
||||
};
|
||||
|
||||
if (props.card)
|
||||
await mutation.updateCard.mutateAsync({
|
||||
body: {
|
||||
...metadata,
|
||||
...(!props.card.archivedAt && financial),
|
||||
version,
|
||||
},
|
||||
id: props.card.id,
|
||||
});
|
||||
else
|
||||
await mutation.createCard.mutateAsync({
|
||||
id: intent,
|
||||
...metadata,
|
||||
...financial,
|
||||
});
|
||||
setOpened(false);
|
||||
}
|
||||
catch (error_) {
|
||||
setError(error_);
|
||||
}
|
||||
});
|
||||
|
||||
const onReloadRecord = async () => {
|
||||
const response = await fresh.refetch();
|
||||
if (response.data && !response.error) setLatest(response.data);
|
||||
else setError(response.error);
|
||||
};
|
||||
|
||||
const onAdoptVersion = () => {
|
||||
if (!latest) return;
|
||||
setVersion(latest.version);
|
||||
setLatest(undefined);
|
||||
setError(undefined);
|
||||
};
|
||||
|
||||
const onCancel = () => setOpened(false);
|
||||
|
||||
return {
|
||||
dialogTitle,
|
||||
error,
|
||||
isPending,
|
||||
latest,
|
||||
methods,
|
||||
onAdoptVersion,
|
||||
onCancel,
|
||||
onReloadRecord,
|
||||
onRequestClose,
|
||||
onSubmit,
|
||||
opened,
|
||||
t,
|
||||
version,
|
||||
};
|
||||
}
|
||||
|
||||
export { useBankCardFormVm };
|
||||
@@ -11,9 +11,11 @@ type BankFeedbackProps = {
|
||||
loadingError?: boolean;
|
||||
retry?: () => void;
|
||||
};
|
||||
|
||||
const BankFeedback: FC<BankFeedbackProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
const code = apiErrorCode(props.error);
|
||||
|
||||
return (
|
||||
<Alert color="orange" role="alert">
|
||||
<Group>
|
||||
@@ -26,6 +28,7 @@ const BankFeedback: FC<BankFeedbackProps> = (props) => {
|
||||
),
|
||||
})}
|
||||
</Text>
|
||||
|
||||
{props.retry && (
|
||||
<Button onClick={props.retry} variant="default">
|
||||
{t("bank.retry")}
|
||||
|
||||
@@ -1,365 +0,0 @@
|
||||
.icon {
|
||||
overflow: visible;
|
||||
|
||||
& path {
|
||||
--motion: none;
|
||||
transform-box: fill-box;
|
||||
transform-origin: center;
|
||||
}
|
||||
}
|
||||
|
||||
.deposit path:nth-child(-n + 2) {
|
||||
transform-box: view-box;
|
||||
transform-origin: 12px 9px;
|
||||
--motion: bank-operation-coin-turn 1000ms ease-in-out both;
|
||||
}
|
||||
|
||||
.repayment path:last-child {
|
||||
--motion: bank-operation-ruble-in 1000ms ease-out both;
|
||||
}
|
||||
|
||||
.topup path:last-child {
|
||||
--motion: bank-operation-plus-in 900ms ease-out both;
|
||||
}
|
||||
|
||||
.transfer path {
|
||||
--shift: 3px;
|
||||
--motion: bank-operation-exchange 700ms ease-in-out both;
|
||||
&:last-child {
|
||||
--shift: -3px;
|
||||
}
|
||||
}
|
||||
|
||||
.growth {
|
||||
& path:nth-child(2) {
|
||||
stroke-dasharray: 1;
|
||||
--motion: bank-operation-draw 450ms ease-out both;
|
||||
}
|
||||
& path:last-child {
|
||||
--motion: bank-operation-arrow-rise 350ms ease-out 400ms both;
|
||||
}
|
||||
}
|
||||
|
||||
.server {
|
||||
& path:nth-child(3) {
|
||||
--motion: bank-operation-blink 500ms ease-in-out both;
|
||||
}
|
||||
& path:nth-child(4) {
|
||||
--motion: bank-operation-blink 500ms ease-in-out 220ms both;
|
||||
}
|
||||
}
|
||||
|
||||
.basket {
|
||||
& path:not(:last-child) {
|
||||
--motion: bank-operation-settle 850ms ease-in-out both;
|
||||
}
|
||||
& path:last-child {
|
||||
opacity: 0;
|
||||
fill: currentColor;
|
||||
--motion: bank-operation-grocery-drop 850ms ease-out both;
|
||||
}
|
||||
}
|
||||
|
||||
.wine {
|
||||
--motion: bank-operation-cheers 1100ms ease-in-out both;
|
||||
transform-origin: 12px 21px;
|
||||
& path:nth-child(2) {
|
||||
fill: currentColor;
|
||||
fill-opacity: 0.2;
|
||||
transform-origin: bottom;
|
||||
--motion: bank-operation-fill-glass 1100ms ease-out both;
|
||||
}
|
||||
}
|
||||
|
||||
.coffee {
|
||||
& path:nth-child(3),
|
||||
& path:nth-child(4) {
|
||||
--motion: bank-operation-steam 1000ms ease-out var(--delay, 0ms) both;
|
||||
}
|
||||
& path:nth-child(4) {
|
||||
--delay: 180ms;
|
||||
}
|
||||
}
|
||||
|
||||
.grid path {
|
||||
--x: -1.5px;
|
||||
--y: -1.5px;
|
||||
--turn: 0deg;
|
||||
--motion: bank-operation-rearrange 850ms ease-in-out both;
|
||||
&:nth-child(2) {
|
||||
--x: 1.5px;
|
||||
--turn: 90deg;
|
||||
}
|
||||
&:nth-child(3) {
|
||||
--y: 1.5px;
|
||||
}
|
||||
&:nth-child(4) {
|
||||
--x: 1.5px;
|
||||
--y: 1.5px;
|
||||
}
|
||||
}
|
||||
|
||||
.wifi path {
|
||||
--motion: bank-operation-signal 450ms ease-out var(--delay, 0ms) both;
|
||||
&:nth-child(1) {
|
||||
--delay: 360ms;
|
||||
}
|
||||
&:nth-child(2) {
|
||||
--delay: 240ms;
|
||||
}
|
||||
&:nth-child(3) {
|
||||
--delay: 120ms;
|
||||
}
|
||||
}
|
||||
|
||||
.car {
|
||||
--motion: bank-operation-drive 1100ms ease-in-out both;
|
||||
& path:nth-child(-n + 3) {
|
||||
--motion: bank-operation-suspension 275ms ease-in-out 4 both;
|
||||
}
|
||||
& path:nth-last-child(-n + 2) {
|
||||
--motion: bank-operation-wheel-roll 1100ms ease-in-out both;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.icon[data-icon-animating] {
|
||||
animation: var(--motion, none);
|
||||
& path {
|
||||
animation: var(--motion, none);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-coin-turn) {
|
||||
0%,
|
||||
100% {
|
||||
transform: scaleX(1);
|
||||
}
|
||||
35%,
|
||||
65% {
|
||||
transform: scaleX(0.12);
|
||||
}
|
||||
50% {
|
||||
transform: scaleX(-1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-settle) {
|
||||
0%,
|
||||
30%,
|
||||
100% {
|
||||
transform: translateY(0);
|
||||
}
|
||||
45% {
|
||||
transform: translateY(1.5px);
|
||||
}
|
||||
65% {
|
||||
transform: translateY(-0.5px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-ruble-in) {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateY(-9px) scale(0.7);
|
||||
}
|
||||
25% {
|
||||
opacity: 1;
|
||||
}
|
||||
65% {
|
||||
transform: translateY(0) scale(1.15);
|
||||
}
|
||||
80% {
|
||||
transform: scale(0.95);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-plus-in) {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateY(-5px) scale(0.5);
|
||||
}
|
||||
55% {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1.3);
|
||||
}
|
||||
75% {
|
||||
transform: scale(0.9);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-exchange) {
|
||||
0%,
|
||||
100% {
|
||||
transform: translateX(0);
|
||||
}
|
||||
45% {
|
||||
transform: translateX(var(--shift));
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-draw) {
|
||||
from {
|
||||
stroke-dashoffset: 1;
|
||||
}
|
||||
to {
|
||||
stroke-dashoffset: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-arrow-rise) {
|
||||
0%,
|
||||
100% {
|
||||
transform: translateY(0);
|
||||
}
|
||||
45% {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-blink) {
|
||||
0%,
|
||||
100% {
|
||||
stroke-width: 1.6;
|
||||
}
|
||||
45% {
|
||||
stroke: var(--mantine-color-green-6);
|
||||
stroke-width: 3;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-grocery-drop) {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateY(-5px);
|
||||
}
|
||||
20% {
|
||||
opacity: 1;
|
||||
}
|
||||
55% {
|
||||
opacity: 1;
|
||||
transform: translateY(7px);
|
||||
}
|
||||
80%,
|
||||
100% {
|
||||
opacity: 0;
|
||||
transform: translateY(7px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-fill-glass) {
|
||||
0% {
|
||||
transform: scaleY(0.05);
|
||||
}
|
||||
45%,
|
||||
75% {
|
||||
transform: scaleY(1);
|
||||
fill-opacity: 0.5;
|
||||
}
|
||||
100% {
|
||||
transform: scaleY(1);
|
||||
fill-opacity: 0.2;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-cheers) {
|
||||
0%,
|
||||
40%,
|
||||
100% {
|
||||
transform: rotate(0);
|
||||
}
|
||||
65% {
|
||||
transform: rotate(8deg);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-steam) {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateY(2px);
|
||||
}
|
||||
25% {
|
||||
opacity: 1;
|
||||
}
|
||||
70% {
|
||||
opacity: 0;
|
||||
transform: translateY(-3px);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-rearrange) {
|
||||
0%,
|
||||
100% {
|
||||
transform: translate(0, 0) rotate(0);
|
||||
}
|
||||
50% {
|
||||
transform: translate(var(--x), var(--y)) rotate(var(--turn));
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-signal) {
|
||||
0% {
|
||||
opacity: 0.1;
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-drive) {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateX(-4px);
|
||||
}
|
||||
20% {
|
||||
opacity: 1;
|
||||
}
|
||||
80% {
|
||||
opacity: 1;
|
||||
transform: translateX(3px);
|
||||
}
|
||||
90% {
|
||||
opacity: 0;
|
||||
transform: translateX(4px);
|
||||
}
|
||||
91% {
|
||||
opacity: 0;
|
||||
transform: translateX(0);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-suspension) {
|
||||
0%,
|
||||
100% {
|
||||
transform: translateY(0);
|
||||
}
|
||||
50% {
|
||||
transform: translateY(-0.5px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes :global(bank-operation-wheel-roll) {
|
||||
from {
|
||||
transform: rotate(0);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,17 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
|
||||
import { Stack } from "@mantine/core";
|
||||
import { OperationIcon } from "@wealthledger/icons";
|
||||
import { EntryCard } from "@wealthledger/ui";
|
||||
|
||||
import { BankOperationIcon } from "./BankOperationIcon";
|
||||
import { bankOperationAppearance } from "../../model/operation-appearance";
|
||||
|
||||
const BankOperationIcon = (props: {
|
||||
categoryName?: null | string;
|
||||
kind: "expense" | "refund" | "topup" | "transfer";
|
||||
}) => (
|
||||
<OperationIcon {...bankOperationAppearance(props.kind, props.categoryName)} />
|
||||
);
|
||||
|
||||
const meta = {
|
||||
args: { categoryName: "Продукты", kind: "expense" },
|
||||
@@ -11,8 +19,11 @@ const meta = {
|
||||
tags: ["autodocs"],
|
||||
title: "Product/BankCards/OperationIcons",
|
||||
} satisfies Meta<typeof BankOperationIcon>;
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Categories: Story = {
|
||||
render: () => (
|
||||
<Stack maw={640}>
|
||||
@@ -55,6 +66,7 @@ export const Categories: Story = {
|
||||
valueLabel="Расход"
|
||||
/>
|
||||
))}
|
||||
|
||||
<EntryCard
|
||||
color="green"
|
||||
icon={<BankOperationIcon kind="topup" />}
|
||||
|
||||
@@ -1,12 +1,21 @@
|
||||
import { render } from "@testing-library/react";
|
||||
import { OperationIcon } from "@wealthledger/icons";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { BankOperationIcon } from "./BankOperationIcon";
|
||||
import { bankOperationAppearance } from "../../model/operation-appearance";
|
||||
|
||||
const BankOperationIcon = (props: {
|
||||
categoryName?: null | string;
|
||||
kind: "expense" | "refund" | "topup" | "transfer";
|
||||
}) => (
|
||||
<OperationIcon {...bankOperationAppearance(props.kind, props.categoryName)} />
|
||||
);
|
||||
|
||||
it("matches normalized category names, falls back after renaming and distinguishes operation kinds", () => {
|
||||
const { container, rerender } = render(
|
||||
<BankOperationIcon categoryName="Жильё" kind="expense" />,
|
||||
);
|
||||
|
||||
// eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
|
||||
const path = () => container.querySelector("path")?.getAttribute("d");
|
||||
const housing = path();
|
||||
@@ -15,16 +24,25 @@ it("matches normalized category names, falls back after renaming and distinguish
|
||||
rerender(<BankOperationIcon categoryName="Другое" kind="expense" />);
|
||||
const fallback = path();
|
||||
expect(fallback).not.toBe(housing);
|
||||
for (const categoryName of ["Моя категория", "constructor", /* eslint-disable-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract. */ null]) {
|
||||
|
||||
for (const categoryName of [
|
||||
"Моя категория",
|
||||
"constructor",
|
||||
// eslint-disable-next-line unicorn/no-null -- Exercise the explicit null returned by the production API/DOM contract.
|
||||
null,
|
||||
]) {
|
||||
rerender(<BankOperationIcon categoryName={categoryName} kind="expense" />);
|
||||
expect(path()).toBe(fallback);
|
||||
}
|
||||
|
||||
const paths = [fallback, housing];
|
||||
|
||||
for (const kind of ["topup", "transfer", "refund"] as const) {
|
||||
rerender(<BankOperationIcon categoryName="Жильё" kind={kind} />);
|
||||
expect(path()).toBeTruthy();
|
||||
paths.push(path());
|
||||
}
|
||||
|
||||
expect(new Set(paths).size).toBe(5);
|
||||
// eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
|
||||
expect(container.querySelector("svg")).toHaveAttribute("aria-hidden", "true");
|
||||
@@ -34,8 +52,10 @@ it("provides a distinct icon for every existing named category", () => {
|
||||
const { container, rerender } = render(
|
||||
<BankOperationIcon categoryName="Другое" kind="expense" />,
|
||||
);
|
||||
|
||||
// eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- This assertion checks DOM structure, decoration or focus behavior that semantic queries cannot establish.
|
||||
const paths = new Set([container.querySelector("path")?.getAttribute("d")]);
|
||||
|
||||
for (const categoryName of [
|
||||
"Алкоголь",
|
||||
"Вклады",
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import type { FC } from "react";
|
||||
|
||||
import { bindIconAnimation } from "@/shared/lib";
|
||||
|
||||
import type { BankOperation } from "../../api/queries";
|
||||
|
||||
import { bankOperationAppearance } from "../../model/operation-appearance";
|
||||
import classes from "./BankOperationIcon.module.css";
|
||||
|
||||
type BankOperationIconProps = {
|
||||
categoryName?: null | string;
|
||||
kind: BankOperation["kind"];
|
||||
};
|
||||
const BankOperationIcon: FC<BankOperationIconProps> = (props) => {
|
||||
const icon = bankOperationAppearance(props.kind, props.categoryName);
|
||||
return (
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
className={`${classes.icon} ${icon.animation ? classes[icon.animation] : ""}`}
|
||||
fill="none"
|
||||
focusable="false"
|
||||
height="24"
|
||||
ref={bindIconAnimation}
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="1.6"
|
||||
style={{ color: `var(--mantine-color-${icon.color}-7)`, flexShrink: 0 }}
|
||||
viewBox="0 0 24 24"
|
||||
width="24"
|
||||
>
|
||||
{icon.path.split(" M").map((part, index) => (
|
||||
<path d={index ? `M${part}` : part} key={part} pathLength={1} />
|
||||
))}
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export { BankOperationIcon };
|
||||
+7
-15
@@ -1,29 +1,21 @@
|
||||
import { DatePickerInput } from "@mantine/dates";
|
||||
import { type FC, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { type FC } from "react";
|
||||
|
||||
import { useBankPeriodPickerVm } from "./BankPeriodPicker.vm";
|
||||
|
||||
type BankPeriodPickerProps = {
|
||||
onChange: (value: [null | string, null | string]) => void;
|
||||
period: { from: string; to: string };
|
||||
};
|
||||
|
||||
const BankPeriodPicker: FC<BankPeriodPickerProps> = (props) => {
|
||||
const { onChange, period } = props;
|
||||
const { t } = useTranslation();
|
||||
const scope = `${period.from}-${period.to}`;
|
||||
const [draft, setDraft] = useState<{
|
||||
scope: string;
|
||||
value: [null | string, null | string];
|
||||
}>();
|
||||
const value: [null | string, null | string]
|
||||
= draft?.scope === scope ? draft.value : [period.from, period.to];
|
||||
const { onPeriodChange, t, value } = useBankPeriodPickerVm(props);
|
||||
|
||||
return (
|
||||
<DatePickerInput
|
||||
allowSingleDateInRange
|
||||
label={t("bank.period")}
|
||||
onChange={(next) => {
|
||||
setDraft({ scope, value: next });
|
||||
onChange(next);
|
||||
}}
|
||||
onChange={onPeriodChange}
|
||||
popoverProps={{
|
||||
middlewares: { shift: { crossAxis: true } },
|
||||
returnFocus: true,
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
type BankPeriodPickerProps = {
|
||||
onChange: (value: [null | string, null | string]) => void;
|
||||
period: { from: string; to: string };
|
||||
};
|
||||
|
||||
function useBankPeriodPickerVm(props: BankPeriodPickerProps) {
|
||||
const { onChange, period } = props;
|
||||
const { t } = useTranslation();
|
||||
const scope = `${period.from}-${period.to}`;
|
||||
|
||||
const [draft, setDraft] = useState<{
|
||||
scope: string;
|
||||
value: [null | string, null | string];
|
||||
}>();
|
||||
|
||||
const value: [null | string, null | string]
|
||||
= draft?.scope === scope ? draft.value : [period.from, period.to];
|
||||
|
||||
const onPeriodChange = (next: [null | string, null | string]) => {
|
||||
setDraft({ scope, value: next });
|
||||
onChange(next);
|
||||
};
|
||||
|
||||
return { onChange, onPeriodChange, t, value };
|
||||
}
|
||||
|
||||
export { useBankPeriodPickerVm };
|
||||
@@ -3,69 +3,75 @@ import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { BankSummaryView } from "./BankSummary.view";
|
||||
|
||||
const money = (value: string) => ({ currency: "RUB", value });
|
||||
const meta = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
args: {
|
||||
data: {
|
||||
cardId: null,
|
||||
categories: [
|
||||
{
|
||||
categoryId: "food",
|
||||
categoryName: "Продукты",
|
||||
expenses: money("3500"),
|
||||
net: money("2500"),
|
||||
refunds: money("1000"),
|
||||
},
|
||||
{
|
||||
categoryId: "cafe",
|
||||
categoryName: "Кафе",
|
||||
expenses: money("2200"),
|
||||
net: money("2200"),
|
||||
refunds: money("0"),
|
||||
},
|
||||
{
|
||||
categoryId: "taxi",
|
||||
categoryName: "Такси",
|
||||
expenses: money("1800"),
|
||||
net: money("1800"),
|
||||
refunds: money("0"),
|
||||
},
|
||||
{
|
||||
categoryId: "health",
|
||||
categoryName: "Здоровье",
|
||||
expenses: money("1000"),
|
||||
net: money("1000"),
|
||||
refunds: money("0"),
|
||||
},
|
||||
],
|
||||
expenses: money("8500"),
|
||||
month: "2026-09",
|
||||
net: money("7500"),
|
||||
refunds: money("1000"),
|
||||
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
|
||||
const meta
|
||||
= {
|
||||
args: {
|
||||
data: {
|
||||
cardId: null,
|
||||
categories: [
|
||||
{
|
||||
categoryId: "food",
|
||||
categoryName: "Продукты",
|
||||
expenses: money("3500"),
|
||||
net: money("2500"),
|
||||
refunds: money("1000"),
|
||||
},
|
||||
{
|
||||
categoryId: "cafe",
|
||||
categoryName: "Кафе",
|
||||
expenses: money("2200"),
|
||||
net: money("2200"),
|
||||
refunds: money("0"),
|
||||
},
|
||||
{
|
||||
categoryId: "taxi",
|
||||
categoryName: "Такси",
|
||||
expenses: money("1800"),
|
||||
net: money("1800"),
|
||||
refunds: money("0"),
|
||||
},
|
||||
{
|
||||
categoryId: "health",
|
||||
categoryName: "Здоровье",
|
||||
expenses: money("1000"),
|
||||
net: money("1000"),
|
||||
refunds: money("0"),
|
||||
},
|
||||
],
|
||||
expenses: money("8500"),
|
||||
month: "2026-09",
|
||||
net: money("7500"),
|
||||
refunds: money("1000"),
|
||||
},
|
||||
error: false,
|
||||
fetching: false,
|
||||
loading: false,
|
||||
retry: () => {},
|
||||
},
|
||||
error: false,
|
||||
fetching: false,
|
||||
loading: false,
|
||||
retry: () => {},
|
||||
},
|
||||
component: BankSummaryView,
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
"Месячные расходы ручного учёта. Вымышленные суммы, без API и сохранения. Один итог с учётом возвратов и компактные строки категорий. Отрицательные суммы сохраняют знак.",
|
||||
component: BankSummaryView,
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
"Месячные расходы ручного учёта. Вымышленные суммы, без API и сохранения. Один итог с учётом возвратов и компактные строки категорий. Отрицательные суммы сохраняют знак.",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
tags: ["autodocs"],
|
||||
title: "Product/BankCards/Summary",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */) satisfies Meta<typeof BankSummaryView>;
|
||||
tags: ["autodocs"],
|
||||
title: "Product/BankCards/Summary",
|
||||
} satisfies /* eslint-enable unicorn/no-null */ Meta<typeof BankSummaryView>;
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Loaded: Story = { name: "Расходы по категориям" };
|
||||
export const RefundMonth: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
export const RefundMonth: Story
|
||||
= {
|
||||
args: {
|
||||
data: {
|
||||
cardId: null,
|
||||
@@ -73,7 +79,7 @@ export const RefundMonth: Story = (/* eslint-disable unicorn/no-null -- Fixture
|
||||
{
|
||||
categoryId: "shopping",
|
||||
categoryName:
|
||||
"Покупки с длинным пользовательским названием категории",
|
||||
"Покупки с длинным пользовательским названием категории",
|
||||
expenses: money("0"),
|
||||
net: money("-600"),
|
||||
refunds: money("600"),
|
||||
@@ -86,10 +92,11 @@ export const RefundMonth: Story = (/* eslint-disable unicorn/no-null -- Fixture
|
||||
},
|
||||
},
|
||||
name: "Возврат покупки прошлого месяца",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
export const Empty: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
};
|
||||
/* eslint-enable unicorn/no-null */
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
export const Empty: Story
|
||||
= {
|
||||
args: {
|
||||
data: {
|
||||
cardId: null,
|
||||
@@ -101,8 +108,8 @@ export const Empty: Story = (/* eslint-disable unicorn/no-null -- Fixture preser
|
||||
},
|
||||
},
|
||||
name: "Известные нули",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
};
|
||||
/* eslint-enable unicorn/no-null */
|
||||
export const Loading: Story = {
|
||||
args: { data: undefined, loading: true },
|
||||
name: "Начальная загрузка",
|
||||
@@ -115,8 +122,9 @@ export const CachedError: Story = {
|
||||
args: { error: true },
|
||||
name: "Сохранённые суммы при ошибке обновления",
|
||||
};
|
||||
export const LongAmounts: Story = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
{
|
||||
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
|
||||
export const LongAmounts: Story
|
||||
= {
|
||||
args: {
|
||||
data: {
|
||||
cardId: null,
|
||||
@@ -136,5 +144,5 @@ export const LongAmounts: Story = (/* eslint-disable unicorn/no-null -- Fixture
|
||||
},
|
||||
},
|
||||
name: "Точный итог длиннее предела отдельного ввода",
|
||||
}
|
||||
/* eslint-enable unicorn/no-null */);
|
||||
};
|
||||
/* eslint-enable unicorn/no-null */
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { CSSProperties, FC } from "react";
|
||||
|
||||
import { Button, Group, Skeleton, Stack, Text, Title } from "@mantine/core";
|
||||
import { OperationIcon } from "@wealthledger/icons";
|
||||
import { LoadingSkeleton } from "@wealthledger/ui";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@@ -8,7 +9,7 @@ import { formatMoney } from "@/shared/lib";
|
||||
|
||||
import type { BankSummary } from "../../api/queries";
|
||||
|
||||
import { BankOperationIcon } from "../BankOperationIcon/BankOperationIcon";
|
||||
import { bankOperationAppearance } from "../../model/operation-appearance";
|
||||
import classes from "./BankSummary.module.css";
|
||||
|
||||
const CATEGORY_COLUMNS = 2;
|
||||
@@ -21,77 +22,93 @@ type BankSummaryViewProps = {
|
||||
loading: boolean;
|
||||
retry: () => void;
|
||||
};
|
||||
|
||||
const BankSummaryViewCategories: FC<BankSummaryViewProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (props.data) {
|
||||
if (props.data.categories.length > 0) {
|
||||
return (
|
||||
<dl
|
||||
className={classes.categories}
|
||||
style={
|
||||
{
|
||||
"--category-rows": Math.ceil(
|
||||
props.data.categories.length / CATEGORY_COLUMNS,
|
||||
),
|
||||
} as CSSProperties
|
||||
}
|
||||
>
|
||||
{props.data.categories.map(category => (
|
||||
<div className={classes.category} key={category.categoryId}>
|
||||
<dt className={classes.label}>
|
||||
<OperationIcon
|
||||
{...bankOperationAppearance("expense", category.categoryName)}
|
||||
/>
|
||||
|
||||
<span>{category.categoryName}</span>
|
||||
</dt>
|
||||
|
||||
<dd className={classes.amount}>
|
||||
{formatMoney(category.net, { withZeroCents: true })}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("bank.noExpenses")}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.loading) {
|
||||
return (
|
||||
<LoadingSkeleton label={t("bank.loading")}>
|
||||
<Stack gap="sm">
|
||||
<Skeleton h={32} w="35%" />
|
||||
|
||||
<Skeleton h={40} />
|
||||
|
||||
<Skeleton h={40} />
|
||||
</Stack>
|
||||
</LoadingSkeleton>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const BankSummaryView: FC<BankSummaryViewProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
function renderCategories() {
|
||||
if (props.data) {
|
||||
if (props.data.categories.length > 0) {
|
||||
return (
|
||||
<dl
|
||||
className={classes.categories}
|
||||
style={
|
||||
{
|
||||
"--category-rows": Math.ceil(props.data.categories.length / CATEGORY_COLUMNS),
|
||||
} as CSSProperties
|
||||
}
|
||||
>
|
||||
{props.data.categories.map(category => (
|
||||
<div className={classes.category} key={category.categoryId}>
|
||||
<dt className={classes.label}>
|
||||
<BankOperationIcon
|
||||
categoryName={category.categoryName}
|
||||
kind="expense"
|
||||
/>
|
||||
<span>{category.categoryName}</span>
|
||||
</dt>
|
||||
<dd className={classes.amount}>
|
||||
{formatMoney(category.net, { withZeroCents: true })}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("bank.noExpenses")}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
if (props.loading) {
|
||||
return (
|
||||
<LoadingSkeleton label={t("bank.loading")}>
|
||||
<Stack gap="sm">
|
||||
<Skeleton h={32} w="35%" />
|
||||
<Skeleton h={40} />
|
||||
<Skeleton h={40} />
|
||||
</Stack>
|
||||
</LoadingSkeleton>
|
||||
);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Stack aria-busy={props.loading || props.fetching} gap="md">
|
||||
<div className={classes.header}>
|
||||
<Title order={2}>
|
||||
{t(props.all ? "bank.allSummary" : "bank.summary")}
|
||||
</Title>
|
||||
|
||||
{props.data && (
|
||||
<Text className={classes.total}>
|
||||
{formatMoney(props.data.net, { withZeroCents: true })}
|
||||
</Text>
|
||||
)}
|
||||
</div>
|
||||
{renderCategories()}
|
||||
|
||||
<BankSummaryViewCategories {...props} />
|
||||
|
||||
{props.error && (
|
||||
<Group role="alert">
|
||||
<Text>{t(props.data ? "bank.refreshError" : "bank.error")}</Text>
|
||||
|
||||
<Button onClick={props.retry} variant="default">
|
||||
{t("bank.retry")}
|
||||
</Button>
|
||||
</Group>
|
||||
)}
|
||||
|
||||
{props.data && props.fetching && (
|
||||
<Text role="status">{t("bank.refreshing")}</Text>
|
||||
)}
|
||||
|
||||
@@ -23,18 +23,23 @@ describe("CategoryManager", () => {
|
||||
clear: () => {},
|
||||
refresh: () => Promise.resolve(false),
|
||||
});
|
||||
|
||||
const categories = [
|
||||
{ id: "a", isDefault: false, name: "Первая", version: 1 },
|
||||
{ id: "b", isDefault: false, name: "Вторая", version: 4 },
|
||||
];
|
||||
|
||||
let reads = 0;
|
||||
|
||||
const { promise: reloaded, resolve: release } = Promise.withResolvers<void>();
|
||||
const { promise: reloaded, resolve: release }
|
||||
= Promise.withResolvers<void>();
|
||||
|
||||
const patches: { body: unknown; id: unknown }[] = [];
|
||||
server.use(
|
||||
http.get("*/api/v1/bank-cards/categories", async () => {
|
||||
reads++;
|
||||
if (reads === 3) await reloaded;
|
||||
|
||||
return HttpResponse.json(
|
||||
categories.map(category =>
|
||||
category.id === "a" && reads > 1
|
||||
@@ -51,6 +56,7 @@ describe("CategoryManager", () => {
|
||||
"*/api/v1/bank-cards/categories/:id",
|
||||
async ({ params, request }) => {
|
||||
patches.push({ body: await request.json(), id: params.id });
|
||||
|
||||
return patches.length === 1
|
||||
? HttpResponse.json(
|
||||
{ code: "BANK_VERSION_CONFLICT" },
|
||||
@@ -67,7 +73,11 @@ describe("CategoryManager", () => {
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
const renameButtons = await screen.findAllByRole("button", { name: "Переименовать" });
|
||||
|
||||
const renameButtons = await screen.findAllByRole("button", {
|
||||
name: "Переименовать",
|
||||
});
|
||||
|
||||
fireEvent.click(renameButtons[0]);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Сохранить" }));
|
||||
fireEvent.click(
|
||||
@@ -122,6 +132,7 @@ describe("CategoryManager", () => {
|
||||
),
|
||||
http.patch("*/api/v1/bank-cards/categories/a", () => {
|
||||
version = 2;
|
||||
|
||||
return ++writes === 1
|
||||
? HttpResponse.json(
|
||||
{ code: "BANK_VERSION_CONFLICT" },
|
||||
@@ -163,12 +174,14 @@ describe("CategoryManager", () => {
|
||||
clear: () => {},
|
||||
refresh: () => Promise.resolve(false),
|
||||
});
|
||||
|
||||
let category = {
|
||||
id: "default",
|
||||
isDefault: true,
|
||||
name: "Другое",
|
||||
version: 1,
|
||||
};
|
||||
|
||||
let creates = 0;
|
||||
let body: unknown;
|
||||
server.use(
|
||||
@@ -177,6 +190,7 @@ describe("CategoryManager", () => {
|
||||
),
|
||||
http.post("*/api/v1/bank-cards/categories", () => {
|
||||
creates++;
|
||||
|
||||
return HttpResponse.json({});
|
||||
}),
|
||||
http.patch(
|
||||
@@ -184,6 +198,7 @@ describe("CategoryManager", () => {
|
||||
async ({ request }) => {
|
||||
body = await request.json();
|
||||
category = { ...category, name: "Остальное", version: 2 };
|
||||
|
||||
return HttpResponse.json(category);
|
||||
},
|
||||
),
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
@@ -8,218 +7,148 @@ import {
|
||||
Text,
|
||||
TextInput,
|
||||
} from "@mantine/core";
|
||||
import { type FC, useRef, useState } from "react";
|
||||
import {
|
||||
Controller,
|
||||
FormProvider,
|
||||
useForm,
|
||||
useFormContext,
|
||||
} from "react-hook-form";
|
||||
import { OperationIcon } from "@wealthledger/icons";
|
||||
import { type FC } from "react";
|
||||
import { FormProvider, useController, useFormContext } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { z } from "zod";
|
||||
|
||||
import { validationMessage } from "@/shared/i18n";
|
||||
|
||||
import { useBankMutations } from "../../api/mutations";
|
||||
import { type ExpenseCategory, useBankCategories } from "../../api/queries";
|
||||
import { bankOperationAppearance } from "../../model/operation-appearance";
|
||||
import { BankFeedback } from "../BankFeedback";
|
||||
import classes from "../BankForms.module.css";
|
||||
import { BankOperationIcon } from "../BankOperationIcon/BankOperationIcon";
|
||||
import { useBankFormFocus } from "../useBankFormFocus";
|
||||
|
||||
const MAX_CATEGORY_NAME_LENGTH = 80;
|
||||
import { useCategoryManagerVm } from "./CategoryManager.vm";
|
||||
|
||||
type CategoryManagerProps = {
|
||||
onClose: () => void;
|
||||
onCreated?: (id: string) => void;
|
||||
};
|
||||
|
||||
type CategoryValues = { name: string };
|
||||
|
||||
const CategoryFields: FC = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const {
|
||||
control,
|
||||
formState: { errors },
|
||||
} = useFormContext<CategoryValues>();
|
||||
|
||||
const { field: nameField } = useController({ control, name: "name" });
|
||||
|
||||
return (
|
||||
<Controller
|
||||
control={control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<TextInput
|
||||
label={t("bank.categoryName")}
|
||||
required
|
||||
{...field}
|
||||
error={errors.name?.message}
|
||||
/>
|
||||
)}
|
||||
<TextInput
|
||||
label={t("bank.categoryName")}
|
||||
required
|
||||
{...nameField}
|
||||
error={errors.name?.message}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const CategoryManager: FC<CategoryManagerProps> = (props) => {
|
||||
useBankFormFocus();
|
||||
const [opened, setOpened] = useState(true);
|
||||
const { t } = useTranslation();
|
||||
const categories = useBankCategories();
|
||||
const mutation = useBankMutations();
|
||||
const [editing, setEditing] = useState<ExpenseCategory>();
|
||||
const editSessionRef = useRef(0);
|
||||
const [error, setError] = useState<unknown>();
|
||||
const [latest, setLatest] = useState<ExpenseCategory>();
|
||||
const schema = z.object({
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.refine(
|
||||
value =>
|
||||
value.length > 0 && value.length <= MAX_CATEGORY_NAME_LENGTH,
|
||||
{ error: validationMessage("bank.validation.category") },
|
||||
)
|
||||
.refine(
|
||||
value =>
|
||||
!categories.data?.some(
|
||||
c =>
|
||||
c.id !== editing?.id
|
||||
&& c.name.toLocaleLowerCase("ru-RU")
|
||||
=== value.toLocaleLowerCase("ru-RU"),
|
||||
),
|
||||
{ error: validationMessage("bank.validation.duplicate") },
|
||||
),
|
||||
});
|
||||
const methods = useForm<CategoryValues>({ defaultValues: { name: "" }, resolver: zodResolver(schema) });
|
||||
const isPending = !opened || methods.formState.isSubmitting;
|
||||
const {
|
||||
categories,
|
||||
categoryRows,
|
||||
editing,
|
||||
error,
|
||||
isPending,
|
||||
latest,
|
||||
methods,
|
||||
onAdoptVersion,
|
||||
onCancel,
|
||||
onDismiss,
|
||||
onReloadRecord,
|
||||
onRequestClose,
|
||||
onSubmit,
|
||||
opened,
|
||||
retryCategories,
|
||||
t,
|
||||
} = useCategoryManagerVm(props);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
closeButtonProps={{ "aria-label": t("bank.close"), "disabled": isPending }}
|
||||
closeOnClickOutside={!isPending}
|
||||
closeOnEscape={!isPending}
|
||||
onClose={() => !isPending && setOpened(false)}
|
||||
onClose={onRequestClose}
|
||||
onExitTransitionEnd={props.onClose}
|
||||
opened={opened}
|
||||
title={t("bank.categories")}
|
||||
>
|
||||
<FormProvider {...methods}>
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
void methods.handleSubmit(async (values) => {
|
||||
setError(undefined);
|
||||
try {
|
||||
if (editing)
|
||||
await mutation.updateCategory.mutateAsync({
|
||||
body: { name: values.name, version: editing.version },
|
||||
id: editing.id,
|
||||
});
|
||||
else {
|
||||
const result = await mutation.createCategory.mutateAsync({
|
||||
name: values.name,
|
||||
});
|
||||
if (result) props.onCreated?.(result.id);
|
||||
}
|
||||
editSessionRef.current++;
|
||||
setEditing(undefined);
|
||||
setLatest(undefined);
|
||||
methods.reset({ name: "" });
|
||||
}
|
||||
catch (error_) {
|
||||
setError(error_);
|
||||
}
|
||||
})(event);
|
||||
}}
|
||||
>
|
||||
<form onSubmit={onSubmit}>
|
||||
<fieldset className={classes.fieldset} disabled={isPending}>
|
||||
<Stack>
|
||||
{categories.data?.map(category => (
|
||||
<Group justify="space-between" key={category.id}>
|
||||
<Group gap="xs">
|
||||
<BankOperationIcon
|
||||
categoryName={category.name}
|
||||
kind="expense"
|
||||
/>
|
||||
<Text>{category.name}</Text>
|
||||
{category.isDefault && (
|
||||
<Badge>{t("bank.defaultCategory")}</Badge>
|
||||
)}
|
||||
{categoryRows?.map((category) => {
|
||||
return (
|
||||
<Group justify="space-between" key={category.id}>
|
||||
<Group gap="xs">
|
||||
<OperationIcon
|
||||
{...bankOperationAppearance("expense", category.name)}
|
||||
/>
|
||||
|
||||
<Text>{category.name}</Text>
|
||||
|
||||
{category.isDefault && (
|
||||
<Badge>{t("bank.defaultCategory")}</Badge>
|
||||
)}
|
||||
</Group>
|
||||
|
||||
<Button onClick={category.onRename} variant="subtle">
|
||||
{t("bank.rename")}
|
||||
</Button>
|
||||
</Group>
|
||||
<Button
|
||||
onClick={() => {
|
||||
editSessionRef.current++;
|
||||
setEditing(category);
|
||||
methods.reset({ name: category.name });
|
||||
setError(undefined);
|
||||
setLatest(undefined);
|
||||
}}
|
||||
variant="subtle"
|
||||
>
|
||||
{t("bank.rename")}
|
||||
</Button>
|
||||
</Group>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
|
||||
{categories.isLoading && (
|
||||
<Text role="status">{t("bank.loading")}</Text>
|
||||
)}
|
||||
|
||||
{categories.isError && (
|
||||
<BankFeedback
|
||||
cached={Boolean(categories.data)}
|
||||
error={categories.error}
|
||||
loadingError
|
||||
retry={() => void categories.refetch()}
|
||||
retry={retryCategories}
|
||||
/>
|
||||
)}
|
||||
|
||||
<CategoryFields />
|
||||
{!!(error) && ((
|
||||
|
||||
{!!error && (
|
||||
<>
|
||||
<BankFeedback error={error} />
|
||||
|
||||
{editing && (
|
||||
<Button
|
||||
onClick={async () => {
|
||||
const session = editSessionRef.current;
|
||||
const response = await categories.refetch();
|
||||
if (session !== editSessionRef.current) return;
|
||||
if (response.error) setError(response.error);
|
||||
else
|
||||
setLatest(
|
||||
response.data?.find(c => c.id === editing.id),
|
||||
);
|
||||
}}
|
||||
variant="default"
|
||||
>
|
||||
<Button onClick={onReloadRecord} variant="default">
|
||||
{t("bank.reloadRecord")}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
))}
|
||||
)}
|
||||
|
||||
{latest && latest.id === editing?.id && (
|
||||
<>
|
||||
<Text>{t("bank.versionHint", { details: latest.name })}</Text>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setEditing(latest);
|
||||
setLatest(undefined);
|
||||
setError(undefined);
|
||||
}}
|
||||
>
|
||||
|
||||
<Button onClick={onAdoptVersion}>
|
||||
{t("bank.adoptVersion", { version: latest.version })}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Group>
|
||||
<Button loading={isPending} type="submit">
|
||||
{t(editing ? "bank.save" : "bank.addCategory")}
|
||||
</Button>
|
||||
|
||||
{editing && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
editSessionRef.current++;
|
||||
setEditing(undefined);
|
||||
setLatest(undefined);
|
||||
methods.reset({ name: "" });
|
||||
setError(undefined);
|
||||
}}
|
||||
variant="default"
|
||||
>
|
||||
<Button onClick={onCancel} variant="default">
|
||||
{t("bank.cancel")}
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={() => setOpened(false)} variant="default">
|
||||
|
||||
<Button onClick={onDismiss} variant="default">
|
||||
{t("bank.close")}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import type { ComponentProps } from "react";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useRef, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { useBankMutations } from "../../api/mutations";
|
||||
import { type ExpenseCategory, useBankCategories } from "../../api/queries";
|
||||
import { categorySchema } from "../../model/category.schema";
|
||||
import { useBankFormFocus } from "../useBankFormFocus";
|
||||
|
||||
type CategoryManagerProps = {
|
||||
onClose: () => void;
|
||||
onCreated?: (id: string) => void;
|
||||
};
|
||||
|
||||
type CategoryValues = { name: string };
|
||||
|
||||
function useCategoryManagerVm(props: CategoryManagerProps) {
|
||||
useBankFormFocus();
|
||||
const [opened, setOpened] = useState(true);
|
||||
const { t } = useTranslation();
|
||||
const categories = useBankCategories();
|
||||
const mutation = useBankMutations();
|
||||
const [editing, setEditing] = useState<ExpenseCategory>();
|
||||
const editSessionRef = useRef(0);
|
||||
const [error, setError] = useState<unknown>();
|
||||
const [latest, setLatest] = useState<ExpenseCategory>();
|
||||
const schema = categorySchema(categories.data, editing?.id);
|
||||
|
||||
const methods = useForm<CategoryValues>({
|
||||
defaultValues: { name: "" },
|
||||
resolver: zodResolver(schema),
|
||||
});
|
||||
|
||||
const isPending = !opened || methods.formState.isSubmitting;
|
||||
const onRequestClose = () => !isPending && setOpened(false);
|
||||
|
||||
const onSubmit: ComponentProps<"form">["onSubmit"] = (event) => {
|
||||
void methods.handleSubmit(async (values) => {
|
||||
setError(undefined);
|
||||
|
||||
try {
|
||||
if (editing)
|
||||
await mutation.updateCategory.mutateAsync({
|
||||
body: { name: values.name, version: editing.version },
|
||||
id: editing.id,
|
||||
});
|
||||
else {
|
||||
const result = await mutation.createCategory.mutateAsync({
|
||||
name: values.name,
|
||||
});
|
||||
|
||||
if (result) props.onCreated?.(result.id);
|
||||
}
|
||||
|
||||
editSessionRef.current++;
|
||||
setEditing(undefined);
|
||||
setLatest(undefined);
|
||||
methods.reset({ name: "" });
|
||||
}
|
||||
catch (error_) {
|
||||
setError(error_);
|
||||
}
|
||||
})(event);
|
||||
};
|
||||
|
||||
const retryCategories = () => void categories.refetch();
|
||||
|
||||
const onReloadRecord = async () => {
|
||||
if (!editing) return;
|
||||
const session = editSessionRef.current;
|
||||
const response = await categories.refetch();
|
||||
if (session !== editSessionRef.current) return;
|
||||
if (response.error) setError(response.error);
|
||||
else setLatest(response.data?.find(c => c.id === editing.id));
|
||||
};
|
||||
|
||||
const onAdoptVersion = () => {
|
||||
setEditing(latest);
|
||||
setLatest(undefined);
|
||||
setError(undefined);
|
||||
};
|
||||
|
||||
const onCancel = () => {
|
||||
editSessionRef.current++;
|
||||
setEditing(undefined);
|
||||
setLatest(undefined);
|
||||
methods.reset({ name: "" });
|
||||
setError(undefined);
|
||||
};
|
||||
|
||||
const onDismiss = () => setOpened(false);
|
||||
|
||||
const categoryRows = categories.data?.map((category) => {
|
||||
const onRename = () => {
|
||||
editSessionRef.current++;
|
||||
setEditing(category);
|
||||
methods.reset({ name: category.name });
|
||||
setError(undefined);
|
||||
setLatest(undefined);
|
||||
};
|
||||
|
||||
return { ...category, onRename };
|
||||
});
|
||||
|
||||
return {
|
||||
categories,
|
||||
categoryRows,
|
||||
editing,
|
||||
error,
|
||||
isPending,
|
||||
latest,
|
||||
methods,
|
||||
onAdoptVersion,
|
||||
onCancel,
|
||||
onDismiss,
|
||||
onReloadRecord,
|
||||
onRequestClose,
|
||||
onSubmit,
|
||||
opened,
|
||||
retryCategories,
|
||||
t,
|
||||
};
|
||||
}
|
||||
|
||||
export { useCategoryManagerVm };
|
||||
Reference in New Issue
Block a user