250 lines
9.5 KiB
TypeScript
250 lines
9.5 KiB
TypeScript
import { useState, useCallback, useMemo } from "react";
|
|
import { useNavigate } from "react-router-dom";
|
|
import { useTranslation } from "react-i18next";
|
|
import { useForm } from "react-hook-form";
|
|
import { FormInput, type SelectOption } from "@/components/formInput";
|
|
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
|
import { FormActions } from "@/components/formActions";
|
|
import { type CardBalance } from "@/features/cardBalance/api/cardBalanceApi";
|
|
import { useCreateCardBalance, useUpdateCardBalance } from "@/features/cardBalance/hooks/useCardBalance";
|
|
import { cardBalanceFormSchema, DEFAULT_FORM_VALUES, mapInitial, buildPayload } from "@/features/cardBalance/schemas/cardBalance.schema";
|
|
import type { CardBalanceFormData } from "@/features/cardBalance/schemas/cardBalance.schema";
|
|
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
|
|
import { useWebSelfLock } from "@/features/shared/hooks/useWebSelfLock";
|
|
import { MONTH_OPTIONS, CARD_YEAR_OPTIONS } from "@/constants";
|
|
|
|
interface CardBalanceFormProps {
|
|
mode: "create" | "edit";
|
|
initialData?: CardBalance;
|
|
}
|
|
|
|
type FlatErrors = Partial<Record<keyof CardBalanceFormData, string>>;
|
|
|
|
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
|
const result: FlatErrors = {};
|
|
for (const key of Object.keys(errors)) {
|
|
const msg = errors[key]?.message;
|
|
if (msg) result[key as keyof CardBalanceFormData] = msg;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
// ─── Constants ────────────────────────────────────────────────────────────────
|
|
|
|
const STATUS_OPTIONS: SelectOption[] = [
|
|
{ value: "pending", label: "Garaşylýar" },
|
|
{ value: "approved", label: "Tassyklanan" },
|
|
{ value: "rejected", label: "Ret edilen" },
|
|
];
|
|
|
|
const CURRENCY_OPTIONS: SelectOption[] = [
|
|
{ value: "TMT", label: "TMT" },
|
|
{ value: "USD", label: "USD" },
|
|
{ value: "RUB", label: "RUB" },
|
|
{ value: "EUR", label: "EUR" },
|
|
];
|
|
|
|
// ─── Component ────────────────────────────────────────────────────────────────
|
|
|
|
export function CardBalanceForm({ mode, initialData }: CardBalanceFormProps) {
|
|
const { t } = useTranslation();
|
|
const navigate = useNavigate();
|
|
|
|
const createMutation = useCreateCardBalance();
|
|
const updateMutation = useUpdateCardBalance(initialData?.id ?? 0);
|
|
const isPending = createMutation.isPending || updateMutation.isPending;
|
|
|
|
const [userSearch, setUserSearch] = useState("");
|
|
const { locked: userLocked, userId: selfUserId, userName } = useWebSelfLock(true);
|
|
const userQuery = useInfiniteUsers(userSearch, !userLocked);
|
|
|
|
const userOptions: InfiniteSelectOption[] = useMemo(() => {
|
|
const opts: InfiniteSelectOption[] = (userQuery.data?.pages ?? [])
|
|
.flatMap((p) => p?.users ?? [])
|
|
.map((u) => ({ value: String(u.id), label: u.name || u.username || String(u.id) }))
|
|
.filter((o) => !userLocked || o.value === selfUserId);
|
|
if (selfUserId && !opts.some((o) => o.value === selfUserId)) {
|
|
opts.unshift({ value: selfUserId, label: userName });
|
|
}
|
|
if (initialData?.createdBy?.id && !opts.some((o) => o.value === String(initialData.createdBy.id))) {
|
|
opts.unshift({
|
|
value: String(initialData.createdBy.id),
|
|
label: initialData.createdBy.name || String(initialData.createdBy.id),
|
|
});
|
|
}
|
|
return opts;
|
|
}, [userQuery, initialData, userLocked, selfUserId, userName]);
|
|
|
|
const {
|
|
watch,
|
|
setValue,
|
|
getValues,
|
|
formState: { errors: rhfErrors },
|
|
clearErrors,
|
|
setError,
|
|
} = useForm<CardBalanceFormData>({
|
|
defaultValues: initialData
|
|
? { ...mapInitial(initialData), ...(userLocked ? { createdBy: selfUserId } : {}) }
|
|
: { ...DEFAULT_FORM_VALUES, createdBy: selfUserId },
|
|
});
|
|
|
|
const form = watch();
|
|
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
|
|
|
const set = useCallback(
|
|
<K extends keyof CardBalanceFormData>(key: K, value: CardBalanceFormData[K]) => {
|
|
(setValue as (name: K, val: CardBalanceFormData[K]) => void)(key, value);
|
|
clearErrors(key);
|
|
},
|
|
[setValue, clearErrors],
|
|
);
|
|
|
|
const setString = (key: keyof CardBalanceFormData) => (value: string) => set(key, value as CardBalanceFormData[typeof key]);
|
|
|
|
const errMsg = (msg: string | undefined) => (!msg ? undefined : msg.startsWith("validation.") ? t(msg, msg) : msg);
|
|
|
|
const handleSubmit = async () => {
|
|
const result = cardBalanceFormSchema.safeParse(getValues());
|
|
if (!result.success) {
|
|
for (const issue of result.error.issues) {
|
|
const key = issue.path[0] as keyof CardBalanceFormData;
|
|
setError(key, { message: issue.message });
|
|
}
|
|
return;
|
|
}
|
|
const payload = buildPayload(result.data);
|
|
if (mode === "create") {
|
|
await createMutation.mutateAsync(payload);
|
|
navigate("/card-balances");
|
|
} else {
|
|
await updateMutation.mutateAsync(payload);
|
|
navigate(`/card-balances/${initialData!.id}`);
|
|
}
|
|
};
|
|
|
|
const handleCancel = () => {
|
|
if (mode === "create") navigate("/card-balances");
|
|
else navigate(`/card-balances/${initialData!.id}`);
|
|
};
|
|
|
|
return (
|
|
<div className="flex flex-col gap-5">
|
|
<h1 className="text-xl font-semibold text-foreground">
|
|
{mode === "create"
|
|
? t("cardBalance.createTitle", "Kart galyndysy dörediň")
|
|
: t("cardBalance.editTitle", "Kart galyndysy üýtgetmek")}
|
|
</h1>
|
|
<div className="rounded-lg border border-border bg-card p-6">
|
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
<FormInput
|
|
type="select"
|
|
label={t("Status", "Status")}
|
|
value={form.status}
|
|
onChange={setString("status")}
|
|
options={STATUS_OPTIONS}
|
|
placeholder={t("Select", "Saýlamak üçin basyň")}
|
|
error={errMsg(errors.status)}
|
|
required
|
|
/>
|
|
<FormInput
|
|
type="text"
|
|
label={t("Passport number", "Pasport belgisi")}
|
|
value={form.passportNumber}
|
|
onChange={setString("passportNumber")}
|
|
placeholder="999999"
|
|
error={errMsg(errors.passportNumber)}
|
|
required
|
|
/>
|
|
|
|
<FormInput
|
|
type="card-number"
|
|
label={t("Card number", "Kart belgisi")}
|
|
value={form.cardNumber}
|
|
onChange={setString("cardNumber")}
|
|
placeholder="9800 0000 0000 0000"
|
|
error={errMsg(errors.cardNumber)}
|
|
required
|
|
/>
|
|
<div className="grid grid-cols-2 gap-3">
|
|
<FormInput
|
|
type="select"
|
|
label={t("Card expiry month", "Kart Möhleti (aý)")}
|
|
value={form.expiryMonth}
|
|
onChange={setString("expiryMonth")}
|
|
options={MONTH_OPTIONS}
|
|
placeholder={t("Select", "Saýlamak üçin basyň")}
|
|
error={errMsg(errors.expiryMonth)}
|
|
required
|
|
/>
|
|
<FormInput
|
|
type="select"
|
|
label={t("Card expiry year", "Kart Möhleti (ýyl)")}
|
|
value={form.expiryYear}
|
|
onChange={setString("expiryYear")}
|
|
options={CARD_YEAR_OPTIONS}
|
|
placeholder={t("Select", "Saýlamak üçin basyň")}
|
|
error={errMsg(errors.expiryYear)}
|
|
required
|
|
/>
|
|
</div>
|
|
|
|
<FormInput
|
|
type="number"
|
|
label={t("Balance amount", "Galyndy möçberi")}
|
|
value={form.balanceAmount}
|
|
onChange={setString("balanceAmount")}
|
|
placeholder="0.00"
|
|
error={errMsg(errors.balanceAmount)}
|
|
required
|
|
/>
|
|
<FormInput
|
|
type="searchable-select"
|
|
label={t("Balance currency", "Galyndy walýutasy")}
|
|
value={form.balanceCurrency}
|
|
onChange={setString("balanceCurrency")}
|
|
options={CURRENCY_OPTIONS}
|
|
placeholder={t("Select", "Saýlamak üçin basyň")}
|
|
error={errMsg(errors.balanceCurrency)}
|
|
required
|
|
/>
|
|
|
|
<FormInput
|
|
type="date"
|
|
label={t("Checked at", "Barlan senesi")}
|
|
value={form.checkedAt}
|
|
onChange={setString("checkedAt")}
|
|
error={errMsg(errors.checkedAt)}
|
|
required
|
|
/>
|
|
<InfiniteSelect
|
|
label={t("Created by", "Döreden")}
|
|
value={form.createdBy}
|
|
onChange={(v) => set("createdBy", v)}
|
|
options={userOptions}
|
|
placeholder={t("Select user", "Ulanyjyny saýlaň")}
|
|
disabled={userLocked}
|
|
loading={userQuery.isLoading}
|
|
isLoadingMore={userQuery.isFetchingNextPage}
|
|
hasNextPage={!!userQuery.hasNextPage}
|
|
onLoadMore={() => userQuery.fetchNextPage()}
|
|
searchValue={userSearch}
|
|
onSearchChange={setUserSearch}
|
|
error={errMsg(errors.createdBy)}
|
|
required
|
|
/>
|
|
</div>
|
|
|
|
<FormActions
|
|
isPending={isPending}
|
|
onSubmit={handleSubmit}
|
|
onCancel={handleCancel}
|
|
cancelLabel={t("Cancel", "Ýatyr")}
|
|
loadingLabel={t("Saving...", "Saklanýar...")}
|
|
submitLabel={mode === "create" ? t("Create card balance", "Kart galyndysy dörediň") : t("Save changes", "Üýtgetmeleri sakla")}
|
|
className="mt-6"
|
|
/>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|