278 lines
11 KiB
TypeScript
278 lines
11 KiB
TypeScript
import { useMemo, useState } from "react";
|
|
import { useForm } from "react-hook-form";
|
|
import { useNavigate } from "react-router-dom";
|
|
import { useTranslation } from "react-i18next";
|
|
import { FormInput } from "@/components/formInput";
|
|
import { FormActions } from "@/components/formActions";
|
|
import { BentoGrid, BentoCard } from "@/components/bento";
|
|
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
|
import type { Card } from "../api/cardTransactionsApi";
|
|
import { useCreateCardTransaction, useUpdateCardTransaction } from "../hooks/useCardTransactions";
|
|
import { useInfiniteClients } from "@/features/clients/hooks/useClients";
|
|
import { useWebSelfLock } from "@/features/shared/hooks/useWebSelfLock";
|
|
import { useCardTypes } from "@/features/cardTypes/hooks/useCardTypes";
|
|
import { resolveCardTypeTitle, type LocalizedTitle } from "@/features/cardTypes/api/cardTypesApi";
|
|
import { cardTransactionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardTransaction.schema";
|
|
import type { CardTransactionFormData } from "../schemas/cardTransaction.schema";
|
|
import { MONTH_OPTIONS, CARD_YEAR_OPTIONS } from "@/constants";
|
|
|
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
|
|
|
interface CardTransactionFormProps {
|
|
mode: "create" | "edit";
|
|
initialData?: Card;
|
|
}
|
|
|
|
// ─── Form errors helper ───────────────────────────────────────────────────────
|
|
|
|
type FlatErrors = Partial<Record<keyof CardTransactionFormData, string>>;
|
|
|
|
type CardiacTransactionLoose = Partial<Record<keyof CardTransactionFormData, 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 CardTransactionFormData] = msg;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
// ─── Component ────────────────────────────────────────────────────────────────
|
|
|
|
export function CardTransactionForm({ mode, initialData }: CardTransactionFormProps) {
|
|
const { t, i18n } = useTranslation();
|
|
const navigate = useNavigate();
|
|
|
|
const { locked: userLocked, userId: selfUserId, userName } = useWebSelfLock(true);
|
|
|
|
const [clientSearch, setClientSearch] = useState("");
|
|
const clientsQuery = useInfiniteClients(clientSearch, !userLocked);
|
|
const { data: cardTypesData } = useCardTypes({ page: 1, limit: 25 });
|
|
|
|
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedTitle;
|
|
|
|
const clientOptions: InfiniteSelectOption[] = useMemo(() => {
|
|
const opts: InfiniteSelectOption[] = (clientsQuery.data?.pages ?? [])
|
|
.flatMap((p) => p?.users ?? [])
|
|
.map((u) => ({
|
|
value: String(u.id),
|
|
label: u.name || `${u.firstName || ""} ${u.lastName || ""}`.trim() || 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?.user?.id && !opts.some((o) => o.value === String(initialData.user!.id))) {
|
|
opts.unshift({ value: String(initialData.user!.id), label: initialData.user!.name || String(initialData.user!.id) });
|
|
}
|
|
return opts;
|
|
}, [clientsQuery.data, initialData, userLocked, selfUserId, userName]);
|
|
|
|
const cardTypeOptions = useMemo(() => {
|
|
const opts = (cardTypesData?.paymentCards ?? []).map((ct) => ({
|
|
value: String(ct.id),
|
|
label: resolveCardTypeTitle(ct.title, lang),
|
|
}));
|
|
|
|
if (initialData?.type && !opts.some((o) => o.value === initialData.type)) {
|
|
opts.unshift({ value: initialData.type, label: initialData.type });
|
|
}
|
|
return opts;
|
|
}, [cardTypesData, lang, initialData]);
|
|
|
|
const {
|
|
watch,
|
|
setValue,
|
|
getValues,
|
|
formState: { errors: rhfErrors },
|
|
clearErrors,
|
|
setError,
|
|
} = useForm<CardTransactionFormData>({
|
|
defaultValues: initialData
|
|
? {
|
|
...DEFAULT_FORM_VALUES,
|
|
number: initialData.number ?? "",
|
|
name: initialData.name ?? "",
|
|
type: initialData.type ?? "",
|
|
month: initialData.month ?? "",
|
|
year: initialData.year ?? "",
|
|
userId: userLocked ? selfUserId : String(initialData.user?.id ?? ""),
|
|
}
|
|
: { ...DEFAULT_FORM_VALUES, userId: selfUserId },
|
|
});
|
|
|
|
const form = watch();
|
|
|
|
// Live schema errors, only surfaced once the user attempts to submit, so
|
|
// required-field warnings reliably show under fields (avoids RHF setError
|
|
// snapshot timing; mirrors the step-based forms' submitted validation).
|
|
const [submitAttempted, setSubmitAttempted] = useState(false);
|
|
|
|
const liveErrors = useMemo<FlatErrors>(() => {
|
|
if (!submitAttempted) return {};
|
|
const normalized: CardiacTransactionLoose = { ...DEFAULT_FORM_VALUES, ...form };
|
|
for (const key of Object.keys(DEFAULT_FORM_VALUES) as (keyof CardTransactionFormData)[]) {
|
|
if (normalized[key] == null) normalized[key] = "";
|
|
}
|
|
const parsed = cardTransactionFormSchema.safeParse(normalized);
|
|
if (parsed.success) return {};
|
|
const result: FlatErrors = {};
|
|
for (const issue of parsed.error.issues) {
|
|
const key = issue.path[0] as keyof CardTransactionFormData;
|
|
result[key] = issue.message;
|
|
}
|
|
return result;
|
|
}, [submitAttempted, form]);
|
|
|
|
const errors = useMemo(() => {
|
|
const fromRHF = flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>);
|
|
return { ...fromRHF, ...liveErrors };
|
|
}, [rhfErrors, liveErrors]);
|
|
|
|
const createMutation = useCreateCardTransaction();
|
|
const updateMutation = useUpdateCardTransaction(initialData?.id ?? 0);
|
|
|
|
const isPending = createMutation.isPending || updateMutation.isPending;
|
|
|
|
const setField = (field: keyof CardTransactionFormData) => (value: string) => {
|
|
setValue(field, value);
|
|
clearErrors(field);
|
|
};
|
|
|
|
const errMsg = (msg: string | undefined) => (!msg ? undefined : msg.startsWith("validation.") ? t(msg, msg) : msg);
|
|
|
|
const handleSubmit = async () => {
|
|
const raw: CardiacTransactionLoose = { ...DEFAULT_FORM_VALUES, ...getValues() };
|
|
for (const key of Object.keys(DEFAULT_FORM_VALUES) as (keyof CardTransactionFormData)[]) {
|
|
if (raw[key] == null) raw[key] = "";
|
|
}
|
|
const result = cardTransactionFormSchema.safeParse(raw);
|
|
if (!result.success) {
|
|
setSubmitAttempted(true);
|
|
for (const issue of result.error.issues) {
|
|
const key = issue.path[0] as keyof CardTransactionFormData;
|
|
setError(key, { message: issue.message });
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (mode === "create") {
|
|
await createMutation.mutateAsync(buildPayload(result.data));
|
|
navigate("/card-transactions");
|
|
} else {
|
|
await updateMutation.mutateAsync(buildPayload(result.data));
|
|
navigate(`/card-transactions/${initialData!.id}`);
|
|
}
|
|
};
|
|
|
|
const handleCancel = () => {
|
|
if (mode === "create") {
|
|
navigate("/card-transactions");
|
|
} else {
|
|
navigate(`/card-transactions/${initialData!.id}`);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div className="flex flex-col gap-5">
|
|
<h1 className="text-xl font-semibold text-foreground">
|
|
{mode === "create" ? t("cardTransaction.createTitle", "Kart dörediň") : t("cardTransaction.editTitle", "Karty üýtgetmek")}
|
|
</h1>
|
|
<BentoGrid cols={1}>
|
|
<BentoCard>
|
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
{/* Name */}
|
|
<FormInput
|
|
type="card-name"
|
|
label={t("Card name", "Kartyň ady")}
|
|
value={form.name}
|
|
onChange={setField("name")}
|
|
placeholder={t("Card name", "Kartyň ady")}
|
|
error={errMsg(errors.name)}
|
|
required
|
|
/>
|
|
|
|
{/* Type */}
|
|
<FormInput
|
|
type="searchable-select"
|
|
label={t("Card type", "Kart görnüşi")}
|
|
value={form.type}
|
|
onChange={setField("type")}
|
|
options={cardTypeOptions}
|
|
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
|
error={errMsg(errors.type)}
|
|
required
|
|
/>
|
|
|
|
{/* Card Number */}
|
|
<FormInput
|
|
type="card-number"
|
|
label={t("Card number", "Kart belgisi")}
|
|
value={form.number}
|
|
onChange={setField("number")}
|
|
placeholder="9999 9999 9999 9999"
|
|
error={errMsg(errors.number)}
|
|
required
|
|
/>
|
|
|
|
{/* User (Client) */}
|
|
<InfiniteSelect
|
|
label={t("User ID", "Ulanyjy ID")}
|
|
required
|
|
value={form.userId}
|
|
onChange={(v) => setField("userId")(v)}
|
|
options={clientOptions}
|
|
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
|
error={errMsg(errors.userId)}
|
|
disabled={userLocked}
|
|
loading={clientsQuery.isLoading}
|
|
isLoadingMore={clientsQuery.isFetchingNextPage}
|
|
hasNextPage={!!clientsQuery.hasNextPage}
|
|
onLoadMore={() => clientsQuery.fetchNextPage()}
|
|
searchValue={clientSearch}
|
|
onSearchChange={setClientSearch}
|
|
/>
|
|
|
|
{/* Expiry Month + Year side by side */}
|
|
<div className="grid grid-cols-2 gap-3">
|
|
<FormInput
|
|
type="select"
|
|
label={t("Card expiry month", "Kart möhleti (aý)")}
|
|
value={form.month}
|
|
onChange={setField("month")}
|
|
options={MONTH_OPTIONS}
|
|
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
|
error={errMsg(errors.month)}
|
|
required
|
|
/>
|
|
|
|
<FormInput
|
|
type="select"
|
|
label={t("Card expiry year", "Kart möhleti (ýyl)")}
|
|
value={form.year}
|
|
onChange={setField("year")}
|
|
options={CARD_YEAR_OPTIONS}
|
|
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
|
error={errMsg(errors.year)}
|
|
required
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<FormActions
|
|
isPending={isPending}
|
|
onSubmit={handleSubmit}
|
|
onCancel={handleCancel}
|
|
cancelLabel={t("Cancel", "Ýatyr")}
|
|
loadingLabel={t("Saving...", "Saklanýar...")}
|
|
submitLabel={mode === "create" ? t("Create card", "Kart dörediň") : t("Save changes", "Üýtgetmeleri sakla")}
|
|
/>
|
|
</BentoCard>
|
|
</BentoGrid>
|
|
</div>
|
|
);
|
|
}
|