fixed some ui styles
This commit is contained in:
@@ -1,40 +1,33 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
interface BentoGridProps {
|
||||
cols?: 1 | 2 | 3 | 4
|
||||
children: ReactNode
|
||||
cols?: 1 | 2 | 3 | 4;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function BentoGrid({ cols = 2, children }: BentoGridProps) {
|
||||
const colClass = {
|
||||
1: 'grid-cols-1',
|
||||
2: 'grid-cols-1 sm:grid-cols-2',
|
||||
3: 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-3',
|
||||
4: 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-4',
|
||||
}[cols]
|
||||
return <div className={`grid ${colClass} gap-4`}>{children}</div>
|
||||
1: "grid-cols-1",
|
||||
2: "grid-cols-1 sm:grid-cols-2",
|
||||
3: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3",
|
||||
4: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-4",
|
||||
}[cols];
|
||||
return <div className={`grid ${colClass} gap-4`}>{children}</div>;
|
||||
}
|
||||
|
||||
interface BentoCardProps {
|
||||
title?: string
|
||||
span?: 'full' | 2 | 3
|
||||
children: ReactNode
|
||||
title?: string;
|
||||
span?: "full" | 2 | 3;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function BentoCard({ title, span, children }: BentoCardProps) {
|
||||
const spanClass =
|
||||
span === 'full' ? 'sm:col-span-full' :
|
||||
span === 2 ? 'sm:col-span-2' :
|
||||
span === 3 ? 'sm:col-span-3' : ''
|
||||
const spanClass = span === "full" ? "sm:col-span-full" : span === 2 ? "sm:col-span-2" : span === 3 ? "sm:col-span-3" : "";
|
||||
|
||||
return (
|
||||
<div className={`bg-card border border-border rounded-xl p-5 space-y-4 ${spanClass}`}>
|
||||
{title && (
|
||||
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
{title}
|
||||
</p>
|
||||
)}
|
||||
<div className={`bg-card border border-border rounded-lg p-6 space-y-4 ${spanClass}`}>
|
||||
{title && <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">{title}</p>}
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,98 +1,105 @@
|
||||
import { useMemo, useEffect, useCallback } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { useCreateUser, useUpdateUser } from '../hooks/useAllUsers'
|
||||
import type { User } from '../api/allUsersApi'
|
||||
import { allUserFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/allUser.schema'
|
||||
import type { AllUserFormData } from '../schemas/allUser.schema'
|
||||
import { useMemo, useEffect, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { useCreateUser, useUpdateUser } from "../hooks/useAllUsers";
|
||||
import type { User } from "../api/allUsersApi";
|
||||
import { allUserFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/allUser.schema";
|
||||
import type { AllUserFormData } from "../schemas/allUser.schema";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface UserFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: User
|
||||
mode: "create" | "edit";
|
||||
initialData?: User;
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
type FlatErrors = Partial<Record<keyof AllUserFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof AllUserFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof AllUserFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof AllUserFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── UserForm ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export function UserForm({ mode, initialData }: UserFormProps) {
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t, i18n.language],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createUser = useCreateUser()
|
||||
const updateUser = useUpdateUser(initialData?.id ?? 0)
|
||||
const createUser = useCreateUser();
|
||||
const updateUser = useUpdateUser(initialData?.id ?? 0);
|
||||
|
||||
const isPending = createUser.isPending || updateUser.isPending
|
||||
const isPending = createUser.isPending || updateUser.isPending;
|
||||
|
||||
const schema = useMemo(() => allUserFormSchema(mode, t), [mode, t, i18n.language])
|
||||
const schema = useMemo(() => allUserFormSchema(mode, t), [mode, t, i18n.language]);
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
trigger,
|
||||
} = useForm<AllUserFormData>({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
resolver: zodResolver(schema as any),
|
||||
defaultValues: initialData
|
||||
? {
|
||||
...DEFAULT_FORM_VALUES,
|
||||
username: initialData.username,
|
||||
name: initialData.name,
|
||||
phone: initialData.phone.replace(/^\+993[-\s]?/, ''),
|
||||
email: initialData.email ?? '',
|
||||
password: '',
|
||||
phone: initialData.phone.replace(/^\+993[-\s]?/, ""),
|
||||
email: initialData.email ?? "",
|
||||
password: "",
|
||||
phoneVerified: initialData.phoneVerified,
|
||||
isActive: initialData.isActive,
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
});
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
const setField = <K extends keyof AllUserFormData>(key: K, value: AllUserFormData[K]) => {
|
||||
(setValue as (name: K, val: AllUserFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}
|
||||
(setValue as (name: K, val: AllUserFormData[K]) => void)(key, value);
|
||||
clearErrors(key);
|
||||
};
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) {
|
||||
trigger()
|
||||
trigger();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
}, [i18n.language]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
const isValid = await trigger();
|
||||
if (!isValid) return;
|
||||
|
||||
const data = getValues()
|
||||
const data = getValues();
|
||||
|
||||
if (mode === 'create') {
|
||||
const payload = buildPayload(data)
|
||||
await createUser.mutateAsync(payload)
|
||||
navigate('/users')
|
||||
if (mode === "create") {
|
||||
const payload = buildPayload(data);
|
||||
await createUser.mutateAsync(payload);
|
||||
navigate("/users");
|
||||
} else {
|
||||
await updateUser.mutateAsync({
|
||||
username: data.username.trim(),
|
||||
@@ -101,188 +108,119 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
||||
email: data.email.trim() || undefined,
|
||||
phoneVerified: data.phoneVerified,
|
||||
isActive: data.isActive,
|
||||
})
|
||||
navigate(`/users/${initialData!.id}`)
|
||||
});
|
||||
navigate(`/users/${initialData!.id}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('users.createTitle', 'Ulanyjy dörediň')
|
||||
: t('users.editTitle', 'Ulanyjy üýtgetmek')}
|
||||
{mode === "create" ? t("users.createTitle", "Ulanyjy dörediň") : t("users.editTitle", "Ulanyjy üýtgetmek")}
|
||||
</h1>
|
||||
<div className="space-y-6">
|
||||
{/* Form card */}
|
||||
<div className="bg-card border border-border rounded-xl divide-y divide-border">
|
||||
|
||||
{/* Username */}
|
||||
<div className="grid grid-cols-[280px_1fr] items-start px-6 py-4">
|
||||
<div className="pt-0.5">
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{t('users.fields.username', 'Ulanyjy ady')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t('users.fields.usernameHint', 'Unikal login ady')}
|
||||
</p>
|
||||
</div>
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("users.fields.username", "Ulanyjy ady")}
|
||||
value={form.username}
|
||||
onChange={(v) => setField('username', v)}
|
||||
placeholder={t('users.fields.username', 'Ulanyjy ady')}
|
||||
onChange={(v) => setField("username", v)}
|
||||
placeholder={t("users.fields.username", "Ulanyjy ady")}
|
||||
error={errors.username}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Full name */}
|
||||
<div className="grid grid-cols-[280px_1fr] items-start px-6 py-4">
|
||||
<div className="pt-0.5">
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{t('users.fields.name', 'Ady')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t('users.fields.nameHint', 'Doly ady we familiýasy')}
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.usernameHint", "Unikal login ady")}</p>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("users.fields.name", "Ady")}
|
||||
value={form.name}
|
||||
onChange={(v) => setField('name', v)}
|
||||
placeholder={t('users.fields.name', 'Ady')}
|
||||
onChange={(v) => setField("name", v)}
|
||||
placeholder={t("users.fields.name", "Ady")}
|
||||
error={errors.name}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Phone */}
|
||||
<div className="grid grid-cols-[280px_1fr] items-start px-6 py-4">
|
||||
<div className="pt-0.5">
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{t('users.fields.phone', 'Telefon')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t('users.fields.phoneHint', '+993 bilen başlanýar')}
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.nameHint", "Doly ady we familiýasy")}</p>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="phone"
|
||||
label={t("users.fields.phone", "Telefon")}
|
||||
value={form.phone}
|
||||
onChange={(v) => setField('phone', v)}
|
||||
onChange={(v) => setField("phone", v)}
|
||||
placeholder="62-38-49-56"
|
||||
error={errors.phone}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Email */}
|
||||
<div className="grid grid-cols-[280px_1fr] items-start px-6 py-4">
|
||||
<div className="pt-0.5">
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{t('users.fields.email', 'E-poçta')}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t('users.fields.emailHint', 'Islege görä')}
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.phoneHint", "+993 bilen başlanýar")}</p>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="email"
|
||||
label={t("users.fields.email", "E-poçta")}
|
||||
value={form.email}
|
||||
onChange={(v) => setField('email', v)}
|
||||
placeholder={t('users.fields.email', 'E-poçta')}
|
||||
onChange={(v) => setField("email", v)}
|
||||
placeholder={t("users.fields.email", "E-poçta")}
|
||||
error={errors.email}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Password — only in create mode */}
|
||||
{mode === 'create' && (
|
||||
<div className="grid grid-cols-[280px_1fr] items-start px-6 py-4">
|
||||
<div className="pt-0.5">
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{t('users.fields.password', 'Açar sözi')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t('users.fields.passwordHint', 'Iň az 6 harp')}
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.emailHint", "Islege görä")}</p>
|
||||
</BentoCard>
|
||||
{mode === "create" && (
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="password"
|
||||
label={t("users.fields.password", "Açar sözi")}
|
||||
value={form.password}
|
||||
onChange={(v) => setField('password', v)}
|
||||
placeholder={t('users.fields.password', 'Açar sözi')}
|
||||
onChange={(v) => setField("password", v)}
|
||||
placeholder={t("users.fields.password", "Açar sözi")}
|
||||
error={errors.password}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.passwordHint", "Iň az 6 harp")}</p>
|
||||
</BentoCard>
|
||||
)}
|
||||
|
||||
{/* Phone verified */}
|
||||
<div className="grid grid-cols-[280px_1fr] items-center px-6 py-4">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{t('users.fields.phoneVerified', 'Telefon tassyklanan')}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t('users.fields.phoneVerifiedHint', 'SMS arkaly tassyklandy')}
|
||||
</p>
|
||||
<BentoCard>
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.phoneVerified", "Telefon tassyklanan")}</p>
|
||||
<p className="text-xs text-muted-foreground">{t("users.fields.phoneVerifiedHint", "SMS arkaly tassyklandy")}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="phoneVerified"
|
||||
checked={form.phoneVerified}
|
||||
onCheckedChange={(v) => setField('phoneVerified', !!v)}
|
||||
onCheckedChange={(v) => setField("phoneVerified", !!v)}
|
||||
disabled={isPending}
|
||||
/>
|
||||
<Label htmlFor="phoneVerified" className="text-sm text-muted-foreground cursor-pointer">
|
||||
{form.phoneVerified
|
||||
? t('common.yes', 'Hawa')
|
||||
: t('common.no', 'Ýok')}
|
||||
{form.phoneVerified ? t("common.yes", "Hawa") : t("common.no", "Ýok")}
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Active */}
|
||||
<div className="grid grid-cols-[280px_1fr] items-center px-6 py-4">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{t('users.fields.isActive', 'Işjeň')}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t('users.fields.isActiveHint', 'Ulanyjynyň ulgama girip-bilmezligi')}
|
||||
</p>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.isActive", "Işjeň")}</p>
|
||||
<p className="text-xs text-muted-foreground">{t("users.fields.isActiveHint", "Ulanyjynyň ulgama girip-bilmezligi")}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="isActive"
|
||||
checked={form.isActive}
|
||||
onCheckedChange={(v) => setField('isActive', !!v)}
|
||||
disabled={isPending}
|
||||
/>
|
||||
<Checkbox id="isActive" checked={form.isActive} onCheckedChange={(v) => setField("isActive", !!v)} disabled={isPending} />
|
||||
<Label htmlFor="isActive" className="text-sm text-muted-foreground cursor-pointer">
|
||||
{form.isActive
|
||||
? t('common.active', 'Işjeň')
|
||||
: t('common.inactive', 'Işjeň däl')}
|
||||
{form.isActive ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => navigate(-1)}
|
||||
submitLabel={mode === 'create'
|
||||
? t('users.actions.create', 'Ulanyjy dörediň')
|
||||
: t('users.actions.save', 'Ýatda sakla')}
|
||||
submitLabel={mode === "create" ? t("users.actions.create", "Ulanyjy dörediň") : t("users.actions.save", "Ýatda sakla")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,36 +1,36 @@
|
||||
import { useCallback, useMemo, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { MultiLangInput } from '@/components/multiLangInput'
|
||||
import type { CardReason } from '../api/cardReasonsApi'
|
||||
import { useCreateCardReason, useUpdateCardReason } from '../hooks/useCardReasons'
|
||||
import { createCardReasonFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardReason.schema'
|
||||
import type { CardReasonFormData } from '../schemas/cardReason.schema'
|
||||
import { useCallback, useMemo, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { MultiLangInput } from "@/components/multiLangInput";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import type { CardReason } from "../api/cardReasonsApi";
|
||||
import { useCreateCardReason, useUpdateCardReason } from "../hooks/useCardReasons";
|
||||
import { createCardReasonFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardReason.schema";
|
||||
import type { CardReasonFormData } from "../schemas/cardReason.schema";
|
||||
|
||||
// ─── Form errors helper ──────────────────────────────────────────────────────
|
||||
|
||||
type FlatErrors = Partial<Record<keyof CardReasonFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof CardReasonFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof CardReasonFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof CardReasonFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
// ─── CardReasonForm ─────────────────────────────────────────────────────────────
|
||||
|
||||
interface CardReasonFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CardReason
|
||||
mode: "create" | "edit";
|
||||
initialData?: CardReason;
|
||||
}
|
||||
|
||||
function mapInitial(data: CardReason): CardReasonFormData {
|
||||
@@ -39,142 +39,128 @@ function mapInitial(data: CardReason): CardReasonFormData {
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
value: String(data.value),
|
||||
description: data.description ?? '',
|
||||
description: data.description ?? "",
|
||||
isActive: data.isActive,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function CardReasonForm({ mode, initialData }: CardReasonFormProps) {
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t, i18n.language],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateCardReason()
|
||||
const updateMutation = useUpdateCardReason()
|
||||
const createMutation = useCreateCardReason();
|
||||
const updateMutation = useUpdateCardReason();
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const schema = useMemo(() => createCardReasonFormSchema(t), [t, i18n.language])
|
||||
const schema = useMemo(() => createCardReasonFormSchema(t), [t, i18n.language]);
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
trigger,
|
||||
} = useForm<CardReasonFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
})
|
||||
});
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
const set = useCallback(<K extends keyof CardReasonFormData>(key: K, value: CardReasonFormData[K]) => {
|
||||
(setValue as (name: K, val: CardReasonFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
const set = useCallback(
|
||||
<K extends keyof CardReasonFormData>(key: K, value: CardReasonFormData[K]) => {
|
||||
(setValue as (name: K, val: CardReasonFormData[K]) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
}, [i18n.language]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
const isValid = await trigger();
|
||||
if (!isValid) return;
|
||||
|
||||
const values = getValues()
|
||||
const payload = buildPayload(values)
|
||||
const values = getValues();
|
||||
const payload = buildPayload(values);
|
||||
|
||||
if (mode === 'create') {
|
||||
if (mode === "create") {
|
||||
createMutation.mutate(payload, {
|
||||
onSuccess: () => navigate('/resources/card-states'),
|
||||
})
|
||||
onSuccess: () => navigate("/resources/card-states"),
|
||||
});
|
||||
} else if (initialData) {
|
||||
updateMutation.mutate(
|
||||
{ id: initialData.id, ...payload },
|
||||
{ onSuccess: () => navigate('/resources/card-states') }
|
||||
)
|
||||
updateMutation.mutate({ id: initialData.id, ...payload }, { onSuccess: () => navigate("/resources/card-states") });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const nameFields = {
|
||||
tk: { value: form.nameTk, onChange: (v: string) => set('nameTk', v), error: errors.nameTk },
|
||||
ru: { value: form.nameRu, onChange: (v: string) => set('nameRu', v), error: errors.nameRu },
|
||||
en: { value: form.nameEn, onChange: (v: string) => set('nameEn', v), error: errors.nameEn },
|
||||
}
|
||||
tk: { value: form.nameTk, onChange: (v: string) => set("nameTk", v), error: errors.nameTk },
|
||||
ru: { value: form.nameRu, onChange: (v: string) => set("nameRu", v), error: errors.nameRu },
|
||||
en: { value: form.nameEn, onChange: (v: string) => set("nameEn", v), error: errors.nameEn },
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('cardReasons.createTitle', 'Sebäp dörediň')
|
||||
: t('cardReasons.editTitle', 'Sebäp üýtgetmek')}
|
||||
{mode === "create" ? t("cardReasons.createTitle", "Sebäp dörediň") : t("cardReasons.editTitle", "Sebäp üýtgetmek")}
|
||||
</h1>
|
||||
<div>
|
||||
{/* Form rows */}
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden">
|
||||
{/* Name row */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-4 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('cardReasons.fields.name', 'Ady')}
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard span="full">
|
||||
<p className="text-sm font-semibold text-muted-foreground mb-1">
|
||||
{t("cardReasons.fields.name", "Ady")}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<MultiLangInput fields={nameFields} placeholder={t('cardReasons.fields.name', 'Ady')} disabled={isPending} />
|
||||
</div>
|
||||
|
||||
{/* Value row */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('cardReasons.fields.value', 'Baha')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
</p>
|
||||
<MultiLangInput fields={nameFields} placeholder={t("cardReasons.fields.name", "Ady")} disabled={isPending} />
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="number"
|
||||
label={t("cardReasons.fields.value", "Baha")}
|
||||
value={form.value}
|
||||
onChange={(v) => set('value', v)}
|
||||
placeholder={t('cardReasons.fields.value', 'Baha')}
|
||||
onChange={(v) => set("value", v)}
|
||||
placeholder={t("cardReasons.fields.value", "Baha")}
|
||||
error={errors.value}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Description row */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('cardReasons.fields.description', 'Bellikler')}
|
||||
</span>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardReasons.fields.description", "Bellikler")}
|
||||
value={form.description}
|
||||
onChange={(v) => set('description', v)}
|
||||
placeholder={t('cardReasons.fields.description', 'Bellikler')}
|
||||
onChange={(v) => set("description", v)}
|
||||
placeholder={t("cardReasons.fields.description", "Bellikler")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* isActive row */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('cardReasons.fields.isActive', 'Işjeň')}
|
||||
</span>
|
||||
<Checkbox
|
||||
checked={form.isActive}
|
||||
onCheckedChange={(checked) => set('isActive', !!checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<div className="flex items-center gap-3 pt-1">
|
||||
<span className="text-sm font-semibold text-muted-foreground">{t("cardReasons.fields.isActive", "Işjeň")}</span>
|
||||
<Checkbox checked={form.isActive} onCheckedChange={(checked) => set("isActive", !!checked)} />
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => navigate('/resources/card-states')}
|
||||
onCancel={() => navigate("/resources/card-states")}
|
||||
cancelVariant="ghost"
|
||||
submitLabel={mode === 'create'
|
||||
? t('cardReasons.actions.create', 'Kartyň çykarylmagynyň sebäbini döretdiň')
|
||||
: t('cardReasons.actions.update', 'Täzelemek')}
|
||||
className="mt-6"
|
||||
submitLabel={
|
||||
mode === "create"
|
||||
? t("cardReasons.actions.create", "Kartyň çykarylmagynyň sebäbini döretdiň")
|
||||
: t("cardReasons.actions.update", "Täzelemek")
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,196 +1,197 @@
|
||||
import { useMemo } 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 type { CardTransaction } from '../api/cardTransactionsApi'
|
||||
import { useCreateCardTransaction, useUpdateCardTransaction } from '../hooks/useCardTransactions'
|
||||
import { cardTransactionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardTransaction.schema'
|
||||
import type { CardTransactionFormData } from '../schemas/cardTransaction.schema'
|
||||
import { useMemo } 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 type { CardTransaction } from "../api/cardTransactionsApi";
|
||||
import { useCreateCardTransaction, useUpdateCardTransaction } from "../hooks/useCardTransactions";
|
||||
import { cardTransactionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardTransaction.schema";
|
||||
import type { CardTransactionFormData } from "../schemas/cardTransaction.schema";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface CardTransactionFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CardTransaction
|
||||
mode: "create" | "edit";
|
||||
initialData?: CardTransaction;
|
||||
}
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
const PASSPORT_SERIES_OPTIONS = [
|
||||
{ value: 'I-LB', label: 'I-LB' },
|
||||
{ value: 'II-LB', label: 'II-LB' },
|
||||
{ value: 'III-LB', label: 'III-LB' },
|
||||
{ value: 'A', label: 'A' },
|
||||
{ value: 'B', label: 'B' },
|
||||
]
|
||||
{ value: "I-LB", label: "I-LB" },
|
||||
{ value: "II-LB", label: "II-LB" },
|
||||
{ value: "III-LB", label: "III-LB" },
|
||||
{ value: "A", label: "A" },
|
||||
{ value: "B", label: "B" },
|
||||
];
|
||||
|
||||
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => {
|
||||
const val = String(i + 1).padStart(2, '0')
|
||||
return { value: val, label: val }
|
||||
})
|
||||
const val = String(i + 1).padStart(2, "0");
|
||||
return { value: val, label: val };
|
||||
});
|
||||
|
||||
const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => {
|
||||
const year = String(new Date().getFullYear() + i)
|
||||
return { value: year, label: year }
|
||||
})
|
||||
const year = String(new Date().getFullYear() + i);
|
||||
return { value: year, label: year };
|
||||
});
|
||||
|
||||
// ─── Form errors helper ───────────────────────────────────────────────────────
|
||||
|
||||
type FlatErrors = Partial<Record<keyof CardTransactionFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof CardTransactionFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof CardTransactionFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof CardTransactionFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── Component ────────────────────────────────────────────────────────────────
|
||||
|
||||
export function CardTransactionForm({
|
||||
mode,
|
||||
initialData,
|
||||
}: CardTransactionFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
export function CardTransactionForm({ mode, initialData }: CardTransactionFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, setError,
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
setError,
|
||||
} = useForm<CardTransactionFormData>({
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...initialData }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...initialData } : DEFAULT_FORM_VALUES,
|
||||
});
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
const createMutation = useCreateCardTransaction()
|
||||
const updateMutation = useUpdateCardTransaction(initialData?.id ?? 0)
|
||||
const createMutation = useCreateCardTransaction();
|
||||
const updateMutation = useUpdateCardTransaction(initialData?.id ?? 0);
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const setField = (field: keyof CardTransactionFormData) => (value: string) => {
|
||||
setValue(field, value)
|
||||
clearErrors(field)
|
||||
}
|
||||
setValue(field, value);
|
||||
clearErrors(field);
|
||||
};
|
||||
|
||||
const errMsg = (msg: string | undefined) =>
|
||||
!msg ? undefined : msg.startsWith('validation.') ? t(msg, msg) : msg
|
||||
const errMsg = (msg: string | undefined) => (!msg ? undefined : msg.startsWith("validation.") ? t(msg, msg) : msg);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const result = cardTransactionFormSchema.safeParse(getValues())
|
||||
const result = cardTransactionFormSchema.safeParse(getValues());
|
||||
if (!result.success) {
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof CardTransactionFormData
|
||||
setError(key, { message: issue.message })
|
||||
const key = issue.path[0] as keyof CardTransactionFormData;
|
||||
setError(key, { message: issue.message });
|
||||
}
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
if (mode === 'create') {
|
||||
await createMutation.mutateAsync(buildPayload(result.data))
|
||||
navigate('/card-transactions')
|
||||
if (mode === "create") {
|
||||
await createMutation.mutateAsync(buildPayload(result.data));
|
||||
navigate("/card-transactions");
|
||||
} else {
|
||||
await updateMutation.mutateAsync(buildPayload(result.data))
|
||||
navigate(`/card-transactions/${initialData!.id}`)
|
||||
await updateMutation.mutateAsync(buildPayload(result.data));
|
||||
navigate(`/card-transactions/${initialData!.id}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
if (mode === 'create') {
|
||||
navigate('/card-transactions')
|
||||
if (mode === "create") {
|
||||
navigate("/card-transactions");
|
||||
} else {
|
||||
navigate(`/card-transactions/${initialData!.id}`)
|
||||
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 herekedi dörediň')
|
||||
: t('cardTransaction.editTitle', 'Kart herekedi üýtgetmek')}
|
||||
{mode === "create"
|
||||
? t("cardTransaction.createTitle", "Kart herekedi dörediň")
|
||||
: t("cardTransaction.editTitle", "Kart herekedi üý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">
|
||||
{/* Passport Series */}
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('Passport series', 'Pasport seriýasy')}
|
||||
value={form.passport_series}
|
||||
onChange={setField('passport_series')}
|
||||
options={PASSPORT_SERIES_OPTIONS}
|
||||
placeholder={t('Select to choose', 'Saýlamak üçin basyň')}
|
||||
error={errMsg(errors.passport_series)}
|
||||
required
|
||||
/>
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{/* Passport Series */}
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t("Passport series", "Pasport seriýasy")}
|
||||
value={form.passport_series}
|
||||
onChange={setField("passport_series")}
|
||||
options={PASSPORT_SERIES_OPTIONS}
|
||||
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
||||
error={errMsg(errors.passport_series)}
|
||||
required
|
||||
/>
|
||||
|
||||
{/* Passport Number */}
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Passport number', 'Pasport belgisi')}
|
||||
value={form.passport_number}
|
||||
onChange={setField('passport_number')}
|
||||
placeholder={t('Passport number', 'Pasport belgisi')}
|
||||
error={errMsg(errors.passport_number)}
|
||||
required
|
||||
/>
|
||||
{/* Passport Number */}
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Passport number", "Pasport belgisi")}
|
||||
value={form.passport_number}
|
||||
onChange={setField("passport_number")}
|
||||
placeholder={t("Passport number", "Pasport belgisi")}
|
||||
error={errMsg(errors.passport_number)}
|
||||
required
|
||||
/>
|
||||
|
||||
{/* Card Number */}
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Card number', 'Kart belgisi')}
|
||||
value={form.card_number}
|
||||
onChange={setField('card_number')}
|
||||
placeholder={t('Card number', 'Kart belgisi')}
|
||||
error={errMsg(errors.card_number)}
|
||||
required
|
||||
/>
|
||||
{/* Card Number */}
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Card number", "Kart belgisi")}
|
||||
value={form.card_number}
|
||||
onChange={setField("card_number")}
|
||||
placeholder={t("Card number", "Kart belgisi")}
|
||||
error={errMsg(errors.card_number)}
|
||||
required
|
||||
/>
|
||||
|
||||
{/* 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.card_expiry_month}
|
||||
onChange={setField('card_expiry_month')}
|
||||
options={MONTH_OPTIONS}
|
||||
placeholder={t('Select to choose', 'Saýlamak üçin basyň')}
|
||||
error={errMsg(errors.card_expiry_month)}
|
||||
required
|
||||
{/* 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.card_expiry_month}
|
||||
onChange={setField("card_expiry_month")}
|
||||
options={MONTH_OPTIONS}
|
||||
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
||||
error={errMsg(errors.card_expiry_month)}
|
||||
required
|
||||
/>
|
||||
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Card expiry year", "Kart Möhleti (ýyl)")}
|
||||
value={form.card_expiry_year}
|
||||
onChange={setField("card_expiry_year")}
|
||||
options={YEAR_OPTIONS}
|
||||
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
||||
error={errMsg(errors.card_expiry_year)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={handleCancel}
|
||||
cancelVariant="ghost"
|
||||
cancelLabel={t("Cancel", "Ýatyr")}
|
||||
loadingLabel={t("Saving...", "Saklanýar...")}
|
||||
submitLabel={
|
||||
mode === "create" ? t("Create card transaction", "Kart herekedi dörediň") : t("Save changes", "Üýtgetmeleri sakla")
|
||||
}
|
||||
/>
|
||||
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t('Card expiry year', 'Kart Möhleti (ýyl)')}
|
||||
value={form.card_expiry_year}
|
||||
onChange={setField('card_expiry_year')}
|
||||
options={YEAR_OPTIONS}
|
||||
placeholder={t('Select to choose', 'Saýlamak üçin basyň')}
|
||||
error={errMsg(errors.card_expiry_year)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={handleCancel}
|
||||
cancelVariant="ghost"
|
||||
cancelLabel={t('Cancel', 'Ýatyr')}
|
||||
loadingLabel={t('Saving...', 'Saklanýar...')}
|
||||
submitLabel={mode === 'create'
|
||||
? t('Create card transaction', 'Kart herekedi dörediň')
|
||||
: t('Save changes', 'Üýtgetmeleri sakla')}
|
||||
className="mt-6"
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,22 +1,23 @@
|
||||
import { useCallback, useMemo, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { MultiLangInput } from '@/components/multiLangInput'
|
||||
import type { CardType } from '../api/cardTypesApi'
|
||||
import { useCreateCardType, useUpdateCardType } from '../hooks/useCardTypes'
|
||||
import { createCardTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardType.schema'
|
||||
import type { CardTypeFormData } from '../schemas/cardType.schema'
|
||||
import { useCallback, useMemo, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { MultiLangInput } from "@/components/multiLangInput";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import type { CardType } from "../api/cardTypesApi";
|
||||
import { useCreateCardType, useUpdateCardType } from "../hooks/useCardTypes";
|
||||
import { createCardTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardType.schema";
|
||||
import type { CardTypeFormData } from "../schemas/cardType.schema";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface CardTypeFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CardType
|
||||
mode: "create" | "edit";
|
||||
initialData?: CardType;
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
@@ -27,38 +28,38 @@ function mapInitial(data: CardType): CardTypeFormData {
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
value: String(data.value),
|
||||
description: data.description ?? '',
|
||||
description: data.description ?? "",
|
||||
isActive: data.isActive,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
type FlatErrors = Partial<Record<keyof CardTypeFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof CardTypeFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof CardTypeFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof CardTypeFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── CardTypeForm ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function CardTypeForm({ mode, initialData }: CardTypeFormProps) {
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t, i18n.language],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateCardType()
|
||||
const updateMutation = useUpdateCardType()
|
||||
const createMutation = useCreateCardType();
|
||||
const updateMutation = useUpdateCardType();
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const schema = useMemo(() => createCardTypeFormSchema(t), [t, i18n.language])
|
||||
const schema = useMemo(() => createCardTypeFormSchema(t), [t, i18n.language]);
|
||||
|
||||
const {
|
||||
watch,
|
||||
@@ -69,124 +70,95 @@ export function CardTypeForm({ mode, initialData }: CardTypeFormProps) {
|
||||
getValues,
|
||||
} = useForm<CardTypeFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
});
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(
|
||||
() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>),
|
||||
[rhfErrors],
|
||||
)
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
const set = useCallback(
|
||||
(key: keyof CardTypeFormData) => (value: string | boolean) => {
|
||||
(setValue as (k: keyof CardTypeFormData, v: string | boolean) => void)(key, value)
|
||||
clearErrors(key)
|
||||
(setValue as (k: keyof CardTypeFormData, v: string | boolean) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
)
|
||||
);
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
}, [i18n.language]);
|
||||
|
||||
const handleSubmit = useCallback(async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
const isValid = await trigger();
|
||||
if (!isValid) return;
|
||||
|
||||
const payload = buildPayload(getValues())
|
||||
const payload = buildPayload(getValues());
|
||||
|
||||
if (mode === 'create') {
|
||||
if (mode === "create") {
|
||||
createMutation.mutate(payload, {
|
||||
onSuccess: () => navigate('/settings/card/card-types'),
|
||||
})
|
||||
onSuccess: () => navigate("/settings/card/card-types"),
|
||||
});
|
||||
} else if (initialData) {
|
||||
updateMutation.mutate(
|
||||
{ id: initialData.id, ...payload },
|
||||
{ onSuccess: () => navigate('/settings/card/card-types') },
|
||||
)
|
||||
updateMutation.mutate({ id: initialData.id, ...payload }, { onSuccess: () => navigate("/settings/card/card-types") });
|
||||
}
|
||||
}, [mode, initialData, createMutation, updateMutation, navigate, trigger, getValues])
|
||||
}, [mode, initialData, createMutation, updateMutation, navigate, trigger, getValues]);
|
||||
|
||||
const nameFields = {
|
||||
tk: { value: form.nameTk, onChange: (v: string) => set('nameTk')(v), error: errors.nameTk },
|
||||
ru: { value: form.nameRu, onChange: (v: string) => set('nameRu')(v), error: errors.nameRu },
|
||||
en: { value: form.nameEn, onChange: (v: string) => set('nameEn')(v), error: errors.nameEn },
|
||||
}
|
||||
tk: { value: form.nameTk, onChange: (v: string) => set("nameTk")(v), error: errors.nameTk },
|
||||
ru: { value: form.nameRu, onChange: (v: string) => set("nameRu")(v), error: errors.nameRu },
|
||||
en: { value: form.nameEn, onChange: (v: string) => set("nameEn")(v), error: errors.nameEn },
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('cardTypes.createTitle', 'Kart görnüşi dörediň')
|
||||
: t('cardTypes.editTitle', 'Kart görnüşi üýtgetmek')}
|
||||
{mode === "create" ? t("cardTypes.createTitle", "Kart görnüşi dörediň") : t("cardTypes.editTitle", "Kart görnüşi üýtgetmek")}
|
||||
</h1>
|
||||
<div>
|
||||
{/* Form rows */}
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden">
|
||||
{/* Name */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-4 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('cardTypes.fields.name', 'Ady')}
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard span="full">
|
||||
<p className="text-sm font-semibold text-muted-foreground mb-1">
|
||||
{t("cardTypes.fields.name", "Ady")}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<MultiLangInput fields={nameFields} placeholder={t('cardTypes.fields.name', 'Ady')} disabled={isPending} />
|
||||
</div>
|
||||
|
||||
{/* Value */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('cardTypes.fields.value', 'Baha')}
|
||||
</span>
|
||||
</p>
|
||||
<MultiLangInput fields={nameFields} placeholder={t("cardTypes.fields.name", "Ady")} disabled={isPending} />
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="number"
|
||||
label={t("cardTypes.fields.value", "Baha")}
|
||||
value={form.value}
|
||||
onChange={set('value')}
|
||||
placeholder={t('cardTypes.fields.value', 'Baha')}
|
||||
onChange={set("value")}
|
||||
placeholder={t("cardTypes.fields.value", "Baha")}
|
||||
error={errors.value}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('cardTypes.fields.description', 'Bellikler')}
|
||||
</span>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardTypes.fields.description", "Bellikler")}
|
||||
value={form.description}
|
||||
onChange={set('description')}
|
||||
placeholder={t('cardTypes.fields.description', 'Bellikler')}
|
||||
onChange={set("description")}
|
||||
placeholder={t("cardTypes.fields.description", "Bellikler")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* isActive */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('cardTypes.fields.isActive', 'Işjeň')}
|
||||
</span>
|
||||
<Checkbox
|
||||
checked={form.isActive}
|
||||
onCheckedChange={(checked) => set('isActive')(!!checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<div className="flex items-center gap-3 pt-1">
|
||||
<span className="text-sm font-semibold text-muted-foreground">{t("cardTypes.fields.isActive", "Işjeň")}</span>
|
||||
<Checkbox checked={form.isActive} onCheckedChange={(checked) => set("isActive")(!!checked)} />
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => navigate('/settings/card/card-types')}
|
||||
onCancel={() => navigate("/settings/card/card-types")}
|
||||
cancelVariant="ghost"
|
||||
submitLabel={mode === 'create'
|
||||
? t('cardTypes.actions.create', 'Kart görnüşi döretdiň')
|
||||
: t('cardTypes.actions.update', 'Täzelemek')}
|
||||
className="mt-6"
|
||||
submitLabel={
|
||||
mode === "create" ? t("cardTypes.actions.create", "Kart görnüşi döretdiň") : t("cardTypes.actions.update", "Täzelemek")
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,237 +1,215 @@
|
||||
import { useMemo, useEffect, useCallback } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { useCreateClient, useUpdateClient } from '../hooks/useClients'
|
||||
import { clientFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/client.schema'
|
||||
import type { ClientFormData } from '../schemas/client.schema'
|
||||
import type { Client } from '../api/clientsApi'
|
||||
import { useMemo, useEffect, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { useCreateClient, useUpdateClient } from "../hooks/useClients";
|
||||
import { clientFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/client.schema";
|
||||
import type { ClientFormData } from "../schemas/client.schema";
|
||||
import type { Client } from "../api/clientsApi";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface ClientFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: Client
|
||||
mode: "create" | "edit";
|
||||
initialData?: Client;
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
type FlatErrors = Partial<Record<keyof ClientFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof ClientFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof ClientFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof ClientFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── ClientForm ───────────────────────────────────────────────────────────────
|
||||
|
||||
export function ClientForm({ mode, initialData }: ClientFormProps) {
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t, i18n.language],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateClient()
|
||||
const updateMutation = useUpdateClient(initialData?.id ?? 0)
|
||||
const createMutation = useCreateClient();
|
||||
const updateMutation = useUpdateClient(initialData?.id ?? 0);
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const schema = useMemo(() => clientFormSchema(mode, t), [mode, t, i18n.language])
|
||||
const schema = useMemo(() => clientFormSchema(mode, t), [mode, t, i18n.language]);
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
trigger,
|
||||
} = useForm<ClientFormData>({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
resolver: zodResolver(schema as any),
|
||||
defaultValues: initialData
|
||||
? {
|
||||
...DEFAULT_FORM_VALUES,
|
||||
username: initialData.username,
|
||||
name: initialData.name,
|
||||
phone: initialData.phone ?? '',
|
||||
email: initialData.email ?? '',
|
||||
password: '',
|
||||
phone: initialData.phone ?? "",
|
||||
email: initialData.email ?? "",
|
||||
password: "",
|
||||
isActive: initialData.isActive,
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
});
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
const setField = <K extends keyof ClientFormData>(key: K, value: ClientFormData[K]) => {
|
||||
;(setValue as (name: K, val: ClientFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}
|
||||
(setValue as (name: K, val: ClientFormData[K]) => void)(key, value);
|
||||
clearErrors(key);
|
||||
};
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) {
|
||||
trigger()
|
||||
trigger();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
}, [i18n.language]);
|
||||
|
||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
const isValid = await trigger();
|
||||
if (!isValid) return;
|
||||
|
||||
const data = getValues()
|
||||
const data = getValues();
|
||||
|
||||
if (mode === 'create') {
|
||||
const payload = buildPayload(data)
|
||||
if (mode === "create") {
|
||||
const payload = buildPayload(data);
|
||||
createMutation.mutate(payload, {
|
||||
onSuccess: () => navigate('/clients'),
|
||||
})
|
||||
onSuccess: () => navigate("/clients"),
|
||||
});
|
||||
} else {
|
||||
updateMutation.mutate({
|
||||
username: data.username.trim(),
|
||||
name: data.name.trim(),
|
||||
phone: data.phone.trim(),
|
||||
email: data.email.trim() || undefined,
|
||||
isActive: data.isActive,
|
||||
...(data.password.trim() ? { password: data.password } : {}),
|
||||
}, {
|
||||
onSuccess: () => navigate(`/clients/${initialData!.id}`),
|
||||
})
|
||||
updateMutation.mutate(
|
||||
{
|
||||
username: data.username.trim(),
|
||||
name: data.name.trim(),
|
||||
phone: data.phone.trim(),
|
||||
email: data.email.trim() || undefined,
|
||||
isActive: data.isActive,
|
||||
...(data.password.trim() ? { password: data.password } : {}),
|
||||
},
|
||||
{
|
||||
onSuccess: () => navigate(`/clients/${initialData!.id}`),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ── Render ──────────────────────────────────────────────────────────────────
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('clients.createTitle', 'Müşderi dörediň')
|
||||
: t('clients.editTitle', 'Müşderi üýtgetmek')}
|
||||
{mode === "create" ? t("clients.createTitle", "Müşderi dörediň") : t("clients.editTitle", "Müşderi üýtgetmek")}
|
||||
</h1>
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden">
|
||||
{/* Username */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('clients.fields.username', 'Ulanyjy ady')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.username}
|
||||
onChange={(v) => setField('username', v)}
|
||||
placeholder={t('clients.fields.username', 'Ulanyjy ady')}
|
||||
error={errors.username}
|
||||
disabled={isPending}
|
||||
className="max-w-lg"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Name */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('clients.fields.name', 'Ady')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.name}
|
||||
onChange={(v) => setField('name', v)}
|
||||
placeholder={t('clients.fields.name', 'Ady')}
|
||||
error={errors.name}
|
||||
disabled={isPending}
|
||||
className="max-w-lg"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Phone */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('clients.fields.phone', 'Telefon')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<FormInput
|
||||
type="phone"
|
||||
value={form.phone}
|
||||
onChange={(v) => setField('phone', v)}
|
||||
error={errors.phone}
|
||||
disabled={isPending}
|
||||
className="max-w-lg"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Email */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('clients.fields.email', 'E-poçta')}
|
||||
</span>
|
||||
<FormInput
|
||||
type="email"
|
||||
value={form.email}
|
||||
onChange={(v) => setField('email', v)}
|
||||
placeholder={t('clients.fields.email', 'E-poçta')}
|
||||
disabled={isPending}
|
||||
className="max-w-lg"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Password */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('clients.fields.password', 'Açar sözi')}
|
||||
{mode === 'create' && <span className="text-destructive ml-0.5">*</span>}
|
||||
</span>
|
||||
<div className="max-w-lg space-y-1">
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("clients.fields.username", "Ulanyjy ady")}
|
||||
value={form.username}
|
||||
onChange={(v) => setField("username", v)}
|
||||
placeholder={t("clients.fields.username", "Ulanyjy ady")}
|
||||
error={errors.username}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("clients.fields.name", "Ady")}
|
||||
value={form.name}
|
||||
onChange={(v) => setField("name", v)}
|
||||
placeholder={t("clients.fields.name", "Ady")}
|
||||
error={errors.name}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="phone"
|
||||
label={t("clients.fields.phone", "Telefon")}
|
||||
value={form.phone}
|
||||
onChange={(v) => setField("phone", v)}
|
||||
error={errors.phone}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="email"
|
||||
label={t("clients.fields.email", "E-poçta")}
|
||||
value={form.email}
|
||||
onChange={(v) => setField("email", v)}
|
||||
placeholder={t("clients.fields.email", "E-poçta")}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="password"
|
||||
label={t("clients.fields.password", "Açar sözi") + (mode === "create" ? " *" : "")}
|
||||
value={form.password}
|
||||
onChange={(v) => setField('password', v)}
|
||||
onChange={(v) => setField("password", v)}
|
||||
placeholder={
|
||||
mode === 'edit'
|
||||
? t('clients.fields.passwordEditHint', 'Üýtgetmek üçin täze açar söz giriziň')
|
||||
: t('clients.fields.password', 'Açar sözi')
|
||||
mode === "edit"
|
||||
? t("clients.fields.passwordEditHint", "Üýtgetmek üçin täze açar söz giriziň")
|
||||
: t("clients.fields.password", "Açar sözi")
|
||||
}
|
||||
error={errors.password}
|
||||
disabled={isPending}
|
||||
/>
|
||||
{mode === 'edit' && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('clients.fields.passwordEditNote', 'Boş goýsaňyz, açar sözi üýtgemez')}
|
||||
{mode === "edit" && (
|
||||
<p className="text-xs text-muted-foreground -mt-3">
|
||||
{t("clients.fields.passwordEditNote", "Boş goýsaňyz, açar sözi üýtgemez")}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* isActive */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-center py-4 px-6">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('clients.fields.isActive', 'Işjeň')}
|
||||
</span>
|
||||
<Checkbox
|
||||
checked={form.isActive}
|
||||
onCheckedChange={(v) => setField('isActive', !!v)}
|
||||
disabled={isPending}
|
||||
className="data-[state=checked]:bg-primary data-[state=checked]:border-primary"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => navigate(-1)}
|
||||
cancelVariant="ghost"
|
||||
submitLabel={mode === 'create'
|
||||
? t('clients.createBtn', 'Müşderi döredin')
|
||||
: t('clients.updateBtn', 'Üýtgetmeleri sakla')}
|
||||
className="px-6 py-4 border-t border-border bg-muted/20"
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm text-muted-foreground">{t("clients.fields.isActive", "Işjeň")}</span>
|
||||
<Checkbox
|
||||
checked={form.isActive}
|
||||
onCheckedChange={(v) => setField("isActive", !!v)}
|
||||
disabled={isPending}
|
||||
className="data-[state=checked]:bg-primary data-[state=checked]:border-primary"
|
||||
/>
|
||||
</div>
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => navigate(-1)}
|
||||
cancelVariant="ghost"
|
||||
submitLabel={mode === "create" ? t("clients.createBtn", "Müşderi döredin") : t("clients.updateBtn", "Üýtgetmeleri sakla")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,55 +1,51 @@
|
||||
// features/currencyRates/components/CurrencyRateForm.tsx
|
||||
|
||||
import { useCallback, useMemo, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { CURRENCY_OPTIONS, type CurrencyRate } from '../api/currencyRatesApi'
|
||||
import { useCreateCurrencyRate, useUpdateCurrencyRate } from '../hooks/useCurrencyRates'
|
||||
import {
|
||||
createCurrencyRateFormSchema,
|
||||
DEFAULT_FORM_VALUES,
|
||||
buildPayload,
|
||||
type CurrencyRateFormData,
|
||||
} from '../schemas/currencyRate.schema'
|
||||
import { useCallback, useMemo, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { CURRENCY_OPTIONS, type CurrencyRate } from "../api/currencyRatesApi";
|
||||
import { useCreateCurrencyRate, useUpdateCurrencyRate } from "../hooks/useCurrencyRates";
|
||||
import { createCurrencyRateFormSchema, DEFAULT_FORM_VALUES, buildPayload, type CurrencyRateFormData } from "../schemas/currencyRate.schema";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface CurrencyRateFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CurrencyRate
|
||||
mode: "create" | "edit";
|
||||
initialData?: CurrencyRate;
|
||||
}
|
||||
|
||||
type FlatErrors = Partial<Record<keyof CurrencyRateFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof CurrencyRateFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof CurrencyRateFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof CurrencyRateFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── CurrencyRateForm ─────────────────────────────────────────────────────────
|
||||
|
||||
export function CurrencyRateForm({ mode, initialData }: CurrencyRateFormProps) {
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t, i18n.language],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateCurrencyRate()
|
||||
const updateMutation = useUpdateCurrencyRate(initialData?.id ?? 0)
|
||||
const createMutation = useCreateCurrencyRate();
|
||||
const updateMutation = useUpdateCurrencyRate(initialData?.id ?? 0);
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const schema = useMemo(() => createCurrencyRateFormSchema(t), [t, i18n.language])
|
||||
const schema = useMemo(() => createCurrencyRateFormSchema(t), [t, i18n.language]);
|
||||
|
||||
const {
|
||||
watch,
|
||||
@@ -63,136 +59,118 @@ export function CurrencyRateForm({ mode, initialData }: CurrencyRateFormProps) {
|
||||
defaultValues: initialData
|
||||
? {
|
||||
currencyFrom: initialData.currencyFrom,
|
||||
currencyTo: initialData.currencyTo,
|
||||
value: String(initialData.value),
|
||||
currencyTo: initialData.currencyTo,
|
||||
value: String(initialData.value),
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
});
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(
|
||||
() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>),
|
||||
[rhfErrors],
|
||||
)
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) {
|
||||
trigger()
|
||||
trigger();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
}, [i18n.language]);
|
||||
|
||||
const setField = useCallback(
|
||||
(key: keyof CurrencyRateFormData) => (value: string) => {
|
||||
setValue(key, value)
|
||||
clearErrors(key)
|
||||
setValue(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
)
|
||||
);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
const isValid = await trigger();
|
||||
if (!isValid) return;
|
||||
|
||||
const payload = buildPayload(getValues())
|
||||
const payload = buildPayload(getValues());
|
||||
|
||||
if (mode === 'create') {
|
||||
await createMutation.mutateAsync(payload)
|
||||
navigate('/resources/currency-rates')
|
||||
if (mode === "create") {
|
||||
await createMutation.mutateAsync(payload);
|
||||
navigate("/resources/currency-rates");
|
||||
} else {
|
||||
await updateMutation.mutateAsync(payload)
|
||||
navigate(`/resources/currency-rates/${initialData!.id}`)
|
||||
await updateMutation.mutateAsync(payload);
|
||||
navigate(`/resources/currency-rates/${initialData!.id}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
if (mode === 'create') {
|
||||
navigate('/resources/currency-rates')
|
||||
if (mode === "create") {
|
||||
navigate("/resources/currency-rates");
|
||||
} else {
|
||||
navigate(`/resources/currency-rates/${initialData!.id}`)
|
||||
navigate(`/resources/currency-rates/${initialData!.id}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('currencyRates.createTitle', 'Walýuta kursy dörediň')
|
||||
: t('currencyRates.editTitle', 'Walýuta kursy üýtgetmek')}
|
||||
{mode === "create"
|
||||
? t("currencyRates.createTitle", "Walýuta kursy dörediň")
|
||||
: t("currencyRates.editTitle", "Walýuta kursy üýtgetmek")}
|
||||
</h1>
|
||||
<div className="space-y-6 bg-card border border-border rounded-xl overflow-hidden">
|
||||
{/* Currency From */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
|
||||
<label className="text-sm text-muted-foreground pt-1.5">
|
||||
{t('currencyRates.fields.currencyFrom', 'Currency from')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</label>
|
||||
<div className="space-y-1">
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t("currencyRates.fields.currencyFrom", "Currency from")}
|
||||
value={form.currencyFrom}
|
||||
onChange={setField('currencyFrom')}
|
||||
onChange={setField("currencyFrom")}
|
||||
options={CURRENCY_OPTIONS}
|
||||
placeholder={t('common.selectPlaceholder', 'Saýlamak üçin basyň')}
|
||||
placeholder={t("common.selectPlaceholder", "Saýlamak üçin basyň")}
|
||||
error={errors.currencyFrom}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('currencyRates.hints.oneUnit', '1 möçberi')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Currency To */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
|
||||
<label className="text-sm text-muted-foreground pt-1.5">
|
||||
{t('currencyRates.fields.currencyTo', 'Currency to')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</label>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
value={form.currencyTo}
|
||||
onChange={setField('currencyTo')}
|
||||
options={CURRENCY_OPTIONS}
|
||||
placeholder={t('common.selectPlaceholder', 'Saýlamak üçin basyň')}
|
||||
error={errors.currencyTo}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Value */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6">
|
||||
<label className="text-sm text-muted-foreground pt-1.5">
|
||||
{t('currencyRates.fields.value', 'Value')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</label>
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs text-muted-foreground -mt-3">{t("currencyRates.hints.oneUnit", "1 möçberi")}</p>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t("currencyRates.fields.currencyTo", "Currency to")}
|
||||
value={form.currencyTo}
|
||||
onChange={setField("currencyTo")}
|
||||
options={CURRENCY_OPTIONS}
|
||||
placeholder={t("common.selectPlaceholder", "Saýlamak üçin basyň")}
|
||||
error={errors.currencyTo}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="number"
|
||||
label={t("currencyRates.fields.value", "Value")}
|
||||
value={form.value}
|
||||
onChange={setField('value')}
|
||||
placeholder={t('currencyRates.fields.value', 'Value')}
|
||||
onChange={setField("value")}
|
||||
placeholder={t("currencyRates.fields.value", "Value")}
|
||||
error={errors.value}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground italic">
|
||||
{t('currencyRates.hints.decimalNote', 'Bitin däl sanlary "." bilen ýazmaly')}
|
||||
<p className="text-xs text-muted-foreground italic -mt-3">
|
||||
{t("currencyRates.hints.decimalNote", 'Bitin däl sanlary "." bilen ýazmaly')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={handleCancel}
|
||||
cancelVariant="ghost"
|
||||
submitLabel={mode === 'create'
|
||||
? t('currencyRates.actions.create', 'Walýuta kursy dörediň')
|
||||
: t('currencyRates.actions.update', 'Ýatda sakla')}
|
||||
className="px-6 py-4 border-t border-border"
|
||||
/>
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={handleCancel}
|
||||
cancelVariant="ghost"
|
||||
submitLabel={
|
||||
mode === "create"
|
||||
? t("currencyRates.actions.create", "Walýuta kursy dörediň")
|
||||
: t("currencyRates.actions.update", "Ýatda sakla")
|
||||
}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,31 +1,32 @@
|
||||
import { useCallback, useMemo, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { MultiLangInput } from '@/components/multiLangInput'
|
||||
import type { District } from '../api/districtsApi'
|
||||
import { useCreateDistrict, useUpdateDistrict } from '../hooks/useDistricts'
|
||||
import { createDistrictFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/district.schema'
|
||||
import type { DistrictFormData } from '../schemas/district.schema'
|
||||
import { useCallback, useMemo, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { MultiLangInput } from "@/components/multiLangInput";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import type { District } from "../api/districtsApi";
|
||||
import { useCreateDistrict, useUpdateDistrict } from "../hooks/useDistricts";
|
||||
import { createDistrictFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/district.schema";
|
||||
import type { DistrictFormData } from "../schemas/district.schema";
|
||||
|
||||
type FlatErrors = Partial<Record<keyof DistrictFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof DistrictFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof DistrictFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof DistrictFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
export interface DistrictFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: District
|
||||
mode: "create" | "edit";
|
||||
initialData?: District;
|
||||
}
|
||||
|
||||
function mapInitial(data: District): DistrictFormData {
|
||||
@@ -33,123 +34,113 @@ function mapInitial(data: District): DistrictFormData {
|
||||
nameTk: data.name.tk,
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
description: data.description ?? '',
|
||||
description: data.description ?? "",
|
||||
isActive: data.isActive,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function DistrictForm({ mode, initialData }: DistrictFormProps) {
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t, i18n.language],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateDistrict()
|
||||
const updateMutation = useUpdateDistrict()
|
||||
const createMutation = useCreateDistrict();
|
||||
const updateMutation = useUpdateDistrict();
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const schema = useMemo(() => createDistrictFormSchema(t), [t, i18n.language])
|
||||
const schema = useMemo(() => createDistrictFormSchema(t), [t, i18n.language]);
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
trigger,
|
||||
} = useForm<DistrictFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
})
|
||||
});
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
const set = useCallback(<K extends keyof DistrictFormData>(key: K) =>
|
||||
(value: DistrictFormData[K]) => {
|
||||
(setValue as (name: K, val: DistrictFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
const set = useCallback(
|
||||
<K extends keyof DistrictFormData>(key: K) =>
|
||||
(value: DistrictFormData[K]) => {
|
||||
(setValue as (name: K, val: DistrictFormData[K]) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
}, [i18n.language]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
const isValid = await trigger();
|
||||
if (!isValid) return;
|
||||
|
||||
const payload = buildPayload(getValues())
|
||||
const payload = buildPayload(getValues());
|
||||
|
||||
if (mode === 'create') {
|
||||
if (mode === "create") {
|
||||
createMutation.mutate(payload, {
|
||||
onSuccess: () => navigate('/settings/location/districts'),
|
||||
})
|
||||
onSuccess: () => navigate("/settings/location/districts"),
|
||||
});
|
||||
} else if (initialData) {
|
||||
updateMutation.mutate(
|
||||
{ id: initialData.id, ...payload },
|
||||
{ onSuccess: () => navigate('/settings/location/districts') },
|
||||
)
|
||||
updateMutation.mutate({ id: initialData.id, ...payload }, { onSuccess: () => navigate("/settings/location/districts") });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const nameFields = {
|
||||
tk: { value: form.nameTk, onChange: set('nameTk'), error: errors.nameTk },
|
||||
ru: { value: form.nameRu, onChange: set('nameRu'), error: errors.nameRu },
|
||||
en: { value: form.nameEn, onChange: set('nameEn'), error: errors.nameEn },
|
||||
}
|
||||
tk: { value: form.nameTk, onChange: set("nameTk"), error: errors.nameTk },
|
||||
ru: { value: form.nameRu, onChange: set("nameRu"), error: errors.nameRu },
|
||||
en: { value: form.nameEn, onChange: set("nameEn"), error: errors.nameEn },
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('districts.createTitle', 'Etrap dörediň')
|
||||
: t('districts.editTitle', 'Etrap üýtgetmek')}
|
||||
{mode === "create" ? t("districts.createTitle", "Etrap dörediň") : t("districts.editTitle", "Etrap üýtgetmek")}
|
||||
</h1>
|
||||
<div>
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden">
|
||||
<div className="grid grid-cols-[220px_1fr] items-start px-4 py-4 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('districts.fields.name', 'Ady')}
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard span="full">
|
||||
<p className="text-sm font-semibold text-muted-foreground mb-1">
|
||||
{t("districts.fields.name", "Ady")}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<MultiLangInput fields={nameFields} placeholder={t('districts.fields.name', 'Ady')} />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('districts.fields.description', 'Bellikler')}
|
||||
</span>
|
||||
</p>
|
||||
<MultiLangInput fields={nameFields} placeholder={t("districts.fields.name", "Ady")} />
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("districts.fields.description", "Bellikler")}
|
||||
value={form.description}
|
||||
onChange={set('description')}
|
||||
placeholder={t('districts.fields.description', 'Bellikler')}
|
||||
onChange={set("description")}
|
||||
placeholder={t("districts.fields.description", "Bellikler")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('districts.fields.isActive', 'Işjeň')}
|
||||
</span>
|
||||
<Checkbox
|
||||
checked={form.isActive}
|
||||
onCheckedChange={(checked) => set('isActive')(!!checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<div className="flex items-center gap-3 pt-1">
|
||||
<span className="text-sm font-semibold text-muted-foreground">{t("districts.fields.isActive", "Işjeň")}</span>
|
||||
<Checkbox checked={form.isActive} onCheckedChange={(checked) => set("isActive")(!!checked)} />
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => navigate('/settings/location/districts')}
|
||||
onCancel={() => navigate("/settings/location/districts")}
|
||||
cancelVariant="ghost"
|
||||
submitLabel={mode === 'create'
|
||||
? t('districts.actions.create', 'Etrap döret')
|
||||
: t('districts.actions.update', 'Täzelemek')}
|
||||
className="mt-6"
|
||||
submitLabel={mode === "create" ? t("districts.actions.create", "Etrap döret") : t("districts.actions.update", "Täzelemek")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,41 +1,36 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { toast } from 'sonner'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
|
||||
import {
|
||||
useCreateLoanPaidOffLetter,
|
||||
useUpdateLoanPaidOffLetter,
|
||||
} from '../hooks/useLoanPaidOffLetters'
|
||||
import type { LoanPaidOffLetter } from '../api/loanPaidOffLettersApi'
|
||||
import { useCreateLoanPaidOffLetter, useUpdateLoanPaidOffLetter } from "../hooks/useLoanPaidOffLetters";
|
||||
import type { LoanPaidOffLetter } from "../api/loanPaidOffLettersApi";
|
||||
import {
|
||||
loanPaidOffLetterFormSchema,
|
||||
type LoanPaidOffLetterFormData,
|
||||
DEFAULT_FORM_VALUES,
|
||||
buildPayload,
|
||||
} from '../schemas/loanPaidOffLetter.schema'
|
||||
} from "../schemas/loanPaidOffLetter.schema";
|
||||
|
||||
interface LoanPaidOffLetterFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: LoanPaidOffLetter
|
||||
mode: "create" | "edit";
|
||||
initialData?: LoanPaidOffLetter;
|
||||
}
|
||||
|
||||
export function LoanPaidOffLetterForm({
|
||||
mode,
|
||||
initialData,
|
||||
}: LoanPaidOffLetterFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
export function LoanPaidOffLetterForm({ mode, initialData }: LoanPaidOffLetterFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateLoanPaidOffLetter()
|
||||
const updateMutation = useUpdateLoanPaidOffLetter(initialData?.id ?? 0)
|
||||
const createMutation = useCreateLoanPaidOffLetter();
|
||||
const updateMutation = useUpdateLoanPaidOffLetter(initialData?.id ?? 0);
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const {
|
||||
handleSubmit,
|
||||
@@ -46,104 +41,103 @@ export function LoanPaidOffLetterForm({
|
||||
} = useForm<LoanPaidOffLetterFormData>({
|
||||
resolver: zodResolver(loanPaidOffLetterFormSchema),
|
||||
defaultValues: DEFAULT_FORM_VALUES,
|
||||
mode: 'onSubmit',
|
||||
})
|
||||
mode: "onSubmit",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (mode === 'edit' && initialData) {
|
||||
if (mode === "edit" && initialData) {
|
||||
reset({
|
||||
passportSeries: initialData.passportSeries,
|
||||
passportNumber: initialData.passportNumber,
|
||||
loanAccount: initialData.loanAccount,
|
||||
issuedAt: initialData.issuedAt,
|
||||
})
|
||||
});
|
||||
}
|
||||
}, [mode, initialData, reset])
|
||||
}, [mode, initialData, reset]);
|
||||
|
||||
const onSubmit = (data: LoanPaidOffLetterFormData) => {
|
||||
const payload = buildPayload(data)
|
||||
const payload = buildPayload(data);
|
||||
|
||||
if (mode === 'create') {
|
||||
if (mode === "create") {
|
||||
createMutation.mutate(payload, {
|
||||
onSuccess: () => {
|
||||
toast.success(t('common.success.create', 'Üstünlikli döredildi'))
|
||||
navigate('/loan-paid-off-letters')
|
||||
toast.success(t("common.success.create", "Üstünlikli döredildi"));
|
||||
navigate("/loan-paid-off-letters");
|
||||
},
|
||||
})
|
||||
});
|
||||
} else {
|
||||
updateMutation.mutate(payload, {
|
||||
onSuccess: () => {
|
||||
toast.success(t('common.success.save', 'Üstünlikli ýatda saklandy'))
|
||||
navigate('/loan-paid-off-letters')
|
||||
toast.success(t("common.success.save", "Üstünlikli ýatda saklandy"));
|
||||
navigate("/loan-paid-off-letters");
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const errMsg = (msg: string | undefined) =>
|
||||
msg?.startsWith('validation.') ? t(msg, msg) : msg
|
||||
const errMsg = (msg: string | undefined) => (msg?.startsWith("validation.") ? t(msg, msg) : msg);
|
||||
|
||||
const onError = () => {
|
||||
toast.error(t('common.errors.fillRequired', 'Hökman doldurylmaly öýjükleri dolduryň'))
|
||||
}
|
||||
toast.error(t("common.errors.fillRequired", "Hökman doldurylmaly öýjükleri dolduryň"));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('loanPaidOffLetters.createTitle', 'Karzyň ýapylandygy barada güwanama almak dörediň')
|
||||
: t('loanPaidOffLetters.editTitle', 'Karzyň ýapylandygy barada güwanama almak üýtgetmek')}
|
||||
{mode === "create"
|
||||
? t("loanPaidOffLetters.createTitle", "Karzyň ýapylandygy barada güwanama almak dörediň")
|
||||
: t("loanPaidOffLetters.editTitle", "Karzyň ýapylandygy barada güwanama almak üýtgetmek")}
|
||||
</h1>
|
||||
<form onSubmit={handleSubmit(onSubmit, onError)} className="space-y-6">
|
||||
<div className="bg-card border border-border rounded-xl p-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<FormInput
|
||||
label={t('loanPaidOffLetters.columns.passportSeries', 'Pasport seriýasy')}
|
||||
required
|
||||
value={watch('passportSeries')}
|
||||
onChange={(v) => setValue('passportSeries', v)}
|
||||
placeholder={t('loanPaidOffLetters.placeholders.passportSeries', 'TM')}
|
||||
error={errMsg(errors.passportSeries?.message)}
|
||||
/>
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<FormInput
|
||||
label={t("loanPaidOffLetters.columns.passportSeries", "Pasport seriýasy")}
|
||||
required
|
||||
value={watch("passportSeries")}
|
||||
onChange={(v) => setValue("passportSeries", v)}
|
||||
placeholder={t("loanPaidOffLetters.placeholders.passportSeries", "TM")}
|
||||
error={errMsg(errors.passportSeries?.message)}
|
||||
/>
|
||||
|
||||
<FormInput
|
||||
label={t('loanPaidOffLetters.columns.passportNumber', 'Pasport belgisi')}
|
||||
required
|
||||
value={watch('passportNumber')}
|
||||
onChange={(v) => setValue('passportNumber', v)}
|
||||
placeholder="A123456"
|
||||
error={errMsg(errors.passportNumber?.message)}
|
||||
/>
|
||||
<FormInput
|
||||
label={t("loanPaidOffLetters.columns.passportNumber", "Pasport belgisi")}
|
||||
required
|
||||
value={watch("passportNumber")}
|
||||
onChange={(v) => setValue("passportNumber", v)}
|
||||
placeholder="A123456"
|
||||
error={errMsg(errors.passportNumber?.message)}
|
||||
/>
|
||||
|
||||
<FormInput
|
||||
label={t('loanPaidOffLetters.columns.loanAccount', 'Karz hasaby')}
|
||||
required
|
||||
value={watch('loanAccount')}
|
||||
onChange={(v) => setValue('loanAccount', v)}
|
||||
placeholder="LOAN-..."
|
||||
error={errMsg(errors.loanAccount?.message)}
|
||||
/>
|
||||
<FormInput
|
||||
label={t("loanPaidOffLetters.columns.loanAccount", "Karz hasaby")}
|
||||
required
|
||||
value={watch("loanAccount")}
|
||||
onChange={(v) => setValue("loanAccount", v)}
|
||||
placeholder="LOAN-..."
|
||||
error={errMsg(errors.loanAccount?.message)}
|
||||
/>
|
||||
|
||||
<FormInput
|
||||
label={t('loanPaidOffLetters.columns.issuedAt', 'Berlen wagty')}
|
||||
required
|
||||
type="date"
|
||||
value={watch('issuedAt')}
|
||||
onChange={(v) => setValue('issuedAt', v)}
|
||||
error={errMsg(errors.issuedAt?.message)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<FormInput
|
||||
label={t("loanPaidOffLetters.columns.issuedAt", "Berlen wagty")}
|
||||
required
|
||||
type="date"
|
||||
value={watch("issuedAt")}
|
||||
onChange={(v) => setValue("issuedAt", v)}
|
||||
error={errMsg(errors.issuedAt?.message)}
|
||||
/>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit(onSubmit, onError)}
|
||||
onCancel={() => navigate('/loan-paid-off-letters')}
|
||||
submitLabel={mode === 'create'
|
||||
? t('common.create', 'Döret')
|
||||
: t('common.save', 'Ýatda sakla')}
|
||||
/>
|
||||
</form>
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit(onSubmit, onError)}
|
||||
onCancel={() => navigate("/loan-paid-off-letters")}
|
||||
submitLabel={mode === "create" ? t("common.create", "Döret") : t("common.save", "Ýatda sakla")}
|
||||
/>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,41 +1,31 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { toast } from 'sonner'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
|
||||
import {
|
||||
useCreateLoanRemaining,
|
||||
useUpdateLoanRemaining,
|
||||
} from '../hooks/useLoanRemaining'
|
||||
import type { LoanRemaining } from '../api/loanRemainingApi'
|
||||
import {
|
||||
loanRemainingFormSchema,
|
||||
type LoanRemainingFormData,
|
||||
DEFAULT_FORM_VALUES,
|
||||
buildPayload,
|
||||
} from '../schemas/loanRemaining.schema'
|
||||
import { useCreateLoanRemaining, useUpdateLoanRemaining } from "../hooks/useLoanRemaining";
|
||||
import type { LoanRemaining } from "../api/loanRemainingApi";
|
||||
import { loanRemainingFormSchema, type LoanRemainingFormData, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/loanRemaining.schema";
|
||||
|
||||
interface LoanRemainingFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: LoanRemaining
|
||||
mode: "create" | "edit";
|
||||
initialData?: LoanRemaining;
|
||||
}
|
||||
|
||||
export function LoanRemainingForm({
|
||||
mode,
|
||||
initialData,
|
||||
}: LoanRemainingFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
export function LoanRemainingForm({ mode, initialData }: LoanRemainingFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateLoanRemaining()
|
||||
const updateMutation = useUpdateLoanRemaining(initialData?.id ?? 0)
|
||||
const createMutation = useCreateLoanRemaining();
|
||||
const updateMutation = useUpdateLoanRemaining(initialData?.id ?? 0);
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const {
|
||||
handleSubmit,
|
||||
@@ -46,96 +36,95 @@ export function LoanRemainingForm({
|
||||
} = useForm<LoanRemainingFormData>({
|
||||
resolver: zodResolver(loanRemainingFormSchema),
|
||||
defaultValues: DEFAULT_FORM_VALUES,
|
||||
mode: 'onSubmit',
|
||||
})
|
||||
mode: "onSubmit",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (mode === 'edit' && initialData) {
|
||||
if (mode === "edit" && initialData) {
|
||||
reset({
|
||||
passportSeries: initialData.passportSeries,
|
||||
passportNumber: initialData.passportNumber,
|
||||
loanAccount: initialData.loanAccount,
|
||||
})
|
||||
});
|
||||
}
|
||||
}, [mode, initialData, reset])
|
||||
}, [mode, initialData, reset]);
|
||||
|
||||
const onSubmit = (data: LoanRemainingFormData) => {
|
||||
const payload = buildPayload(data)
|
||||
const payload = buildPayload(data);
|
||||
|
||||
if (mode === 'create') {
|
||||
if (mode === "create") {
|
||||
createMutation.mutate(payload, {
|
||||
onSuccess: () => {
|
||||
toast.success(t('common.success.create', 'Üstünlikli döredildi'))
|
||||
navigate('/loan-remaining')
|
||||
toast.success(t("common.success.create", "Üstünlikli döredildi"));
|
||||
navigate("/loan-remaining");
|
||||
},
|
||||
})
|
||||
});
|
||||
} else {
|
||||
updateMutation.mutate(payload, {
|
||||
onSuccess: () => {
|
||||
toast.success(t('common.success.save', 'Üstünlikli ýatda saklandy'))
|
||||
navigate('/loan-remaining')
|
||||
toast.success(t("common.success.save", "Üstünlikli ýatda saklandy"));
|
||||
navigate("/loan-remaining");
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const errMsg = (msg: string | undefined) =>
|
||||
msg?.startsWith('validation.') ? t(msg, msg) : msg
|
||||
const errMsg = (msg: string | undefined) => (msg?.startsWith("validation.") ? t(msg, msg) : msg);
|
||||
|
||||
const onError = () => {
|
||||
toast.error(t('common.errors.fillRequired', 'Hökman doldurylmaly öýjükleri dolduryň'))
|
||||
}
|
||||
toast.error(t("common.errors.fillRequired", "Hökman doldurylmaly öýjükleri dolduryň"));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('loanRemaining.createTitle', 'Karzyň galyndysy dörediň')
|
||||
: t('loanRemaining.editTitle', 'Karzyň galyndysy üýtgetmek')}
|
||||
{mode === "create"
|
||||
? t("loanRemaining.createTitle", "Karzyň galyndysy dörediň")
|
||||
: t("loanRemaining.editTitle", "Karzyň galyndysy üýtgetmek")}
|
||||
</h1>
|
||||
<form onSubmit={handleSubmit(onSubmit, onError)} className="space-y-6">
|
||||
<div className="bg-card border border-border rounded-xl p-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<FormInput
|
||||
label={t('loanRemaining.columns.passportSeries', 'Pasport seriýasy')}
|
||||
required
|
||||
value={watch('passportSeries')}
|
||||
onChange={(v) => setValue('passportSeries', v)}
|
||||
placeholder={t('loanRemaining.placeholders.passportSeries', 'TM')}
|
||||
error={errMsg(errors.passportSeries?.message)}
|
||||
/>
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<FormInput
|
||||
label={t("loanRemaining.columns.passportSeries", "Pasport seriýasy")}
|
||||
required
|
||||
value={watch("passportSeries")}
|
||||
onChange={(v) => setValue("passportSeries", v)}
|
||||
placeholder={t("loanRemaining.placeholders.passportSeries", "TM")}
|
||||
error={errMsg(errors.passportSeries?.message)}
|
||||
/>
|
||||
|
||||
<FormInput
|
||||
label={t('loanRemaining.columns.passportNumber', 'Pasport belgisi')}
|
||||
required
|
||||
value={watch('passportNumber')}
|
||||
onChange={(v) => setValue('passportNumber', v)}
|
||||
placeholder="A123456"
|
||||
error={errMsg(errors.passportNumber?.message)}
|
||||
/>
|
||||
<FormInput
|
||||
label={t("loanRemaining.columns.passportNumber", "Pasport belgisi")}
|
||||
required
|
||||
value={watch("passportNumber")}
|
||||
onChange={(v) => setValue("passportNumber", v)}
|
||||
placeholder="A123456"
|
||||
error={errMsg(errors.passportNumber?.message)}
|
||||
/>
|
||||
|
||||
<div className="md:col-span-2">
|
||||
<FormInput
|
||||
label={t('loanRemaining.columns.loanAccount', 'Karz hasaby')}
|
||||
required
|
||||
value={watch('loanAccount')}
|
||||
onChange={(v) => setValue('loanAccount', v)}
|
||||
placeholder="NOVA-..."
|
||||
error={errMsg(errors.loanAccount?.message)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="md:col-span-2">
|
||||
<FormInput
|
||||
label={t("loanRemaining.columns.loanAccount", "Karz hasaby")}
|
||||
required
|
||||
value={watch("loanAccount")}
|
||||
onChange={(v) => setValue("loanAccount", v)}
|
||||
placeholder="NOVA-..."
|
||||
error={errMsg(errors.loanAccount?.message)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit(onSubmit, onError)}
|
||||
onCancel={() => navigate('/loan-remaining')}
|
||||
submitLabel={mode === 'create'
|
||||
? t('common.create', 'Döret')
|
||||
: t('common.save', 'Ýatda sakla')}
|
||||
/>
|
||||
</form>
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit(onSubmit, onError)}
|
||||
onCancel={() => navigate("/loan-remaining")}
|
||||
submitLabel={mode === "create" ? t("common.create", "Döret") : t("common.save", "Ýatda sakla")}
|
||||
/>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,36 +1,37 @@
|
||||
import { useCallback, useMemo, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { MultiLangInput } from '@/components/multiLangInput'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { useCreateLoanType, useUpdateLoanType } from '../hooks/useLoanTypes'
|
||||
import type { LoanType } from '../api/loanTypesApi'
|
||||
import { createLoanTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/loanType.schema'
|
||||
import type { LoanTypeFormData } from '../schemas/loanType.schema'
|
||||
import { useCallback, useMemo, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { MultiLangInput } from "@/components/multiLangInput";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { useCreateLoanType, useUpdateLoanType } from "../hooks/useLoanTypes";
|
||||
import type { LoanType } from "../api/loanTypesApi";
|
||||
import { createLoanTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/loanType.schema";
|
||||
import type { LoanTypeFormData } from "../schemas/loanType.schema";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
type FormMode = 'create' | 'edit'
|
||||
type FormMode = "create" | "edit";
|
||||
|
||||
interface LoanTypeFormProps {
|
||||
mode: FormMode
|
||||
initialData?: LoanType
|
||||
mode: FormMode;
|
||||
initialData?: LoanType;
|
||||
}
|
||||
|
||||
type FlatErrors = Partial<Record<keyof LoanTypeFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof LoanTypeFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof LoanTypeFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof LoanTypeFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
function mapInitial(data: LoanType): LoanTypeFormData {
|
||||
@@ -38,32 +39,31 @@ function mapInitial(data: LoanType): LoanTypeFormData {
|
||||
nameTk: data.name.tk,
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
notesTk: data.notes?.tk ?? '',
|
||||
notesRu: data.notes?.ru ?? '',
|
||||
notesEn: data.notes?.en ?? '',
|
||||
notesTk: data.notes?.tk ?? "",
|
||||
notesRu: data.notes?.ru ?? "",
|
||||
notesEn: data.notes?.en ?? "",
|
||||
tax: String(data.tax),
|
||||
loanTerm: String(data.loanTerm),
|
||||
isActive: data.isActive,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// ─── LoanTypeForm ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function LoanTypeForm({ mode, initialData }: LoanTypeFormProps) {
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t, i18n.language],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateLoanType()
|
||||
const updateMutation = useUpdateLoanType(initialData?.id ?? 0)
|
||||
const createMutation = useCreateLoanType();
|
||||
const updateMutation = useUpdateLoanType(initialData?.id ?? 0);
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const schema = useMemo(() => createLoanTypeFormSchema(t), [t, i18n.language])
|
||||
const schema = useMemo(() => createLoanTypeFormSchema(t), [t, i18n.language]);
|
||||
|
||||
const {
|
||||
watch,
|
||||
@@ -74,152 +74,115 @@ export function LoanTypeForm({ mode, initialData }: LoanTypeFormProps) {
|
||||
getValues,
|
||||
} = useForm<LoanTypeFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
});
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(
|
||||
() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>),
|
||||
[rhfErrors],
|
||||
)
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
}, [i18n.language]);
|
||||
|
||||
const set = useCallback(
|
||||
(key: keyof LoanTypeFormData) => (value: string | boolean) => {
|
||||
(setValue as (k: keyof LoanTypeFormData, v: string | boolean) => void)(key, value)
|
||||
clearErrors(key)
|
||||
(setValue as (k: keyof LoanTypeFormData, v: string | boolean) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
)
|
||||
);
|
||||
|
||||
// ── Submit ─────────────────────────────────────────────────────────────────
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
const isValid = await trigger();
|
||||
if (!isValid) return;
|
||||
|
||||
const payload = buildPayload(getValues())
|
||||
const payload = buildPayload(getValues());
|
||||
|
||||
if (mode === 'create') {
|
||||
const result = await createMutation.mutateAsync(payload)
|
||||
navigate(`/resources/loan-types/${result.id}`)
|
||||
if (mode === "create") {
|
||||
const result = await createMutation.mutateAsync(payload);
|
||||
navigate(`/resources/loan-types/${result.id}`);
|
||||
} else {
|
||||
await updateMutation.mutateAsync(payload)
|
||||
navigate(`/resources/loan-types/${initialData!.id}`)
|
||||
await updateMutation.mutateAsync(payload);
|
||||
navigate(`/resources/loan-types/${initialData!.id}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => navigate('/resources/loan-types')
|
||||
const handleCancel = () => navigate("/resources/loan-types");
|
||||
|
||||
// ── Name fields per lang ───────────────────────────────────────────────────
|
||||
const nameFields = {
|
||||
tk: { value: form.nameTk, onChange: set('nameTk'), error: errors.nameTk },
|
||||
ru: { value: form.nameRu, onChange: set('nameRu'), error: errors.nameRu },
|
||||
en: { value: form.nameEn, onChange: set('nameEn'), error: errors.nameEn },
|
||||
}
|
||||
tk: { value: form.nameTk, onChange: set("nameTk"), error: errors.nameTk },
|
||||
ru: { value: form.nameRu, onChange: set("nameRu"), error: errors.nameRu },
|
||||
en: { value: form.nameEn, onChange: set("nameEn"), error: errors.nameEn },
|
||||
};
|
||||
|
||||
const notesFields = {
|
||||
tk: { value: form.notesTk ?? '', onChange: set('notesTk') },
|
||||
ru: { value: form.notesRu ?? '', onChange: set('notesRu') },
|
||||
en: { value: form.notesEn ?? '', onChange: set('notesEn') },
|
||||
}
|
||||
tk: { value: form.notesTk ?? "", onChange: set("notesTk") },
|
||||
ru: { value: form.notesRu ?? "", onChange: set("notesRu") },
|
||||
en: { value: form.notesEn ?? "", onChange: set("notesEn") },
|
||||
};
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('loanTypes.createTitle', 'Karz görnüşi dörediň')
|
||||
: t('loanTypes.editTitle', 'Karz görnüşi üýtgetmek')}
|
||||
{mode === "create" ? t("loanTypes.createTitle", "Karz görnüşi dörediň") : t("loanTypes.editTitle", "Karz görnüşi üýtgetmek")}
|
||||
</h1>
|
||||
<div className="space-y-0">
|
||||
{/* Form card */}
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden divide-y divide-border">
|
||||
{/* Ady */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start px-4 py-4">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('loanTypes.fields.name', 'Ady')}
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard span="full">
|
||||
<p className="text-sm font-semibold text-muted-foreground mb-1">
|
||||
{t("loanTypes.fields.name", "Ady")}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<MultiLangInput fields={nameFields} placeholder={t('loanTypes.fields.name', 'Ady')} disabled={isPending} />
|
||||
</div>
|
||||
|
||||
{/* Salgyt */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-center px-4 py-3">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('loanTypes.fields.tax', 'Salgyt')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
</p>
|
||||
<MultiLangInput fields={nameFields} placeholder={t("loanTypes.fields.name", "Ady")} disabled={isPending} />
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="number"
|
||||
label={t("loanTypes.fields.tax", "Salgyt")}
|
||||
value={form.tax}
|
||||
onChange={set('tax')}
|
||||
placeholder={t('loanTypes.fields.tax', 'Salgyt')}
|
||||
onChange={set("tax")}
|
||||
placeholder={t("loanTypes.fields.tax", "Salgyt")}
|
||||
error={errors.tax}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Karz möhleti */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-center px-4 py-3">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('loanTypes.fields.loanTerm', 'Karz möhleti')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="number"
|
||||
label={t("loanTypes.fields.loanTerm", "Karz möhleti")}
|
||||
value={form.loanTerm}
|
||||
onChange={set('loanTerm')}
|
||||
placeholder={t('loanTypes.fields.loanTerm', 'Karz möhleti')}
|
||||
onChange={set("loanTerm")}
|
||||
placeholder={t("loanTypes.fields.loanTerm", "Karz möhleti")}
|
||||
error={errors.loanTerm}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Bellikler */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start px-4 py-4">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('loanTypes.fields.notes', 'Bellikler')}
|
||||
</span>
|
||||
<MultiLangInput fields={notesFields} placeholder={t('loanTypes.fields.notes', 'Bellikler')} disabled={isPending} />
|
||||
</div>
|
||||
|
||||
{/* Işjeň */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-center px-4 py-3">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('loanTypes.fields.isActive', 'Işjeň')}
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="isActive"
|
||||
checked={form.isActive}
|
||||
onCheckedChange={(checked) => set('isActive')(!!checked)}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard span="full">
|
||||
<p className="text-sm font-semibold text-muted-foreground mb-1">{t("loanTypes.fields.notes", "Bellikler")}</p>
|
||||
<MultiLangInput fields={notesFields} placeholder={t("loanTypes.fields.notes", "Bellikler")} disabled={isPending} />
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<div className="flex items-center gap-2 pt-1">
|
||||
<span className="text-sm font-semibold text-muted-foreground">{t("loanTypes.fields.isActive", "Işjeň")}</span>
|
||||
<Checkbox id="isActive" checked={form.isActive} onCheckedChange={(checked) => set("isActive")(!!checked)} />
|
||||
<Label htmlFor="isActive" className="text-sm text-foreground cursor-pointer">
|
||||
{form.isActive
|
||||
? t('common.active', 'Işjeň')
|
||||
: t('common.inactive', 'Işjeň däl')}
|
||||
{form.isActive ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={handleCancel}
|
||||
cancelVariant="ghost"
|
||||
submitLabel={mode === 'create'
|
||||
? t('loanTypes.actions.create', 'Karz görnüşi dörediň')
|
||||
: t('loanTypes.actions.save', 'Ýatda sakla')}
|
||||
className="pt-4"
|
||||
submitLabel={mode === "create" ? t("loanTypes.actions.create", "Karz görnüşi dörediň") : t("loanTypes.actions.save", "Ýatda sakla")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,58 +1,64 @@
|
||||
import { useMemo, useEffect, useCallback } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { MultiLangInput } from '@/components/multiLangInput'
|
||||
import { useCreatePermission, useUpdatePermission } from '../hooks/usePermissions'
|
||||
import { createPermissionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/permission.schema'
|
||||
import type { PermissionFormData } from '../schemas/permission.schema'
|
||||
import type { Permission } from '../api/permissionsApi'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { useMemo, useEffect, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { MultiLangInput } from "@/components/multiLangInput";
|
||||
import { useCreatePermission, useUpdatePermission } from "../hooks/usePermissions";
|
||||
import { createPermissionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/permission.schema";
|
||||
import type { PermissionFormData } from "../schemas/permission.schema";
|
||||
import type { Permission } from "../api/permissionsApi";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface PermissionFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: Permission
|
||||
mode: "create" | "edit";
|
||||
initialData?: Permission;
|
||||
}
|
||||
|
||||
const GUARD_OPTIONS = [
|
||||
{ value: 'web', label: 'web' },
|
||||
{ value: 'api', label: 'api' },
|
||||
{ value: 'sanctum', label: 'sanctum' },
|
||||
]
|
||||
{ value: "web", label: "web" },
|
||||
{ value: "api", label: "api" },
|
||||
{ value: "sanctum", label: "sanctum" },
|
||||
];
|
||||
|
||||
type FlatErrors = Partial<Record<keyof PermissionFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof PermissionFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof PermissionFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof PermissionFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── PermissionForm ───────────────────────────────────────────────────────────
|
||||
|
||||
export function PermissionForm({ mode, initialData }: PermissionFormProps) {
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t, i18n.language],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createPermission = useCreatePermission()
|
||||
const updatePermission = useUpdatePermission(initialData?.id ?? 0)
|
||||
const createPermission = useCreatePermission();
|
||||
const updatePermission = useUpdatePermission(initialData?.id ?? 0);
|
||||
|
||||
const isPending = createPermission.isPending || updatePermission.isPending
|
||||
const isPending = createPermission.isPending || updatePermission.isPending;
|
||||
|
||||
const schema = useMemo(() => createPermissionFormSchema(t), [t, i18n.language])
|
||||
const schema = useMemo(() => createPermissionFormSchema(t), [t, i18n.language]);
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
trigger,
|
||||
} = useForm<PermissionFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData
|
||||
@@ -65,113 +71,118 @@ export function PermissionForm({ mode, initialData }: PermissionFormProps) {
|
||||
guard_name: initialData.guard_name,
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
});
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
const setField = useCallback(
|
||||
(key: keyof PermissionFormData) => (value: string) => {
|
||||
(setValue as (k: keyof PermissionFormData, v: string) => void)(key, value)
|
||||
clearErrors(key)
|
||||
(setValue as (k: keyof PermissionFormData, v: string) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
)
|
||||
);
|
||||
|
||||
const nameFields = {
|
||||
tk: { value: form.nameTk, onChange: (v: string) => { setValue('nameTk', v); clearErrors('nameTk'); }, error: errors.nameTk },
|
||||
ru: { value: form.nameRu, onChange: (v: string) => { setValue('nameRu', v); clearErrors('nameRu'); }, error: errors.nameRu },
|
||||
en: { value: form.nameEn, onChange: (v: string) => { setValue('nameEn', v); clearErrors('nameEn'); }, error: errors.nameEn },
|
||||
}
|
||||
tk: {
|
||||
value: form.nameTk,
|
||||
onChange: (v: string) => {
|
||||
setValue("nameTk", v);
|
||||
clearErrors("nameTk");
|
||||
},
|
||||
error: errors.nameTk,
|
||||
},
|
||||
ru: {
|
||||
value: form.nameRu,
|
||||
onChange: (v: string) => {
|
||||
setValue("nameRu", v);
|
||||
clearErrors("nameRu");
|
||||
},
|
||||
error: errors.nameRu,
|
||||
},
|
||||
en: {
|
||||
value: form.nameEn,
|
||||
onChange: (v: string) => {
|
||||
setValue("nameEn", v);
|
||||
clearErrors("nameEn");
|
||||
},
|
||||
error: errors.nameEn,
|
||||
},
|
||||
};
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
}, [i18n.language]);
|
||||
|
||||
// ── Submit ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
const isValid = await trigger();
|
||||
if (!isValid) return;
|
||||
|
||||
const values = getValues()
|
||||
const payload = buildPayload(values)
|
||||
const values = getValues();
|
||||
const payload = buildPayload(values);
|
||||
|
||||
if (mode === 'create') {
|
||||
if (mode === "create") {
|
||||
createPermission.mutate(payload, {
|
||||
onSuccess: () => navigate('/settings/users/permissions'),
|
||||
})
|
||||
onSuccess: () => navigate("/settings/users/permissions"),
|
||||
});
|
||||
} else {
|
||||
updatePermission.mutate(payload, {
|
||||
onSuccess: () => navigate('/settings/users/permissions'),
|
||||
})
|
||||
onSuccess: () => navigate("/settings/users/permissions"),
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('permissions.createTitle', 'Rugsat dörediň')
|
||||
: t('permissions.editTitle', 'Rugsat üýtgetmek')}
|
||||
{mode === "create" ? t("permissions.createTitle", "Rugsat dörediň") : t("permissions.editTitle", "Rugsat üýtgetmek")}
|
||||
</h1>
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden">
|
||||
|
||||
{/* Code */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start p-5 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('permissions.fields.code', 'Kod')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.code}
|
||||
onChange={setField('code')}
|
||||
placeholder={t('permissions.fields.code', 'Kod')}
|
||||
error={errors.code}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Name (multilingual) */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start p-5 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('permissions.fields.name', 'Ady')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<MultiLangInput fields={nameFields} placeholder={t('permissions.fields.name', 'Ady')} disabled={isPending} />
|
||||
</div>
|
||||
|
||||
{/* Guard name */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start p-5">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('permissions.fields.guardName', 'Guard name')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<FormInput
|
||||
type="select"
|
||||
value={form.guard_name}
|
||||
onChange={setField('guard_name')}
|
||||
options={GUARD_OPTIONS}
|
||||
error={errors.guard_name}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("permissions.fields.code", "Kod")}
|
||||
value={form.code}
|
||||
onChange={setField("code")}
|
||||
placeholder={t("permissions.fields.code", "Kod")}
|
||||
error={errors.code}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("permissions.fields.guardName", "Guard name")}
|
||||
value={form.guard_name}
|
||||
onChange={setField("guard_name")}
|
||||
options={GUARD_OPTIONS}
|
||||
error={errors.guard_name}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard span="full">
|
||||
<p className="text-sm font-semibold text-muted-foreground mb-1">
|
||||
{t("permissions.fields.name", "Ady")}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</p>
|
||||
<MultiLangInput fields={nameFields} placeholder={t("permissions.fields.name", "Ady")} disabled={isPending} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => navigate('/settings/users/permissions')}
|
||||
submitLabel={mode === 'create'
|
||||
? t('permissions.actions.create', 'Rugsat dörediň')
|
||||
: t('permissions.actions.save', 'Ýatda sakla')}
|
||||
className="px-5 py-4 border-t border-border bg-muted/20"
|
||||
onCancel={() => navigate("/settings/users/permissions")}
|
||||
submitLabel={mode === "create" ? t("permissions.actions.create", "Rugsat dörediň") : t("permissions.actions.save", "Ýatda sakla")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -27,21 +27,11 @@ import {
|
||||
import { cn } from "@/lib/utils";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import {
|
||||
useCreateRequiredDocument,
|
||||
useUpdateRequiredDocument,
|
||||
} from "../hooks/useRequiredDocuments";
|
||||
import {
|
||||
createRequiredDocumentFormSchema,
|
||||
DEFAULT_FORM_VALUES,
|
||||
buildPayload,
|
||||
mapInitial,
|
||||
} from "../schemas/requiredDocument.schema";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { useCreateRequiredDocument, useUpdateRequiredDocument } from "../hooks/useRequiredDocuments";
|
||||
import { createRequiredDocumentFormSchema, DEFAULT_FORM_VALUES, buildPayload, mapInitial } from "../schemas/requiredDocument.schema";
|
||||
import type { RequiredDocumentFormData } from "../schemas/requiredDocument.schema";
|
||||
import type {
|
||||
LoanDocument,
|
||||
LoanDocumentTranslation,
|
||||
} from "../api/requiredDocumentsApi";
|
||||
import type { LoanDocument, LoanDocumentTranslation } from "../api/requiredDocumentsApi";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -79,6 +69,8 @@ function RichTextToolbar({ editor, onFileAttach }: RichTextToolbarProps) {
|
||||
setShowLinkModal(false);
|
||||
};
|
||||
|
||||
const handleAttachmentClick = () => fileInputRef.current?.click();
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
@@ -159,14 +151,13 @@ function RichTextToolbar({ editor, onFileAttach }: RichTextToolbarProps) {
|
||||
},
|
||||
{
|
||||
icon: Paperclip,
|
||||
action: () => fileInputRef.current?.click(),
|
||||
action: handleAttachmentClick,
|
||||
active: false,
|
||||
title: "Attachment",
|
||||
},
|
||||
{
|
||||
icon: Type,
|
||||
action: () =>
|
||||
editor.chain().focus().selectAll().clearNodes().unsetAllMarks().run(),
|
||||
action: () => editor.chain().focus().selectAll().clearNodes().unsetAllMarks().run(),
|
||||
active: false,
|
||||
title: "Clear format",
|
||||
},
|
||||
@@ -175,52 +166,39 @@ function RichTextToolbar({ editor, onFileAttach }: RichTextToolbarProps) {
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center gap-0.5 p-1.5 border-b border-border bg-muted/30">
|
||||
{tools.map(({ icon: Icon, action, active, title }) => (
|
||||
<button
|
||||
key={title}
|
||||
type="button"
|
||||
title={title}
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
action();
|
||||
}}
|
||||
className={cn(
|
||||
"flex items-center justify-center w-7 h-7 rounded text-muted-foreground",
|
||||
"hover:bg-muted hover:text-foreground transition-colors",
|
||||
active && "bg-primary/10 text-primary",
|
||||
)}
|
||||
>
|
||||
<Icon size={14} />
|
||||
</button>
|
||||
))}
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
className="hidden"
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
{
|
||||
// eslint-disable-next-line react-hooks/refs
|
||||
tools.map(({ icon: Icon, action, active, title }) => (
|
||||
<button
|
||||
key={title}
|
||||
type="button"
|
||||
title={title}
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
action();
|
||||
}}
|
||||
className={cn(
|
||||
"flex items-center justify-center w-7 h-7 rounded text-muted-foreground",
|
||||
"hover:bg-muted hover:text-foreground transition-colors",
|
||||
active && "bg-primary/10 text-primary",
|
||||
)}
|
||||
>
|
||||
<Icon size={14} />
|
||||
</button>
|
||||
))
|
||||
}
|
||||
<input ref={fileInputRef} type="file" className="hidden" onChange={handleFileChange} />
|
||||
</div>
|
||||
|
||||
{/* Link modal */}
|
||||
{showLinkModal && (
|
||||
<LinkModal
|
||||
onConfirm={handleLinkConfirm}
|
||||
onClose={() => setShowLinkModal(false)}
|
||||
/>
|
||||
)}
|
||||
{showLinkModal && <LinkModal onConfirm={handleLinkConfirm} onClose={() => setShowLinkModal(false)} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Link Modal ───────────────────────────────────────────────────────────────
|
||||
|
||||
function LinkModal({
|
||||
onConfirm,
|
||||
onClose,
|
||||
}: {
|
||||
onConfirm: (url: string) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
function LinkModal({ onConfirm, onClose }: { onConfirm: (url: string) => void; onClose: () => void }) {
|
||||
const [url, setUrl] = useState("");
|
||||
return (
|
||||
<div
|
||||
@@ -244,11 +222,7 @@ function LinkModal({
|
||||
className="border border-input rounded px-2 py-1.5 text-sm w-full focus:outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
<div className="flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="text-sm px-3 py-1 rounded hover:bg-muted text-muted-foreground"
|
||||
>
|
||||
<button type="button" onClick={onClose} className="text-sm px-3 py-1 rounded hover:bg-muted text-muted-foreground">
|
||||
Ýatyr
|
||||
</button>
|
||||
<button
|
||||
@@ -273,12 +247,7 @@ interface RichTextEditorProps {
|
||||
onFileAttach?: (file: File) => void;
|
||||
}
|
||||
|
||||
function RichTextEditor({
|
||||
value,
|
||||
onChange,
|
||||
error,
|
||||
onFileAttach,
|
||||
}: RichTextEditorProps) {
|
||||
function RichTextEditor({ value, onChange, error, onFileAttach }: RichTextEditorProps) {
|
||||
const editor = useEditor({
|
||||
extensions: [
|
||||
StarterKit.configure({
|
||||
@@ -346,20 +315,11 @@ function AttachedFilesList({ files, onRemove }: AttachedFilesListProps) {
|
||||
return (
|
||||
<div className="mt-2 flex flex-col gap-1">
|
||||
{files.map((file, i) => (
|
||||
<div
|
||||
key={`${file.name}-${i}`}
|
||||
className="flex items-center gap-2 text-xs text-muted-foreground bg-muted/40 rounded px-2 py-1.5"
|
||||
>
|
||||
<div key={`${file.name}-${i}`} className="flex items-center gap-2 text-xs text-muted-foreground bg-muted/40 rounded px-2 py-1.5">
|
||||
<FileText size={12} className="shrink-0 text-primary" />
|
||||
<span className="flex-1 truncate">{file.name}</span>
|
||||
<span className="shrink-0 text-muted-foreground/60">
|
||||
{(file.size / 1024).toFixed(1)} KB
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemove(i)}
|
||||
className="shrink-0 hover:text-destructive transition-colors ml-1"
|
||||
>
|
||||
<span className="shrink-0 text-muted-foreground/60">{(file.size / 1024).toFixed(1)} KB</span>
|
||||
<button type="button" onClick={() => onRemove(i)} className="shrink-0 hover:text-destructive transition-colors ml-1">
|
||||
<X size={12} />
|
||||
</button>
|
||||
</div>
|
||||
@@ -386,15 +346,10 @@ function LangTabs({ active, onChange }: LangTabsProps) {
|
||||
onClick={() => onChange(code)}
|
||||
className={cn(
|
||||
"text-sm transition-colors",
|
||||
active === code
|
||||
? "text-primary font-semibold underline underline-offset-4"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
active === code ? "text-primary font-semibold underline underline-offset-4" : "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{t(
|
||||
"languages." + code,
|
||||
code === "tk" ? "Türkmen" : code === "ru" ? "Русский" : "English",
|
||||
)}
|
||||
{t("languages." + code, code === "tk" ? "Türkmen" : code === "ru" ? "Русский" : "English")}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
@@ -414,9 +369,7 @@ const RHF_TO_LEGACY_KEY: Record<string, LegacyErrorKey> = {
|
||||
descEn: "desc_en",
|
||||
};
|
||||
|
||||
function flattenErrors(
|
||||
errors: Record<string, { message?: string } | undefined>,
|
||||
): Partial<Record<LegacyErrorKey, string>> {
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): Partial<Record<LegacyErrorKey, string>> {
|
||||
const result: Partial<Record<LegacyErrorKey, string>> = {};
|
||||
for (const [key, err] of Object.entries(errors)) {
|
||||
const legacyKey = RHF_TO_LEGACY_KEY[key];
|
||||
@@ -429,10 +382,7 @@ function flattenErrors(
|
||||
|
||||
// ─── RequiredDocumentForm ─────────────────────────────────────────────────────
|
||||
|
||||
export function RequiredDocumentForm({
|
||||
mode,
|
||||
initialData,
|
||||
}: RequiredDocumentFormProps) {
|
||||
export function RequiredDocumentForm({ mode, initialData }: RequiredDocumentFormProps) {
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
@@ -460,10 +410,7 @@ export function RequiredDocumentForm({
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const schema = useMemo(
|
||||
() => createRequiredDocumentFormSchema(t),
|
||||
[t, i18n.language],
|
||||
);
|
||||
const schema = useMemo(() => createRequiredDocumentFormSchema(t), [t, i18n.language]);
|
||||
|
||||
const {
|
||||
watch,
|
||||
@@ -473,19 +420,11 @@ export function RequiredDocumentForm({
|
||||
trigger,
|
||||
} = useForm<RequiredDocumentFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
});
|
||||
|
||||
const form = watch();
|
||||
const errors = useMemo(
|
||||
() =>
|
||||
flattenErrors(
|
||||
rhfErrors as Record<string, { message?: string } | undefined>,
|
||||
),
|
||||
[rhfErrors],
|
||||
);
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||
@@ -576,82 +515,46 @@ export function RequiredDocumentForm({
|
||||
: t("loanDocuments.editTitle", "Karz gerekli resminama üýtgetmek")}
|
||||
</h1>
|
||||
<form onSubmit={handleSubmit} noValidate>
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden divide-y divide-border">
|
||||
{/* ── Name field ──────────────────────────────────────────────────── */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-4">
|
||||
<label className="text-sm text-muted-foreground pt-1">
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard span="full">
|
||||
<p className="text-sm font-semibold text-muted-foreground mb-1">
|
||||
{t("loanDocuments.fields.name", "Ady")}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</label>
|
||||
<div>
|
||||
<LangTabs active={nameLang} onChange={setNameLang} />
|
||||
<FormInput
|
||||
type="text"
|
||||
value={name[nameLang]}
|
||||
onChange={(val) =>
|
||||
setName((prev) => ({ ...prev, [nameLang]: val }))
|
||||
}
|
||||
placeholder={t("loanDocuments.fields.namePlaceholder", "Ady")}
|
||||
error={errors[`name_${nameLang}`]}
|
||||
/>
|
||||
{/* Show errors for other locales as hints */}
|
||||
{LOCALES.filter((l) => l !== nameLang && errors[`name_${l}`]).map(
|
||||
(code) => (
|
||||
<p key={code} className="mt-1 text-xs text-destructive/70">
|
||||
{t(
|
||||
"languages." + code,
|
||||
code === "tk"
|
||||
? "Türkmen"
|
||||
: code === "ru"
|
||||
? "Русский"
|
||||
: "English",
|
||||
)}
|
||||
: {errors[`name_${code}`]}
|
||||
</p>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── Description field ────────────────────────────────────────────── */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-4">
|
||||
<label className="text-sm text-muted-foreground pt-1">
|
||||
</p>
|
||||
<LangTabs active={nameLang} onChange={setNameLang} />
|
||||
<FormInput
|
||||
type="text"
|
||||
value={name[nameLang]}
|
||||
onChange={(val) => setName((prev) => ({ ...prev, [nameLang]: val }))}
|
||||
placeholder={t("loanDocuments.fields.namePlaceholder", "Ady")}
|
||||
error={errors[`name_${nameLang}`]}
|
||||
/>
|
||||
{LOCALES.filter((l) => l !== nameLang && errors[`name_${l}`]).map((code) => (
|
||||
<p key={code} className="text-xs text-destructive/70">
|
||||
{t("languages." + code, code === "tk" ? "Türkmen" : code === "ru" ? "Русский" : "English")}: {errors[`name_${code}`]}
|
||||
</p>
|
||||
))}
|
||||
</BentoCard>
|
||||
<BentoCard span="full">
|
||||
<p className="text-sm font-semibold text-muted-foreground mb-1">
|
||||
{t("loanDocuments.fields.description", "Yazgy")}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</label>
|
||||
<div>
|
||||
<LangTabs active={descLang} onChange={setDescLang} />
|
||||
<RichTextEditor
|
||||
value={description[descLang]}
|
||||
onChange={(val) =>
|
||||
setDescription((prev) => ({ ...prev, [descLang]: val }))
|
||||
}
|
||||
error={errors[`desc_${descLang}`]}
|
||||
onFileAttach={handleFileAttach}
|
||||
/>
|
||||
{/* Attached files list — shown below editor, removable */}
|
||||
<AttachedFilesList
|
||||
files={attachedFiles}
|
||||
onRemove={handleFileRemove}
|
||||
/>
|
||||
{LOCALES.filter((l) => l !== descLang && errors[`desc_${l}`]).map(
|
||||
(code) => (
|
||||
<p key={code} className="mt-1 text-xs text-destructive/70">
|
||||
{t(
|
||||
"languages." + code,
|
||||
code === "tk"
|
||||
? "Türkmen"
|
||||
: code === "ru"
|
||||
? "Русский"
|
||||
: "English",
|
||||
)}
|
||||
: {errors[`desc_${code}`]}
|
||||
</p>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</p>
|
||||
<LangTabs active={descLang} onChange={setDescLang} />
|
||||
<RichTextEditor
|
||||
value={description[descLang]}
|
||||
onChange={(val) => setDescription((prev) => ({ ...prev, [descLang]: val }))}
|
||||
error={errors[`desc_${descLang}`]}
|
||||
onFileAttach={handleFileAttach}
|
||||
/>
|
||||
<AttachedFilesList files={attachedFiles} onRemove={handleFileRemove} />
|
||||
{LOCALES.filter((l) => l !== descLang && errors[`desc_${l}`]).map((code) => (
|
||||
<p key={code} className="text-xs text-destructive/70">
|
||||
{t("languages." + code, code === "tk" ? "Türkmen" : code === "ru" ? "Русский" : "English")}: {errors[`desc_${code}`]}
|
||||
</p>
|
||||
))}
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
|
||||
@@ -1,58 +1,64 @@
|
||||
import { useMemo, useEffect, useCallback } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { MultiLangInput } from '@/components/multiLangInput'
|
||||
import { useCreateRole, useUpdateRole } from '../hooks/useRoles'
|
||||
import { createRoleFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/role.schema'
|
||||
import type { RoleFormData } from '../schemas/role.schema'
|
||||
import type { Role } from '../api/rolesApi'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { useMemo, useEffect, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { MultiLangInput } from "@/components/multiLangInput";
|
||||
import { useCreateRole, useUpdateRole } from "../hooks/useRoles";
|
||||
import { createRoleFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/role.schema";
|
||||
import type { RoleFormData } from "../schemas/role.schema";
|
||||
import type { Role } from "../api/rolesApi";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface RoleFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: Role
|
||||
mode: "create" | "edit";
|
||||
initialData?: Role;
|
||||
}
|
||||
|
||||
const GUARD_OPTIONS = [
|
||||
{ value: 'web', label: 'web' },
|
||||
{ value: 'api', label: 'api' },
|
||||
{ value: 'sanctum', label: 'sanctum' },
|
||||
]
|
||||
{ value: "web", label: "web" },
|
||||
{ value: "api", label: "api" },
|
||||
{ value: "sanctum", label: "sanctum" },
|
||||
];
|
||||
|
||||
type FlatErrors = Partial<Record<keyof RoleFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof RoleFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof RoleFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof RoleFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── RoleForm ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export function RoleForm({ mode, initialData }: RoleFormProps) {
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t, i18n.language],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createRole = useCreateRole()
|
||||
const updateRole = useUpdateRole(initialData?.id ?? 0)
|
||||
const createRole = useCreateRole();
|
||||
const updateRole = useUpdateRole(initialData?.id ?? 0);
|
||||
|
||||
const isPending = createRole.isPending || updateRole.isPending
|
||||
const isPending = createRole.isPending || updateRole.isPending;
|
||||
|
||||
const schema = useMemo(() => createRoleFormSchema(t), [t, i18n.language])
|
||||
const schema = useMemo(() => createRoleFormSchema(t), [t, i18n.language]);
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
trigger,
|
||||
} = useForm<RoleFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData
|
||||
@@ -65,114 +71,119 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
||||
guard_name: initialData.guard_name,
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
});
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
const setField = useCallback(
|
||||
(key: keyof RoleFormData) => (value: string) => {
|
||||
(setValue as (k: keyof RoleFormData, v: string) => void)(key, value)
|
||||
clearErrors(key)
|
||||
(setValue as (k: keyof RoleFormData, v: string) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
)
|
||||
);
|
||||
|
||||
const nameFields = {
|
||||
tk: { value: form.nameTk, onChange: (v: string) => { setValue('nameTk', v); clearErrors('nameTk'); }, error: errors.nameTk },
|
||||
ru: { value: form.nameRu, onChange: (v: string) => { setValue('nameRu', v); clearErrors('nameRu'); }, error: errors.nameRu },
|
||||
en: { value: form.nameEn, onChange: (v: string) => { setValue('nameEn', v); clearErrors('nameEn'); }, error: errors.nameEn },
|
||||
}
|
||||
tk: {
|
||||
value: form.nameTk,
|
||||
onChange: (v: string) => {
|
||||
setValue("nameTk", v);
|
||||
clearErrors("nameTk");
|
||||
},
|
||||
error: errors.nameTk,
|
||||
},
|
||||
ru: {
|
||||
value: form.nameRu,
|
||||
onChange: (v: string) => {
|
||||
setValue("nameRu", v);
|
||||
clearErrors("nameRu");
|
||||
},
|
||||
error: errors.nameRu,
|
||||
},
|
||||
en: {
|
||||
value: form.nameEn,
|
||||
onChange: (v: string) => {
|
||||
setValue("nameEn", v);
|
||||
clearErrors("nameEn");
|
||||
},
|
||||
error: errors.nameEn,
|
||||
},
|
||||
};
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
}, [i18n.language]);
|
||||
|
||||
// ── Submit ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
const isValid = await trigger();
|
||||
if (!isValid) return;
|
||||
|
||||
const values = getValues()
|
||||
const payload = buildPayload(values)
|
||||
const values = getValues();
|
||||
const payload = buildPayload(values);
|
||||
|
||||
if (mode === 'create') {
|
||||
if (mode === "create") {
|
||||
createRole.mutate(payload, {
|
||||
onSuccess: () => navigate('/settings/users/roles'),
|
||||
})
|
||||
onSuccess: () => navigate("/settings/users/roles"),
|
||||
});
|
||||
} else {
|
||||
updateRole.mutate(payload, {
|
||||
onSuccess: () => navigate('/settings/users/roles'),
|
||||
})
|
||||
onSuccess: () => navigate("/settings/users/roles"),
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('roles.createTitle', 'Rol dörediň')
|
||||
: t('roles.editTitle', 'Rol üýtgetmek')}
|
||||
{mode === "create" ? t("roles.createTitle", "Rol dörediň") : t("roles.editTitle", "Rol üýtgetmek")}
|
||||
</h1>
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden">
|
||||
|
||||
{/* Code */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start p-5 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('roles.fields.code', 'Kod')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.code}
|
||||
onChange={setField('code')}
|
||||
placeholder={t('roles.fields.code', 'Kod')}
|
||||
error={errors.code}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Name (multilingual) */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start p-5 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('roles.fields.name', 'Ady')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<MultiLangInput fields={nameFields} placeholder={t('roles.fields.name', 'Ady')} disabled={isPending} />
|
||||
</div>
|
||||
|
||||
{/* Guard name */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start p-5">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('roles.fields.guardName', 'Guard name')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<FormInput
|
||||
type="select"
|
||||
value={form.guard_name}
|
||||
onChange={setField('guard_name')}
|
||||
options={GUARD_OPTIONS}
|
||||
error={errors.guard_name}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("roles.fields.code", "Kod")}
|
||||
value={form.code}
|
||||
onChange={setField("code")}
|
||||
placeholder={t("roles.fields.code", "Kod")}
|
||||
error={errors.code}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("roles.fields.guardName", "Guard name")}
|
||||
value={form.guard_name}
|
||||
onChange={setField("guard_name")}
|
||||
options={GUARD_OPTIONS}
|
||||
error={errors.guard_name}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard span="full">
|
||||
<p className="text-sm font-semibold text-muted-foreground mb-1">
|
||||
{t("roles.fields.name", "Ady")}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</p>
|
||||
<MultiLangInput fields={nameFields} placeholder={t("roles.fields.name", "Ady")} disabled={isPending} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => navigate('/settings/users/roles')}
|
||||
loadingLabel={t('common.saving', 'Ýüklenýär...')}
|
||||
submitLabel={mode === 'create'
|
||||
? t('roles.actions.create', 'Rol dörediň')
|
||||
: t('roles.actions.save', 'Ýatda sakla')}
|
||||
className="px-5 py-4 border-t border-border bg-muted/20"
|
||||
onCancel={() => navigate("/settings/users/roles")}
|
||||
loadingLabel={t("common.saving", "Ýüklenýär...")}
|
||||
submitLabel={mode === "create" ? t("roles.actions.create", "Rol dörediň") : t("roles.actions.save", "Ýatda sakla")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,79 +1,67 @@
|
||||
import { useCallback, useEffect, useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import type { VisaMasterSetting } from '../api/visaMasterSberSettingsApi'
|
||||
import {
|
||||
useCreateVisaMasterSetting,
|
||||
useUpdateVisaMasterSetting,
|
||||
} from '../hooks/useVisaMasterSettings'
|
||||
import {
|
||||
createVisaMasterSettingFormSchema,
|
||||
DEFAULT_FORM_VALUES,
|
||||
buildPayload,
|
||||
} from '../schemas/visaMasterSberSetting.schema'
|
||||
import type { VisaMasterSettingFormData } from '../schemas/visaMasterSberSetting.schema'
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import type { VisaMasterSetting } from "../api/visaMasterSberSettingsApi";
|
||||
import { useCreateVisaMasterSetting, useUpdateVisaMasterSetting } from "../hooks/useVisaMasterSettings";
|
||||
import { createVisaMasterSettingFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/visaMasterSberSetting.schema";
|
||||
import type { VisaMasterSettingFormData } from "../schemas/visaMasterSberSetting.schema";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface VisaMasterSettingFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: VisaMasterSetting
|
||||
mode: "create" | "edit";
|
||||
initialData?: VisaMasterSetting;
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function mapInitial(data: VisaMasterSetting): VisaMasterSettingFormData {
|
||||
return {
|
||||
kod: data.kod,
|
||||
ady: data.ady,
|
||||
kod: data.kod,
|
||||
ady: data.ady,
|
||||
yazgy: data.yazgy,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
type FlatErrors = Partial<Record<keyof VisaMasterSettingFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof VisaMasterSettingFormData, string>>;
|
||||
|
||||
function flattenErrors(
|
||||
errors: Record<string, { message?: string } | undefined>
|
||||
): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
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 VisaMasterSettingFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof VisaMasterSettingFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── VisaMasterSettingForm ────────────────────────────────────────────────────
|
||||
|
||||
export function VisaMasterSettingForm({
|
||||
mode,
|
||||
initialData,
|
||||
}: VisaMasterSettingFormProps) {
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
export function VisaMasterSettingForm({ mode, initialData }: VisaMasterSettingFormProps) {
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t, i18n.language],
|
||||
)
|
||||
);
|
||||
|
||||
const errMsg = (msg: string | undefined) =>
|
||||
!msg ? undefined : msg.startsWith('validation.') ? t(msg, msg) : msg
|
||||
const navigate = useNavigate()
|
||||
const errMsg = (msg: string | undefined) => (!msg ? undefined : msg.startsWith("validation.") ? t(msg, msg) : msg);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateVisaMasterSetting()
|
||||
const updateMutation = useUpdateVisaMasterSetting(initialData?.id ?? 0)
|
||||
const createMutation = useCreateVisaMasterSetting();
|
||||
const updateMutation = useUpdateVisaMasterSetting(initialData?.id ?? 0);
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const schema = useMemo(
|
||||
() => createVisaMasterSettingFormSchema(t),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[i18n.language],
|
||||
)
|
||||
);
|
||||
|
||||
const {
|
||||
watch,
|
||||
@@ -84,122 +72,108 @@ export function VisaMasterSettingForm({
|
||||
getValues,
|
||||
} = useForm<VisaMasterSettingFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
});
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(
|
||||
() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>),
|
||||
[rhfErrors],
|
||||
)
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) {
|
||||
trigger()
|
||||
trigger();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
}, [i18n.language]);
|
||||
|
||||
const set = useCallback(
|
||||
(key: keyof VisaMasterSettingFormData) => (value: string) => {
|
||||
setValue(key, value)
|
||||
clearErrors(key)
|
||||
setValue(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
)
|
||||
);
|
||||
|
||||
const handleSubmit = useCallback(async () => {
|
||||
const isValid = await trigger()
|
||||
const isValid = await trigger();
|
||||
if (!isValid) {
|
||||
toast.error(t('common.errors.fillRequiredCorrectly', 'Dogry maglumat girizmegiňizi haýyş edýäris.'))
|
||||
return
|
||||
toast.error(t("common.errors.fillRequiredCorrectly", "Dogry maglumat girizmegiňizi haýyş edýäris."));
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = buildPayload(getValues())
|
||||
const payload = buildPayload(getValues());
|
||||
|
||||
if (mode === 'create') {
|
||||
await createMutation.mutateAsync(payload)
|
||||
navigate('/resources/visa-master-settings')
|
||||
if (mode === "create") {
|
||||
await createMutation.mutateAsync(payload);
|
||||
navigate("/resources/visa-master-settings");
|
||||
} else {
|
||||
await updateMutation.mutateAsync(payload)
|
||||
navigate('/resources/visa-master-settings')
|
||||
await updateMutation.mutateAsync(payload);
|
||||
navigate("/resources/visa-master-settings");
|
||||
}
|
||||
}, [mode, createMutation, updateMutation, navigate, trigger, getValues, t])
|
||||
}, [mode, createMutation, updateMutation, navigate, trigger, getValues, t]);
|
||||
|
||||
const handleCancel = () => navigate('/resources/visa-master-settings')
|
||||
const handleCancel = () => navigate("/resources/visa-master-settings");
|
||||
|
||||
// ─── Render ───────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('visaMasterSettings.createTitle', 'Visa/Master, Sber sazlamalar dörediň')
|
||||
: t('visaMasterSettings.editTitle', 'Visa/Master, Sber sazlamalar üýtgetmek')}
|
||||
{mode === "create"
|
||||
? t("visaMasterSettings.createTitle", "Visa/Master, Sber sazlamalar dörediň")
|
||||
: t("visaMasterSettings.editTitle", "Visa/Master, Sber sazlamalar üýtgetmek")}
|
||||
</h1>
|
||||
<div className="space-y-0 bg-card border border-border rounded-xl overflow-hidden">
|
||||
{/* Kod */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
|
||||
<label className="text-sm text-muted-foreground pt-1.5">
|
||||
{t('visaMasterSettings.fields.kod', 'Kod')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</label>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.kod}
|
||||
onChange={set('kod')}
|
||||
placeholder={t('visaMasterSettings.fields.kod', 'Kod')}
|
||||
error={errMsg(errors.kod)}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Ady */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
|
||||
<label className="text-sm text-muted-foreground pt-1.5">
|
||||
{t('visaMasterSettings.fields.ady', 'Ady')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</label>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.ady}
|
||||
onChange={set('ady')}
|
||||
placeholder={t('visaMasterSettings.fields.ady', 'Ady')}
|
||||
error={errMsg(errors.ady)}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Yazgy */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6">
|
||||
<label className="text-sm text-muted-foreground pt-1.5">
|
||||
{t('visaMasterSettings.fields.yazgy', 'Yazgy')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</label>
|
||||
<FormInput
|
||||
type="textarea"
|
||||
value={form.yazgy}
|
||||
onChange={set('yazgy')}
|
||||
placeholder={t('visaMasterSettings.fields.yazgy', 'Yazgy')}
|
||||
error={errMsg(errors.yazgy)}
|
||||
disabled={isPending}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={handleCancel}
|
||||
cancelVariant="ghost"
|
||||
submitLabel={mode === 'create'
|
||||
? t('visaMasterSettings.actions.create', 'Visa/Master, Sber sazlamalar dörediň')
|
||||
: t('visaMasterSettings.actions.update', 'Ýatda sakla')}
|
||||
className="px-6 py-4 border-t border-border"
|
||||
/>
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("visaMasterSettings.fields.kod", "Kod")}
|
||||
value={form.kod}
|
||||
onChange={set("kod")}
|
||||
placeholder={t("visaMasterSettings.fields.kod", "Kod")}
|
||||
error={errMsg(errors.kod)}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("visaMasterSettings.fields.ady", "Ady")}
|
||||
value={form.ady}
|
||||
onChange={set("ady")}
|
||||
placeholder={t("visaMasterSettings.fields.ady", "Ady")}
|
||||
error={errMsg(errors.ady)}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="textarea"
|
||||
label={t("visaMasterSettings.fields.yazgy", "Yazgy")}
|
||||
value={form.yazgy}
|
||||
onChange={set("yazgy")}
|
||||
placeholder={t("visaMasterSettings.fields.yazgy", "Yazgy")}
|
||||
error={errMsg(errors.yazgy)}
|
||||
disabled={isPending}
|
||||
rows={3}
|
||||
required
|
||||
/>
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={handleCancel}
|
||||
cancelVariant="ghost"
|
||||
submitLabel={
|
||||
mode === "create"
|
||||
? t("visaMasterSettings.actions.create", "Visa/Master, Sber sazlamalar dörediň")
|
||||
: t("visaMasterSettings.actions.update", "Ýatda sakla")
|
||||
}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user