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