added lang support to create pages
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { useMemo } from 'react'
|
||||
import { useMemo, useEffect, useCallback } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
@@ -36,7 +36,11 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
||||
// ─── UserForm ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export function UserForm({ mode, initialData, userId }: UserFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
|
||||
const createUser = useCreateUser()
|
||||
@@ -44,7 +48,7 @@ export function UserForm({ mode, initialData, userId }: UserFormProps) {
|
||||
|
||||
const isPending = createUser.isPending || updateUser.isPending
|
||||
|
||||
const schema = useMemo(() => allUserFormSchema(mode), [mode])
|
||||
const schema = useMemo(() => allUserFormSchema(mode, t), [mode, t, i18n.language])
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
@@ -72,6 +76,14 @@ export function UserForm({ mode, initialData, userId }: UserFormProps) {
|
||||
clearErrors(key)
|
||||
}
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) {
|
||||
trigger()
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
|
||||
@@ -1,39 +1,39 @@
|
||||
import { z } from 'zod'
|
||||
import i18next from 'i18next'
|
||||
import type { CreateUserPayload } from '../api/allUsersApi'
|
||||
|
||||
const t = i18next.t.bind(i18next)
|
||||
export function allUserFormSchema(
|
||||
mode: 'create' | 'edit',
|
||||
t: (key: string, fallback?: string) => string,
|
||||
) {
|
||||
const baseSchema = z.object({
|
||||
username: z.string()
|
||||
.min(1, t('validation.required', 'validation.required'))
|
||||
.min(3, t('validation.minLength', 'validation.minLength')),
|
||||
name: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
phone: z.string()
|
||||
.min(1, t('validation.required', 'validation.required'))
|
||||
.regex(/^\d[\d\s-]{6,}$/, t('validation.invalidPhone', 'validation.invalidPhone')),
|
||||
email: z.string()
|
||||
.refine(
|
||||
(v) => !v || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),
|
||||
t('validation.invalidEmail', 'validation.invalidEmail'),
|
||||
)
|
||||
.default(''),
|
||||
password: z.string(),
|
||||
phoneVerified: z.boolean(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
|
||||
const baseSchema = z.object({
|
||||
username: z.string()
|
||||
.min(1, t('validation.required', 'Ulanyjy ady hökmany'))
|
||||
.min(3, t('validation.minLength', 'Ulanyjy ady iň az 3 harp bolmaly')),
|
||||
name: z.string().min(1, t('validation.required', 'Ady hökmany')),
|
||||
phone: z.string()
|
||||
.min(1, t('validation.required', 'Telefon hökmany'))
|
||||
.regex(/^\d[\d\s-]{6,}$/, t('validation.invalidPhone', 'Nädogry telefon formaty')),
|
||||
email: z.string()
|
||||
.refine(
|
||||
(v) => !v || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),
|
||||
t('validation.invalidEmail', 'Nädogry e-poçta formaty'),
|
||||
)
|
||||
.default(''),
|
||||
password: z.string(),
|
||||
phoneVerified: z.boolean(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
|
||||
export function allUserFormSchema(mode: 'create' | 'edit') {
|
||||
return mode === 'create'
|
||||
? baseSchema.extend({
|
||||
password: z.string()
|
||||
.min(1, t('validation.required', 'Açar sözi hökmany'))
|
||||
.min(6, t('validation.minLength', 'Açar sözi iň az 6 harp bolmaly')),
|
||||
.min(1, t('validation.required', 'validation.required'))
|
||||
.min(6, t('validation.minLength', 'validation.minLength')),
|
||||
})
|
||||
: baseSchema
|
||||
}
|
||||
|
||||
export type AllUserFormData = z.infer<typeof baseSchema>
|
||||
export type AllUserFormData = z.infer<ReturnType<typeof allUserFormSchema>>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: AllUserFormData = {
|
||||
username: '',
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useState, useCallback, useMemo } from 'react'
|
||||
import { useState, 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 { toast } from 'sonner'
|
||||
import { ChevronLeft, ChevronRight, Loader2, Building2, MapPin, Clock } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
@@ -12,7 +13,7 @@ import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
|
||||
import { useCreateBranch, useUpdateBranch } from '@/features/branches/hooks/useBranches'
|
||||
import type { Branch } from '@/features/branches/api/branchesApi'
|
||||
import { getDistrictOptions } from '@/features/branches/api/branchesApi'
|
||||
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from '@/features/branches/schemas/branch.schema'
|
||||
import { createBranchFormSchema, validateStep, DEFAULT_FORM_VALUES, buildPayload } from '@/features/branches/schemas/branch.schema'
|
||||
import type { BranchFormData } from '@/features/branches/schemas/branch.schema'
|
||||
|
||||
type FlatErrors = Partial<Record<keyof BranchFormData, string>>
|
||||
@@ -43,7 +44,7 @@ interface StepDef {
|
||||
shortLabel: string
|
||||
icon: LucideIcon
|
||||
subtitle: string
|
||||
validate: (form: BranchFormData, mode: 'create' | 'edit') => FlatErrors
|
||||
validate: (form: BranchFormData, mode: 'create' | 'edit', t: (key: string, fallback?: string) => string) => FlatErrors
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
@@ -54,7 +55,7 @@ const STEPS: StepDef[] = [
|
||||
shortLabel: 'Esasy',
|
||||
icon: Building2,
|
||||
subtitle: 'Ady, kody, etrapy',
|
||||
validate: (form, mode) => validateStep(0, form, mode),
|
||||
validate: (form, mode, t) => validateStep(0, form, mode, t),
|
||||
},
|
||||
{
|
||||
id: 'address',
|
||||
@@ -63,7 +64,7 @@ const STEPS: StepDef[] = [
|
||||
shortLabel: 'Salgy',
|
||||
icon: MapPin,
|
||||
subtitle: 'Salgy, telefon, e-poçta',
|
||||
validate: (form, mode) => validateStep(1, form, mode),
|
||||
validate: (form, mode, t) => validateStep(1, form, mode, t),
|
||||
},
|
||||
{
|
||||
id: 'hours',
|
||||
@@ -72,10 +73,16 @@ const STEPS: StepDef[] = [
|
||||
shortLabel: 'Wagt',
|
||||
icon: Clock,
|
||||
subtitle: 'Iş wagty we bellikler',
|
||||
validate: (form, mode) => validateStep(2, form, mode),
|
||||
validate: (form, mode, t) => validateStep(2, form, mode, t),
|
||||
},
|
||||
]
|
||||
|
||||
const STEP_FIELDS: Record<number, (keyof BranchFormData)[]> = {
|
||||
0: ['nameTk', 'nameRu', 'nameEn', 'code', 'districtId', 'isActive'],
|
||||
1: ['addressTk', 'addressRu', 'addressEn', 'phone', 'email'],
|
||||
2: ['workingHours', 'description'],
|
||||
}
|
||||
|
||||
interface StepContentProps {
|
||||
form: BranchFormData
|
||||
errors: FlatErrors
|
||||
@@ -264,7 +271,11 @@ function mapInitial(data: Branch): Partial<BranchFormData> {
|
||||
}
|
||||
|
||||
export function BranchForm({ mode, initialData, branchId }: BranchFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
|
||||
const createMutation = useCreateBranch()
|
||||
@@ -273,9 +284,14 @@ export function BranchForm({ mode, initialData, branchId }: BranchFormProps) {
|
||||
|
||||
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
||||
|
||||
const schema = useMemo(() => createBranchFormSchema(t), [t, i18n.language])
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors,
|
||||
} = useForm<BranchFormData>({ defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES })
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
} = useForm<BranchFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
@@ -284,14 +300,15 @@ export function BranchForm({ mode, initialData, branchId }: BranchFormProps) {
|
||||
const [visited, setVisited] = useState<Set<number>>(
|
||||
() => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set<number>(),
|
||||
)
|
||||
const [isValidated, setIsValidated] = useState(false)
|
||||
|
||||
const stepsWithErrors = useMemo(() => {
|
||||
const out = new Set<number>()
|
||||
visited.forEach((i) => {
|
||||
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) out.add(i)
|
||||
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) out.add(i)
|
||||
})
|
||||
return out
|
||||
}, [form, mode, visited])
|
||||
}, [form, mode, visited, t])
|
||||
|
||||
const set = useCallback(<K extends keyof BranchFormData>(key: K, value: BranchFormData[K]) => {
|
||||
(setValue as (name: K, val: BranchFormData[K]) => void)(key, value)
|
||||
@@ -303,10 +320,25 @@ export function BranchForm({ mode, initialData, branchId }: BranchFormProps) {
|
||||
const markVisited = (i: number) =>
|
||||
setVisited((prev) => new Set([...prev, i]))
|
||||
|
||||
const handleNext = () => {
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (!isValidated) return
|
||||
|
||||
const visitedFields = Array.from(visited).flatMap((stepIdx) => STEP_FIELDS[stepIdx] || [])
|
||||
if (visitedFields.length > 0) {
|
||||
trigger(visitedFields)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language, isValidated])
|
||||
|
||||
const handleNext = async () => {
|
||||
setIsValidated(true)
|
||||
markVisited(currentStep)
|
||||
const errs = STEPS[currentStep].validate(form, mode)
|
||||
if (Object.keys(errs).length > 0) {
|
||||
|
||||
const fields = STEP_FIELDS[currentStep] || []
|
||||
const isValid = await trigger(fields)
|
||||
|
||||
if (!isValid) {
|
||||
toast.error(t('common.errors.fillRequiredCorrectly', 'Dogry maglumat girizmegiňizi haýyş edýäris.'))
|
||||
return
|
||||
}
|
||||
@@ -330,16 +362,15 @@ export function BranchForm({ mode, initialData, branchId }: BranchFormProps) {
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
|
||||
const doSubmit = () => {
|
||||
const doSubmit = async () => {
|
||||
setIsValidated(true)
|
||||
setVisited(new Set(STEPS.map((_, i) => i)))
|
||||
|
||||
const allErrors: FlatErrors = {}
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode))
|
||||
|
||||
if (Object.keys(allErrors).length > 0) {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) {
|
||||
toast.error(t('common.errors.requiredFieldsMissing', 'Käbir hökmany meýdanlar doldurylan däldir.'))
|
||||
for (let i = 0; i < STEPS.length; i++) {
|
||||
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) {
|
||||
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) {
|
||||
setCurrentStep(i); break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,40 +1,47 @@
|
||||
import { z } from 'zod'
|
||||
import i18next from 'i18next'
|
||||
import type { CreateBranchPayload } from '@/features/branches/api/branchesApi'
|
||||
|
||||
const t = i18next.t.bind(i18next)
|
||||
export function createBranchFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
code: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
districtId: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
addressTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
addressRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
addressEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
phone: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
email: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
workingHours: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
description: z.string().optional(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
}
|
||||
|
||||
export const branchFormSchema = z.object({
|
||||
nameTk: z.string().min(1, t('validation.required', '')),
|
||||
nameRu: z.string().min(1, t('validation.required', '')),
|
||||
nameEn: z.string().min(1, t('validation.required', '')),
|
||||
code: z.string().min(1, t('validation.required', '')),
|
||||
districtId: z.string().min(1, t('validation.required', '')),
|
||||
addressTk: z.string().min(1, t('validation.required', '')),
|
||||
addressRu: z.string().min(1, t('validation.required', '')),
|
||||
addressEn: z.string().min(1, t('validation.required', '')),
|
||||
phone: z.string().min(1, t('validation.required', '')),
|
||||
email: z.string().min(1, t('validation.required', '')),
|
||||
workingHours: z.string().min(1, t('validation.required', '')),
|
||||
description: z.string().optional(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
export type BranchFormData = z.infer<ReturnType<typeof createBranchFormSchema>>
|
||||
|
||||
export type BranchFormData = z.infer<typeof branchFormSchema>
|
||||
type StepSchemas = Record<number, z.ZodType<Partial<BranchFormData>>>
|
||||
|
||||
export const stepSchemas: Record<number, z.ZodType<Partial<BranchFormData>>> = {
|
||||
0: branchFormSchema.pick({ nameTk: true, nameRu: true, nameEn: true, code: true, districtId: true }),
|
||||
1: branchFormSchema.pick({ addressTk: true, addressRu: true, addressEn: true, phone: true, email: true }),
|
||||
2: branchFormSchema.pick({ workingHours: true }),
|
||||
function createStepSchemas(t: (key: string, fallback?: string) => string): StepSchemas {
|
||||
const schema = createBranchFormSchema(t)
|
||||
return {
|
||||
0: schema.pick({ nameTk: true, nameRu: true, nameEn: true, code: true, districtId: true }),
|
||||
1: schema.pick({ addressTk: true, addressRu: true, addressEn: true, phone: true, email: true }),
|
||||
2: schema.pick({ workingHours: true }),
|
||||
}
|
||||
}
|
||||
|
||||
export function validateStep(
|
||||
stepIndex: number,
|
||||
form: BranchFormData,
|
||||
mode: 'create' | 'edit',
|
||||
t: (key: string, fallback?: string) => string,
|
||||
): Partial<Record<keyof BranchFormData, string>> {
|
||||
void mode
|
||||
const stepSchemas = createStepSchemas(t)
|
||||
const schema = stepSchemas[stepIndex]
|
||||
if (!schema) return {}
|
||||
const result = schema.safeParse(form)
|
||||
if (result.success) return {}
|
||||
const errors: Partial<Record<keyof BranchFormData, string>> = {}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useCallback, useMemo } from 'react'
|
||||
import { useState, useCallback, useMemo, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
@@ -8,7 +8,7 @@ import { FormActions } from '@/components/formActions'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import type { CardReason } from '../api/cardReasonsApi'
|
||||
import { useCreateCardReason, useUpdateCardReason } from '../hooks/useCardReasons'
|
||||
import { cardReasonFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardReason.schema'
|
||||
import { createCardReasonFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardReason.schema'
|
||||
import type { CardReasonFormData } from '../schemas/cardReason.schema'
|
||||
|
||||
// ─── Form errors helper ──────────────────────────────────────────────────────
|
||||
@@ -56,7 +56,11 @@ function mapInitial(data: CardReason): CardReasonFormData {
|
||||
}
|
||||
|
||||
export function CardReasonForm({ mode, initialData, CardReasonId }: CardReasonFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
|
||||
const createMutation = useCreateCardReason()
|
||||
@@ -64,10 +68,12 @@ export function CardReasonForm({ mode, initialData, CardReasonId }: CardReasonFo
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const schema = useMemo(() => createCardReasonFormSchema(t), [t, i18n.language])
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors,
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
} = useForm<CardReasonFormData>({
|
||||
resolver: zodResolver(cardReasonFormSchema),
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
@@ -81,11 +87,17 @@ export function CardReasonForm({ mode, initialData, CardReasonId }: CardReasonFo
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
|
||||
const handleSubmit = () => {
|
||||
const values = getValues()
|
||||
const result = cardReasonFormSchema.safeParse(values)
|
||||
if (!result.success) return
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
|
||||
const values = getValues()
|
||||
const payload = buildPayload(values)
|
||||
|
||||
if (mode === 'create') {
|
||||
|
||||
@@ -1,22 +1,21 @@
|
||||
import { z } from 'zod'
|
||||
import i18next from 'i18next'
|
||||
import type { CreateCardReasonPayload } from '../api/cardReasonsApi'
|
||||
|
||||
const t = i18next.t.bind(i18next)
|
||||
export function createCardReasonFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
value: z.string().min(1, t('validation.invalidNumber', 'validation.invalidNumber')).refine(
|
||||
(v) => !isNaN(Number(v)) && Number(v) >= 0,
|
||||
{ message: t('validation.invalidNumber', 'Dogry san giriziň') },
|
||||
),
|
||||
description: z.string().optional(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
}
|
||||
|
||||
export const cardReasonFormSchema = z.object({
|
||||
nameTk: z.string().min(1, t('validation.required', '')),
|
||||
nameRu: z.string().min(1, t('validation.required', '')),
|
||||
nameEn: z.string().min(1, t('validation.required', '')),
|
||||
value: z.string().min(1, t('validation.invalidNumber', '')).refine(
|
||||
(v) => !isNaN(Number(v)) && Number(v) >= 0,
|
||||
{ message: t('validation.invalidNumber', 'Dogry san giriziň') },
|
||||
),
|
||||
description: z.string().optional(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
|
||||
export type CardReasonFormData = z.infer<typeof cardReasonFormSchema>
|
||||
export type CardReasonFormData = z.infer<ReturnType<typeof createCardReasonFormSchema>>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: CardReasonFormData = {
|
||||
nameTk: '',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useCallback, useMemo } from 'react'
|
||||
import { useState, useCallback, useMemo, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
@@ -8,7 +8,7 @@ import { FormActions } from '@/components/formActions'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import type { CardType } from '../api/cardTypesApi'
|
||||
import { useCreateCardType, useUpdateCardType } from '../hooks/useCardTypes'
|
||||
import { cardTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardType.schema'
|
||||
import { createCardTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardType.schema'
|
||||
import type { CardTypeFormData } from '../schemas/cardType.schema'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
@@ -54,7 +54,11 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
||||
// ─── CardTypeForm ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function CardTypeForm({ mode, initialData, cardTypeId }: CardTypeFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
|
||||
const createMutation = useCreateCardType()
|
||||
@@ -64,6 +68,8 @@ export function CardTypeForm({ mode, initialData, cardTypeId }: CardTypeFormProp
|
||||
|
||||
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
||||
|
||||
const schema = useMemo(() => createCardTypeFormSchema(t), [t, i18n.language])
|
||||
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
@@ -72,7 +78,7 @@ export function CardTypeForm({ mode, initialData, cardTypeId }: CardTypeFormProp
|
||||
trigger,
|
||||
getValues,
|
||||
} = useForm<CardTypeFormData>({
|
||||
resolver: zodResolver(cardTypeFormSchema),
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
@@ -92,6 +98,12 @@ export function CardTypeForm({ mode, initialData, cardTypeId }: CardTypeFormProp
|
||||
[setValue, clearErrors],
|
||||
)
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
|
||||
const handleSubmit = useCallback(async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
|
||||
@@ -1,22 +1,21 @@
|
||||
import { z } from 'zod'
|
||||
import i18next from 'i18next'
|
||||
import type { CreateCardTypePayload } from '../api/cardTypesApi'
|
||||
|
||||
const t = i18next.t.bind(i18next)
|
||||
export function createCardTypeFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
value: z.string().refine(
|
||||
(v) => v.trim() !== '' && !isNaN(Number(v)) && Number(v) >= 0,
|
||||
t('validation.invalidNumber', 'Dogry san giriziň'),
|
||||
),
|
||||
description: z.string().optional(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
}
|
||||
|
||||
export const cardTypeFormSchema = z.object({
|
||||
nameTk: z.string().min(1, t('validation.required', '')),
|
||||
nameRu: z.string().min(1, t('validation.required', '')),
|
||||
nameEn: z.string().min(1, t('validation.required', 'Hökmany meýdan')),
|
||||
value: z.string().refine(
|
||||
(v) => v.trim() !== '' && !isNaN(Number(v)) && Number(v) >= 0,
|
||||
t('validation.invalidNumber', 'Dogry san giriziň'),
|
||||
),
|
||||
description: z.string().optional(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
|
||||
export type CardTypeFormData = z.infer<typeof cardTypeFormSchema>
|
||||
export type CardTypeFormData = z.infer<ReturnType<typeof createCardTypeFormSchema>>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: CardTypeFormData = {
|
||||
nameTk: '',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMemo } from 'react'
|
||||
import { useMemo, useEffect, useCallback } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
@@ -35,7 +35,11 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
||||
// ─── ClientForm ───────────────────────────────────────────────────────────────
|
||||
|
||||
export function ClientForm({ mode, initialData, clientId }: ClientFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
|
||||
const createMutation = useCreateClient()
|
||||
@@ -43,7 +47,7 @@ export function ClientForm({ mode, initialData, clientId }: ClientFormProps) {
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const schema = useMemo(() => clientFormSchema(mode), [mode])
|
||||
const schema = useMemo(() => clientFormSchema(mode, t), [mode, t, i18n.language])
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
@@ -70,6 +74,14 @@ export function ClientForm({ mode, initialData, clientId }: ClientFormProps) {
|
||||
clearErrors(key)
|
||||
}
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) {
|
||||
trigger()
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
|
||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger()
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
import { z } from 'zod'
|
||||
import i18next from 'i18next'
|
||||
import type { CreateClientPayload } from '../api/clientsApi'
|
||||
|
||||
const t = i18next.t.bind(i18next)
|
||||
export function clientFormSchema(
|
||||
mode: 'create' | 'edit',
|
||||
t: (key: string, fallback?: string) => string,
|
||||
) {
|
||||
const baseSchema = z.object({
|
||||
username: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
name: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
phone: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
email: z.string().default(''),
|
||||
password: z.string(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
|
||||
const baseSchema = z.object({
|
||||
username: z.string().min(1, t('validation.required', '')),
|
||||
name: z.string().min(1, t('validation.required', '')),
|
||||
phone: z.string().min(1, t('validation.required', '')),
|
||||
email: z.string().default(''),
|
||||
password: z.string(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
|
||||
export function clientFormSchema(mode: 'create' | 'edit') {
|
||||
return mode === 'create'
|
||||
? baseSchema.extend({
|
||||
password: z.string().min(1, t('validation.required', '')),
|
||||
password: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
})
|
||||
: baseSchema
|
||||
}
|
||||
|
||||
export type ClientFormData = z.infer<typeof baseSchema>
|
||||
export type ClientFormData = z.infer<ReturnType<typeof clientFormSchema>>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: ClientFormData = {
|
||||
username: '',
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// features/currencyRates/components/CurrencyRateForm.tsx
|
||||
|
||||
import { useCallback, useMemo } from 'react'
|
||||
import { useCallback, useMemo, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
@@ -10,7 +10,7 @@ import { FormActions } from '@/components/formActions'
|
||||
import { CURRENCY_OPTIONS, type CurrencyRate } from '../api/currencyRatesApi'
|
||||
import { useCreateCurrencyRate, useUpdateCurrencyRate } from '../hooks/useCurrencyRates'
|
||||
import {
|
||||
currencyRateFormSchema,
|
||||
createCurrencyRateFormSchema,
|
||||
DEFAULT_FORM_VALUES,
|
||||
buildPayload,
|
||||
type CurrencyRateFormData,
|
||||
@@ -38,7 +38,11 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
||||
// ─── CurrencyRateForm ─────────────────────────────────────────────────────────
|
||||
|
||||
export function CurrencyRateForm({ mode, initialData, rateId }: CurrencyRateFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
|
||||
const createMutation = useCreateCurrencyRate()
|
||||
@@ -46,6 +50,8 @@ export function CurrencyRateForm({ mode, initialData, rateId }: CurrencyRateForm
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const schema = useMemo(() => createCurrencyRateFormSchema(t), [t, i18n.language])
|
||||
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
@@ -54,7 +60,7 @@ export function CurrencyRateForm({ mode, initialData, rateId }: CurrencyRateForm
|
||||
trigger,
|
||||
getValues,
|
||||
} = useForm<CurrencyRateFormData>({
|
||||
resolver: zodResolver(currencyRateFormSchema),
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData
|
||||
? {
|
||||
currencyFrom: initialData.currencyFrom,
|
||||
@@ -70,6 +76,14 @@ export function CurrencyRateForm({ mode, initialData, rateId }: CurrencyRateForm
|
||||
[rhfErrors],
|
||||
)
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) {
|
||||
trigger()
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
|
||||
const setField = useCallback(
|
||||
(key: keyof CurrencyRateFormData) => (value: string) => {
|
||||
setValue(key, value)
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
import { z } from 'zod'
|
||||
import i18next from 'i18next'
|
||||
import type { CreateCurrencyRatePayload, CurrencyCode } from '../api/currencyRatesApi'
|
||||
|
||||
const t = i18next.t.bind(i18next)
|
||||
export function createCurrencyRateFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
currencyFrom: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
currencyTo: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
value: z
|
||||
.string()
|
||||
.min(1, t('validation.required', 'validation.required'))
|
||||
.refine((v) => !isNaN(Number(v)) && Number(v) > 0, t('validation.valuePositive', 'validation.valuePositive')),
|
||||
})
|
||||
}
|
||||
|
||||
export const currencyRateFormSchema = z.object({
|
||||
currencyFrom: z.string().min(1, t('validation.required', 'Hökmany meýdan')),
|
||||
currencyTo: z.string().min(1, t('validation.required', 'Hökmany meýdan')),
|
||||
value: z
|
||||
.string()
|
||||
.min(1, t('validation.required', 'Hökmany meýdan'))
|
||||
.refine((v) => !isNaN(Number(v)) && Number(v) > 0, t('validation.valuePositive', 'Baha 0-dan uly bolmaly')),
|
||||
})
|
||||
|
||||
export type CurrencyRateFormData = z.infer<typeof currencyRateFormSchema>
|
||||
export type CurrencyRateFormData = z.infer<ReturnType<typeof createCurrencyRateFormSchema>>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: CurrencyRateFormData = {
|
||||
currencyFrom: '',
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { useState, useCallback, useMemo } from 'react'
|
||||
import { useState, 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 type { District } from '../api/districtsApi'
|
||||
import { useCreateDistrict, useUpdateDistrict } from '../hooks/useDistricts'
|
||||
import { districtFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/district.schema'
|
||||
import { createDistrictFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/district.schema'
|
||||
import type { DistrictFormData } from '../schemas/district.schema'
|
||||
|
||||
type FlatErrors = Partial<Record<keyof DistrictFormData, string>>
|
||||
@@ -48,7 +49,11 @@ function mapInitial(data: District): DistrictFormData {
|
||||
}
|
||||
|
||||
export function DistrictForm({ mode, initialData, districtId }: DistrictFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
|
||||
const createMutation = useCreateDistrict()
|
||||
@@ -56,9 +61,12 @@ export function DistrictForm({ mode, initialData, districtId }: DistrictFormProp
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const schema = useMemo(() => createDistrictFormSchema(t), [t, i18n.language])
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors,
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
} = useForm<DistrictFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
@@ -73,12 +81,17 @@ export function DistrictForm({ mode, initialData, districtId }: DistrictFormProp
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
|
||||
const handleSubmit = () => {
|
||||
const values = getValues()
|
||||
const result = districtFormSchema.safeParse(values)
|
||||
if (!result.success) return
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
|
||||
const payload = buildPayload(values)
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
|
||||
const payload = buildPayload(getValues())
|
||||
|
||||
if (mode === 'create') {
|
||||
createMutation.mutate(payload, {
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
import { z } from 'zod'
|
||||
import i18next from 'i18next'
|
||||
import type { CreateDistrictPayload } from '../api/districtsApi'
|
||||
|
||||
const t = i18next.t.bind(i18next)
|
||||
export function createDistrictFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
description: z.string().optional(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
}
|
||||
|
||||
export const districtFormSchema = z.object({
|
||||
nameTk: z.string().min(1, t('validation.required', '')),
|
||||
nameRu: z.string().min(1, t('validation.required', '')),
|
||||
nameEn: z.string().min(1, t('validation.required', '')),
|
||||
description: z.string().optional(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
|
||||
export type DistrictFormData = z.infer<typeof districtFormSchema>
|
||||
export type DistrictFormData = z.infer<ReturnType<typeof createDistrictFormSchema>>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: DistrictFormData = {
|
||||
nameTk: '',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useCallback, useMemo } from 'react'
|
||||
import { useState, useCallback, useMemo, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
@@ -9,7 +9,7 @@ import { FormActions } from '@/components/formActions'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { useCreateLoanType, useUpdateLoanType } from '../hooks/useLoanTypes'
|
||||
import type { LoanType } from '../api/loanTypesApi'
|
||||
import { loanTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/loanType.schema'
|
||||
import { createLoanTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/loanType.schema'
|
||||
import type { LoanTypeFormData } from '../schemas/loanType.schema'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
@@ -60,7 +60,11 @@ const LANG_TABS: { key: Lang; label: string }[] = [
|
||||
// ─── LoanTypeForm ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
|
||||
const createMutation = useCreateLoanType()
|
||||
@@ -70,6 +74,8 @@ export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProp
|
||||
|
||||
const [activeLang, setActiveLang] = useState<Lang>('tk')
|
||||
|
||||
const schema = useMemo(() => createLoanTypeFormSchema(t), [t, i18n.language])
|
||||
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
@@ -78,7 +84,7 @@ export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProp
|
||||
trigger,
|
||||
getValues,
|
||||
} = useForm<LoanTypeFormData>({
|
||||
resolver: zodResolver(loanTypeFormSchema),
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
@@ -90,6 +96,12 @@ export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProp
|
||||
[rhfErrors],
|
||||
)
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
|
||||
const set = useCallback(
|
||||
(key: keyof LoanTypeFormData) => (value: string | boolean) => {
|
||||
(setValue as (k: keyof LoanTypeFormData, v: string | boolean) => void)(key, value)
|
||||
|
||||
@@ -1,28 +1,27 @@
|
||||
import { z } from 'zod'
|
||||
import i18next from 'i18next'
|
||||
import type { CreateLoanTypePayload } from '../api/loanTypesApi'
|
||||
|
||||
const t = i18next.t.bind(i18next)
|
||||
export function createLoanTypeFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
notesTk: z.string().optional(),
|
||||
notesRu: z.string().optional(),
|
||||
notesEn: z.string().optional(),
|
||||
tax: z.string().refine(
|
||||
(v) => v.trim() !== '' && !isNaN(Number(v)) && Number(v) > 0,
|
||||
t('validation.positiveNumber', 'validation.positiveNumber'),
|
||||
),
|
||||
loanTerm: z.string().refine(
|
||||
(v) => v.trim() !== '' && !isNaN(Number(v)) && Number(v) > 0,
|
||||
t('validation.positiveNumber', 'validation.positiveNumber'),
|
||||
),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
}
|
||||
|
||||
export const loanTypeFormSchema = z.object({
|
||||
nameTk: z.string().min(1, t('validation.required', '')),
|
||||
nameRu: z.string().min(1, t('validation.required', '')),
|
||||
nameEn: z.string().min(1, t('validation.required', '')),
|
||||
notesTk: z.string().optional(),
|
||||
notesRu: z.string().optional(),
|
||||
notesEn: z.string().optional(),
|
||||
tax: z.string().refine(
|
||||
(v) => v.trim() !== '' && !isNaN(Number(v)) && Number(v) > 0,
|
||||
t('validation.positiveNumber', 'Oňyn san gerek'),
|
||||
),
|
||||
loanTerm: z.string().refine(
|
||||
(v) => v.trim() !== '' && !isNaN(Number(v)) && Number(v) > 0,
|
||||
t('validation.positiveNumber', 'Oňyn san gerek'),
|
||||
),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
|
||||
export type LoanTypeFormData = z.infer<typeof loanTypeFormSchema>
|
||||
export type LoanTypeFormData = z.infer<ReturnType<typeof createLoanTypeFormSchema>>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: LoanTypeFormData = {
|
||||
nameTk: '',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMemo } from 'react'
|
||||
import { useMemo, useEffect, useCallback } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
@@ -35,7 +35,11 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
||||
// ─── OperatorForm ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function OperatorForm({ mode, initialData, operatorId }: OperatorFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
|
||||
const createMutation = useCreateOperator()
|
||||
@@ -43,7 +47,7 @@ export function OperatorForm({ mode, initialData, operatorId }: OperatorFormProp
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const schema = useMemo(() => operatorFormSchema(mode), [mode])
|
||||
const schema = useMemo(() => operatorFormSchema(mode, t), [mode, t, i18n.language])
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
@@ -70,6 +74,14 @@ export function OperatorForm({ mode, initialData, operatorId }: OperatorFormProp
|
||||
clearErrors(key)
|
||||
}
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) {
|
||||
trigger()
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
|
||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger()
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
import { z } from 'zod'
|
||||
import i18next from 'i18next'
|
||||
import type { CreateOperatorPayload } from '../api/operatorsApi'
|
||||
|
||||
const t = i18next.t.bind(i18next)
|
||||
export function operatorFormSchema(
|
||||
mode: 'create' | 'edit',
|
||||
t: (key: string, fallback?: string) => string,
|
||||
) {
|
||||
const baseSchema = z.object({
|
||||
username: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
name: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
phone: z.string().default(''),
|
||||
email: z.string().default(''),
|
||||
password: z.string(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
|
||||
const baseSchema = z.object({
|
||||
username: z.string().min(1, t('validation.required', '')),
|
||||
name: z.string().min(1, t('validation.required', '')),
|
||||
phone: z.string().default(''),
|
||||
email: z.string().default(''),
|
||||
password: z.string(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
|
||||
export function operatorFormSchema(mode: 'create' | 'edit') {
|
||||
return mode === 'create'
|
||||
? baseSchema.extend({
|
||||
password: z.string().min(1, t('validation.required', '')),
|
||||
password: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
})
|
||||
: baseSchema
|
||||
}
|
||||
|
||||
export type OperatorFormData = z.infer<typeof baseSchema>
|
||||
export type OperatorFormData = z.infer<ReturnType<typeof operatorFormSchema>>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: OperatorFormData = {
|
||||
username: '',
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { useState } from 'react'
|
||||
import { useState, 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 { FormActions } from '@/components/formActions'
|
||||
import { useCreatePermission, useUpdatePermission } from '../hooks/usePermissions'
|
||||
import type { Permission, PermissionPayload } from '../api/permissionsApi'
|
||||
import { createPermissionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/permission.schema'
|
||||
import type { PermissionFormData } from '../schemas/permission.schema'
|
||||
import type { Permission } from '../api/permissionsApi'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -14,14 +18,6 @@ interface PermissionFormProps {
|
||||
permissionId?: number
|
||||
}
|
||||
|
||||
interface FormErrors {
|
||||
code?: string
|
||||
name_tk?: string
|
||||
name_ru?: string
|
||||
name_en?: string
|
||||
guard_name?: string
|
||||
}
|
||||
|
||||
type LangKey = 'tk' | 'ru' | 'en'
|
||||
|
||||
const LANG_TABS: { key: LangKey; label: string }[] = [
|
||||
@@ -36,10 +32,25 @@ const GUARD_OPTIONS = [
|
||||
{ value: 'sanctum', label: 'sanctum' },
|
||||
]
|
||||
|
||||
type FlatErrors = Partial<Record<keyof PermissionFormData, string>>
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof PermissionFormData] = msg
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ─── PermissionForm ───────────────────────────────────────────────────────────
|
||||
|
||||
export function PermissionForm({ mode, initialData, permissionId }: PermissionFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
|
||||
const createPermission = useCreatePermission()
|
||||
@@ -48,57 +59,63 @@ export function PermissionForm({ mode, initialData, permissionId }: PermissionFo
|
||||
const isPending = createPermission.isPending || updatePermission.isPending
|
||||
|
||||
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
|
||||
const [form, setForm] = useState<PermissionPayload>({
|
||||
code: initialData?.code ?? '',
|
||||
guard_name: initialData?.guard_name ?? 'web',
|
||||
name: {
|
||||
tk: initialData?.name?.tk ?? '',
|
||||
ru: initialData?.name?.ru ?? '',
|
||||
en: initialData?.name?.en ?? '',
|
||||
},
|
||||
const schema = useMemo(() => createPermissionFormSchema(t), [t, i18n.language])
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
} = useForm<PermissionFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData
|
||||
? {
|
||||
...DEFAULT_FORM_VALUES,
|
||||
code: initialData.code,
|
||||
nameTk: initialData.name.tk,
|
||||
nameRu: initialData.name.ru,
|
||||
nameEn: initialData.name.en,
|
||||
guard_name: initialData.guard_name,
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
|
||||
const setField = (field: keyof Omit<PermissionPayload, 'name'>, value: string) => {
|
||||
setForm((prev) => ({ ...prev, [field]: value }))
|
||||
setErrors((prev) => ({ ...prev, [field]: undefined }))
|
||||
}
|
||||
const setField = useCallback(
|
||||
(key: keyof PermissionFormData) => (value: string) => {
|
||||
(setValue as (k: keyof PermissionFormData, v: string) => void)(key, value)
|
||||
clearErrors(key)
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
)
|
||||
|
||||
const setNameField = (lang: LangKey, value: string) => {
|
||||
setForm((prev) => ({ ...prev, name: { ...prev.name, [lang]: value } }))
|
||||
setErrors((prev) => ({ ...prev, [`name_${lang}`]: undefined }))
|
||||
const key = `name${lang.charAt(0).toUpperCase() + lang.slice(1)}` as 'nameTk' | 'nameRu' | 'nameEn'
|
||||
setValue(key, value)
|
||||
clearErrors(key)
|
||||
}
|
||||
|
||||
// ── Validation ─────────────────────────────────────────────────────────────
|
||||
|
||||
const validate = (): boolean => {
|
||||
const newErrors: FormErrors = {}
|
||||
|
||||
if (!form.code.trim())
|
||||
newErrors.code = t('permissions.validation.codeRequired', 'Kod hökman!')
|
||||
if (!form.name.tk.trim())
|
||||
newErrors.name_tk = t('permissions.validation.nameTkRequired', 'Türkmençe ady hökman!')
|
||||
if (!form.guard_name.trim())
|
||||
newErrors.guard_name = t('permissions.validation.guardRequired', 'Guard name hökman!')
|
||||
|
||||
setErrors(newErrors)
|
||||
return Object.keys(newErrors).length === 0
|
||||
}
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
|
||||
// ── Submit ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!validate()) return
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
|
||||
const values = getValues()
|
||||
const payload = buildPayload(values)
|
||||
|
||||
if (mode === 'create') {
|
||||
createPermission.mutate(form, {
|
||||
createPermission.mutate(payload, {
|
||||
onSuccess: () => navigate('/settings/users/permissions'),
|
||||
})
|
||||
} else {
|
||||
updatePermission.mutate(form, {
|
||||
updatePermission.mutate(payload, {
|
||||
onSuccess: () => navigate('/settings/users/permissions'),
|
||||
})
|
||||
}
|
||||
@@ -106,6 +123,9 @@ export function PermissionForm({ mode, initialData, permissionId }: PermissionFo
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const activeNameKey = `name${activeLang.charAt(0).toUpperCase() + activeLang.slice(1)}` as 'nameTk' | 'nameRu' | 'nameEn'
|
||||
const nameError = errors[activeNameKey]
|
||||
|
||||
return (
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden">
|
||||
|
||||
@@ -118,7 +138,7 @@ export function PermissionForm({ mode, initialData, permissionId }: PermissionFo
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.code}
|
||||
onChange={(v) => setField('code', v)}
|
||||
onChange={setField('code')}
|
||||
placeholder={t('permissions.fields.code', 'Kod')}
|
||||
error={errors.code}
|
||||
disabled={isPending}
|
||||
@@ -150,10 +170,10 @@ export function PermissionForm({ mode, initialData, permissionId }: PermissionFo
|
||||
</div>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.name[activeLang]}
|
||||
value={form[activeNameKey]}
|
||||
onChange={(v) => setNameField(activeLang, v)}
|
||||
placeholder={t('permissions.fields.name', 'Ady')}
|
||||
error={errors[`name_${activeLang}` as keyof FormErrors]}
|
||||
error={nameError}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
@@ -168,7 +188,7 @@ export function PermissionForm({ mode, initialData, permissionId }: PermissionFo
|
||||
<FormInput
|
||||
type="select"
|
||||
value={form.guard_name}
|
||||
onChange={(v) => setField('guard_name', v)}
|
||||
onChange={setField('guard_name')}
|
||||
options={GUARD_OPTIONS}
|
||||
error={errors.guard_name}
|
||||
disabled={isPending}
|
||||
|
||||
34
src/features/permissions/schemas/permission.schema.ts
Normal file
34
src/features/permissions/schemas/permission.schema.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { z } from 'zod'
|
||||
import type { PermissionPayload } from '../api/permissionsApi'
|
||||
|
||||
export function createPermissionFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
code: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
guard_name: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
})
|
||||
}
|
||||
|
||||
export type PermissionFormData = z.infer<ReturnType<typeof createPermissionFormSchema>>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: PermissionFormData = {
|
||||
code: '',
|
||||
nameTk: '',
|
||||
nameRu: '',
|
||||
nameEn: '',
|
||||
guard_name: 'web',
|
||||
}
|
||||
|
||||
export function buildPayload(data: PermissionFormData): PermissionPayload {
|
||||
return {
|
||||
code: data.code,
|
||||
name: {
|
||||
tk: data.nameTk,
|
||||
ru: data.nameRu,
|
||||
en: data.nameEn,
|
||||
},
|
||||
guard_name: data.guard_name,
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ import { cn } from '@/lib/utils'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { useCreateRequiredDocument, useUpdateRequiredDocument } from '../hooks/useRequiredDocuments'
|
||||
import { requiredDocumentFormSchema, DEFAULT_FORM_VALUES, buildPayload, mapInitial } from '../schemas/requiredDocument.schema'
|
||||
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'
|
||||
|
||||
@@ -199,7 +199,11 @@ function flattenErrors(
|
||||
// ─── RequiredDocumentForm ─────────────────────────────────────────────────────────
|
||||
|
||||
export function RequiredDocumentForm({ mode, initialData, requiredDocumentId }: RequiredDocumentFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
|
||||
// Per-field locale tabs (UI only, not form state)
|
||||
@@ -211,6 +215,8 @@ export function RequiredDocumentForm({ mode, initialData, requiredDocumentId }:
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const schema = useMemo(() => createRequiredDocumentFormSchema(t), [t, i18n.language])
|
||||
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
@@ -218,7 +224,7 @@ export function RequiredDocumentForm({ mode, initialData, requiredDocumentId }:
|
||||
formState: { errors: rhfErrors },
|
||||
trigger,
|
||||
} = useForm<RequiredDocumentFormData>({
|
||||
resolver: zodResolver(requiredDocumentFormSchema),
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
@@ -230,6 +236,12 @@ export function RequiredDocumentForm({ mode, initialData, requiredDocumentId }:
|
||||
[rhfErrors],
|
||||
)
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
|
||||
// Derive LoanDocumentTranslation objects so the JSX stays unchanged
|
||||
const name: LoanDocumentTranslation = useMemo(
|
||||
() => ({ tk: form.nameTk, ru: form.nameRu, en: form.nameEn }),
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
import { z } from 'zod'
|
||||
import i18next from 'i18next'
|
||||
import type { LoanDocument, LoanDocumentPayload } from '../api/requiredDocumentsApi'
|
||||
|
||||
const t = i18next.t.bind(i18next)
|
||||
export function createRequiredDocumentFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
descTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
descRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
descEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
})
|
||||
}
|
||||
|
||||
export const requiredDocumentFormSchema = z.object({
|
||||
nameTk: z.string().min(1, t('validation.required', '')),
|
||||
nameRu: z.string().min(1, t('validation.required', '')),
|
||||
nameEn: z.string().min(1, t('validation.required', '')),
|
||||
descTk: z.string().min(1, t('validation.required', '')),
|
||||
descRu: z.string().min(1, t('validation.required', '')),
|
||||
descEn: z.string().min(1, t('validation.required', '')),
|
||||
})
|
||||
|
||||
export type RequiredDocumentFormData = z.infer<typeof requiredDocumentFormSchema>
|
||||
export type RequiredDocumentFormData = z.infer<ReturnType<typeof createRequiredDocumentFormSchema>>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: RequiredDocumentFormData = {
|
||||
nameTk: '',
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { useState } from 'react'
|
||||
import { useState, 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 { FormActions } from '@/components/formActions'
|
||||
import { useCreateRole, useUpdateRole } from '../hooks/useRoles'
|
||||
import type { Role, RolePayload } from '../api/rolesApi'
|
||||
import { createRoleFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/role.schema'
|
||||
import type { RoleFormData } from '../schemas/role.schema'
|
||||
import type { Role } from '../api/rolesApi'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -14,14 +18,6 @@ interface RoleFormProps {
|
||||
roleId?: number
|
||||
}
|
||||
|
||||
interface FormErrors {
|
||||
code?: string
|
||||
name_tk?: string
|
||||
name_ru?: string
|
||||
name_en?: string
|
||||
guard_name?: string
|
||||
}
|
||||
|
||||
type LangKey = 'tk' | 'ru' | 'en'
|
||||
|
||||
const LANG_TABS: { key: LangKey; label: string }[] = [
|
||||
@@ -36,10 +32,25 @@ const GUARD_OPTIONS = [
|
||||
{ value: 'sanctum', label: 'sanctum' },
|
||||
]
|
||||
|
||||
type FlatErrors = Partial<Record<keyof RoleFormData, string>>
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof RoleFormData] = msg
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ─── RoleForm ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export function RoleForm({ mode, initialData, roleId }: RoleFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
|
||||
const createRole = useCreateRole()
|
||||
@@ -48,57 +59,63 @@ export function RoleForm({ mode, initialData, roleId }: RoleFormProps) {
|
||||
const isPending = createRole.isPending || updateRole.isPending
|
||||
|
||||
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
|
||||
const [form, setForm] = useState<RolePayload>({
|
||||
code: initialData?.code ?? '',
|
||||
guard_name: initialData?.guard_name ?? 'web',
|
||||
name: {
|
||||
tk: initialData?.name?.tk ?? '',
|
||||
ru: initialData?.name?.ru ?? '',
|
||||
en: initialData?.name?.en ?? '',
|
||||
},
|
||||
const schema = useMemo(() => createRoleFormSchema(t), [t, i18n.language])
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
} = useForm<RoleFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData
|
||||
? {
|
||||
...DEFAULT_FORM_VALUES,
|
||||
code: initialData.code,
|
||||
nameTk: initialData.name.tk,
|
||||
nameRu: initialData.name.ru,
|
||||
nameEn: initialData.name.en,
|
||||
guard_name: initialData.guard_name,
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
|
||||
const setField = (field: keyof Omit<RolePayload, 'name'>, value: string) => {
|
||||
setForm((prev) => ({ ...prev, [field]: value }))
|
||||
setErrors((prev) => ({ ...prev, [field]: undefined }))
|
||||
}
|
||||
const setField = useCallback(
|
||||
(key: keyof RoleFormData) => (value: string) => {
|
||||
(setValue as (k: keyof RoleFormData, v: string) => void)(key, value)
|
||||
clearErrors(key)
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
)
|
||||
|
||||
const setNameField = (lang: LangKey, value: string) => {
|
||||
setForm((prev) => ({ ...prev, name: { ...prev.name, [lang]: value } }))
|
||||
setErrors((prev) => ({ ...prev, [`name_${lang}`]: undefined }))
|
||||
const key = `name${lang.charAt(0).toUpperCase() + lang.slice(1)}` as 'nameTk' | 'nameRu' | 'nameEn'
|
||||
setValue(key, value)
|
||||
clearErrors(key)
|
||||
}
|
||||
|
||||
// ── Validation ─────────────────────────────────────────────────────────────
|
||||
|
||||
const validate = (): boolean => {
|
||||
const newErrors: FormErrors = {}
|
||||
|
||||
if (!form.code.trim())
|
||||
newErrors.code = t('roles.validation.codeRequired', 'Kod hökman!')
|
||||
if (!form.name.tk.trim())
|
||||
newErrors.name_tk = t('roles.validation.nameTkRequired', 'Türkmençe ady hökman!')
|
||||
if (!form.guard_name.trim())
|
||||
newErrors.guard_name = t('roles.validation.guardRequired', 'Guard name hökman!')
|
||||
|
||||
setErrors(newErrors)
|
||||
return Object.keys(newErrors).length === 0
|
||||
}
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
|
||||
// ── Submit ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!validate()) return
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
|
||||
const values = getValues()
|
||||
const payload = buildPayload(values)
|
||||
|
||||
if (mode === 'create') {
|
||||
createRole.mutate(form, {
|
||||
createRole.mutate(payload, {
|
||||
onSuccess: () => navigate('/settings/users/roles'),
|
||||
})
|
||||
} else {
|
||||
updateRole.mutate(form, {
|
||||
updateRole.mutate(payload, {
|
||||
onSuccess: () => navigate('/settings/users/roles'),
|
||||
})
|
||||
}
|
||||
@@ -106,6 +123,9 @@ export function RoleForm({ mode, initialData, roleId }: RoleFormProps) {
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const activeNameKey = `name${activeLang.charAt(0).toUpperCase() + activeLang.slice(1)}` as 'nameTk' | 'nameRu' | 'nameEn'
|
||||
const nameError = activeLang === 'tk' ? errors[activeNameKey] : undefined
|
||||
|
||||
return (
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden">
|
||||
|
||||
@@ -118,7 +138,7 @@ export function RoleForm({ mode, initialData, roleId }: RoleFormProps) {
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.code}
|
||||
onChange={(v) => setField('code', v)}
|
||||
onChange={setField('code')}
|
||||
placeholder={t('roles.fields.code', 'Kod')}
|
||||
error={errors.code}
|
||||
disabled={isPending}
|
||||
@@ -132,7 +152,6 @@ export function RoleForm({ mode, initialData, roleId }: RoleFormProps) {
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<div className="space-y-2">
|
||||
{/* Language tabs */}
|
||||
<div className="flex gap-1 justify-end">
|
||||
{LANG_TABS.map((tab) => (
|
||||
<button
|
||||
@@ -151,10 +170,10 @@ export function RoleForm({ mode, initialData, roleId }: RoleFormProps) {
|
||||
</div>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.name[activeLang]}
|
||||
value={form[activeNameKey]}
|
||||
onChange={(v) => setNameField(activeLang, v)}
|
||||
placeholder={t('roles.fields.name', 'Ady')}
|
||||
error={errors[`name_${activeLang}` as keyof FormErrors]}
|
||||
error={nameError}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
@@ -169,7 +188,7 @@ export function RoleForm({ mode, initialData, roleId }: RoleFormProps) {
|
||||
<FormInput
|
||||
type="select"
|
||||
value={form.guard_name}
|
||||
onChange={(v) => setField('guard_name', v)}
|
||||
onChange={setField('guard_name')}
|
||||
options={GUARD_OPTIONS}
|
||||
error={errors.guard_name}
|
||||
disabled={isPending}
|
||||
|
||||
34
src/features/roles/schemas/role.schema.ts
Normal file
34
src/features/roles/schemas/role.schema.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { z } from 'zod'
|
||||
import type { RolePayload } from '../api/rolesApi'
|
||||
|
||||
export function createRoleFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
code: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
guard_name: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
})
|
||||
}
|
||||
|
||||
export type RoleFormData = z.infer<ReturnType<typeof createRoleFormSchema>>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: RoleFormData = {
|
||||
code: '',
|
||||
nameTk: '',
|
||||
nameRu: '',
|
||||
nameEn: '',
|
||||
guard_name: 'web',
|
||||
}
|
||||
|
||||
export function buildPayload(data: RoleFormData): RolePayload {
|
||||
return {
|
||||
code: data.code,
|
||||
name: {
|
||||
tk: data.nameTk,
|
||||
ru: data.nameRu,
|
||||
en: data.nameEn,
|
||||
},
|
||||
guard_name: data.guard_name,
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useMemo } from 'react'
|
||||
import { useState, useMemo, useEffect, useCallback } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
@@ -59,24 +59,24 @@ type SentDocKey =
|
||||
| 'snt_passport_tm' | 'snt_zagran_passport' | 'snt_entry_stamp'
|
||||
| 'snt_relation_doc' | 'snt_new_passport_series' | 'snt_old_passport_series'
|
||||
|
||||
const ACCEPTED_DOCS: { key: AcceptedDocKey; label: string }[] = [
|
||||
{ key: 'acc_sberbank_card', label: 'Talýba degişli SBERBANK kartynyň rekwizitleri' },
|
||||
{ key: 'acc_enrollment', label: 'Daşary ýurt ÝOM-da okaýandygy baradaky güwänamasy' },
|
||||
{ key: 'acc_summons', label: 'Çagyrylma hatynyn göçürmesi' },
|
||||
{ key: 'acc_passport_tm', label: 'TM içki pasportynyň asyl görnüşi we göçürmesi' },
|
||||
{ key: 'acc_zagran_passport', label: 'Daşary ýurt (zagran) pasportynyň göçürmesi' },
|
||||
{ key: 'acc_visa_page', label: 'Daşary ýurda rugsat (wizasy) bellenen sahypasynyň göçürmesi' },
|
||||
{ key: 'acc_entry_stamp', label: 'Daşary ýurt döwletine girenliği baradaky ştamply sahypasynyň göçürmesi' },
|
||||
{ key: 'acc_school_letter', label: 'ÝOM-dan hat (daşary ýurt dilinde maglumatly)' },
|
||||
const ACCEPTED_DOCS = (t: (key: string, fallback?: string) => string): { key: AcceptedDocKey; label: string }[] => [
|
||||
{ key: 'acc_sberbank_card', label: t('sberPayments.documents.sberbankCard', 'Talýba degişli SBERBANK kartynyň rekwizitleri') },
|
||||
{ key: 'acc_enrollment', label: t('sberPayments.documents.enrollment', 'Daşary ýurt ÝOM-da okaýandygy baradaky güwänamasy') },
|
||||
{ key: 'acc_summons', label: t('sberPayments.documents.summons', 'Çagyrylma hatynyn göçürmesi') },
|
||||
{ key: 'acc_passport_tm', label: t('sberPayments.documents.passportTm', 'TM içki pasportynyň asyl görnüşi we göçürmesi') },
|
||||
{ key: 'acc_zagran_passport', label: t('sberPayments.documents.zagranPassport', 'Daşary ýurt (zagran) pasportynyň göçürmesi') },
|
||||
{ key: 'acc_visa_page', label: t('sberPayments.documents.visaPage', 'Daşary ýurda rugsat (wizasy) bellenen sahypasynyň göçürmesi') },
|
||||
{ key: 'acc_entry_stamp', label: t('sberPayments.documents.entryStamp', 'Daşary ýurt döwletine girenliği baradaky ştamply sahypasynyň göçürmesi') },
|
||||
{ key: 'acc_school_letter', label: t('sberPayments.documents.schoolLetter', 'ÝOM-dan hat (daşary ýurt dilinde maglumatly)') },
|
||||
]
|
||||
|
||||
const SENT_DOCS: { key: SentDocKey; label: string }[] = [
|
||||
{ key: 'snt_passport_tm', label: 'Ugradyjynyň TM içki pasportynyň asyl görnüşi we göçürmesi' },
|
||||
{ key: 'snt_zagran_passport', label: 'Ugradyjynyň daşary ýurt pasportynyň asyl görnüşi we göçürmesi' },
|
||||
{ key: 'snt_entry_stamp', label: 'Ugradyjynyň daşary döwletine girenliği ştamply sahypasynyň göçürmesi' },
|
||||
{ key: 'snt_relation_doc', label: 'Ugradyjy we kabul edijiniň garyndaşlyk tassyklaýjy resminamasynyn göçürmesi' },
|
||||
{ key: 'snt_new_passport_series', label: 'Ugradyjy/kabul ediji täze (2015+) pasport seriýasy maglumaty' },
|
||||
{ key: 'snt_old_passport_series', label: 'Ugradyjy/kabul ediji köne pasport seriýasy baradaky güwänamasy' },
|
||||
const SENT_DOCS = (t: (key: string, fallback?: string) => string): { key: SentDocKey; label: string }[] => [
|
||||
{ key: 'snt_passport_tm', label: t('sberPayments.documents.sentPassportTm', 'Ugradyjynyň TM içki pasportynyň asyl görnüşi we göçürmesi') },
|
||||
{ key: 'snt_zagran_passport', label: t('sberPayments.documents.sentZagranPassport', 'Ugradyjynyň daşary ýurt pasportynyň asyl görnüşi we göçürmesi') },
|
||||
{ key: 'snt_entry_stamp', label: t('sberPayments.documents.sentEntryStamp', 'Ugradyjynyň daşary döwletine girenliği ştamply sahypasynyň göçürmesi') },
|
||||
{ key: 'snt_relation_doc', label: t('sberPayments.documents.sentRelationDoc', 'Ugradyjy we kabul edijiniň garyndaşlyk tassyklaýjy resminamasynyn göçürmesi') },
|
||||
{ key: 'snt_new_passport_series', label: t('sberPayments.documents.sentNewPassportSeries', 'Ugradyjy/kabul ediji täze (2015+) pasport seriýasy maglumaty') },
|
||||
{ key: 'snt_old_passport_series', label: t('sberPayments.documents.sentOldPassportSeries', 'Ugradyjy/kabul ediji köne pasport seriýasy baradaky güwänamasy') },
|
||||
]
|
||||
|
||||
|
||||
@@ -118,30 +118,31 @@ function BentoCard({
|
||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||
|
||||
function StepGeneral({
|
||||
form, errors, set,
|
||||
form, errors, set, t,
|
||||
}: {
|
||||
form: SberPaymentFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||
t: (key: string, fallback?: string) => string
|
||||
}) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title="Müşderi">
|
||||
<BentoCard title={t('sberPayments.cards.musteri', 'Müşderi')}>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label="Ulanyjy"
|
||||
label={t('sberPayments.fields.client_id', 'Ulanyjy')}
|
||||
value={form.client_id}
|
||||
onChange={(v) => set('client_id', v)}
|
||||
options={[]}
|
||||
placeholder="Saýlamak üçin basyň"
|
||||
placeholder={t('sberPayments.placeholders.select', 'Saýlamak üçin basyň')}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title="Status">
|
||||
<BentoCard title={t('sberPayments.cards.status', 'Status')}>
|
||||
<FormInput
|
||||
type="select"
|
||||
label="Status"
|
||||
label={t('sberPayments.fields.status', 'Status')}
|
||||
value={form.status}
|
||||
onChange={(v) => set('status', v as PaymentStatus)}
|
||||
options={STATUSES}
|
||||
@@ -150,13 +151,13 @@ function StepGeneral({
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title="Bellik" span="full">
|
||||
<BentoCard title={t('sberPayments.cards.bellik', 'Bellik')} span="full">
|
||||
<FormInput
|
||||
type="textarea"
|
||||
label="Bellik"
|
||||
label={t('sberPayments.fields.bellik', 'Bellik')}
|
||||
value={form.bellik}
|
||||
onChange={(v) => set('bellik', v)}
|
||||
placeholder="Bellik..."
|
||||
placeholder={t('sberPayments.placeholders.bellik', 'Bellik...')}
|
||||
rows={2}
|
||||
/>
|
||||
</BentoCard>
|
||||
@@ -165,40 +166,41 @@ function StepGeneral({
|
||||
}
|
||||
|
||||
function StepLocation({
|
||||
form, errors, set,
|
||||
form, errors, set, t,
|
||||
}: {
|
||||
form: SberPaymentFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||
t: (key: string, fallback?: string) => string
|
||||
}) {
|
||||
const branches = form.welayat ? (SAHAMCALAR[form.welayat] ?? []) : []
|
||||
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title="Welaýat">
|
||||
<BentoCard title={t('sberPayments.cards.welayat', 'Welaýat')}>
|
||||
<FormInput
|
||||
type="select"
|
||||
label="Welaýat"
|
||||
label={t('sberPayments.fields.welayat', 'Welaýat')}
|
||||
value={form.welayat}
|
||||
onChange={(v) => { set('welayat', v); set('sahamca', '') }}
|
||||
options={WELAYATLAR.map((w) => ({ value: w, label: w }))}
|
||||
placeholder="Aşgabat"
|
||||
placeholder={t('sberPayments.placeholders.welayat', 'Aşgabat')}
|
||||
error={errors.welayat}
|
||||
required
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Welaýaty saýlasaňyz şahamçalar güncellenar.
|
||||
{t('sberPayments.hints.selectRegion', 'Welaýaty saýlasaňyz şahamçalar güncellenar.')}
|
||||
</p>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title="Şahamça">
|
||||
<BentoCard title={t('sberPayments.cards.sahamca', 'Şahamça')}>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label="Şahamça"
|
||||
label={t('sberPayments.fields.sahamca', 'Şahamça')}
|
||||
value={form.sahamca}
|
||||
onChange={(v) => set('sahamca', v)}
|
||||
options={branches.map((b) => ({ value: b, label: b }))}
|
||||
placeholder="Saýlamak üçin basyň"
|
||||
placeholder={t('sberPayments.placeholders.select', 'Saýlamak üçin basyň')}
|
||||
disabled={!form.welayat}
|
||||
error={errors.sahamca}
|
||||
required
|
||||
@@ -209,39 +211,40 @@ function StepLocation({
|
||||
}
|
||||
|
||||
function StepPersonal({
|
||||
form, errors, set,
|
||||
form, errors, set, t,
|
||||
}: {
|
||||
form: SberPaymentFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||
t: (key: string, fallback?: string) => string
|
||||
}) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title="At-familýa">
|
||||
<BentoCard title={t('sberPayments.cards.atFamilia', 'At-familýa')}>
|
||||
<FormInput
|
||||
type="text"
|
||||
label="Pasportdaky familiýa"
|
||||
label={t('sberPayments.fields.lastName', 'Pasportdaky familiýa')}
|
||||
value={form.lastName}
|
||||
onChange={(v) => set('lastName', v)}
|
||||
placeholder="NURYYEW"
|
||||
placeholder={t('sberPayments.placeholders.lastName', 'NURYYEW')}
|
||||
error={errors.lastName}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label="Pasportdaky ady"
|
||||
label={t('sberPayments.fields.firstName', 'Pasportdaky ady')}
|
||||
value={form.firstName}
|
||||
onChange={(v) => set('firstName', v)}
|
||||
placeholder="HAÝDAR"
|
||||
placeholder={t('sberPayments.placeholders.firstName', 'HAÝDAR')}
|
||||
error={errors.firstName}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title="Kontakt">
|
||||
<BentoCard title={t('sberPayments.cards.kontakt', 'Kontakt')}>
|
||||
<FormInput
|
||||
type="phone"
|
||||
label="Telefon"
|
||||
label={t('sberPayments.fields.phone', 'Telefon')}
|
||||
value={form.phone}
|
||||
onChange={(v) => set('phone', v)}
|
||||
error={errors.phone}
|
||||
@@ -249,20 +252,20 @@ function StepPersonal({
|
||||
/>
|
||||
<FormInput
|
||||
type="email"
|
||||
label="E-poçta"
|
||||
label={t('sberPayments.fields.email', 'E-poçta')}
|
||||
value={form.email}
|
||||
onChange={(v) => set('email', v)}
|
||||
placeholder="email@example.com"
|
||||
placeholder={t('sberPayments.placeholders.email', 'email@example.com')}
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title="Häzirki ýaşyş ýeri" span="full">
|
||||
<BentoCard title={t('sberPayments.cards.yasysYeri', 'Häzirki ýaşyş ýeri')} span="full">
|
||||
<FormInput
|
||||
type="text"
|
||||
label="Salgy"
|
||||
label={t('sberPayments.fields.address', 'Salgy')}
|
||||
value={form.address}
|
||||
onChange={(v) => set('address', v)}
|
||||
placeholder="Köçe, jaý belgisi..."
|
||||
placeholder={t('sberPayments.placeholders.address', 'Köçe, jaý belgisi...')}
|
||||
error={errors.address}
|
||||
required
|
||||
/>
|
||||
@@ -272,18 +275,19 @@ function StepPersonal({
|
||||
}
|
||||
|
||||
function StepPayment({
|
||||
form, errors, set,
|
||||
form, errors, set, t,
|
||||
}: {
|
||||
form: SberPaymentFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||
t: (key: string, fallback?: string) => string
|
||||
}) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title="Pasport maglumatlary">
|
||||
<BentoCard title={t('sberPayments.cards.pasportMaglumatlary', 'Pasport maglumatlary')}>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label="Pasport seriýasy"
|
||||
label={t('sberPayments.fields.passportSeries', 'Pasport seriýasy')}
|
||||
value={form.passportSeries}
|
||||
onChange={(v) => set('passportSeries', v)}
|
||||
options={[
|
||||
@@ -292,37 +296,37 @@ function StepPayment({
|
||||
{ value: 'II-MC', label: 'II-MC' },
|
||||
{ value: 'II-MD', label: 'II-MD' },
|
||||
]}
|
||||
placeholder="Saýlamak üçin basyň"
|
||||
placeholder={t('sberPayments.placeholders.select', 'Saýlamak üçin basyň')}
|
||||
error={errors.passportSeries}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label="Pasport nomeri"
|
||||
label={t('sberPayments.fields.passportNumber', 'Pasport nomeri')}
|
||||
value={form.passportNumber}
|
||||
onChange={(v) => set('passportNumber', v)}
|
||||
placeholder="A123456"
|
||||
placeholder={t('sberPayments.placeholders.passportNumber', 'A123456')}
|
||||
error={errors.passportNumber}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title="Ugradyjy">
|
||||
<BentoCard title={t('sberPayments.cards.ugradyjy', 'Ugradyjy')}>
|
||||
<FormInput
|
||||
type="text"
|
||||
label="Ady Familiýasy Atasynyň ady"
|
||||
label={t('sberPayments.fields.fullName', 'Ady Familiýasy Atasynyň ady')}
|
||||
value={form.fullName}
|
||||
onChange={(v) => set('fullName', v)}
|
||||
placeholder="Doly ady..."
|
||||
placeholder={t('sberPayments.placeholders.fullName', 'Doly ady...')}
|
||||
error={errors.fullName}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label="Goýum hasaby"
|
||||
label={t('sberPayments.fields.accountNumber', 'Goýum hasaby')}
|
||||
value={form.accountNumber}
|
||||
onChange={(v) => set('accountNumber', v)}
|
||||
placeholder="1234 5678 ..."
|
||||
placeholder={t('sberPayments.placeholders.accountNumber', '1234 5678 ...')}
|
||||
error={errors.accountNumber}
|
||||
required
|
||||
/>
|
||||
@@ -332,16 +336,17 @@ function StepPayment({
|
||||
}
|
||||
|
||||
function StepDocs({
|
||||
form, set,
|
||||
form, set, t,
|
||||
}: {
|
||||
form: SberPaymentFormData
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||
t: (key: string, fallback?: string) => string
|
||||
}) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title="Kabul ediji talyp — 8 resminama">
|
||||
<BentoCard title={t('sberPayments.cards.documentsAccepted', 'Kabul ediji talyp — 8 resminama')}>
|
||||
<div className="space-y-3">
|
||||
{ACCEPTED_DOCS.map(({ key, label }) => (
|
||||
{ACCEPTED_DOCS(t).map(({ key, label }) => (
|
||||
<FormInput
|
||||
key={key}
|
||||
type="file"
|
||||
@@ -354,9 +359,9 @@ function StepDocs({
|
||||
</div>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title="Ugradyjy — 6 resminama">
|
||||
<BentoCard title={t('sberPayments.cards.documentsSent', 'Ugradyjy — 6 resminama')}>
|
||||
<div className="space-y-3">
|
||||
{SENT_DOCS.map(({ key, label }) => (
|
||||
{SENT_DOCS(t).map(({ key, label }) => (
|
||||
<FormInput
|
||||
key={key}
|
||||
type="file"
|
||||
@@ -376,12 +381,12 @@ function StepDocs({
|
||||
|
||||
type StepId = 'general' | 'location' | 'personal' | 'payment' | 'docs'
|
||||
|
||||
const STEPS: { id: StepId; title: string; subtitle: string }[] = [
|
||||
{ id: 'general', title: 'Esasy', subtitle: 'Status, müşderi' },
|
||||
{ id: 'location', title: 'Lokasiýa', subtitle: 'Welaýat, şahamça' },
|
||||
{ id: 'personal', title: 'Şahsy', subtitle: 'Pasport, kontakt' },
|
||||
{ id: 'payment', title: 'Töleg', subtitle: 'Hasap, ugradyjy' },
|
||||
{ id: 'docs', title: 'Resminamalar', subtitle: '14 resminama' },
|
||||
const getSteps = (t: (key: string, fallback?: string) => string): { id: StepId; title: string; subtitle: string }[] => [
|
||||
{ id: 'general', title: t('sberPayments.steps.general.title', 'Esasy'), subtitle: t('sberPayments.steps.general.subtitle', 'Status, müşderi') },
|
||||
{ id: 'location', title: t('sberPayments.steps.location.title', 'Lokasiýa'), subtitle: t('sberPayments.steps.location.subtitle', 'Welaýat, şahamça') },
|
||||
{ id: 'personal', title: t('sberPayments.steps.personal.title', 'Şahsy'), subtitle: t('sberPayments.steps.personal.subtitle', 'Pasport, kontakt') },
|
||||
{ id: 'payment', title: t('sberPayments.steps.payment.title', 'Töleg'), subtitle: t('sberPayments.steps.payment.subtitle', 'Hasap, ugradyjy') },
|
||||
{ id: 'docs', title: t('sberPayments.steps.docs.title', 'Resminamalar'), subtitle: t('sberPayments.steps.docs.subtitle', '14 resminama') },
|
||||
]
|
||||
|
||||
// ─── Initial data mapper ──────────────────────────────────────────────────────
|
||||
@@ -407,7 +412,11 @@ function mapInitialData(data: SberPaymentOrder): Partial<SberPaymentFormData> {
|
||||
// ─── Main component ───────────────────────────────────────────────────────────
|
||||
|
||||
export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
const createMutation = useCreateSberPayment()
|
||||
const updateMutation = useUpdateSberPayment()
|
||||
@@ -422,33 +431,59 @@ export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormP
|
||||
})
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
const [validationErrors, setValidationErrors] = useState<FlatErrors>({})
|
||||
|
||||
const rhfFlat = useMemo(
|
||||
() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>),
|
||||
[rhfErrors],
|
||||
)
|
||||
const errors = useMemo(
|
||||
() => ({ ...rhfFlat, ...validationErrors }),
|
||||
[rhfFlat, validationErrors],
|
||||
)
|
||||
|
||||
const steps = useMemo(() => getSteps(t), [i18n.language])
|
||||
|
||||
const [currentStep, setCurrentStep] = useState(0)
|
||||
const [stepStatuses, setStepStatuses] = useState<StepStatus[]>(
|
||||
() => mode === 'edit'
|
||||
? STEPS.map((_, i) => (i === 0 ? 'active' : i < 4 ? 'done' : 'idle'))
|
||||
: STEPS.map((_, i) => (i === 0 ? 'active' : 'idle')),
|
||||
? steps.map((_, i) => (i === 0 ? 'active' : i < 4 ? 'done' : 'idle'))
|
||||
: steps.map((_, i) => (i === 0 ? 'active' : 'idle')),
|
||||
)
|
||||
|
||||
// ── Field setter ──
|
||||
const set = <K extends keyof SberPaymentFormData>(key: K, value: SberPaymentFormData[K]) => {
|
||||
(setValue as (name: K, val: SberPaymentFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
setValidationErrors((prev) => {
|
||||
const next = { ...prev }
|
||||
delete next[key]
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
// ── Step validation ──
|
||||
const doValidateAll = (): FlatErrors => {
|
||||
const errs: FlatErrors = {}
|
||||
for (let i = 0; i <= 3; i++) {
|
||||
Object.assign(errs, validateStep(i, form, mode))
|
||||
Object.assign(errs, validateStep(i, form, mode, t))
|
||||
}
|
||||
setValidationErrors(errs)
|
||||
return errs
|
||||
}
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
const hasErrors = Object.keys(validationErrors).length > 0 || Object.keys(rhfErrors).length > 0
|
||||
if (hasErrors) {
|
||||
doValidateAll()
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
|
||||
// ── Navigation ──
|
||||
const goStep = (idx: number) => {
|
||||
if (idx < 0 || idx >= STEPS.length) return
|
||||
if (idx < 0 || idx >= steps.length) return
|
||||
setStepStatuses((prev) => {
|
||||
const next = [...prev]
|
||||
if (idx > currentStep) next[currentStep] = 'done'
|
||||
@@ -461,18 +496,21 @@ export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormP
|
||||
return next
|
||||
})
|
||||
clearErrors()
|
||||
setValidationErrors({})
|
||||
setCurrentStep(idx)
|
||||
}
|
||||
|
||||
const handleNext = () => {
|
||||
const stepErrors = validateStep(currentStep, form, mode)
|
||||
const stepErrors = validateStep(currentStep, form, mode, t)
|
||||
if (Object.keys(stepErrors).length > 0) {
|
||||
setValidationErrors(stepErrors)
|
||||
setStepStatuses((prev) => {
|
||||
const next = [...prev]; next[currentStep] = 'error'; return next
|
||||
})
|
||||
return
|
||||
}
|
||||
if (currentStep === STEPS.length - 1) {
|
||||
setValidationErrors({})
|
||||
if (currentStep === steps.length - 1) {
|
||||
handleSubmit()
|
||||
} else {
|
||||
goStep(currentStep + 1)
|
||||
@@ -499,7 +537,7 @@ export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormP
|
||||
}
|
||||
|
||||
// ── StepBarCards data ──
|
||||
const stepCardItems: StepCardItem[] = STEPS.map((s, i) => ({
|
||||
const stepCardItems: StepCardItem[] = steps.map((s, i) => ({
|
||||
id: s.id,
|
||||
title: s.title,
|
||||
subtitle: s.subtitle,
|
||||
@@ -507,16 +545,18 @@ export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormP
|
||||
icon: ([User, MapPin, IdCard, CreditCard, Files] as const)[i],
|
||||
}))
|
||||
|
||||
const isLastStep = currentStep === STEPS.length - 1
|
||||
const isLastStep = currentStep === steps.length - 1
|
||||
|
||||
const submitLabel = mode === 'create'
|
||||
? 'Sber töleg (talyplar üçin) dörediň'
|
||||
: 'Ýatda sakla'
|
||||
? t('sberPayments.buttons.create', 'Sber töleg (talyplar üçin) dörediň')
|
||||
: t('sberPayments.buttons.update', 'Ýatda sakla')
|
||||
|
||||
return (
|
||||
<div className="mx-auto space-y-6 pb-8">
|
||||
<h1 className="text-2xl font-bold text-foreground">
|
||||
{mode === 'create' ? 'Sber töleg dörediň' : 'Sber töleg redaktirläň'}
|
||||
{mode === 'create'
|
||||
? t('sberPayments.formTitle.create', 'Sber töleg dörediň')
|
||||
: t('sberPayments.formTitle.edit', 'Sber töleg redaktirläň')}
|
||||
</h1>
|
||||
|
||||
{/* ── Step bar ──────────────────────────────────────────────────────── */}
|
||||
@@ -530,11 +570,11 @@ export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormP
|
||||
</div>
|
||||
|
||||
{/* ── Step content ─────────────────────────────────────────────────── */}
|
||||
{STEPS[currentStep].id === 'general' && <StepGeneral form={form} errors={errors} set={set} />}
|
||||
{STEPS[currentStep].id === 'location' && <StepLocation form={form} errors={errors} set={set} />}
|
||||
{STEPS[currentStep].id === 'personal' && <StepPersonal form={form} errors={errors} set={set} />}
|
||||
{STEPS[currentStep].id === 'payment' && <StepPayment form={form} errors={errors} set={set} />}
|
||||
{STEPS[currentStep].id === 'docs' && <StepDocs form={form} set={set} />}
|
||||
{steps[currentStep].id === 'general' && <StepGeneral form={form} errors={errors} set={set} t={t} />}
|
||||
{steps[currentStep].id === 'location' && <StepLocation form={form} errors={errors} set={set} t={t} />}
|
||||
{steps[currentStep].id === 'personal' && <StepPersonal form={form} errors={errors} set={set} t={t} />}
|
||||
{steps[currentStep].id === 'payment' && <StepPayment form={form} errors={errors} set={set} t={t} />}
|
||||
{steps[currentStep].id === 'docs' && <StepDocs form={form} set={set} t={t} />}
|
||||
|
||||
{/* ── Actions ───────────────────────────────────────────────────────── */}
|
||||
<FormActions
|
||||
@@ -545,7 +585,7 @@ export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormP
|
||||
showSubmit={isLastStep}
|
||||
onSubmit={isLastStep ? handleNext : undefined}
|
||||
submitLabel={submitLabel}
|
||||
loadingLabel="Ýüklenýär..."
|
||||
loadingLabel={t('sberPayments.buttons.loading', 'Ýüklenýär...')}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,25 +1,22 @@
|
||||
import { z } from 'zod'
|
||||
import i18next from 'i18next'
|
||||
import type { CreateSberPaymentPayload, PaymentStatus } from '@/features/sberPayments/api/sberPaymentsApi'
|
||||
|
||||
const t = i18next.t.bind(i18next)
|
||||
|
||||
const fileField = z.custom<File | null>((val) => val === null || val instanceof File).nullable()
|
||||
|
||||
export const sberPaymentFormSchema = z.object({
|
||||
welayat: z.string().min(1, t('validation.required', '')),
|
||||
sahamca: z.string().min(1, t('validation.required', '')),
|
||||
firstName: z.string().min(1, t('validation.required', '')),
|
||||
lastName: z.string().min(1, t('validation.required', '')),
|
||||
phone: z.string().min(1, t('validation.required', '')),
|
||||
welayat: z.string().min(1, 'validation.required'),
|
||||
sahamca: z.string().min(1, 'validation.required'),
|
||||
firstName: z.string().min(1, 'validation.required'),
|
||||
lastName: z.string().min(1, 'validation.required'),
|
||||
phone: z.string().min(1, 'validation.required'),
|
||||
email: z.string(),
|
||||
address: z.string().min(1, t('validation.required', '')),
|
||||
status: z.string().min(1, t('validation.required', '')),
|
||||
address: z.string().min(1, 'validation.required'),
|
||||
status: z.string().min(1, 'validation.required'),
|
||||
bellik: z.string(),
|
||||
accountNumber: z.string().min(1, t('validation.required', '')),
|
||||
passportSeries: z.string().min(1, t('validation.required', '')),
|
||||
passportNumber: z.string().min(1, t('validation.required', '')),
|
||||
fullName: z.string().min(1, t('validation.required', '')),
|
||||
accountNumber: z.string().min(1, 'validation.required'),
|
||||
passportSeries: z.string().min(1, 'validation.required'),
|
||||
passportNumber: z.string().min(1, 'validation.required'),
|
||||
fullName: z.string().min(1, 'validation.required'),
|
||||
client_id: z.string().optional(),
|
||||
acc_sberbank_card: fileField,
|
||||
acc_enrollment: fileField,
|
||||
@@ -50,6 +47,7 @@ export function validateStep(
|
||||
stepIndex: number,
|
||||
form: SberPaymentFormData,
|
||||
mode: 'create' | 'edit',
|
||||
t?: (key: string, fallback?: string) => string,
|
||||
): Partial<Record<keyof SberPaymentFormData, string>> {
|
||||
void mode
|
||||
const schema = stepSchemas[stepIndex]
|
||||
@@ -59,7 +57,10 @@ export function validateStep(
|
||||
const errors: Partial<Record<keyof SberPaymentFormData, string>> = {}
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof SberPaymentFormData
|
||||
if (!errors[key]) errors[key] = issue.message
|
||||
if (!errors[key]) {
|
||||
const msg = issue.message
|
||||
errors[key] = t && msg.startsWith('validation.') ? t(msg, msg) : msg
|
||||
}
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useMemo } from 'react'
|
||||
import { useCallback, useEffect, useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
useUpdateVisaMasterSetting,
|
||||
} from '../hooks/useVisaMasterSettings'
|
||||
import {
|
||||
visaMasterSettingFormSchema,
|
||||
createVisaMasterSettingFormSchema,
|
||||
DEFAULT_FORM_VALUES,
|
||||
buildPayload,
|
||||
} from '../schemas/visaMasterSberSetting.schema'
|
||||
@@ -56,7 +56,11 @@ export function VisaMasterSettingForm({
|
||||
initialData,
|
||||
settingId,
|
||||
}: VisaMasterSettingFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t],
|
||||
)
|
||||
|
||||
const errMsg = (msg: string | undefined) =>
|
||||
!msg ? undefined : msg.startsWith('validation.') ? t(msg, msg) : msg
|
||||
@@ -67,6 +71,12 @@ export function VisaMasterSettingForm({
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const schema = useMemo(
|
||||
() => createVisaMasterSettingFormSchema(t),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[i18n.language],
|
||||
)
|
||||
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
@@ -75,7 +85,7 @@ export function VisaMasterSettingForm({
|
||||
trigger,
|
||||
getValues,
|
||||
} = useForm<VisaMasterSettingFormData>({
|
||||
resolver: zodResolver(visaMasterSettingFormSchema),
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
@@ -87,6 +97,13 @@ export function VisaMasterSettingForm({
|
||||
[rhfErrors],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) {
|
||||
trigger()
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language])
|
||||
|
||||
const set = useCallback(
|
||||
(key: keyof VisaMasterSettingFormData) => (value: string) => {
|
||||
setValue(key, value)
|
||||
@@ -111,7 +128,7 @@ export function VisaMasterSettingForm({
|
||||
await updateMutation.mutateAsync(payload)
|
||||
navigate('/resources/visa-master-settings')
|
||||
}
|
||||
}, [mode, createMutation, updateMutation, navigate, trigger, getValues])
|
||||
}, [mode, createMutation, updateMutation, navigate, trigger, getValues, t])
|
||||
|
||||
const handleCancel = () => navigate('/resources/visa-master-settings')
|
||||
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import { z } from 'zod'
|
||||
import type { VisaMasterSettingPayload } from '../api/visaMasterSberSettingsApi'
|
||||
|
||||
export const visaMasterSettingFormSchema = z.object({
|
||||
kod: z.string().min(1, 'validation.required'),
|
||||
ady: z.string().min(1, 'validation.required'),
|
||||
yazgy: z.string().min(1, 'validation.required'),
|
||||
})
|
||||
export function createVisaMasterSettingFormSchema(
|
||||
t: (key: string, fallback?: string) => string,
|
||||
) {
|
||||
return z.object({
|
||||
kod: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
ady: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
yazgy: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
})
|
||||
}
|
||||
|
||||
export type VisaMasterSettingFormData = z.infer<typeof visaMasterSettingFormSchema>
|
||||
export type VisaMasterSettingFormData = z.infer<ReturnType<typeof createVisaMasterSettingFormSchema>>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: VisaMasterSettingFormData = {
|
||||
kod: '',
|
||||
|
||||
Reference in New Issue
Block a user