diff --git a/src/components/bento.tsx b/src/components/bento.tsx index 62697d6..eefc1df 100644 --- a/src/components/bento.tsx +++ b/src/components/bento.tsx @@ -1,40 +1,33 @@ -import type { ReactNode } from 'react' +import type { ReactNode } from "react"; interface BentoGridProps { - cols?: 1 | 2 | 3 | 4 - children: ReactNode + cols?: 1 | 2 | 3 | 4; + children: ReactNode; } export function BentoGrid({ cols = 2, children }: BentoGridProps) { const colClass = { - 1: 'grid-cols-1', - 2: 'grid-cols-1 sm:grid-cols-2', - 3: 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-3', - 4: 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-4', - }[cols] - return
{children}
+ 1: "grid-cols-1", + 2: "grid-cols-1 sm:grid-cols-2", + 3: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3", + 4: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-4", + }[cols]; + return
{children}
; } interface BentoCardProps { - title?: string - span?: 'full' | 2 | 3 - children: ReactNode + title?: string; + span?: "full" | 2 | 3; + children: ReactNode; } export function BentoCard({ title, span, children }: BentoCardProps) { - const spanClass = - span === 'full' ? 'sm:col-span-full' : - span === 2 ? 'sm:col-span-2' : - span === 3 ? 'sm:col-span-3' : '' + const spanClass = span === "full" ? "sm:col-span-full" : span === 2 ? "sm:col-span-2" : span === 3 ? "sm:col-span-3" : ""; return ( -
- {title && ( -

- {title} -

- )} +
+ {title &&

{title}

} {children}
- ) + ); } diff --git a/src/features/allUsers/components/allUsersForm.tsx b/src/features/allUsers/components/allUsersForm.tsx index be9fc46..00ed4d7 100644 --- a/src/features/allUsers/components/allUsersForm.tsx +++ b/src/features/allUsers/components/allUsersForm.tsx @@ -1,98 +1,105 @@ -import { useMemo, useEffect, useCallback } from 'react' -import { useNavigate } from 'react-router-dom' -import { useTranslation } from 'react-i18next' -import { useForm } from 'react-hook-form' -import { zodResolver } from '@hookform/resolvers/zod' -import { FormInput } from '@/components/formInput' -import { Checkbox } from '@/components/ui/checkbox' -import { Label } from '@/components/ui/label' -import { FormActions } from '@/components/formActions' -import { useCreateUser, useUpdateUser } from '../hooks/useAllUsers' -import type { User } from '../api/allUsersApi' -import { allUserFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/allUser.schema' -import type { AllUserFormData } from '../schemas/allUser.schema' +import { useMemo, useEffect, useCallback } from "react"; +import { useNavigate } from "react-router-dom"; +import { useTranslation } from "react-i18next"; +import { useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { FormInput } from "@/components/formInput"; +import { Checkbox } from "@/components/ui/checkbox"; +import { Label } from "@/components/ui/label"; +import { FormActions } from "@/components/formActions"; +import { BentoGrid, BentoCard } from "@/components/bento"; +import { useCreateUser, useUpdateUser } from "../hooks/useAllUsers"; +import type { User } from "../api/allUsersApi"; +import { allUserFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/allUser.schema"; +import type { AllUserFormData } from "../schemas/allUser.schema"; // ─── Types ──────────────────────────────────────────────────────────────────── interface UserFormProps { - mode: 'create' | 'edit' - initialData?: User + mode: "create" | "edit"; + initialData?: User; } // ─── Helpers ────────────────────────────────────────────────────────────────── -type FlatErrors = Partial> +type FlatErrors = Partial>; function flattenErrors(errors: Record): FlatErrors { - const result: FlatErrors = {} + const result: FlatErrors = {}; for (const key of Object.keys(errors)) { - const msg = errors[key]?.message - if (msg) result[key as keyof AllUserFormData] = msg + const msg = errors[key]?.message; + if (msg) result[key as keyof AllUserFormData] = msg; } - return result + return result; } // ─── UserForm ───────────────────────────────────────────────────────────────── export function UserForm({ mode, initialData }: UserFormProps) { - const { t: _t, i18n } = useTranslation() + const { t: _t, i18n } = useTranslation(); const t: (key: string, fallback?: string) => string = useCallback( (key, fallback) => _t(key, fallback ?? key) as string, [_t, i18n.language], - ) - const navigate = useNavigate() + ); + const navigate = useNavigate(); - const createUser = useCreateUser() - const updateUser = useUpdateUser(initialData?.id ?? 0) + const createUser = useCreateUser(); + const updateUser = useUpdateUser(initialData?.id ?? 0); - const isPending = createUser.isPending || updateUser.isPending + const isPending = createUser.isPending || updateUser.isPending; - const schema = useMemo(() => allUserFormSchema(mode, t), [mode, t, i18n.language]) + const schema = useMemo(() => allUserFormSchema(mode, t), [mode, t, i18n.language]); const { - watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger, + watch, + setValue, + getValues, + formState: { errors: rhfErrors }, + clearErrors, + trigger, } = useForm({ + // eslint-disable-next-line @typescript-eslint/no-explicit-any resolver: zodResolver(schema as any), defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, username: initialData.username, name: initialData.name, - phone: initialData.phone.replace(/^\+993[-\s]?/, ''), - email: initialData.email ?? '', - password: '', + phone: initialData.phone.replace(/^\+993[-\s]?/, ""), + email: initialData.email ?? "", + password: "", phoneVerified: initialData.phoneVerified, isActive: initialData.isActive, } : DEFAULT_FORM_VALUES, - }) + }); - const form = watch() - const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]) + const form = watch(); + const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]); const setField = (key: K, value: AllUserFormData[K]) => { - (setValue as (name: K, val: AllUserFormData[K]) => void)(key, value) - clearErrors(key) - } + (setValue as (name: K, val: AllUserFormData[K]) => void)(key, value); + clearErrors(key); + }; // ── Re-validate on language change ── useEffect(() => { if (Object.keys(rhfErrors).length > 0) { - trigger() + trigger(); } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [i18n.language]) + }, [i18n.language]); const handleSubmit = async () => { - const isValid = await trigger() - if (!isValid) return + const isValid = await trigger(); + if (!isValid) return; - const data = getValues() + const data = getValues(); - if (mode === 'create') { - const payload = buildPayload(data) - await createUser.mutateAsync(payload) - navigate('/users') + if (mode === "create") { + const payload = buildPayload(data); + await createUser.mutateAsync(payload); + navigate("/users"); } else { await updateUser.mutateAsync({ username: data.username.trim(), @@ -101,188 +108,119 @@ export function UserForm({ mode, initialData }: UserFormProps) { email: data.email.trim() || undefined, phoneVerified: data.phoneVerified, isActive: data.isActive, - }) - navigate(`/users/${initialData!.id}`) + }); + navigate(`/users/${initialData!.id}`); } - } + }; return (

- {mode === 'create' - ? t('users.createTitle', 'Ulanyjy dörediň') - : t('users.editTitle', 'Ulanyjy üýtgetmek')} + {mode === "create" ? t("users.createTitle", "Ulanyjy dörediň") : t("users.editTitle", "Ulanyjy üýtgetmek")}

-
- {/* Form card */} -
- - {/* Username */} -
-
-

- {t('users.fields.username', 'Ulanyjy ady')} - * -

-

- {t('users.fields.usernameHint', 'Unikal login ady')} -

-
+ + setField('username', v)} - placeholder={t('users.fields.username', 'Ulanyjy ady')} + onChange={(v) => setField("username", v)} + placeholder={t("users.fields.username", "Ulanyjy ady")} error={errors.username} disabled={isPending} + required /> -
- - {/* Full name */} -
-
-

- {t('users.fields.name', 'Ady')} - * -

-

- {t('users.fields.nameHint', 'Doly ady we familiýasy')} -

-
+

{t("users.fields.usernameHint", "Unikal login ady")}

+ + setField('name', v)} - placeholder={t('users.fields.name', 'Ady')} + onChange={(v) => setField("name", v)} + placeholder={t("users.fields.name", "Ady")} error={errors.name} disabled={isPending} + required /> -
- - {/* Phone */} -
-
-

- {t('users.fields.phone', 'Telefon')} - * -

-

- {t('users.fields.phoneHint', '+993 bilen başlanýar')} -

-
+

{t("users.fields.nameHint", "Doly ady we familiýasy")}

+ + setField('phone', v)} + onChange={(v) => setField("phone", v)} placeholder="62-38-49-56" error={errors.phone} disabled={isPending} + required /> -
- - {/* Email */} -
-
-

- {t('users.fields.email', 'E-poçta')} -

-

- {t('users.fields.emailHint', 'Islege görä')} -

-
+

{t("users.fields.phoneHint", "+993 bilen başlanýar")}

+ + setField('email', v)} - placeholder={t('users.fields.email', 'E-poçta')} + onChange={(v) => setField("email", v)} + placeholder={t("users.fields.email", "E-poçta")} error={errors.email} disabled={isPending} /> -
- - {/* Password — only in create mode */} - {mode === 'create' && ( -
-
-

- {t('users.fields.password', 'Açar sözi')} - * -

-

- {t('users.fields.passwordHint', 'Iň az 6 harp')} -

-
+

{t("users.fields.emailHint", "Islege görä")}

+ + {mode === "create" && ( + setField('password', v)} - placeholder={t('users.fields.password', 'Açar sözi')} + onChange={(v) => setField("password", v)} + placeholder={t("users.fields.password", "Açar sözi")} error={errors.password} disabled={isPending} + required /> -
+

{t("users.fields.passwordHint", "Iň az 6 harp")}

+ )} - - {/* Phone verified */} -
-
-

- {t('users.fields.phoneVerified', 'Telefon tassyklanan')} -

-

- {t('users.fields.phoneVerifiedHint', 'SMS arkaly tassyklandy')} -

+ +
+

{t("users.fields.phoneVerified", "Telefon tassyklanan")}

+

{t("users.fields.phoneVerifiedHint", "SMS arkaly tassyklandy")}

setField('phoneVerified', !!v)} + onCheckedChange={(v) => setField("phoneVerified", !!v)} disabled={isPending} />
-
- - {/* Active */} -
-
-

- {t('users.fields.isActive', 'Işjeň')} -

-

- {t('users.fields.isActiveHint', 'Ulanyjynyň ulgama girip-bilmezligi')} -

+ + +
+

{t("users.fields.isActive", "Işjeň")}

+

{t("users.fields.isActiveHint", "Ulanyjynyň ulgama girip-bilmezligi")}

- setField('isActive', !!v)} - disabled={isPending} - /> + setField("isActive", !!v)} disabled={isPending} />
-
-
- + + navigate(-1)} - submitLabel={mode === 'create' - ? t('users.actions.create', 'Ulanyjy dörediň') - : t('users.actions.save', 'Ýatda sakla')} + submitLabel={mode === "create" ? t("users.actions.create", "Ulanyjy dörediň") : t("users.actions.save", "Ýatda sakla")} />
-
- ) + ); } diff --git a/src/features/cardReasons/components/reasonForm.tsx b/src/features/cardReasons/components/reasonForm.tsx index 2099d39..c85c8b9 100644 --- a/src/features/cardReasons/components/reasonForm.tsx +++ b/src/features/cardReasons/components/reasonForm.tsx @@ -1,36 +1,36 @@ -import { useCallback, useMemo, useEffect } from 'react' -import { useNavigate } from 'react-router-dom' -import { useTranslation } from 'react-i18next' -import { useForm } from 'react-hook-form' -import { zodResolver } from '@hookform/resolvers/zod' -import { Checkbox } from '@/components/ui/checkbox' -import { FormActions } from '@/components/formActions' -import { FormInput } from '@/components/formInput' -import { MultiLangInput } from '@/components/multiLangInput' -import type { CardReason } from '../api/cardReasonsApi' -import { useCreateCardReason, useUpdateCardReason } from '../hooks/useCardReasons' -import { createCardReasonFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardReason.schema' -import type { CardReasonFormData } from '../schemas/cardReason.schema' +import { useCallback, useMemo, useEffect } from "react"; +import { useNavigate } from "react-router-dom"; +import { useTranslation } from "react-i18next"; +import { useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { Checkbox } from "@/components/ui/checkbox"; +import { FormActions } from "@/components/formActions"; +import { FormInput } from "@/components/formInput"; +import { MultiLangInput } from "@/components/multiLangInput"; +import { BentoGrid, BentoCard } from "@/components/bento"; +import type { CardReason } from "../api/cardReasonsApi"; +import { useCreateCardReason, useUpdateCardReason } from "../hooks/useCardReasons"; +import { createCardReasonFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardReason.schema"; +import type { CardReasonFormData } from "../schemas/cardReason.schema"; // ─── Form errors helper ────────────────────────────────────────────────────── -type FlatErrors = Partial> +type FlatErrors = Partial>; function flattenErrors(errors: Record): FlatErrors { - const result: FlatErrors = {} + const result: FlatErrors = {}; for (const key of Object.keys(errors)) { - const msg = errors[key]?.message - if (msg) result[key as keyof CardReasonFormData] = msg + const msg = errors[key]?.message; + if (msg) result[key as keyof CardReasonFormData] = msg; } - return result + return result; } - // ─── CardReasonForm ───────────────────────────────────────────────────────────── interface CardReasonFormProps { - mode: 'create' | 'edit' - initialData?: CardReason + mode: "create" | "edit"; + initialData?: CardReason; } function mapInitial(data: CardReason): CardReasonFormData { @@ -39,142 +39,128 @@ function mapInitial(data: CardReason): CardReasonFormData { nameRu: data.name.ru, nameEn: data.name.en, value: String(data.value), - description: data.description ?? '', + description: data.description ?? "", isActive: data.isActive, - } + }; } export function CardReasonForm({ mode, initialData }: CardReasonFormProps) { - const { t: _t, i18n } = useTranslation() + const { t: _t, i18n } = useTranslation(); const t: (key: string, fallback?: string) => string = useCallback( (key, fallback) => _t(key, fallback ?? key) as string, [_t, i18n.language], - ) - const navigate = useNavigate() + ); + const navigate = useNavigate(); - const createMutation = useCreateCardReason() - const updateMutation = useUpdateCardReason() + const createMutation = useCreateCardReason(); + const updateMutation = useUpdateCardReason(); - const isPending = createMutation.isPending || updateMutation.isPending + const isPending = createMutation.isPending || updateMutation.isPending; - const schema = useMemo(() => createCardReasonFormSchema(t), [t, i18n.language]) + const schema = useMemo(() => createCardReasonFormSchema(t), [t, i18n.language]); const { - watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger, + watch, + setValue, + getValues, + formState: { errors: rhfErrors }, + clearErrors, + trigger, } = useForm({ resolver: zodResolver(schema), defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES, - }) + }); - const form = watch() - const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]) + const form = watch(); + const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]); - const set = useCallback((key: K, value: CardReasonFormData[K]) => { - (setValue as (name: K, val: CardReasonFormData[K]) => void)(key, value) - clearErrors(key) - }, [setValue, clearErrors]) + const set = useCallback( + (key: K, value: CardReasonFormData[K]) => { + (setValue as (name: K, val: CardReasonFormData[K]) => void)(key, value); + clearErrors(key); + }, + [setValue, clearErrors], + ); // ── Re-validate on language change ── useEffect(() => { - if (Object.keys(rhfErrors).length > 0) trigger() + if (Object.keys(rhfErrors).length > 0) trigger(); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [i18n.language]) + }, [i18n.language]); const handleSubmit = async () => { - const isValid = await trigger() - if (!isValid) return + const isValid = await trigger(); + if (!isValid) return; - const values = getValues() - const payload = buildPayload(values) + const values = getValues(); + const payload = buildPayload(values); - if (mode === 'create') { + if (mode === "create") { createMutation.mutate(payload, { - onSuccess: () => navigate('/resources/card-states'), - }) + onSuccess: () => navigate("/resources/card-states"), + }); } else if (initialData) { - updateMutation.mutate( - { id: initialData.id, ...payload }, - { onSuccess: () => navigate('/resources/card-states') } - ) + updateMutation.mutate({ id: initialData.id, ...payload }, { onSuccess: () => navigate("/resources/card-states") }); } - } + }; const nameFields = { - tk: { value: form.nameTk, onChange: (v: string) => set('nameTk', v), error: errors.nameTk }, - ru: { value: form.nameRu, onChange: (v: string) => set('nameRu', v), error: errors.nameRu }, - en: { value: form.nameEn, onChange: (v: string) => set('nameEn', v), error: errors.nameEn }, - } + tk: { value: form.nameTk, onChange: (v: string) => set("nameTk", v), error: errors.nameTk }, + ru: { value: form.nameRu, onChange: (v: string) => set("nameRu", v), error: errors.nameRu }, + en: { value: form.nameEn, onChange: (v: string) => set("nameEn", v), error: errors.nameEn }, + }; return (

- {mode === 'create' - ? t('cardReasons.createTitle', 'Sebäp dörediň') - : t('cardReasons.editTitle', 'Sebäp üýtgetmek')} + {mode === "create" ? t("cardReasons.createTitle", "Sebäp dörediň") : t("cardReasons.editTitle", "Sebäp üýtgetmek")}

-
- {/* Form rows */} -
- {/* Name row */} -
- - {t('cardReasons.fields.name', 'Ady')} + + +

+ {t("cardReasons.fields.name", "Ady")} * - - -

- - {/* Value row */} -
- - {t('cardReasons.fields.value', 'Baha')} - * - +

+ + + set('value', v)} - placeholder={t('cardReasons.fields.value', 'Baha')} + onChange={(v) => set("value", v)} + placeholder={t("cardReasons.fields.value", "Baha")} error={errors.value} + required /> -
- - {/* Description row */} -
- - {t('cardReasons.fields.description', 'Bellikler')} - + + set('description', v)} - placeholder={t('cardReasons.fields.description', 'Bellikler')} + onChange={(v) => set("description", v)} + placeholder={t("cardReasons.fields.description", "Bellikler")} /> -
- - {/* isActive row */} -
- - {t('cardReasons.fields.isActive', 'Işjeň')} - - set('isActive', !!checked)} - /> -
-
- + + +
+ {t("cardReasons.fields.isActive", "Işjeň")} + set("isActive", !!checked)} /> +
+
+ navigate('/resources/card-states')} + onCancel={() => navigate("/resources/card-states")} cancelVariant="ghost" - submitLabel={mode === 'create' - ? t('cardReasons.actions.create', 'Kartyň çykarylmagynyň sebäbini döretdiň') - : t('cardReasons.actions.update', 'Täzelemek')} - className="mt-6" + submitLabel={ + mode === "create" + ? t("cardReasons.actions.create", "Kartyň çykarylmagynyň sebäbini döretdiň") + : t("cardReasons.actions.update", "Täzelemek") + } />
-
- ) + ); } diff --git a/src/features/cardTransactions/components/cardTransactionForm.tsx b/src/features/cardTransactions/components/cardTransactionForm.tsx index 27a5517..6f2b83f 100644 --- a/src/features/cardTransactions/components/cardTransactionForm.tsx +++ b/src/features/cardTransactions/components/cardTransactionForm.tsx @@ -1,196 +1,197 @@ -import { useMemo } from 'react' -import { useForm } from 'react-hook-form' -import { useNavigate } from 'react-router-dom' -import { useTranslation } from 'react-i18next' -import { FormInput } from '@/components/formInput' -import { FormActions } from '@/components/formActions' -import type { CardTransaction } from '../api/cardTransactionsApi' -import { useCreateCardTransaction, useUpdateCardTransaction } from '../hooks/useCardTransactions' -import { cardTransactionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardTransaction.schema' -import type { CardTransactionFormData } from '../schemas/cardTransaction.schema' +import { useMemo } from "react"; +import { useForm } from "react-hook-form"; +import { useNavigate } from "react-router-dom"; +import { useTranslation } from "react-i18next"; +import { FormInput } from "@/components/formInput"; +import { FormActions } from "@/components/formActions"; +import { BentoGrid, BentoCard } from "@/components/bento"; +import type { CardTransaction } from "../api/cardTransactionsApi"; +import { useCreateCardTransaction, useUpdateCardTransaction } from "../hooks/useCardTransactions"; +import { cardTransactionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardTransaction.schema"; +import type { CardTransactionFormData } from "../schemas/cardTransaction.schema"; // ─── Types ──────────────────────────────────────────────────────────────────── interface CardTransactionFormProps { - mode: 'create' | 'edit' - initialData?: CardTransaction + mode: "create" | "edit"; + initialData?: CardTransaction; } // ─── Constants ──────────────────────────────────────────────────────────────── const PASSPORT_SERIES_OPTIONS = [ - { value: 'I-LB', label: 'I-LB' }, - { value: 'II-LB', label: 'II-LB' }, - { value: 'III-LB', label: 'III-LB' }, - { value: 'A', label: 'A' }, - { value: 'B', label: 'B' }, -] + { value: "I-LB", label: "I-LB" }, + { value: "II-LB", label: "II-LB" }, + { value: "III-LB", label: "III-LB" }, + { value: "A", label: "A" }, + { value: "B", label: "B" }, +]; const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => { - const val = String(i + 1).padStart(2, '0') - return { value: val, label: val } -}) + const val = String(i + 1).padStart(2, "0"); + return { value: val, label: val }; +}); const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => { - const year = String(new Date().getFullYear() + i) - return { value: year, label: year } -}) + const year = String(new Date().getFullYear() + i); + return { value: year, label: year }; +}); // ─── Form errors helper ─────────────────────────────────────────────────────── -type FlatErrors = Partial> +type FlatErrors = Partial>; function flattenErrors(errors: Record): FlatErrors { - const result: FlatErrors = {} + const result: FlatErrors = {}; for (const key of Object.keys(errors)) { - const msg = errors[key]?.message - if (msg) result[key as keyof CardTransactionFormData] = msg + const msg = errors[key]?.message; + if (msg) result[key as keyof CardTransactionFormData] = msg; } - return result + return result; } // ─── Component ──────────────────────────────────────────────────────────────── -export function CardTransactionForm({ - mode, - initialData, -}: CardTransactionFormProps) { - const { t } = useTranslation() - const navigate = useNavigate() +export function CardTransactionForm({ mode, initialData }: CardTransactionFormProps) { + const { t } = useTranslation(); + const navigate = useNavigate(); const { - watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, setError, + watch, + setValue, + getValues, + formState: { errors: rhfErrors }, + clearErrors, + setError, } = useForm({ - defaultValues: initialData - ? { ...DEFAULT_FORM_VALUES, ...initialData } - : DEFAULT_FORM_VALUES, - }) + defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...initialData } : DEFAULT_FORM_VALUES, + }); - const form = watch() - const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]) + const form = watch(); + const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]); - const createMutation = useCreateCardTransaction() - const updateMutation = useUpdateCardTransaction(initialData?.id ?? 0) + const createMutation = useCreateCardTransaction(); + const updateMutation = useUpdateCardTransaction(initialData?.id ?? 0); - const isPending = createMutation.isPending || updateMutation.isPending + const isPending = createMutation.isPending || updateMutation.isPending; const setField = (field: keyof CardTransactionFormData) => (value: string) => { - setValue(field, value) - clearErrors(field) - } + setValue(field, value); + clearErrors(field); + }; - const errMsg = (msg: string | undefined) => - !msg ? undefined : msg.startsWith('validation.') ? t(msg, msg) : msg + const errMsg = (msg: string | undefined) => (!msg ? undefined : msg.startsWith("validation.") ? t(msg, msg) : msg); const handleSubmit = async () => { - const result = cardTransactionFormSchema.safeParse(getValues()) + const result = cardTransactionFormSchema.safeParse(getValues()); if (!result.success) { for (const issue of result.error.issues) { - const key = issue.path[0] as keyof CardTransactionFormData - setError(key, { message: issue.message }) + const key = issue.path[0] as keyof CardTransactionFormData; + setError(key, { message: issue.message }); } - return + return; } - if (mode === 'create') { - await createMutation.mutateAsync(buildPayload(result.data)) - navigate('/card-transactions') + if (mode === "create") { + await createMutation.mutateAsync(buildPayload(result.data)); + navigate("/card-transactions"); } else { - await updateMutation.mutateAsync(buildPayload(result.data)) - navigate(`/card-transactions/${initialData!.id}`) + await updateMutation.mutateAsync(buildPayload(result.data)); + navigate(`/card-transactions/${initialData!.id}`); } - } + }; const handleCancel = () => { - if (mode === 'create') { - navigate('/card-transactions') + if (mode === "create") { + navigate("/card-transactions"); } else { - navigate(`/card-transactions/${initialData!.id}`) + navigate(`/card-transactions/${initialData!.id}`); } - } + }; return (

- {mode === 'create' - ? t('cardTransaction.createTitle', 'Kart herekedi dörediň') - : t('cardTransaction.editTitle', 'Kart herekedi üýtgetmek')} + {mode === "create" + ? t("cardTransaction.createTitle", "Kart herekedi dörediň") + : t("cardTransaction.editTitle", "Kart herekedi üýtgetmek")}

-
-
- {/* Passport Series */} - + + +
+ {/* Passport Series */} + - {/* Passport Number */} - + {/* Passport Number */} + - {/* Card Number */} - + {/* Card Number */} + - {/* Expiry Month + Year side by side */} -
- + + + +
+
+ + - - -
-
- - + +
-
- ) + ); } diff --git a/src/features/cardTypes/components/cardTypesForm.tsx b/src/features/cardTypes/components/cardTypesForm.tsx index 48f8a27..0a1549e 100644 --- a/src/features/cardTypes/components/cardTypesForm.tsx +++ b/src/features/cardTypes/components/cardTypesForm.tsx @@ -1,22 +1,23 @@ -import { useCallback, useMemo, useEffect } from 'react' -import { useNavigate } from 'react-router-dom' -import { useTranslation } from 'react-i18next' -import { useForm } from 'react-hook-form' -import { zodResolver } from '@hookform/resolvers/zod' -import { Checkbox } from '@/components/ui/checkbox' -import { FormActions } from '@/components/formActions' -import { FormInput } from '@/components/formInput' -import { MultiLangInput } from '@/components/multiLangInput' -import type { CardType } from '../api/cardTypesApi' -import { useCreateCardType, useUpdateCardType } from '../hooks/useCardTypes' -import { createCardTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardType.schema' -import type { CardTypeFormData } from '../schemas/cardType.schema' +import { useCallback, useMemo, useEffect } from "react"; +import { useNavigate } from "react-router-dom"; +import { useTranslation } from "react-i18next"; +import { useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { Checkbox } from "@/components/ui/checkbox"; +import { FormActions } from "@/components/formActions"; +import { FormInput } from "@/components/formInput"; +import { MultiLangInput } from "@/components/multiLangInput"; +import { BentoGrid, BentoCard } from "@/components/bento"; +import type { CardType } from "../api/cardTypesApi"; +import { useCreateCardType, useUpdateCardType } from "../hooks/useCardTypes"; +import { createCardTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardType.schema"; +import type { CardTypeFormData } from "../schemas/cardType.schema"; // ─── Types ──────────────────────────────────────────────────────────────────── export interface CardTypeFormProps { - mode: 'create' | 'edit' - initialData?: CardType + mode: "create" | "edit"; + initialData?: CardType; } // ─── Helpers ────────────────────────────────────────────────────────────────── @@ -27,38 +28,38 @@ function mapInitial(data: CardType): CardTypeFormData { nameRu: data.name.ru, nameEn: data.name.en, value: String(data.value), - description: data.description ?? '', + description: data.description ?? "", isActive: data.isActive, - } + }; } -type FlatErrors = Partial> +type FlatErrors = Partial>; function flattenErrors(errors: Record): FlatErrors { - const result: FlatErrors = {} + const result: FlatErrors = {}; for (const key of Object.keys(errors)) { - const msg = errors[key]?.message - if (msg) result[key as keyof CardTypeFormData] = msg + const msg = errors[key]?.message; + if (msg) result[key as keyof CardTypeFormData] = msg; } - return result + return result; } // ─── CardTypeForm ───────────────────────────────────────────────────────────── export function CardTypeForm({ mode, initialData }: CardTypeFormProps) { - const { t: _t, i18n } = useTranslation() + const { t: _t, i18n } = useTranslation(); const t: (key: string, fallback?: string) => string = useCallback( (key, fallback) => _t(key, fallback ?? key) as string, [_t, i18n.language], - ) - const navigate = useNavigate() + ); + const navigate = useNavigate(); - const createMutation = useCreateCardType() - const updateMutation = useUpdateCardType() + const createMutation = useCreateCardType(); + const updateMutation = useUpdateCardType(); - const isPending = createMutation.isPending || updateMutation.isPending + const isPending = createMutation.isPending || updateMutation.isPending; - const schema = useMemo(() => createCardTypeFormSchema(t), [t, i18n.language]) + const schema = useMemo(() => createCardTypeFormSchema(t), [t, i18n.language]); const { watch, @@ -69,124 +70,95 @@ export function CardTypeForm({ mode, initialData }: CardTypeFormProps) { getValues, } = useForm({ resolver: zodResolver(schema), - defaultValues: initialData - ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } - : DEFAULT_FORM_VALUES, - }) + defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES, + }); - const form = watch() - const errors = useMemo( - () => flattenErrors(rhfErrors as Record), - [rhfErrors], - ) + const form = watch(); + const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]); const set = useCallback( (key: keyof CardTypeFormData) => (value: string | boolean) => { - (setValue as (k: keyof CardTypeFormData, v: string | boolean) => void)(key, value) - clearErrors(key) + (setValue as (k: keyof CardTypeFormData, v: string | boolean) => void)(key, value); + clearErrors(key); }, [setValue, clearErrors], - ) + ); // ── Re-validate on language change ── useEffect(() => { - if (Object.keys(rhfErrors).length > 0) trigger() + if (Object.keys(rhfErrors).length > 0) trigger(); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [i18n.language]) + }, [i18n.language]); const handleSubmit = useCallback(async () => { - const isValid = await trigger() - if (!isValid) return + const isValid = await trigger(); + if (!isValid) return; - const payload = buildPayload(getValues()) + const payload = buildPayload(getValues()); - if (mode === 'create') { + if (mode === "create") { createMutation.mutate(payload, { - onSuccess: () => navigate('/settings/card/card-types'), - }) + onSuccess: () => navigate("/settings/card/card-types"), + }); } else if (initialData) { - updateMutation.mutate( - { id: initialData.id, ...payload }, - { onSuccess: () => navigate('/settings/card/card-types') }, - ) + updateMutation.mutate({ id: initialData.id, ...payload }, { onSuccess: () => navigate("/settings/card/card-types") }); } - }, [mode, initialData, createMutation, updateMutation, navigate, trigger, getValues]) + }, [mode, initialData, createMutation, updateMutation, navigate, trigger, getValues]); const nameFields = { - tk: { value: form.nameTk, onChange: (v: string) => set('nameTk')(v), error: errors.nameTk }, - ru: { value: form.nameRu, onChange: (v: string) => set('nameRu')(v), error: errors.nameRu }, - en: { value: form.nameEn, onChange: (v: string) => set('nameEn')(v), error: errors.nameEn }, - } + tk: { value: form.nameTk, onChange: (v: string) => set("nameTk")(v), error: errors.nameTk }, + ru: { value: form.nameRu, onChange: (v: string) => set("nameRu")(v), error: errors.nameRu }, + en: { value: form.nameEn, onChange: (v: string) => set("nameEn")(v), error: errors.nameEn }, + }; return (

- {mode === 'create' - ? t('cardTypes.createTitle', 'Kart görnüşi dörediň') - : t('cardTypes.editTitle', 'Kart görnüşi üýtgetmek')} + {mode === "create" ? t("cardTypes.createTitle", "Kart görnüşi dörediň") : t("cardTypes.editTitle", "Kart görnüşi üýtgetmek")}

-
- {/* Form rows */} -
- {/* Name */} -
- - {t('cardTypes.fields.name', 'Ady')} + + +

+ {t("cardTypes.fields.name", "Ady")} * - - -

- - {/* Value */} -
- - {t('cardTypes.fields.value', 'Baha')} - +

+ + + -
- - {/* Description */} -
- - {t('cardTypes.fields.description', 'Bellikler')} - + + -
- - {/* isActive */} -
- - {t('cardTypes.fields.isActive', 'Işjeň')} - - set('isActive')(!!checked)} - /> -
-
- + + +
+ {t("cardTypes.fields.isActive", "Işjeň")} + set("isActive")(!!checked)} /> +
+
+ navigate('/settings/card/card-types')} + onCancel={() => navigate("/settings/card/card-types")} cancelVariant="ghost" - submitLabel={mode === 'create' - ? t('cardTypes.actions.create', 'Kart görnüşi döretdiň') - : t('cardTypes.actions.update', 'Täzelemek')} - className="mt-6" + submitLabel={ + mode === "create" ? t("cardTypes.actions.create", "Kart görnüşi döretdiň") : t("cardTypes.actions.update", "Täzelemek") + } />
-
- ) + ); } diff --git a/src/features/clients/components/clientForm.tsx b/src/features/clients/components/clientForm.tsx index 94427fa..e27c2ce 100644 --- a/src/features/clients/components/clientForm.tsx +++ b/src/features/clients/components/clientForm.tsx @@ -1,237 +1,215 @@ -import { useMemo, useEffect, useCallback } from 'react' -import { useNavigate } from 'react-router-dom' -import { useTranslation } from 'react-i18next' -import { useForm } from 'react-hook-form' -import { zodResolver } from '@hookform/resolvers/zod' -import { Checkbox } from '@/components/ui/checkbox' -import { FormActions } from '@/components/formActions' -import { FormInput } from '@/components/formInput' -import { useCreateClient, useUpdateClient } from '../hooks/useClients' -import { clientFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/client.schema' -import type { ClientFormData } from '../schemas/client.schema' -import type { Client } from '../api/clientsApi' +import { useMemo, useEffect, useCallback } from "react"; +import { useNavigate } from "react-router-dom"; +import { useTranslation } from "react-i18next"; +import { useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { Checkbox } from "@/components/ui/checkbox"; +import { FormActions } from "@/components/formActions"; +import { FormInput } from "@/components/formInput"; +import { BentoGrid, BentoCard } from "@/components/bento"; +import { useCreateClient, useUpdateClient } from "../hooks/useClients"; +import { clientFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/client.schema"; +import type { ClientFormData } from "../schemas/client.schema"; +import type { Client } from "../api/clientsApi"; // ─── Types ──────────────────────────────────────────────────────────────────── interface ClientFormProps { - mode: 'create' | 'edit' - initialData?: Client + mode: "create" | "edit"; + initialData?: Client; } // ─── Helpers ────────────────────────────────────────────────────────────────── -type FlatErrors = Partial> +type FlatErrors = Partial>; function flattenErrors(errors: Record): FlatErrors { - const result: FlatErrors = {} + const result: FlatErrors = {}; for (const key of Object.keys(errors)) { - const msg = errors[key]?.message - if (msg) result[key as keyof ClientFormData] = msg + const msg = errors[key]?.message; + if (msg) result[key as keyof ClientFormData] = msg; } - return result + return result; } // ─── ClientForm ─────────────────────────────────────────────────────────────── export function ClientForm({ mode, initialData }: ClientFormProps) { - const { t: _t, i18n } = useTranslation() + const { t: _t, i18n } = useTranslation(); const t: (key: string, fallback?: string) => string = useCallback( (key, fallback) => _t(key, fallback ?? key) as string, [_t, i18n.language], - ) - const navigate = useNavigate() + ); + const navigate = useNavigate(); - const createMutation = useCreateClient() - const updateMutation = useUpdateClient(initialData?.id ?? 0) + const createMutation = useCreateClient(); + const updateMutation = useUpdateClient(initialData?.id ?? 0); - const isPending = createMutation.isPending || updateMutation.isPending + const isPending = createMutation.isPending || updateMutation.isPending; - const schema = useMemo(() => clientFormSchema(mode, t), [mode, t, i18n.language]) + const schema = useMemo(() => clientFormSchema(mode, t), [mode, t, i18n.language]); const { - watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger, + watch, + setValue, + getValues, + formState: { errors: rhfErrors }, + clearErrors, + trigger, } = useForm({ + // eslint-disable-next-line @typescript-eslint/no-explicit-any resolver: zodResolver(schema as any), defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, username: initialData.username, name: initialData.name, - phone: initialData.phone ?? '', - email: initialData.email ?? '', - password: '', + phone: initialData.phone ?? "", + email: initialData.email ?? "", + password: "", isActive: initialData.isActive, } : DEFAULT_FORM_VALUES, - }) + }); - const form = watch() - const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]) + const form = watch(); + const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]); const setField = (key: K, value: ClientFormData[K]) => { - ;(setValue as (name: K, val: ClientFormData[K]) => void)(key, value) - clearErrors(key) - } + (setValue as (name: K, val: ClientFormData[K]) => void)(key, value); + clearErrors(key); + }; // ── Re-validate on language change ── useEffect(() => { if (Object.keys(rhfErrors).length > 0) { - trigger() + trigger(); } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [i18n.language]) + }, [i18n.language]); // ── Submit ────────────────────────────────────────────────────────────────── const handleSubmit = async () => { - const isValid = await trigger() - if (!isValid) return + const isValid = await trigger(); + if (!isValid) return; - const data = getValues() + const data = getValues(); - if (mode === 'create') { - const payload = buildPayload(data) + if (mode === "create") { + const payload = buildPayload(data); createMutation.mutate(payload, { - onSuccess: () => navigate('/clients'), - }) + onSuccess: () => navigate("/clients"), + }); } else { - updateMutation.mutate({ - username: data.username.trim(), - name: data.name.trim(), - phone: data.phone.trim(), - email: data.email.trim() || undefined, - isActive: data.isActive, - ...(data.password.trim() ? { password: data.password } : {}), - }, { - onSuccess: () => navigate(`/clients/${initialData!.id}`), - }) + updateMutation.mutate( + { + username: data.username.trim(), + name: data.name.trim(), + phone: data.phone.trim(), + email: data.email.trim() || undefined, + isActive: data.isActive, + ...(data.password.trim() ? { password: data.password } : {}), + }, + { + onSuccess: () => navigate(`/clients/${initialData!.id}`), + }, + ); } - } + }; // ── Render ────────────────────────────────────────────────────────────────── return (

- {mode === 'create' - ? t('clients.createTitle', 'Müşderi dörediň') - : t('clients.editTitle', 'Müşderi üýtgetmek')} + {mode === "create" ? t("clients.createTitle", "Müşderi dörediň") : t("clients.editTitle", "Müşderi üýtgetmek")}

-
- {/* Username */} -
- - {t('clients.fields.username', 'Ulanyjy ady')} - * - - setField('username', v)} - placeholder={t('clients.fields.username', 'Ulanyjy ady')} - error={errors.username} - disabled={isPending} - className="max-w-lg" - /> -
- - {/* Name */} -
- - {t('clients.fields.name', 'Ady')} - * - - setField('name', v)} - placeholder={t('clients.fields.name', 'Ady')} - error={errors.name} - disabled={isPending} - className="max-w-lg" - /> -
- - {/* Phone */} -
- - {t('clients.fields.phone', 'Telefon')} - * - - setField('phone', v)} - error={errors.phone} - disabled={isPending} - className="max-w-lg" - /> -
- - {/* Email */} -
- - {t('clients.fields.email', 'E-poçta')} - - setField('email', v)} - placeholder={t('clients.fields.email', 'E-poçta')} - disabled={isPending} - className="max-w-lg" - /> -
- - {/* Password */} -
- - {t('clients.fields.password', 'Açar sözi')} - {mode === 'create' && *} - -
+ + + setField("username", v)} + placeholder={t("clients.fields.username", "Ulanyjy ady")} + error={errors.username} + disabled={isPending} + required + /> + + + setField("name", v)} + placeholder={t("clients.fields.name", "Ady")} + error={errors.name} + disabled={isPending} + required + /> + + + setField("phone", v)} + error={errors.phone} + disabled={isPending} + required + /> + + + setField("email", v)} + placeholder={t("clients.fields.email", "E-poçta")} + disabled={isPending} + /> + + + + setField('password', v)} + onChange={(v) => setField("password", v)} placeholder={ - mode === 'edit' - ? t('clients.fields.passwordEditHint', 'Üýtgetmek üçin täze açar söz giriziň') - : t('clients.fields.password', 'Açar sözi') + mode === "edit" + ? t("clients.fields.passwordEditHint", "Üýtgetmek üçin täze açar söz giriziň") + : t("clients.fields.password", "Açar sözi") } error={errors.password} disabled={isPending} /> - {mode === 'edit' && ( -

- {t('clients.fields.passwordEditNote', 'Boş goýsaňyz, açar sözi üýtgemez')} + {mode === "edit" && ( +

+ {t("clients.fields.passwordEditNote", "Boş goýsaňyz, açar sözi üýtgemez")}

)} -
-
- - {/* isActive */} -
- - {t('clients.fields.isActive', 'Işjeň')} - - setField('isActive', !!v)} - disabled={isPending} - className="data-[state=checked]:bg-primary data-[state=checked]:border-primary" - /> -
- - navigate(-1)} - cancelVariant="ghost" - submitLabel={mode === 'create' - ? t('clients.createBtn', 'Müşderi döredin') - : t('clients.updateBtn', 'Üýtgetmeleri sakla')} - className="px-6 py-4 border-t border-border bg-muted/20" - /> + + +
+ {t("clients.fields.isActive", "Işjeň")} + setField("isActive", !!v)} + disabled={isPending} + className="data-[state=checked]:bg-primary data-[state=checked]:border-primary" + /> +
+ navigate(-1)} + cancelVariant="ghost" + submitLabel={mode === "create" ? t("clients.createBtn", "Müşderi döredin") : t("clients.updateBtn", "Üýtgetmeleri sakla")} + /> +
+
-
- ) -} \ No newline at end of file + ); +} diff --git a/src/features/currencyRates/components/currencyRatesForm.tsx b/src/features/currencyRates/components/currencyRatesForm.tsx index e0cb994..478d5cc 100644 --- a/src/features/currencyRates/components/currencyRatesForm.tsx +++ b/src/features/currencyRates/components/currencyRatesForm.tsx @@ -1,55 +1,51 @@ // features/currencyRates/components/CurrencyRateForm.tsx -import { useCallback, useMemo, useEffect } from 'react' -import { useNavigate } from 'react-router-dom' -import { useTranslation } from 'react-i18next' -import { useForm } from 'react-hook-form' -import { zodResolver } from '@hookform/resolvers/zod' -import { FormInput } from '@/components/formInput' -import { FormActions } from '@/components/formActions' -import { CURRENCY_OPTIONS, type CurrencyRate } from '../api/currencyRatesApi' -import { useCreateCurrencyRate, useUpdateCurrencyRate } from '../hooks/useCurrencyRates' -import { - createCurrencyRateFormSchema, - DEFAULT_FORM_VALUES, - buildPayload, - type CurrencyRateFormData, -} from '../schemas/currencyRate.schema' +import { useCallback, useMemo, useEffect } from "react"; +import { useNavigate } from "react-router-dom"; +import { useTranslation } from "react-i18next"; +import { useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { FormInput } from "@/components/formInput"; +import { FormActions } from "@/components/formActions"; +import { BentoGrid, BentoCard } from "@/components/bento"; +import { CURRENCY_OPTIONS, type CurrencyRate } from "../api/currencyRatesApi"; +import { useCreateCurrencyRate, useUpdateCurrencyRate } from "../hooks/useCurrencyRates"; +import { createCurrencyRateFormSchema, DEFAULT_FORM_VALUES, buildPayload, type CurrencyRateFormData } from "../schemas/currencyRate.schema"; // ─── Types ──────────────────────────────────────────────────────────────────── export interface CurrencyRateFormProps { - mode: 'create' | 'edit' - initialData?: CurrencyRate + mode: "create" | "edit"; + initialData?: CurrencyRate; } -type FlatErrors = Partial> +type FlatErrors = Partial>; function flattenErrors(errors: Record): FlatErrors { - const result: FlatErrors = {} + const result: FlatErrors = {}; for (const key of Object.keys(errors)) { - const msg = errors[key]?.message - if (msg) result[key as keyof CurrencyRateFormData] = msg + const msg = errors[key]?.message; + if (msg) result[key as keyof CurrencyRateFormData] = msg; } - return result + return result; } // ─── CurrencyRateForm ───────────────────────────────────────────────────────── export function CurrencyRateForm({ mode, initialData }: CurrencyRateFormProps) { - const { t: _t, i18n } = useTranslation() + const { t: _t, i18n } = useTranslation(); const t: (key: string, fallback?: string) => string = useCallback( (key, fallback) => _t(key, fallback ?? key) as string, [_t, i18n.language], - ) - const navigate = useNavigate() + ); + const navigate = useNavigate(); - const createMutation = useCreateCurrencyRate() - const updateMutation = useUpdateCurrencyRate(initialData?.id ?? 0) + const createMutation = useCreateCurrencyRate(); + const updateMutation = useUpdateCurrencyRate(initialData?.id ?? 0); - const isPending = createMutation.isPending || updateMutation.isPending + const isPending = createMutation.isPending || updateMutation.isPending; - const schema = useMemo(() => createCurrencyRateFormSchema(t), [t, i18n.language]) + const schema = useMemo(() => createCurrencyRateFormSchema(t), [t, i18n.language]); const { watch, @@ -63,136 +59,118 @@ export function CurrencyRateForm({ mode, initialData }: CurrencyRateFormProps) { defaultValues: initialData ? { currencyFrom: initialData.currencyFrom, - currencyTo: initialData.currencyTo, - value: String(initialData.value), + currencyTo: initialData.currencyTo, + value: String(initialData.value), } : DEFAULT_FORM_VALUES, - }) + }); - const form = watch() - const errors = useMemo( - () => flattenErrors(rhfErrors as Record), - [rhfErrors], - ) + const form = watch(); + const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]); // ── Re-validate on language change ── useEffect(() => { if (Object.keys(rhfErrors).length > 0) { - trigger() + trigger(); } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [i18n.language]) + }, [i18n.language]); const setField = useCallback( (key: keyof CurrencyRateFormData) => (value: string) => { - setValue(key, value) - clearErrors(key) + setValue(key, value); + clearErrors(key); }, [setValue, clearErrors], - ) + ); const handleSubmit = async () => { - const isValid = await trigger() - if (!isValid) return + const isValid = await trigger(); + if (!isValid) return; - const payload = buildPayload(getValues()) + const payload = buildPayload(getValues()); - if (mode === 'create') { - await createMutation.mutateAsync(payload) - navigate('/resources/currency-rates') + if (mode === "create") { + await createMutation.mutateAsync(payload); + navigate("/resources/currency-rates"); } else { - await updateMutation.mutateAsync(payload) - navigate(`/resources/currency-rates/${initialData!.id}`) + await updateMutation.mutateAsync(payload); + navigate(`/resources/currency-rates/${initialData!.id}`); } - } + }; const handleCancel = () => { - if (mode === 'create') { - navigate('/resources/currency-rates') + if (mode === "create") { + navigate("/resources/currency-rates"); } else { - navigate(`/resources/currency-rates/${initialData!.id}`) + navigate(`/resources/currency-rates/${initialData!.id}`); } - } + }; return (

- {mode === 'create' - ? t('currencyRates.createTitle', 'Walýuta kursy dörediň') - : t('currencyRates.editTitle', 'Walýuta kursy üýtgetmek')} + {mode === "create" + ? t("currencyRates.createTitle", "Walýuta kursy dörediň") + : t("currencyRates.editTitle", "Walýuta kursy üýtgetmek")}

-
- {/* Currency From */} -
- -
+ + -

- {t('currencyRates.hints.oneUnit', '1 möçberi')} -

-
-
- - {/* Currency To */} -
- - -
- - {/* Value */} -
- -
+

{t("currencyRates.hints.oneUnit", "1 möçberi")}

+ + + + + + + -

- {t('currencyRates.hints.decimalNote', 'Bitin däl sanlary "." bilen ýazmaly')} +

+ {t("currencyRates.hints.decimalNote", 'Bitin däl sanlary "." bilen ýazmaly')}

-
-
- - + + +
-
- ) -} \ No newline at end of file + ); +} diff --git a/src/features/districts/components/districtsForm.tsx b/src/features/districts/components/districtsForm.tsx index 1ffaad5..b30dc67 100644 --- a/src/features/districts/components/districtsForm.tsx +++ b/src/features/districts/components/districtsForm.tsx @@ -1,31 +1,32 @@ -import { useCallback, useMemo, useEffect } from 'react' -import { useNavigate } from 'react-router-dom' -import { useTranslation } from 'react-i18next' -import { useForm } from 'react-hook-form' -import { zodResolver } from '@hookform/resolvers/zod' -import { Checkbox } from '@/components/ui/checkbox' -import { FormActions } from '@/components/formActions' -import { FormInput } from '@/components/formInput' -import { MultiLangInput } from '@/components/multiLangInput' -import type { District } from '../api/districtsApi' -import { useCreateDistrict, useUpdateDistrict } from '../hooks/useDistricts' -import { createDistrictFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/district.schema' -import type { DistrictFormData } from '../schemas/district.schema' +import { useCallback, useMemo, useEffect } from "react"; +import { useNavigate } from "react-router-dom"; +import { useTranslation } from "react-i18next"; +import { useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { Checkbox } from "@/components/ui/checkbox"; +import { FormActions } from "@/components/formActions"; +import { FormInput } from "@/components/formInput"; +import { MultiLangInput } from "@/components/multiLangInput"; +import { BentoGrid, BentoCard } from "@/components/bento"; +import type { District } from "../api/districtsApi"; +import { useCreateDistrict, useUpdateDistrict } from "../hooks/useDistricts"; +import { createDistrictFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/district.schema"; +import type { DistrictFormData } from "../schemas/district.schema"; -type FlatErrors = Partial> +type FlatErrors = Partial>; function flattenErrors(errors: Record): FlatErrors { - const result: FlatErrors = {} + const result: FlatErrors = {}; for (const key of Object.keys(errors)) { - const msg = errors[key]?.message - if (msg) result[key as keyof DistrictFormData] = msg + const msg = errors[key]?.message; + if (msg) result[key as keyof DistrictFormData] = msg; } - return result + return result; } export interface DistrictFormProps { - mode: 'create' | 'edit' - initialData?: District + mode: "create" | "edit"; + initialData?: District; } function mapInitial(data: District): DistrictFormData { @@ -33,123 +34,113 @@ function mapInitial(data: District): DistrictFormData { nameTk: data.name.tk, nameRu: data.name.ru, nameEn: data.name.en, - description: data.description ?? '', + description: data.description ?? "", isActive: data.isActive, - } + }; } export function DistrictForm({ mode, initialData }: DistrictFormProps) { - const { t: _t, i18n } = useTranslation() + const { t: _t, i18n } = useTranslation(); const t: (key: string, fallback?: string) => string = useCallback( (key, fallback) => _t(key, fallback ?? key) as string, [_t, i18n.language], - ) - const navigate = useNavigate() + ); + const navigate = useNavigate(); - const createMutation = useCreateDistrict() - const updateMutation = useUpdateDistrict() + const createMutation = useCreateDistrict(); + const updateMutation = useUpdateDistrict(); - const isPending = createMutation.isPending || updateMutation.isPending + const isPending = createMutation.isPending || updateMutation.isPending; - const schema = useMemo(() => createDistrictFormSchema(t), [t, i18n.language]) + const schema = useMemo(() => createDistrictFormSchema(t), [t, i18n.language]); const { - watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger, + watch, + setValue, + getValues, + formState: { errors: rhfErrors }, + clearErrors, + trigger, } = useForm({ resolver: zodResolver(schema), defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES, - }) + }); - const form = watch() - const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]) + const form = watch(); + const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]); - const set = useCallback((key: K) => - (value: DistrictFormData[K]) => { - (setValue as (name: K, val: DistrictFormData[K]) => void)(key, value) - clearErrors(key) - }, [setValue, clearErrors]) + const set = useCallback( + (key: K) => + (value: DistrictFormData[K]) => { + (setValue as (name: K, val: DistrictFormData[K]) => void)(key, value); + clearErrors(key); + }, + [setValue, clearErrors], + ); // ── Re-validate on language change ── useEffect(() => { - if (Object.keys(rhfErrors).length > 0) trigger() + if (Object.keys(rhfErrors).length > 0) trigger(); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [i18n.language]) + }, [i18n.language]); const handleSubmit = async () => { - const isValid = await trigger() - if (!isValid) return + const isValid = await trigger(); + if (!isValid) return; - const payload = buildPayload(getValues()) + const payload = buildPayload(getValues()); - if (mode === 'create') { + if (mode === "create") { createMutation.mutate(payload, { - onSuccess: () => navigate('/settings/location/districts'), - }) + onSuccess: () => navigate("/settings/location/districts"), + }); } else if (initialData) { - updateMutation.mutate( - { id: initialData.id, ...payload }, - { onSuccess: () => navigate('/settings/location/districts') }, - ) + updateMutation.mutate({ id: initialData.id, ...payload }, { onSuccess: () => navigate("/settings/location/districts") }); } - } + }; const nameFields = { - tk: { value: form.nameTk, onChange: set('nameTk'), error: errors.nameTk }, - ru: { value: form.nameRu, onChange: set('nameRu'), error: errors.nameRu }, - en: { value: form.nameEn, onChange: set('nameEn'), error: errors.nameEn }, - } + tk: { value: form.nameTk, onChange: set("nameTk"), error: errors.nameTk }, + ru: { value: form.nameRu, onChange: set("nameRu"), error: errors.nameRu }, + en: { value: form.nameEn, onChange: set("nameEn"), error: errors.nameEn }, + }; return (

- {mode === 'create' - ? t('districts.createTitle', 'Etrap dörediň') - : t('districts.editTitle', 'Etrap üýtgetmek')} + {mode === "create" ? t("districts.createTitle", "Etrap dörediň") : t("districts.editTitle", "Etrap üýtgetmek")}

-
-
-
- - {t('districts.fields.name', 'Ady')} + + +

+ {t("districts.fields.name", "Ady")} * - - -

- -
- - {t('districts.fields.description', 'Bellikler')} - +

+ + + -
- -
- - {t('districts.fields.isActive', 'Işjeň')} - - set('isActive')(!!checked)} - /> -
-
- + + +
+ {t("districts.fields.isActive", "Işjeň")} + set("isActive")(!!checked)} /> +
+
+ navigate('/settings/location/districts')} + onCancel={() => navigate("/settings/location/districts")} cancelVariant="ghost" - submitLabel={mode === 'create' - ? t('districts.actions.create', 'Etrap döret') - : t('districts.actions.update', 'Täzelemek')} - className="mt-6" + submitLabel={mode === "create" ? t("districts.actions.create", "Etrap döret") : t("districts.actions.update", "Täzelemek")} />
-
- ) + ); } diff --git a/src/features/loanPaidOffLetters/components/LoanPaidOffLetterForm.tsx b/src/features/loanPaidOffLetters/components/LoanPaidOffLetterForm.tsx index cc99b5d..634961f 100644 --- a/src/features/loanPaidOffLetters/components/LoanPaidOffLetterForm.tsx +++ b/src/features/loanPaidOffLetters/components/LoanPaidOffLetterForm.tsx @@ -1,41 +1,36 @@ -import { useEffect } from 'react' -import { useTranslation } from 'react-i18next' -import { useNavigate } from 'react-router-dom' -import { toast } from 'sonner' -import { useForm } from 'react-hook-form' -import { zodResolver } from '@hookform/resolvers/zod' +import { useEffect } from "react"; +import { useTranslation } from "react-i18next"; +import { useNavigate } from "react-router-dom"; +import { toast } from "sonner"; +import { useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; -import { FormInput } from '@/components/formInput' -import { FormActions } from '@/components/formActions' +import { FormInput } from "@/components/formInput"; +import { FormActions } from "@/components/formActions"; +import { BentoGrid, BentoCard } from "@/components/bento"; -import { - useCreateLoanPaidOffLetter, - useUpdateLoanPaidOffLetter, -} from '../hooks/useLoanPaidOffLetters' -import type { LoanPaidOffLetter } from '../api/loanPaidOffLettersApi' +import { useCreateLoanPaidOffLetter, useUpdateLoanPaidOffLetter } from "../hooks/useLoanPaidOffLetters"; +import type { LoanPaidOffLetter } from "../api/loanPaidOffLettersApi"; import { loanPaidOffLetterFormSchema, type LoanPaidOffLetterFormData, DEFAULT_FORM_VALUES, buildPayload, -} from '../schemas/loanPaidOffLetter.schema' +} from "../schemas/loanPaidOffLetter.schema"; interface LoanPaidOffLetterFormProps { - mode: 'create' | 'edit' - initialData?: LoanPaidOffLetter + mode: "create" | "edit"; + initialData?: LoanPaidOffLetter; } -export function LoanPaidOffLetterForm({ - mode, - initialData, -}: LoanPaidOffLetterFormProps) { - const { t } = useTranslation() - const navigate = useNavigate() +export function LoanPaidOffLetterForm({ mode, initialData }: LoanPaidOffLetterFormProps) { + const { t } = useTranslation(); + const navigate = useNavigate(); - const createMutation = useCreateLoanPaidOffLetter() - const updateMutation = useUpdateLoanPaidOffLetter(initialData?.id ?? 0) + const createMutation = useCreateLoanPaidOffLetter(); + const updateMutation = useUpdateLoanPaidOffLetter(initialData?.id ?? 0); - const isPending = createMutation.isPending || updateMutation.isPending + const isPending = createMutation.isPending || updateMutation.isPending; const { handleSubmit, @@ -46,104 +41,103 @@ export function LoanPaidOffLetterForm({ } = useForm({ resolver: zodResolver(loanPaidOffLetterFormSchema), defaultValues: DEFAULT_FORM_VALUES, - mode: 'onSubmit', - }) + mode: "onSubmit", + }); useEffect(() => { - if (mode === 'edit' && initialData) { + if (mode === "edit" && initialData) { reset({ passportSeries: initialData.passportSeries, passportNumber: initialData.passportNumber, loanAccount: initialData.loanAccount, issuedAt: initialData.issuedAt, - }) + }); } - }, [mode, initialData, reset]) + }, [mode, initialData, reset]); const onSubmit = (data: LoanPaidOffLetterFormData) => { - const payload = buildPayload(data) + const payload = buildPayload(data); - if (mode === 'create') { + if (mode === "create") { createMutation.mutate(payload, { onSuccess: () => { - toast.success(t('common.success.create', 'Üstünlikli döredildi')) - navigate('/loan-paid-off-letters') + toast.success(t("common.success.create", "Üstünlikli döredildi")); + navigate("/loan-paid-off-letters"); }, - }) + }); } else { updateMutation.mutate(payload, { onSuccess: () => { - toast.success(t('common.success.save', 'Üstünlikli ýatda saklandy')) - navigate('/loan-paid-off-letters') + toast.success(t("common.success.save", "Üstünlikli ýatda saklandy")); + navigate("/loan-paid-off-letters"); }, - }) + }); } - } + }; - const errMsg = (msg: string | undefined) => - msg?.startsWith('validation.') ? t(msg, msg) : msg + const errMsg = (msg: string | undefined) => (msg?.startsWith("validation.") ? t(msg, msg) : msg); const onError = () => { - toast.error(t('common.errors.fillRequired', 'Hökman doldurylmaly öýjükleri dolduryň')) - } + toast.error(t("common.errors.fillRequired", "Hökman doldurylmaly öýjükleri dolduryň")); + }; return (

- {mode === 'create' - ? t('loanPaidOffLetters.createTitle', 'Karzyň ýapylandygy barada güwanama almak dörediň') - : t('loanPaidOffLetters.editTitle', 'Karzyň ýapylandygy barada güwanama almak üýtgetmek')} + {mode === "create" + ? t("loanPaidOffLetters.createTitle", "Karzyň ýapylandygy barada güwanama almak dörediň") + : t("loanPaidOffLetters.editTitle", "Karzyň ýapylandygy barada güwanama almak üýtgetmek")}

-
-
- setValue('passportSeries', v)} - placeholder={t('loanPaidOffLetters.placeholders.passportSeries', 'TM')} - error={errMsg(errors.passportSeries?.message)} - /> + + +
+ setValue("passportSeries", v)} + placeholder={t("loanPaidOffLetters.placeholders.passportSeries", "TM")} + error={errMsg(errors.passportSeries?.message)} + /> - setValue('passportNumber', v)} - placeholder="A123456" - error={errMsg(errors.passportNumber?.message)} - /> + setValue("passportNumber", v)} + placeholder="A123456" + error={errMsg(errors.passportNumber?.message)} + /> - setValue('loanAccount', v)} - placeholder="LOAN-..." - error={errMsg(errors.loanAccount?.message)} - /> + setValue("loanAccount", v)} + placeholder="LOAN-..." + error={errMsg(errors.loanAccount?.message)} + /> - setValue('issuedAt', v)} - error={errMsg(errors.issuedAt?.message)} - /> -
-
+ setValue("issuedAt", v)} + error={errMsg(errors.issuedAt?.message)} + /> +
+ + - navigate('/loan-paid-off-letters')} - submitLabel={mode === 'create' - ? t('common.create', 'Döret') - : t('common.save', 'Ýatda sakla')} - /> - + navigate("/loan-paid-off-letters")} + submitLabel={mode === "create" ? t("common.create", "Döret") : t("common.save", "Ýatda sakla")} + /> +
- ) + ); } diff --git a/src/features/loanRemaining/components/LoanRemainingForm.tsx b/src/features/loanRemaining/components/LoanRemainingForm.tsx index 9e58fae..4fea779 100644 --- a/src/features/loanRemaining/components/LoanRemainingForm.tsx +++ b/src/features/loanRemaining/components/LoanRemainingForm.tsx @@ -1,41 +1,31 @@ -import { useEffect } from 'react' -import { useTranslation } from 'react-i18next' -import { useNavigate } from 'react-router-dom' -import { toast } from 'sonner' -import { useForm } from 'react-hook-form' -import { zodResolver } from '@hookform/resolvers/zod' +import { useEffect } from "react"; +import { useTranslation } from "react-i18next"; +import { useNavigate } from "react-router-dom"; +import { toast } from "sonner"; +import { useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; -import { FormInput } from '@/components/formInput' -import { FormActions } from '@/components/formActions' +import { FormInput } from "@/components/formInput"; +import { FormActions } from "@/components/formActions"; +import { BentoGrid, BentoCard } from "@/components/bento"; -import { - useCreateLoanRemaining, - useUpdateLoanRemaining, -} from '../hooks/useLoanRemaining' -import type { LoanRemaining } from '../api/loanRemainingApi' -import { - loanRemainingFormSchema, - type LoanRemainingFormData, - DEFAULT_FORM_VALUES, - buildPayload, -} from '../schemas/loanRemaining.schema' +import { useCreateLoanRemaining, useUpdateLoanRemaining } from "../hooks/useLoanRemaining"; +import type { LoanRemaining } from "../api/loanRemainingApi"; +import { loanRemainingFormSchema, type LoanRemainingFormData, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/loanRemaining.schema"; interface LoanRemainingFormProps { - mode: 'create' | 'edit' - initialData?: LoanRemaining + mode: "create" | "edit"; + initialData?: LoanRemaining; } -export function LoanRemainingForm({ - mode, - initialData, -}: LoanRemainingFormProps) { - const { t } = useTranslation() - const navigate = useNavigate() +export function LoanRemainingForm({ mode, initialData }: LoanRemainingFormProps) { + const { t } = useTranslation(); + const navigate = useNavigate(); - const createMutation = useCreateLoanRemaining() - const updateMutation = useUpdateLoanRemaining(initialData?.id ?? 0) + const createMutation = useCreateLoanRemaining(); + const updateMutation = useUpdateLoanRemaining(initialData?.id ?? 0); - const isPending = createMutation.isPending || updateMutation.isPending + const isPending = createMutation.isPending || updateMutation.isPending; const { handleSubmit, @@ -46,96 +36,95 @@ export function LoanRemainingForm({ } = useForm({ resolver: zodResolver(loanRemainingFormSchema), defaultValues: DEFAULT_FORM_VALUES, - mode: 'onSubmit', - }) + mode: "onSubmit", + }); useEffect(() => { - if (mode === 'edit' && initialData) { + if (mode === "edit" && initialData) { reset({ passportSeries: initialData.passportSeries, passportNumber: initialData.passportNumber, loanAccount: initialData.loanAccount, - }) + }); } - }, [mode, initialData, reset]) + }, [mode, initialData, reset]); const onSubmit = (data: LoanRemainingFormData) => { - const payload = buildPayload(data) + const payload = buildPayload(data); - if (mode === 'create') { + if (mode === "create") { createMutation.mutate(payload, { onSuccess: () => { - toast.success(t('common.success.create', 'Üstünlikli döredildi')) - navigate('/loan-remaining') + toast.success(t("common.success.create", "Üstünlikli döredildi")); + navigate("/loan-remaining"); }, - }) + }); } else { updateMutation.mutate(payload, { onSuccess: () => { - toast.success(t('common.success.save', 'Üstünlikli ýatda saklandy')) - navigate('/loan-remaining') + toast.success(t("common.success.save", "Üstünlikli ýatda saklandy")); + navigate("/loan-remaining"); }, - }) + }); } - } + }; - const errMsg = (msg: string | undefined) => - msg?.startsWith('validation.') ? t(msg, msg) : msg + const errMsg = (msg: string | undefined) => (msg?.startsWith("validation.") ? t(msg, msg) : msg); const onError = () => { - toast.error(t('common.errors.fillRequired', 'Hökman doldurylmaly öýjükleri dolduryň')) - } + toast.error(t("common.errors.fillRequired", "Hökman doldurylmaly öýjükleri dolduryň")); + }; return (

- {mode === 'create' - ? t('loanRemaining.createTitle', 'Karzyň galyndysy dörediň') - : t('loanRemaining.editTitle', 'Karzyň galyndysy üýtgetmek')} + {mode === "create" + ? t("loanRemaining.createTitle", "Karzyň galyndysy dörediň") + : t("loanRemaining.editTitle", "Karzyň galyndysy üýtgetmek")}

-
-
- setValue('passportSeries', v)} - placeholder={t('loanRemaining.placeholders.passportSeries', 'TM')} - error={errMsg(errors.passportSeries?.message)} - /> + + +
+ setValue("passportSeries", v)} + placeholder={t("loanRemaining.placeholders.passportSeries", "TM")} + error={errMsg(errors.passportSeries?.message)} + /> - setValue('passportNumber', v)} - placeholder="A123456" - error={errMsg(errors.passportNumber?.message)} - /> + setValue("passportNumber", v)} + placeholder="A123456" + error={errMsg(errors.passportNumber?.message)} + /> -
- setValue('loanAccount', v)} - placeholder="NOVA-..." - error={errMsg(errors.loanAccount?.message)} - /> -
-
-
+
+ setValue("loanAccount", v)} + placeholder="NOVA-..." + error={errMsg(errors.loanAccount?.message)} + /> +
+
+ + - navigate('/loan-remaining')} - submitLabel={mode === 'create' - ? t('common.create', 'Döret') - : t('common.save', 'Ýatda sakla')} - /> - + navigate("/loan-remaining")} + submitLabel={mode === "create" ? t("common.create", "Döret") : t("common.save", "Ýatda sakla")} + /> +
- ) + ); } diff --git a/src/features/loanTypes/components/loanTypesForm.tsx b/src/features/loanTypes/components/loanTypesForm.tsx index a3452cb..ff9d138 100644 --- a/src/features/loanTypes/components/loanTypesForm.tsx +++ b/src/features/loanTypes/components/loanTypesForm.tsx @@ -1,36 +1,37 @@ -import { useCallback, useMemo, useEffect } from 'react' -import { useNavigate } from 'react-router-dom' -import { useTranslation } from 'react-i18next' -import { useForm } from 'react-hook-form' -import { zodResolver } from '@hookform/resolvers/zod' -import { FormInput } from '@/components/formInput' -import { Label } from '@/components/ui/label' -import { FormActions } from '@/components/formActions' -import { MultiLangInput } from '@/components/multiLangInput' -import { Checkbox } from '@/components/ui/checkbox' -import { useCreateLoanType, useUpdateLoanType } from '../hooks/useLoanTypes' -import type { LoanType } from '../api/loanTypesApi' -import { createLoanTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/loanType.schema' -import type { LoanTypeFormData } from '../schemas/loanType.schema' +import { useCallback, useMemo, useEffect } from "react"; +import { useNavigate } from "react-router-dom"; +import { useTranslation } from "react-i18next"; +import { useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { FormInput } from "@/components/formInput"; +import { Label } from "@/components/ui/label"; +import { FormActions } from "@/components/formActions"; +import { MultiLangInput } from "@/components/multiLangInput"; +import { Checkbox } from "@/components/ui/checkbox"; +import { BentoGrid, BentoCard } from "@/components/bento"; +import { useCreateLoanType, useUpdateLoanType } from "../hooks/useLoanTypes"; +import type { LoanType } from "../api/loanTypesApi"; +import { createLoanTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/loanType.schema"; +import type { LoanTypeFormData } from "../schemas/loanType.schema"; // ─── Types ──────────────────────────────────────────────────────────────────── -type FormMode = 'create' | 'edit' +type FormMode = "create" | "edit"; interface LoanTypeFormProps { - mode: FormMode - initialData?: LoanType + mode: FormMode; + initialData?: LoanType; } -type FlatErrors = Partial> +type FlatErrors = Partial>; function flattenErrors(errors: Record): FlatErrors { - const result: FlatErrors = {} + const result: FlatErrors = {}; for (const key of Object.keys(errors)) { - const msg = errors[key]?.message - if (msg) result[key as keyof LoanTypeFormData] = msg + const msg = errors[key]?.message; + if (msg) result[key as keyof LoanTypeFormData] = msg; } - return result + return result; } function mapInitial(data: LoanType): LoanTypeFormData { @@ -38,32 +39,31 @@ function mapInitial(data: LoanType): LoanTypeFormData { nameTk: data.name.tk, nameRu: data.name.ru, nameEn: data.name.en, - notesTk: data.notes?.tk ?? '', - notesRu: data.notes?.ru ?? '', - notesEn: data.notes?.en ?? '', + notesTk: data.notes?.tk ?? "", + notesRu: data.notes?.ru ?? "", + notesEn: data.notes?.en ?? "", tax: String(data.tax), loanTerm: String(data.loanTerm), isActive: data.isActive, - } + }; } // ─── LoanTypeForm ───────────────────────────────────────────────────────────── export function LoanTypeForm({ mode, initialData }: LoanTypeFormProps) { - const { t: _t, i18n } = useTranslation() + const { t: _t, i18n } = useTranslation(); const t: (key: string, fallback?: string) => string = useCallback( (key, fallback) => _t(key, fallback ?? key) as string, [_t, i18n.language], - ) - const navigate = useNavigate() + ); + const navigate = useNavigate(); - const createMutation = useCreateLoanType() - const updateMutation = useUpdateLoanType(initialData?.id ?? 0) + const createMutation = useCreateLoanType(); + const updateMutation = useUpdateLoanType(initialData?.id ?? 0); + const isPending = createMutation.isPending || updateMutation.isPending; - const isPending = createMutation.isPending || updateMutation.isPending - - const schema = useMemo(() => createLoanTypeFormSchema(t), [t, i18n.language]) + const schema = useMemo(() => createLoanTypeFormSchema(t), [t, i18n.language]); const { watch, @@ -74,152 +74,115 @@ export function LoanTypeForm({ mode, initialData }: LoanTypeFormProps) { getValues, } = useForm({ resolver: zodResolver(schema), - defaultValues: initialData - ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } - : DEFAULT_FORM_VALUES, - }) + defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES, + }); - const form = watch() - const errors = useMemo( - () => flattenErrors(rhfErrors as Record), - [rhfErrors], - ) + const form = watch(); + const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]); // ── Re-validate on language change ── useEffect(() => { - if (Object.keys(rhfErrors).length > 0) trigger() + if (Object.keys(rhfErrors).length > 0) trigger(); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [i18n.language]) + }, [i18n.language]); const set = useCallback( (key: keyof LoanTypeFormData) => (value: string | boolean) => { - (setValue as (k: keyof LoanTypeFormData, v: string | boolean) => void)(key, value) - clearErrors(key) + (setValue as (k: keyof LoanTypeFormData, v: string | boolean) => void)(key, value); + clearErrors(key); }, [setValue, clearErrors], - ) + ); // ── Submit ───────────────────────────────────────────────────────────────── const handleSubmit = async () => { - const isValid = await trigger() - if (!isValid) return + const isValid = await trigger(); + if (!isValid) return; - const payload = buildPayload(getValues()) + const payload = buildPayload(getValues()); - if (mode === 'create') { - const result = await createMutation.mutateAsync(payload) - navigate(`/resources/loan-types/${result.id}`) + if (mode === "create") { + const result = await createMutation.mutateAsync(payload); + navigate(`/resources/loan-types/${result.id}`); } else { - await updateMutation.mutateAsync(payload) - navigate(`/resources/loan-types/${initialData!.id}`) + await updateMutation.mutateAsync(payload); + navigate(`/resources/loan-types/${initialData!.id}`); } - } + }; - const handleCancel = () => navigate('/resources/loan-types') + const handleCancel = () => navigate("/resources/loan-types"); // ── Name fields per lang ─────────────────────────────────────────────────── const nameFields = { - tk: { value: form.nameTk, onChange: set('nameTk'), error: errors.nameTk }, - ru: { value: form.nameRu, onChange: set('nameRu'), error: errors.nameRu }, - en: { value: form.nameEn, onChange: set('nameEn'), error: errors.nameEn }, - } + tk: { value: form.nameTk, onChange: set("nameTk"), error: errors.nameTk }, + ru: { value: form.nameRu, onChange: set("nameRu"), error: errors.nameRu }, + en: { value: form.nameEn, onChange: set("nameEn"), error: errors.nameEn }, + }; const notesFields = { - tk: { value: form.notesTk ?? '', onChange: set('notesTk') }, - ru: { value: form.notesRu ?? '', onChange: set('notesRu') }, - en: { value: form.notesEn ?? '', onChange: set('notesEn') }, - } + tk: { value: form.notesTk ?? "", onChange: set("notesTk") }, + ru: { value: form.notesRu ?? "", onChange: set("notesRu") }, + en: { value: form.notesEn ?? "", onChange: set("notesEn") }, + }; // ───────────────────────────────────────────────────────────────────────── return (

- {mode === 'create' - ? t('loanTypes.createTitle', 'Karz görnüşi dörediň') - : t('loanTypes.editTitle', 'Karz görnüşi üýtgetmek')} + {mode === "create" ? t("loanTypes.createTitle", "Karz görnüşi dörediň") : t("loanTypes.editTitle", "Karz görnüşi üýtgetmek")}

-
- {/* Form card */} -
- {/* Ady */} -
- - {t('loanTypes.fields.name', 'Ady')} + + +

+ {t("loanTypes.fields.name", "Ady")} * - - -

- - {/* Salgyt */} -
- - {t('loanTypes.fields.tax', 'Salgyt')} - * - +

+ + + -
- - {/* Karz möhleti */} -
- - {t('loanTypes.fields.loanTerm', 'Karz möhleti')} - * - + + -
- - {/* Bellikler */} -
- - {t('loanTypes.fields.notes', 'Bellikler')} - - -
- - {/* Işjeň */} -
- - {t('loanTypes.fields.isActive', 'Işjeň')} - -
- set('isActive')(!!checked)} - /> + + +

{t("loanTypes.fields.notes", "Bellikler")}

+ +
+ +
+ {t("loanTypes.fields.isActive", "Işjeň")} + set("isActive")(!!checked)} />
-
-
- + +
-
- ) + ); } diff --git a/src/features/permissions/components/permissionsForm.tsx b/src/features/permissions/components/permissionsForm.tsx index 6a17c21..ab59bf7 100644 --- a/src/features/permissions/components/permissionsForm.tsx +++ b/src/features/permissions/components/permissionsForm.tsx @@ -1,58 +1,64 @@ -import { useMemo, useEffect, useCallback } from 'react' -import { useNavigate } from 'react-router-dom' -import { useTranslation } from 'react-i18next' -import { useForm } from 'react-hook-form' -import { zodResolver } from '@hookform/resolvers/zod' -import { FormActions } from '@/components/formActions' -import { MultiLangInput } from '@/components/multiLangInput' -import { useCreatePermission, useUpdatePermission } from '../hooks/usePermissions' -import { createPermissionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/permission.schema' -import type { PermissionFormData } from '../schemas/permission.schema' -import type { Permission } from '../api/permissionsApi' -import { FormInput } from '@/components/formInput' +import { useMemo, useEffect, useCallback } from "react"; +import { useNavigate } from "react-router-dom"; +import { useTranslation } from "react-i18next"; +import { useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { FormActions } from "@/components/formActions"; +import { BentoGrid, BentoCard } from "@/components/bento"; +import { MultiLangInput } from "@/components/multiLangInput"; +import { useCreatePermission, useUpdatePermission } from "../hooks/usePermissions"; +import { createPermissionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/permission.schema"; +import type { PermissionFormData } from "../schemas/permission.schema"; +import type { Permission } from "../api/permissionsApi"; +import { FormInput } from "@/components/formInput"; // ─── Types ──────────────────────────────────────────────────────────────────── interface PermissionFormProps { - mode: 'create' | 'edit' - initialData?: Permission + mode: "create" | "edit"; + initialData?: Permission; } const GUARD_OPTIONS = [ - { value: 'web', label: 'web' }, - { value: 'api', label: 'api' }, - { value: 'sanctum', label: 'sanctum' }, -] + { value: "web", label: "web" }, + { value: "api", label: "api" }, + { value: "sanctum", label: "sanctum" }, +]; -type FlatErrors = Partial> +type FlatErrors = Partial>; function flattenErrors(errors: Record): FlatErrors { - const result: FlatErrors = {} + const result: FlatErrors = {}; for (const key of Object.keys(errors)) { - const msg = errors[key]?.message - if (msg) result[key as keyof PermissionFormData] = msg + const msg = errors[key]?.message; + if (msg) result[key as keyof PermissionFormData] = msg; } - return result + return result; } // ─── PermissionForm ─────────────────────────────────────────────────────────── export function PermissionForm({ mode, initialData }: PermissionFormProps) { - const { t: _t, i18n } = useTranslation() + const { t: _t, i18n } = useTranslation(); const t: (key: string, fallback?: string) => string = useCallback( (key, fallback) => _t(key, fallback ?? key) as string, [_t, i18n.language], - ) - const navigate = useNavigate() + ); + const navigate = useNavigate(); - const createPermission = useCreatePermission() - const updatePermission = useUpdatePermission(initialData?.id ?? 0) + const createPermission = useCreatePermission(); + const updatePermission = useUpdatePermission(initialData?.id ?? 0); - const isPending = createPermission.isPending || updatePermission.isPending + const isPending = createPermission.isPending || updatePermission.isPending; - const schema = useMemo(() => createPermissionFormSchema(t), [t, i18n.language]) + const schema = useMemo(() => createPermissionFormSchema(t), [t, i18n.language]); const { - watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger, + watch, + setValue, + getValues, + formState: { errors: rhfErrors }, + clearErrors, + trigger, } = useForm({ resolver: zodResolver(schema), defaultValues: initialData @@ -65,113 +71,118 @@ export function PermissionForm({ mode, initialData }: PermissionFormProps) { guard_name: initialData.guard_name, } : DEFAULT_FORM_VALUES, - }) + }); - const form = watch() - const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]) + const form = watch(); + const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]); const setField = useCallback( (key: keyof PermissionFormData) => (value: string) => { - (setValue as (k: keyof PermissionFormData, v: string) => void)(key, value) - clearErrors(key) + (setValue as (k: keyof PermissionFormData, v: string) => void)(key, value); + clearErrors(key); }, [setValue, clearErrors], - ) + ); const nameFields = { - tk: { value: form.nameTk, onChange: (v: string) => { setValue('nameTk', v); clearErrors('nameTk'); }, error: errors.nameTk }, - ru: { value: form.nameRu, onChange: (v: string) => { setValue('nameRu', v); clearErrors('nameRu'); }, error: errors.nameRu }, - en: { value: form.nameEn, onChange: (v: string) => { setValue('nameEn', v); clearErrors('nameEn'); }, error: errors.nameEn }, - } + tk: { + value: form.nameTk, + onChange: (v: string) => { + setValue("nameTk", v); + clearErrors("nameTk"); + }, + error: errors.nameTk, + }, + ru: { + value: form.nameRu, + onChange: (v: string) => { + setValue("nameRu", v); + clearErrors("nameRu"); + }, + error: errors.nameRu, + }, + en: { + value: form.nameEn, + onChange: (v: string) => { + setValue("nameEn", v); + clearErrors("nameEn"); + }, + error: errors.nameEn, + }, + }; // ── Re-validate on language change ── useEffect(() => { - if (Object.keys(rhfErrors).length > 0) trigger() + if (Object.keys(rhfErrors).length > 0) trigger(); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [i18n.language]) + }, [i18n.language]); // ── Submit ───────────────────────────────────────────────────────────────── const handleSubmit = async () => { - const isValid = await trigger() - if (!isValid) return + const isValid = await trigger(); + if (!isValid) return; - const values = getValues() - const payload = buildPayload(values) + const values = getValues(); + const payload = buildPayload(values); - if (mode === 'create') { + if (mode === "create") { createPermission.mutate(payload, { - onSuccess: () => navigate('/settings/users/permissions'), - }) + onSuccess: () => navigate("/settings/users/permissions"), + }); } else { updatePermission.mutate(payload, { - onSuccess: () => navigate('/settings/users/permissions'), - }) + onSuccess: () => navigate("/settings/users/permissions"), + }); } - } + }; // ── Render ───────────────────────────────────────────────────────────────── return (

- {mode === 'create' - ? t('permissions.createTitle', 'Rugsat dörediň') - : t('permissions.editTitle', 'Rugsat üýtgetmek')} + {mode === "create" ? t("permissions.createTitle", "Rugsat dörediň") : t("permissions.editTitle", "Rugsat üýtgetmek")}

-
- - {/* Code */} -
- - {t('permissions.fields.code', 'Kod')} - * - - -
- - {/* Name (multilingual) */} -
- - {t('permissions.fields.name', 'Ady')} - * - - -
- - {/* Guard name */} -
- - {t('permissions.fields.guardName', 'Guard name')} - * - - -
- + + + + + + + + +

+ {t("permissions.fields.name", "Ady")} + * +

+ +
+
navigate('/settings/users/permissions')} - submitLabel={mode === 'create' - ? t('permissions.actions.create', 'Rugsat dörediň') - : t('permissions.actions.save', 'Ýatda sakla')} - className="px-5 py-4 border-t border-border bg-muted/20" + onCancel={() => navigate("/settings/users/permissions")} + submitLabel={mode === "create" ? t("permissions.actions.create", "Rugsat dörediň") : t("permissions.actions.save", "Ýatda sakla")} />
-
- ) -} \ No newline at end of file + ); +} diff --git a/src/features/requiredDocuments/components/requiredDocumentsForm.tsx b/src/features/requiredDocuments/components/requiredDocumentsForm.tsx index f66521b..10bbaab 100644 --- a/src/features/requiredDocuments/components/requiredDocumentsForm.tsx +++ b/src/features/requiredDocuments/components/requiredDocumentsForm.tsx @@ -27,21 +27,11 @@ import { import { cn } from "@/lib/utils"; import { FormInput } from "@/components/formInput"; import { FormActions } from "@/components/formActions"; -import { - useCreateRequiredDocument, - useUpdateRequiredDocument, -} from "../hooks/useRequiredDocuments"; -import { - createRequiredDocumentFormSchema, - DEFAULT_FORM_VALUES, - buildPayload, - mapInitial, -} from "../schemas/requiredDocument.schema"; +import { BentoGrid, BentoCard } from "@/components/bento"; +import { useCreateRequiredDocument, useUpdateRequiredDocument } from "../hooks/useRequiredDocuments"; +import { createRequiredDocumentFormSchema, DEFAULT_FORM_VALUES, buildPayload, mapInitial } from "../schemas/requiredDocument.schema"; import type { RequiredDocumentFormData } from "../schemas/requiredDocument.schema"; -import type { - LoanDocument, - LoanDocumentTranslation, -} from "../api/requiredDocumentsApi"; +import type { LoanDocument, LoanDocumentTranslation } from "../api/requiredDocumentsApi"; // ─── Types ──────────────────────────────────────────────────────────────────── @@ -79,6 +69,8 @@ function RichTextToolbar({ editor, onFileAttach }: RichTextToolbarProps) { setShowLinkModal(false); }; + const handleAttachmentClick = () => fileInputRef.current?.click(); + const handleFileChange = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; @@ -159,14 +151,13 @@ function RichTextToolbar({ editor, onFileAttach }: RichTextToolbarProps) { }, { icon: Paperclip, - action: () => fileInputRef.current?.click(), + action: handleAttachmentClick, active: false, title: "Attachment", }, { icon: Type, - action: () => - editor.chain().focus().selectAll().clearNodes().unsetAllMarks().run(), + action: () => editor.chain().focus().selectAll().clearNodes().unsetAllMarks().run(), active: false, title: "Clear format", }, @@ -175,52 +166,39 @@ function RichTextToolbar({ editor, onFileAttach }: RichTextToolbarProps) { return ( <>
- {tools.map(({ icon: Icon, action, active, title }) => ( - - ))} - + { + // eslint-disable-next-line react-hooks/refs + tools.map(({ icon: Icon, action, active, title }) => ( + + )) + } +
{/* Link modal */} - {showLinkModal && ( - setShowLinkModal(false)} - /> - )} + {showLinkModal && setShowLinkModal(false)} />} ); } // ─── Link Modal ─────────────────────────────────────────────────────────────── -function LinkModal({ - onConfirm, - onClose, -}: { - onConfirm: (url: string) => void; - onClose: () => void; -}) { +function LinkModal({ onConfirm, onClose }: { onConfirm: (url: string) => void; onClose: () => void }) { const [url, setUrl] = useState(""); return (
-
@@ -386,15 +346,10 @@ function LangTabs({ active, onChange }: LangTabsProps) { onClick={() => onChange(code)} className={cn( "text-sm transition-colors", - active === code - ? "text-primary font-semibold underline underline-offset-4" - : "text-muted-foreground hover:text-foreground", + active === code ? "text-primary font-semibold underline underline-offset-4" : "text-muted-foreground hover:text-foreground", )} > - {t( - "languages." + code, - code === "tk" ? "Türkmen" : code === "ru" ? "Русский" : "English", - )} + {t("languages." + code, code === "tk" ? "Türkmen" : code === "ru" ? "Русский" : "English")} ))}
@@ -414,9 +369,7 @@ const RHF_TO_LEGACY_KEY: Record = { descEn: "desc_en", }; -function flattenErrors( - errors: Record, -): Partial> { +function flattenErrors(errors: Record): Partial> { const result: Partial> = {}; for (const [key, err] of Object.entries(errors)) { const legacyKey = RHF_TO_LEGACY_KEY[key]; @@ -429,10 +382,7 @@ function flattenErrors( // ─── RequiredDocumentForm ───────────────────────────────────────────────────── -export function RequiredDocumentForm({ - mode, - initialData, -}: RequiredDocumentFormProps) { +export function RequiredDocumentForm({ mode, initialData }: RequiredDocumentFormProps) { const { t: _t, i18n } = useTranslation(); const t: (key: string, fallback?: string) => string = useCallback( (key, fallback) => _t(key, fallback ?? key) as string, @@ -460,10 +410,7 @@ export function RequiredDocumentForm({ const isPending = createMutation.isPending || updateMutation.isPending; - const schema = useMemo( - () => createRequiredDocumentFormSchema(t), - [t, i18n.language], - ); + const schema = useMemo(() => createRequiredDocumentFormSchema(t), [t, i18n.language]); const { watch, @@ -473,19 +420,11 @@ export function RequiredDocumentForm({ trigger, } = useForm({ resolver: zodResolver(schema), - defaultValues: initialData - ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } - : DEFAULT_FORM_VALUES, + defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES, }); const form = watch(); - const errors = useMemo( - () => - flattenErrors( - rhfErrors as Record, - ), - [rhfErrors], - ); + const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]); useEffect(() => { if (Object.keys(rhfErrors).length > 0) trigger(); @@ -576,82 +515,46 @@ export function RequiredDocumentForm({ : t("loanDocuments.editTitle", "Karz gerekli resminama üýtgetmek")}
-
- {/* ── Name field ──────────────────────────────────────────────────── */} -
-
- - {/* ── Description field ────────────────────────────────────────────── */} -
-
-
+

+ + setDescription((prev) => ({ ...prev, [descLang]: val }))} + error={errors[`desc_${descLang}`]} + onFileAttach={handleFileAttach} + /> + + {LOCALES.filter((l) => l !== descLang && errors[`desc_${l}`]).map((code) => ( +

+ {t("languages." + code, code === "tk" ? "Türkmen" : code === "ru" ? "Русский" : "English")}: {errors[`desc_${code}`]} +

+ ))} + + > +type FlatErrors = Partial>; function flattenErrors(errors: Record): FlatErrors { - const result: FlatErrors = {} + const result: FlatErrors = {}; for (const key of Object.keys(errors)) { - const msg = errors[key]?.message - if (msg) result[key as keyof RoleFormData] = msg + const msg = errors[key]?.message; + if (msg) result[key as keyof RoleFormData] = msg; } - return result + return result; } // ─── RoleForm ───────────────────────────────────────────────────────────────── export function RoleForm({ mode, initialData }: RoleFormProps) { - const { t: _t, i18n } = useTranslation() + const { t: _t, i18n } = useTranslation(); const t: (key: string, fallback?: string) => string = useCallback( (key, fallback) => _t(key, fallback ?? key) as string, [_t, i18n.language], - ) - const navigate = useNavigate() + ); + const navigate = useNavigate(); - const createRole = useCreateRole() - const updateRole = useUpdateRole(initialData?.id ?? 0) + const createRole = useCreateRole(); + const updateRole = useUpdateRole(initialData?.id ?? 0); - const isPending = createRole.isPending || updateRole.isPending + const isPending = createRole.isPending || updateRole.isPending; - const schema = useMemo(() => createRoleFormSchema(t), [t, i18n.language]) + const schema = useMemo(() => createRoleFormSchema(t), [t, i18n.language]); const { - watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger, + watch, + setValue, + getValues, + formState: { errors: rhfErrors }, + clearErrors, + trigger, } = useForm({ resolver: zodResolver(schema), defaultValues: initialData @@ -65,114 +71,119 @@ export function RoleForm({ mode, initialData }: RoleFormProps) { guard_name: initialData.guard_name, } : DEFAULT_FORM_VALUES, - }) + }); - const form = watch() - const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]) + const form = watch(); + const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]); const setField = useCallback( (key: keyof RoleFormData) => (value: string) => { - (setValue as (k: keyof RoleFormData, v: string) => void)(key, value) - clearErrors(key) + (setValue as (k: keyof RoleFormData, v: string) => void)(key, value); + clearErrors(key); }, [setValue, clearErrors], - ) + ); const nameFields = { - tk: { value: form.nameTk, onChange: (v: string) => { setValue('nameTk', v); clearErrors('nameTk'); }, error: errors.nameTk }, - ru: { value: form.nameRu, onChange: (v: string) => { setValue('nameRu', v); clearErrors('nameRu'); }, error: errors.nameRu }, - en: { value: form.nameEn, onChange: (v: string) => { setValue('nameEn', v); clearErrors('nameEn'); }, error: errors.nameEn }, - } + tk: { + value: form.nameTk, + onChange: (v: string) => { + setValue("nameTk", v); + clearErrors("nameTk"); + }, + error: errors.nameTk, + }, + ru: { + value: form.nameRu, + onChange: (v: string) => { + setValue("nameRu", v); + clearErrors("nameRu"); + }, + error: errors.nameRu, + }, + en: { + value: form.nameEn, + onChange: (v: string) => { + setValue("nameEn", v); + clearErrors("nameEn"); + }, + error: errors.nameEn, + }, + }; // ── Re-validate on language change ── useEffect(() => { - if (Object.keys(rhfErrors).length > 0) trigger() + if (Object.keys(rhfErrors).length > 0) trigger(); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [i18n.language]) + }, [i18n.language]); // ── Submit ───────────────────────────────────────────────────────────────── const handleSubmit = async () => { - const isValid = await trigger() - if (!isValid) return + const isValid = await trigger(); + if (!isValid) return; - const values = getValues() - const payload = buildPayload(values) + const values = getValues(); + const payload = buildPayload(values); - if (mode === 'create') { + if (mode === "create") { createRole.mutate(payload, { - onSuccess: () => navigate('/settings/users/roles'), - }) + onSuccess: () => navigate("/settings/users/roles"), + }); } else { updateRole.mutate(payload, { - onSuccess: () => navigate('/settings/users/roles'), - }) + onSuccess: () => navigate("/settings/users/roles"), + }); } - } + }; // ── Render ───────────────────────────────────────────────────────────────── return (

- {mode === 'create' - ? t('roles.createTitle', 'Rol dörediň') - : t('roles.editTitle', 'Rol üýtgetmek')} + {mode === "create" ? t("roles.createTitle", "Rol dörediň") : t("roles.editTitle", "Rol üýtgetmek")}

-
- - {/* Code */} -
- - {t('roles.fields.code', 'Kod')} - * - - -
- - {/* Name (multilingual) */} -
- - {t('roles.fields.name', 'Ady')} - * - - -
- - {/* Guard name */} -
- - {t('roles.fields.guardName', 'Guard name')} - * - - -
- + + + + + + + + +

+ {t("roles.fields.name", "Ady")} + * +

+ +
+
navigate('/settings/users/roles')} - loadingLabel={t('common.saving', 'Ýüklenýär...')} - submitLabel={mode === 'create' - ? t('roles.actions.create', 'Rol dörediň') - : t('roles.actions.save', 'Ýatda sakla')} - className="px-5 py-4 border-t border-border bg-muted/20" + onCancel={() => navigate("/settings/users/roles")} + loadingLabel={t("common.saving", "Ýüklenýär...")} + submitLabel={mode === "create" ? t("roles.actions.create", "Rol dörediň") : t("roles.actions.save", "Ýatda sakla")} />
-
- ) -} \ No newline at end of file + ); +} diff --git a/src/features/visaMasterSberSettings/components/visaMasterSberSettingsForm.tsx b/src/features/visaMasterSberSettings/components/visaMasterSberSettingsForm.tsx index 8c8944f..d32cad0 100644 --- a/src/features/visaMasterSberSettings/components/visaMasterSberSettingsForm.tsx +++ b/src/features/visaMasterSberSettings/components/visaMasterSberSettingsForm.tsx @@ -1,79 +1,67 @@ -import { useCallback, useEffect, useMemo } from 'react' -import { useNavigate } from 'react-router-dom' -import { useTranslation } from 'react-i18next' -import { useForm } from 'react-hook-form' -import { toast } from 'sonner' -import { zodResolver } from '@hookform/resolvers/zod' -import { FormInput } from '@/components/formInput' -import { FormActions } from '@/components/formActions' -import type { VisaMasterSetting } from '../api/visaMasterSberSettingsApi' -import { - useCreateVisaMasterSetting, - useUpdateVisaMasterSetting, -} from '../hooks/useVisaMasterSettings' -import { - createVisaMasterSettingFormSchema, - DEFAULT_FORM_VALUES, - buildPayload, -} from '../schemas/visaMasterSberSetting.schema' -import type { VisaMasterSettingFormData } from '../schemas/visaMasterSberSetting.schema' +import { useCallback, useEffect, useMemo } from "react"; +import { useNavigate } from "react-router-dom"; +import { useTranslation } from "react-i18next"; +import { useForm } from "react-hook-form"; +import { toast } from "sonner"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { FormInput } from "@/components/formInput"; +import { FormActions } from "@/components/formActions"; +import { BentoGrid, BentoCard } from "@/components/bento"; +import type { VisaMasterSetting } from "../api/visaMasterSberSettingsApi"; +import { useCreateVisaMasterSetting, useUpdateVisaMasterSetting } from "../hooks/useVisaMasterSettings"; +import { createVisaMasterSettingFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/visaMasterSberSetting.schema"; +import type { VisaMasterSettingFormData } from "../schemas/visaMasterSberSetting.schema"; // ─── Types ──────────────────────────────────────────────────────────────────── export interface VisaMasterSettingFormProps { - mode: 'create' | 'edit' - initialData?: VisaMasterSetting + mode: "create" | "edit"; + initialData?: VisaMasterSetting; } // ─── Helpers ────────────────────────────────────────────────────────────────── function mapInitial(data: VisaMasterSetting): VisaMasterSettingFormData { return { - kod: data.kod, - ady: data.ady, + kod: data.kod, + ady: data.ady, yazgy: data.yazgy, - } + }; } -type FlatErrors = Partial> +type FlatErrors = Partial>; -function flattenErrors( - errors: Record -): FlatErrors { - const result: FlatErrors = {} +function flattenErrors(errors: Record): FlatErrors { + const result: FlatErrors = {}; for (const key of Object.keys(errors)) { - const msg = errors[key]?.message - if (msg) result[key as keyof VisaMasterSettingFormData] = msg + const msg = errors[key]?.message; + if (msg) result[key as keyof VisaMasterSettingFormData] = msg; } - return result + return result; } // ─── VisaMasterSettingForm ──────────────────────────────────────────────────── -export function VisaMasterSettingForm({ - mode, - initialData, -}: VisaMasterSettingFormProps) { - const { t: _t, i18n } = useTranslation() +export function VisaMasterSettingForm({ mode, initialData }: VisaMasterSettingFormProps) { + const { t: _t, i18n } = useTranslation(); const t: (key: string, fallback?: string) => string = useCallback( (key, fallback) => _t(key, fallback ?? key) as string, [_t, i18n.language], - ) + ); - const errMsg = (msg: string | undefined) => - !msg ? undefined : msg.startsWith('validation.') ? t(msg, msg) : msg - const navigate = useNavigate() + const errMsg = (msg: string | undefined) => (!msg ? undefined : msg.startsWith("validation.") ? t(msg, msg) : msg); + const navigate = useNavigate(); - const createMutation = useCreateVisaMasterSetting() - const updateMutation = useUpdateVisaMasterSetting(initialData?.id ?? 0) + const createMutation = useCreateVisaMasterSetting(); + const updateMutation = useUpdateVisaMasterSetting(initialData?.id ?? 0); - const isPending = createMutation.isPending || updateMutation.isPending + const isPending = createMutation.isPending || updateMutation.isPending; const schema = useMemo( () => createVisaMasterSettingFormSchema(t), // eslint-disable-next-line react-hooks/exhaustive-deps [i18n.language], - ) + ); const { watch, @@ -84,122 +72,108 @@ export function VisaMasterSettingForm({ getValues, } = useForm({ resolver: zodResolver(schema), - defaultValues: initialData - ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } - : DEFAULT_FORM_VALUES, - }) + defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES, + }); - const form = watch() - const errors = useMemo( - () => flattenErrors(rhfErrors as Record), - [rhfErrors], - ) + const form = watch(); + const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]); useEffect(() => { if (Object.keys(rhfErrors).length > 0) { - trigger() + trigger(); } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [i18n.language]) + }, [i18n.language]); const set = useCallback( (key: keyof VisaMasterSettingFormData) => (value: string) => { - setValue(key, value) - clearErrors(key) + setValue(key, value); + clearErrors(key); }, [setValue, clearErrors], - ) + ); const handleSubmit = useCallback(async () => { - const isValid = await trigger() + const isValid = await trigger(); if (!isValid) { - toast.error(t('common.errors.fillRequiredCorrectly', 'Dogry maglumat girizmegiňizi haýyş edýäris.')) - return + toast.error(t("common.errors.fillRequiredCorrectly", "Dogry maglumat girizmegiňizi haýyş edýäris.")); + return; } - const payload = buildPayload(getValues()) + const payload = buildPayload(getValues()); - if (mode === 'create') { - await createMutation.mutateAsync(payload) - navigate('/resources/visa-master-settings') + if (mode === "create") { + await createMutation.mutateAsync(payload); + navigate("/resources/visa-master-settings"); } else { - await updateMutation.mutateAsync(payload) - navigate('/resources/visa-master-settings') + await updateMutation.mutateAsync(payload); + navigate("/resources/visa-master-settings"); } - }, [mode, createMutation, updateMutation, navigate, trigger, getValues, t]) + }, [mode, createMutation, updateMutation, navigate, trigger, getValues, t]); - const handleCancel = () => navigate('/resources/visa-master-settings') + const handleCancel = () => navigate("/resources/visa-master-settings"); // ─── Render ─────────────────────────────────────────────────────────────── return (

- {mode === 'create' - ? t('visaMasterSettings.createTitle', 'Visa/Master, Sber sazlamalar dörediň') - : t('visaMasterSettings.editTitle', 'Visa/Master, Sber sazlamalar üýtgetmek')} + {mode === "create" + ? t("visaMasterSettings.createTitle", "Visa/Master, Sber sazlamalar dörediň") + : t("visaMasterSettings.editTitle", "Visa/Master, Sber sazlamalar üýtgetmek")}

-
- {/* Kod */} -
- - -
- - {/* Ady */} -
- - -
- - {/* Yazgy */} -
- - -
- - + + + + + + + + + + + + + +
-
- ) + ); }