added zod validation
This commit is contained in:
@@ -1,12 +1,16 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { useCreateUser, useUpdateUser } from '../hooks/useAllUsers'
|
||||
import type { User, CreateUserPayload, UpdateUserPayload } from '../api/allUsersApi'
|
||||
import type { User } from '../api/allUsersApi'
|
||||
import { allUserFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/allUser.schema'
|
||||
import type { AllUserFormData } from '../schemas/allUser.schema'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -16,47 +20,17 @@ interface UserFormProps {
|
||||
userId?: number
|
||||
}
|
||||
|
||||
interface FormState {
|
||||
username: string
|
||||
name: string
|
||||
phone: string
|
||||
email: string
|
||||
password: string
|
||||
phoneVerified: boolean
|
||||
isActive: boolean
|
||||
}
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
interface FormErrors {
|
||||
username?: string
|
||||
name?: string
|
||||
phone?: string
|
||||
email?: string
|
||||
password?: string
|
||||
}
|
||||
type FlatErrors = Partial<Record<keyof AllUserFormData, string>>
|
||||
|
||||
// ─── Validation ───────────────────────────────────────────────────────────────
|
||||
|
||||
function validateForm(state: FormState, mode: 'create' | 'edit'): FormErrors {
|
||||
const errors: FormErrors = {}
|
||||
|
||||
if (!state.username.trim()) errors.username = 'Ulanyjy ady hökmany'
|
||||
else if (state.username.length < 3) errors.username = 'Ulanyjy ady iň az 3 harp bolmaly'
|
||||
|
||||
if (!state.name.trim()) errors.name = 'Ady hökmany'
|
||||
|
||||
if (!state.phone.trim()) errors.phone = 'Telefon hökmany'
|
||||
else if (!/^\d[\d\s-]{6,}$/.test(state.phone)) errors.phone = 'Nädogry telefon formaty'
|
||||
|
||||
if (state.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(state.email)) {
|
||||
errors.email = 'Nädogry e-poçta formaty'
|
||||
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 AllUserFormData] = msg
|
||||
}
|
||||
|
||||
if (mode === 'create') {
|
||||
if (!state.password) errors.password = 'Açar sözi hökmany'
|
||||
else if (state.password.length < 6) errors.password = 'Açar sözi iň az 6 harp bolmaly'
|
||||
}
|
||||
|
||||
return errors
|
||||
return result
|
||||
}
|
||||
|
||||
// ─── UserForm ─────────────────────────────────────────────────────────────────
|
||||
@@ -70,69 +44,53 @@ export function UserForm({ mode, initialData, userId }: UserFormProps) {
|
||||
|
||||
const isPending = createUser.isPending || updateUser.isPending
|
||||
|
||||
const [form, setForm] = useState<FormState>({
|
||||
username: '',
|
||||
name: '',
|
||||
phone: '',
|
||||
email: '',
|
||||
password: '',
|
||||
phoneVerified: false,
|
||||
isActive: true,
|
||||
const schema = useMemo(() => allUserFormSchema(mode), [mode])
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
} = useForm<AllUserFormData>({
|
||||
resolver: zodResolver(schema as any),
|
||||
defaultValues: initialData
|
||||
? {
|
||||
...DEFAULT_FORM_VALUES,
|
||||
username: initialData.username,
|
||||
name: initialData.name,
|
||||
phone: initialData.phone.replace(/^\+993[-\s]?/, ''),
|
||||
email: initialData.email ?? '',
|
||||
password: '',
|
||||
phoneVerified: initialData.phoneVerified,
|
||||
isActive: initialData.isActive,
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
|
||||
// Populate form when initialData is available (edit mode)
|
||||
useEffect(() => {
|
||||
if (initialData) {
|
||||
setForm({
|
||||
username: initialData.username,
|
||||
name: initialData.name,
|
||||
phone: initialData.phone.replace(/^\+993[-\s]?/, ''),
|
||||
email: initialData.email ?? '',
|
||||
password: '',
|
||||
phoneVerified: initialData.phoneVerified,
|
||||
isActive: initialData.isActive,
|
||||
})
|
||||
}
|
||||
}, [initialData])
|
||||
|
||||
const setField = <K extends keyof FormState>(key: K, value: FormState[K]) => {
|
||||
setForm((prev) => ({ ...prev, [key]: value }))
|
||||
if (errors[key as keyof FormErrors]) {
|
||||
setErrors((prev) => ({ ...prev, [key]: undefined }))
|
||||
}
|
||||
const setField = <K extends keyof AllUserFormData>(key: K, value: AllUserFormData[K]) => {
|
||||
(setValue as (name: K, val: AllUserFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const validationErrors = validateForm(form, mode)
|
||||
if (Object.keys(validationErrors).length > 0) {
|
||||
setErrors(validationErrors)
|
||||
return
|
||||
}
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
|
||||
const data = getValues()
|
||||
|
||||
if (mode === 'create') {
|
||||
const payload: CreateUserPayload = {
|
||||
username: form.username.trim(),
|
||||
name: form.name.trim(),
|
||||
phone: form.phone.trim(),
|
||||
email: form.email.trim() || undefined,
|
||||
password: form.password,
|
||||
phoneVerified: form.phoneVerified,
|
||||
isActive: form.isActive,
|
||||
}
|
||||
const payload = buildPayload(data)
|
||||
await createUser.mutateAsync(payload)
|
||||
navigate('/users')
|
||||
} else {
|
||||
const payload: UpdateUserPayload = {
|
||||
username: form.username.trim(),
|
||||
name: form.name.trim(),
|
||||
phone: form.phone.trim(),
|
||||
email: form.email.trim() || undefined,
|
||||
phoneVerified: form.phoneVerified,
|
||||
isActive: form.isActive,
|
||||
}
|
||||
await updateUser.mutateAsync(payload)
|
||||
await updateUser.mutateAsync({
|
||||
username: data.username.trim(),
|
||||
name: data.name.trim(),
|
||||
phone: data.phone.trim(),
|
||||
email: data.email.trim() || undefined,
|
||||
phoneVerified: data.phoneVerified,
|
||||
isActive: data.isActive,
|
||||
})
|
||||
navigate(`/users/${userId}`)
|
||||
}
|
||||
}
|
||||
@@ -309,4 +267,4 @@ export function UserForm({ mode, initialData, userId }: UserFormProps) {
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
55
src/features/allUsers/schemas/allUser.schema.ts
Normal file
55
src/features/allUsers/schemas/allUser.schema.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateUserPayload } from '../api/allUsersApi'
|
||||
|
||||
const baseSchema = z.object({
|
||||
username: z.string()
|
||||
.min(1, 'Ulanyjy ady hökmany')
|
||||
.min(3, 'Ulanyjy ady iň az 3 harp bolmaly'),
|
||||
name: z.string().min(1, 'Ady hökmany'),
|
||||
phone: z.string()
|
||||
.min(1, 'Telefon hökmany')
|
||||
.regex(/^\d[\d\s-]{6,}$/, 'Nädogry telefon formaty'),
|
||||
email: z.string()
|
||||
.refine(
|
||||
(v) => !v || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),
|
||||
'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, 'Açar sözi hökmany')
|
||||
.min(6, 'Açar sözi iň az 6 harp bolmaly'),
|
||||
})
|
||||
: baseSchema
|
||||
}
|
||||
|
||||
export type AllUserFormData = z.infer<typeof baseSchema>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: AllUserFormData = {
|
||||
username: '',
|
||||
name: '',
|
||||
phone: '',
|
||||
email: '',
|
||||
password: '',
|
||||
phoneVerified: false,
|
||||
isActive: true,
|
||||
}
|
||||
|
||||
export function buildPayload(data: AllUserFormData): CreateUserPayload {
|
||||
return {
|
||||
username: data.username.trim(),
|
||||
name: data.name.trim(),
|
||||
phone: data.phone.trim(),
|
||||
email: data.email.trim() || undefined,
|
||||
password: data.password,
|
||||
phoneVerified: data.phoneVerified,
|
||||
isActive: data.isActive,
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, useCallback, useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import { ChevronLeft, ChevronRight, Loader2, Building2, MapPin, Clock } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
@@ -9,26 +10,23 @@ import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
|
||||
import { useCreateBranch, useUpdateBranch } from '@/features/branches/hooks/useBranches'
|
||||
import type { Branch, CreateBranchPayload } from '@/features/branches/api/branchesApi'
|
||||
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 type { BranchFormData } from '@/features/branches/schemas/branch.schema'
|
||||
|
||||
interface FormState {
|
||||
nameTk: string
|
||||
nameRu: string
|
||||
nameEn: string
|
||||
code: string
|
||||
districtId: string
|
||||
addressTk: string
|
||||
addressRu: string
|
||||
addressEn: string
|
||||
phone: string
|
||||
email: string
|
||||
workingHours: string
|
||||
description: string
|
||||
isActive: boolean
|
||||
type FlatErrors = Partial<Record<keyof BranchFormData, 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 BranchFormData] = msg
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
type FormErrors = Partial<Record<keyof FormState, string>>
|
||||
type FormErrors = FlatErrors
|
||||
|
||||
type LangKey = 'tk' | 'ru' | 'en'
|
||||
|
||||
@@ -45,36 +43,7 @@ interface StepDef {
|
||||
shortLabel: string
|
||||
icon: LucideIcon
|
||||
subtitle: string
|
||||
validate: (form: FormState) => FormErrors
|
||||
}
|
||||
|
||||
const INITIAL_STATE: FormState = {
|
||||
nameTk: '', nameRu: '', nameEn: '',
|
||||
code: '',
|
||||
districtId: '',
|
||||
addressTk: '', addressRu: '', addressEn: '',
|
||||
phone: '', email: '',
|
||||
workingHours: '',
|
||||
description: '',
|
||||
isActive: true,
|
||||
}
|
||||
|
||||
function mapToFormState(data: Branch): FormState {
|
||||
return {
|
||||
nameTk: data.name.tk,
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
code: data.code,
|
||||
districtId: String(data.districtId),
|
||||
addressTk: data.address.tk,
|
||||
addressRu: data.address.ru,
|
||||
addressEn: data.address.en,
|
||||
phone: data.phone,
|
||||
email: data.email,
|
||||
workingHours: data.workingHours,
|
||||
description: data.description ?? '',
|
||||
isActive: data.isActive,
|
||||
}
|
||||
validate: (form: BranchFormData, mode: 'create' | 'edit') => FlatErrors
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
@@ -85,15 +54,7 @@ const STEPS: StepDef[] = [
|
||||
shortLabel: 'Esasy',
|
||||
icon: Building2,
|
||||
subtitle: 'Ady, kody, etrapy',
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.nameTk.trim()) e.nameTk = 'Türkmen ady — hökmany'
|
||||
if (!form.nameRu.trim()) e.nameRu = 'Rus ady — hökmany'
|
||||
if (!form.nameEn.trim()) e.nameEn = 'Iňlis ady — hökmany'
|
||||
if (!form.code.trim()) e.code = 'Kod — hökmany'
|
||||
if (!form.districtId) e.districtId = 'Etrap — hökmany'
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(0, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'address',
|
||||
@@ -102,15 +63,7 @@ const STEPS: StepDef[] = [
|
||||
shortLabel: 'Salgy',
|
||||
icon: MapPin,
|
||||
subtitle: 'Salgy, telefon, e-poçta',
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.addressTk.trim()) e.addressTk = 'Türkmen salgysy — hökmany'
|
||||
if (!form.addressRu.trim()) e.addressRu = 'Rus salgysy — hökmany'
|
||||
if (!form.addressEn.trim()) e.addressEn = 'Iňlis salgysy — hökmany'
|
||||
if (!form.phone.trim()) e.phone = 'Telefon — hökmany'
|
||||
if (!form.email.trim()) e.email = 'E-poçta — hökmany'
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(1, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'hours',
|
||||
@@ -119,18 +72,14 @@ const STEPS: StepDef[] = [
|
||||
shortLabel: 'Wagt',
|
||||
icon: Clock,
|
||||
subtitle: 'Iş wagty we bellikler',
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.workingHours.trim()) e.workingHours = 'Iş wagty — hökmany'
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(2, form, mode),
|
||||
},
|
||||
]
|
||||
|
||||
interface StepContentProps {
|
||||
form: FormState
|
||||
errors: FormErrors
|
||||
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
|
||||
form: BranchFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof BranchFormData>(k: K, v: BranchFormData[K]) => void
|
||||
activeLang: LangKey
|
||||
setActiveLang: (l: LangKey) => void
|
||||
}
|
||||
@@ -296,6 +245,24 @@ export interface BranchFormProps {
|
||||
branchId?: number
|
||||
}
|
||||
|
||||
function mapInitial(data: Branch): Partial<BranchFormData> {
|
||||
return {
|
||||
nameTk: data.name.tk,
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
code: data.code,
|
||||
districtId: String(data.districtId),
|
||||
addressTk: data.address.tk,
|
||||
addressRu: data.address.ru,
|
||||
addressEn: data.address.en,
|
||||
phone: data.phone,
|
||||
email: data.email,
|
||||
workingHours: data.workingHours,
|
||||
description: data.description ?? '',
|
||||
isActive: data.isActive,
|
||||
}
|
||||
}
|
||||
|
||||
export function BranchForm({ mode, initialData, branchId }: BranchFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
@@ -305,25 +272,31 @@ export function BranchForm({ mode, initialData, branchId }: BranchFormProps) {
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
||||
const [form, setForm] = useState<FormState>(() => initialData ? mapToFormState(initialData) : INITIAL_STATE)
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors,
|
||||
} = useForm<BranchFormData>({ defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES })
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
|
||||
const [currentStep, setCurrentStep] = useState(0)
|
||||
const [visited, setVisited] = useState<Set<number>>(
|
||||
() => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set<number>()
|
||||
() => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set<number>(),
|
||||
)
|
||||
|
||||
const stepsWithErrors = useMemo(() => {
|
||||
const out = new Set<number>()
|
||||
visited.forEach((i) => {
|
||||
if (Object.keys(STEPS[i].validate(form)).length > 0) out.add(i)
|
||||
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) out.add(i)
|
||||
})
|
||||
return out
|
||||
}, [form, visited])
|
||||
}, [form, mode, visited])
|
||||
|
||||
const set = useCallback(<K extends keyof FormState>(key: K, value: FormState[K]) => {
|
||||
setForm((prev) => ({ ...prev, [key]: value }))
|
||||
setErrors((prev) => ({ ...prev, [key]: undefined }))
|
||||
}, [])
|
||||
const set = useCallback(<K extends keyof BranchFormData>(key: K, value: BranchFormData[K]) => {
|
||||
(setValue as (name: K, val: BranchFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
|
||||
const stepProps = useMemo(() => ({ form, errors, set, activeLang, setActiveLang }), [form, errors, set, activeLang])
|
||||
|
||||
@@ -332,13 +305,11 @@ export function BranchForm({ mode, initialData, branchId }: BranchFormProps) {
|
||||
|
||||
const handleNext = () => {
|
||||
markVisited(currentStep)
|
||||
const errs = STEPS[currentStep].validate(form)
|
||||
const errs = STEPS[currentStep].validate(form, mode)
|
||||
if (Object.keys(errs).length > 0) {
|
||||
setErrors(errs)
|
||||
toast.error('Dogry maglumat girizmegiňizi haýyş edýäris.')
|
||||
return
|
||||
}
|
||||
setErrors({})
|
||||
if (currentStep < STEPS.length - 1) {
|
||||
setCurrentStep(currentStep + 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
@@ -348,7 +319,6 @@ export function BranchForm({ mode, initialData, branchId }: BranchFormProps) {
|
||||
const handleBack = () => {
|
||||
if (currentStep > 0) {
|
||||
markVisited(currentStep)
|
||||
setErrors({})
|
||||
setCurrentStep(currentStep - 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
@@ -356,40 +326,27 @@ export function BranchForm({ mode, initialData, branchId }: BranchFormProps) {
|
||||
|
||||
const handleGoTo = (i: number) => {
|
||||
markVisited(currentStep)
|
||||
setErrors({})
|
||||
setCurrentStep(i)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
|
||||
const handleSubmit = () => {
|
||||
const doSubmit = () => {
|
||||
setVisited(new Set(STEPS.map((_, i) => i)))
|
||||
|
||||
const allErrors: FormErrors = {}
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(form))
|
||||
const allErrors: FlatErrors = {}
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode))
|
||||
|
||||
if (Object.keys(allErrors).length > 0) {
|
||||
setErrors(allErrors)
|
||||
toast.error('Käbir hökmany meýdanlar doldurylan däldir.')
|
||||
for (let i = 0; i < STEPS.length; i++) {
|
||||
if (Object.keys(STEPS[i].validate(form)).length > 0) {
|
||||
setCurrentStep(i)
|
||||
break
|
||||
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) {
|
||||
setCurrentStep(i); break
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const payload: CreateBranchPayload = {
|
||||
name: { tk: form.nameTk, ru: form.nameRu, en: form.nameEn },
|
||||
code: form.code,
|
||||
districtId: Number(form.districtId),
|
||||
address: { tk: form.addressTk, ru: form.addressRu, en: form.addressEn },
|
||||
phone: form.phone,
|
||||
email: form.email,
|
||||
workingHours: form.workingHours,
|
||||
description: form.description.trim() || null,
|
||||
isActive: form.isActive,
|
||||
}
|
||||
const payload = buildPayload(getValues())
|
||||
|
||||
if (mode === 'create') {
|
||||
createMutation.mutate(payload, { onSuccess: () => navigate('/settings/location/branches') })
|
||||
@@ -466,7 +423,7 @@ export function BranchForm({ mode, initialData, branchId }: BranchFormProps) {
|
||||
</Button>
|
||||
|
||||
{isLastStep ? (
|
||||
<Button type="button" size="sm" onClick={handleSubmit} disabled={isPending} className="min-w-[150px]">
|
||||
<Button type="button" size="sm" onClick={doSubmit} disabled={isPending} className="min-w-[150px]">
|
||||
{isPending ? (
|
||||
<span className="flex items-center gap-2">
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||
|
||||
68
src/features/branches/schemas/branch.schema.ts
Normal file
68
src/features/branches/schemas/branch.schema.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateBranchPayload } from '@/features/branches/api/branchesApi'
|
||||
|
||||
export const branchFormSchema = z.object({
|
||||
nameTk: z.string().min(1, 'Türkmen ady — hökmany'),
|
||||
nameRu: z.string().min(1, 'Rus ady — hökmany'),
|
||||
nameEn: z.string().min(1, 'Iňlis ady — hökmany'),
|
||||
code: z.string().min(1, 'Kod — hökmany'),
|
||||
districtId: z.string().min(1, 'Etrap — hökmany'),
|
||||
addressTk: z.string().min(1, 'Türkmen salgysy — hökmany'),
|
||||
addressRu: z.string().min(1, 'Rus salgysy — hökmany'),
|
||||
addressEn: z.string().min(1, 'Iňlis salgysy — hökmany'),
|
||||
phone: z.string().min(1, 'Telefon — hökmany'),
|
||||
email: z.string().min(1, 'E-poçta — hökmany'),
|
||||
workingHours: z.string().min(1, 'Iş wagty — hökmany'),
|
||||
description: z.string().optional(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
|
||||
export type BranchFormData = z.infer<typeof branchFormSchema>
|
||||
|
||||
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 }),
|
||||
}
|
||||
|
||||
export function validateStep(
|
||||
stepIndex: number,
|
||||
form: BranchFormData,
|
||||
mode: 'create' | 'edit',
|
||||
): Partial<Record<keyof BranchFormData, string>> {
|
||||
void mode
|
||||
const schema = stepSchemas[stepIndex]
|
||||
const result = schema.safeParse(form)
|
||||
if (result.success) return {}
|
||||
const errors: Partial<Record<keyof BranchFormData, string>> = {}
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof BranchFormData
|
||||
if (!errors[key]) errors[key] = issue.message
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
export const DEFAULT_FORM_VALUES: BranchFormData = {
|
||||
nameTk: '', nameRu: '', nameEn: '',
|
||||
code: '',
|
||||
districtId: '',
|
||||
addressTk: '', addressRu: '', addressEn: '',
|
||||
phone: '', email: '',
|
||||
workingHours: '',
|
||||
description: '',
|
||||
isActive: true,
|
||||
}
|
||||
|
||||
export function buildPayload(data: BranchFormData): CreateBranchPayload {
|
||||
return {
|
||||
name: { tk: data.nameTk, ru: data.nameRu, en: data.nameEn },
|
||||
code: data.code,
|
||||
districtId: Number(data.districtId),
|
||||
address: { tk: data.addressTk, ru: data.addressRu, en: data.addressEn },
|
||||
phone: data.phone,
|
||||
email: data.email,
|
||||
workingHours: data.workingHours,
|
||||
description: (data.description ?? '').trim() || null,
|
||||
isActive: data.isActive,
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import {apiClient} from '@/lib/api/client'
|
||||
import apiClient from '@/lib/api/client'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useCallback, useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { type CardBalance } from '@/features/cardBalance/api/cardBalanceApi'
|
||||
import { useCreateCardBalance, useUpdateCardBalance } from '@/features/cardBalance/hooks/useCardBalance'
|
||||
import { DEFAULT_FORM_VALUES, buildPayload } from '@/features/cardBalance/schemas/cardBalance.schema'
|
||||
import type { CardBalanceFormData } from '@/features/cardBalance/schemas/cardBalance.schema'
|
||||
|
||||
interface CardBalanceFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
@@ -12,20 +15,15 @@ interface CardBalanceFormProps {
|
||||
cardBalanceId?: number
|
||||
}
|
||||
|
||||
interface FormState {
|
||||
passport_series: string
|
||||
passport_number: string
|
||||
card_number: string
|
||||
card_expiry_month: string
|
||||
card_expiry_year: string
|
||||
}
|
||||
type FlatErrors = Partial<Record<keyof CardBalanceFormData, string>>
|
||||
|
||||
interface FormErrors {
|
||||
passport_series?: string
|
||||
passport_number?: string
|
||||
card_number?: string
|
||||
card_expiry_month?: string
|
||||
card_expiry_year?: 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 CardBalanceFormData] = msg
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
@@ -56,68 +54,37 @@ const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => {
|
||||
return { value: year, label: year }
|
||||
})
|
||||
|
||||
const EMPTY_FORM: FormState = {
|
||||
passport_series: '',
|
||||
passport_number: '',
|
||||
card_number: '',
|
||||
card_expiry_month: '',
|
||||
card_expiry_year: '',
|
||||
}
|
||||
|
||||
// ─── Validation ───────────────────────────────────────────────────────────────
|
||||
|
||||
function validate(form: FormState, t: (k: string, fallback: string) => string): FormErrors {
|
||||
const errors: FormErrors = {}
|
||||
if (!form.passport_series) errors.passport_series = t('Required', 'Pasport seriýasy hökmanydyr')
|
||||
if (!form.passport_number) errors.passport_number = t('Required', 'Pasport belgisi hökmanydyr')
|
||||
if (!form.card_number) errors.card_number = t('Required', 'Kart belgisi hökmanydyr')
|
||||
if (!form.card_expiry_month) errors.card_expiry_month = t('Required', 'Möhleti (aý) hökmanydyr')
|
||||
if (!form.card_expiry_year) errors.card_expiry_year = t('Required', 'Möhleti (ýyl) hökmanydyr')
|
||||
return errors
|
||||
}
|
||||
|
||||
// ─── Component ────────────────────────────────────────────────────────────────
|
||||
|
||||
export function CardBalanceForm({ mode, initialData, cardBalanceId }: CardBalanceFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const [form, setForm] = useState<FormState>(EMPTY_FORM)
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
|
||||
const createMutation = useCreateCardBalance()
|
||||
const updateMutation = useUpdateCardBalance(cardBalanceId ?? 0)
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
useEffect(() => {
|
||||
if (mode === 'edit' && initialData) {
|
||||
setForm({
|
||||
passport_series: initialData.passport_series,
|
||||
passport_number: initialData.passport_number,
|
||||
card_number: initialData.card_number,
|
||||
card_expiry_month: initialData.card_expiry_month,
|
||||
card_expiry_year: initialData.card_expiry_year,
|
||||
})
|
||||
}
|
||||
}, [mode, initialData])
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors,
|
||||
} = useForm<CardBalanceFormData>({
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...initialData } : DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
const setField = (field: keyof FormState) => (value: string) => {
|
||||
setForm((prev) => ({ ...prev, [field]: value }))
|
||||
if (errors[field]) setErrors((prev) => ({ ...prev, [field]: undefined }))
|
||||
}
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
|
||||
const setField = useCallback((field: keyof CardBalanceFormData) => (value: string) => {
|
||||
(setValue as (name: keyof CardBalanceFormData, val: string) => void)(field, value)
|
||||
clearErrors(field)
|
||||
}, [setValue, clearErrors])
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const validationErrors = validate(form, t)
|
||||
if (Object.keys(validationErrors).length > 0) {
|
||||
setErrors(validationErrors)
|
||||
return
|
||||
}
|
||||
|
||||
const payload = buildPayload(getValues())
|
||||
if (mode === 'create') {
|
||||
await createMutation.mutateAsync(form)
|
||||
await createMutation.mutateAsync(payload)
|
||||
navigate('/card-balances')
|
||||
} else {
|
||||
await updateMutation.mutateAsync(form)
|
||||
await updateMutation.mutateAsync(payload)
|
||||
navigate(`/card-balances/${cardBalanceId}`)
|
||||
}
|
||||
}
|
||||
|
||||
30
src/features/cardBalance/schemas/cardBalance.schema.ts
Normal file
30
src/features/cardBalance/schemas/cardBalance.schema.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateCardBalancePayload } from '../api/cardBalanceApi'
|
||||
|
||||
export const cardBalanceFormSchema = z.object({
|
||||
passport_series: z.string().min(1, 'Pasport seriýasy hökmanydyr'),
|
||||
passport_number: z.string().min(1, 'Pasport belgisi hökmanydyr'),
|
||||
card_number: z.string().min(1, 'Kart belgisi hökmanydyr'),
|
||||
card_expiry_month: z.string().min(1, 'Möhleti (aý) hökmanydyr'),
|
||||
card_expiry_year: z.string().min(1, 'Möhleti (ýyl) hökmanydyr'),
|
||||
})
|
||||
|
||||
export type CardBalanceFormData = z.infer<typeof cardBalanceFormSchema>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: CardBalanceFormData = {
|
||||
passport_series: '',
|
||||
passport_number: '',
|
||||
card_number: '',
|
||||
card_expiry_month: '',
|
||||
card_expiry_year: '',
|
||||
}
|
||||
|
||||
export function buildPayload(data: CardBalanceFormData): CreateCardBalancePayload {
|
||||
return {
|
||||
passport_series: data.passport_series,
|
||||
passport_number: data.passport_number,
|
||||
card_number: data.card_number,
|
||||
card_expiry_month: data.card_expiry_month,
|
||||
card_expiry_year: data.card_expiry_year,
|
||||
}
|
||||
}
|
||||
@@ -1,132 +1,132 @@
|
||||
import { apiClient } from '@/lib/api/client'
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export type CardPinStatus = 'pending' | 'approved' | 'rejected'
|
||||
export type CardPinStatus = "pending" | "approved" | "rejected";
|
||||
|
||||
export interface CardPinItem {
|
||||
id: string
|
||||
card_type: string
|
||||
card_type_label: string
|
||||
card_number: string
|
||||
created_at: string
|
||||
province: string
|
||||
province_label: string
|
||||
branch: string
|
||||
branch_label: string
|
||||
first_name: string
|
||||
last_name: string
|
||||
father_name: string
|
||||
birth_date: string
|
||||
phone: string
|
||||
status: CardPinStatus
|
||||
note: string | null
|
||||
passport_series: string
|
||||
passport_number: string
|
||||
passport_file_1: string | null
|
||||
passport_file_2: string | null
|
||||
passport_file_3: string | null
|
||||
passport_file_4: string | null
|
||||
created_by: string
|
||||
created_by_label: string
|
||||
id: string;
|
||||
card_type: string;
|
||||
card_type_label: string;
|
||||
card_number: string;
|
||||
created_at: string;
|
||||
province: string;
|
||||
province_label: string;
|
||||
branch: string;
|
||||
branch_label: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
father_name: string;
|
||||
birth_date: string;
|
||||
phone: string;
|
||||
status: CardPinStatus;
|
||||
note: string | null;
|
||||
passport_series: string;
|
||||
passport_number: string;
|
||||
passport_file_1: string | null;
|
||||
passport_file_2: string | null;
|
||||
passport_file_3: string | null;
|
||||
passport_file_4: string | null;
|
||||
created_by: string;
|
||||
created_by_label: string;
|
||||
}
|
||||
|
||||
export interface CardPinListParams {
|
||||
page?: number
|
||||
per_page?: number
|
||||
search?: string
|
||||
status?: CardPinStatus | ''
|
||||
province?: string
|
||||
page?: number;
|
||||
per_page?: number;
|
||||
search?: string;
|
||||
status?: CardPinStatus | "";
|
||||
province?: string;
|
||||
}
|
||||
|
||||
export interface CardPinListResponse {
|
||||
data: CardPinItem[]
|
||||
data: CardPinItem[];
|
||||
meta: {
|
||||
current_page: number
|
||||
last_page: number
|
||||
per_page: number
|
||||
total: number
|
||||
}
|
||||
current_page: number;
|
||||
last_page: number;
|
||||
per_page: number;
|
||||
total: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface CardPinCreatePayload {
|
||||
status: CardPinStatus
|
||||
note: string
|
||||
card_type: string
|
||||
card_number: string
|
||||
province: string
|
||||
branch: string
|
||||
first_name: string
|
||||
last_name: string
|
||||
father_name: string
|
||||
birth_date: string
|
||||
phone: string
|
||||
passport_series: string
|
||||
passport_number: string
|
||||
passport_file_1: File | null
|
||||
passport_file_2: File | null
|
||||
passport_file_3: File | null
|
||||
passport_file_4: File | null
|
||||
status: CardPinStatus;
|
||||
note: string;
|
||||
card_type: string;
|
||||
card_number: string;
|
||||
province: string;
|
||||
branch: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
father_name: string;
|
||||
birth_date: string;
|
||||
phone: string;
|
||||
passport_series: string;
|
||||
passport_number: string;
|
||||
passport_file_1: File | null;
|
||||
passport_file_2: File | null;
|
||||
passport_file_3: File | null;
|
||||
passport_file_4: File | null;
|
||||
}
|
||||
|
||||
export type CardPinUpdatePayload = CardPinCreatePayload
|
||||
export type CardPinUpdatePayload = CardPinCreatePayload;
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_CARD_PINS: CardPinItem[] = [
|
||||
{
|
||||
id: '1',
|
||||
card_type: 'altyn_asyr',
|
||||
card_type_label: 'Altyn Asyr',
|
||||
card_number: '8600123456789012',
|
||||
created_at: '2024-05-07 10:00',
|
||||
province: 'ashgabat',
|
||||
province_label: 'Aşgabat',
|
||||
branch: '1',
|
||||
branch_label: 'Merkezi şahamça',
|
||||
first_name: 'Aman',
|
||||
last_name: 'Amanow',
|
||||
father_name: 'Amanowiç',
|
||||
birth_date: '1990-01-01',
|
||||
phone: '99365123456',
|
||||
status: 'pending',
|
||||
note: 'Test bellik',
|
||||
passport_series: 'I-MR',
|
||||
passport_number: '123456',
|
||||
id: "1",
|
||||
card_type: "altyn_asyr",
|
||||
card_type_label: "Altyn Asyr",
|
||||
card_number: "8600123456789012",
|
||||
created_at: "2024-05-07 10:00",
|
||||
province: "ashgabat",
|
||||
province_label: "Aşgabat",
|
||||
branch: "1",
|
||||
branch_label: "Merkezi şahamça",
|
||||
first_name: "Aman",
|
||||
last_name: "Amanow",
|
||||
father_name: "Amanowiç",
|
||||
birth_date: "1990-01-01",
|
||||
phone: "99365123456",
|
||||
status: "pending",
|
||||
note: "Test bellik",
|
||||
passport_series: "I-MR",
|
||||
passport_number: "123456",
|
||||
passport_file_1: null,
|
||||
passport_file_2: null,
|
||||
passport_file_3: null,
|
||||
passport_file_4: null,
|
||||
created_by: '1',
|
||||
created_by_label: 'Admin',
|
||||
created_by: "1",
|
||||
created_by_label: "Admin",
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
card_type: 'visa',
|
||||
card_type_label: 'Visa',
|
||||
card_number: '4400123456789012',
|
||||
created_at: '2024-05-07 11:30',
|
||||
province: 'mary',
|
||||
province_label: 'Mary',
|
||||
branch: '2',
|
||||
branch_label: 'Mary şahamçasy',
|
||||
first_name: 'Berdi',
|
||||
last_name: 'Berdiyew',
|
||||
father_name: 'Berdiyewiç',
|
||||
birth_date: '1995-05-05',
|
||||
phone: '99361112233',
|
||||
status: 'approved',
|
||||
id: "2",
|
||||
card_type: "visa",
|
||||
card_type_label: "Visa",
|
||||
card_number: "4400123456789012",
|
||||
created_at: "2024-05-07 11:30",
|
||||
province: "mary",
|
||||
province_label: "Mary",
|
||||
branch: "2",
|
||||
branch_label: "Mary şahamçasy",
|
||||
first_name: "Berdi",
|
||||
last_name: "Berdiyew",
|
||||
father_name: "Berdiyewiç",
|
||||
birth_date: "1995-05-05",
|
||||
phone: "99361112233",
|
||||
status: "approved",
|
||||
note: null,
|
||||
passport_series: 'I-LB',
|
||||
passport_number: '654321',
|
||||
passport_series: "I-LB",
|
||||
passport_number: "654321",
|
||||
passport_file_1: null,
|
||||
passport_file_2: null,
|
||||
passport_file_3: null,
|
||||
passport_file_4: null,
|
||||
created_by: '1',
|
||||
created_by_label: 'Admin',
|
||||
created_by: "1",
|
||||
created_by_label: "Admin",
|
||||
},
|
||||
]
|
||||
];
|
||||
|
||||
export const cardPinApi = {
|
||||
list: async (params: CardPinListParams): Promise<CardPinListResponse> => {
|
||||
@@ -138,68 +138,77 @@ export const cardPinApi = {
|
||||
last_page: 1,
|
||||
per_page: params.per_page || 25,
|
||||
total: MOCK_CARD_PINS.length,
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
const { data } = await apiClient.get('/card-pins', { params })
|
||||
return data
|
||||
const { data } = await apiClient.get("/card-pins", { params });
|
||||
return data;
|
||||
},
|
||||
|
||||
getById: async (id: string): Promise<CardPinItem> => {
|
||||
const mock = MOCK_CARD_PINS.find(p => p.id === id)
|
||||
if (mock) return mock
|
||||
const mock = MOCK_CARD_PINS.find((p) => p.id === id);
|
||||
if (mock) return mock;
|
||||
|
||||
const { data } = await apiClient.get(`/card-pins/${id}`)
|
||||
return data
|
||||
const { data } = await apiClient.get(`/card-pins/${id}`);
|
||||
return data;
|
||||
},
|
||||
|
||||
create: (payload: CardPinCreatePayload): Promise<CardPinItem> => {
|
||||
const form = buildFormData(payload)
|
||||
return apiClient.post('/card-pins', form, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
}).then((r) => r.data)
|
||||
const form = buildFormData(payload);
|
||||
return apiClient
|
||||
.post("/card-pins", form, {
|
||||
headers: { "Content-Type": "multipart/form-data" },
|
||||
})
|
||||
.then((r) => r.data);
|
||||
},
|
||||
|
||||
update: (id: string, payload: CardPinUpdatePayload): Promise<CardPinItem> => {
|
||||
const form = buildFormData(payload)
|
||||
form.append('_method', 'PUT')
|
||||
return apiClient.post(`/card-pins/${id}`, form, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
}).then((r) => r.data)
|
||||
const form = buildFormData(payload);
|
||||
form.append("_method", "PUT");
|
||||
return apiClient
|
||||
.post(`/card-pins/${id}`, form, {
|
||||
headers: { "Content-Type": "multipart/form-data" },
|
||||
})
|
||||
.then((r) => r.data);
|
||||
},
|
||||
|
||||
delete: (id: string): Promise<void> =>
|
||||
apiClient.delete(`/card-pins/${id}`).then((r) => r.data),
|
||||
}
|
||||
delete: (id: string): Promise<void> => apiClient.delete(`/card-pins/${id}`).then((r) => r.data),
|
||||
};
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function buildFormData(payload: CardPinCreatePayload): FormData {
|
||||
const form = new FormData()
|
||||
const form = new FormData();
|
||||
|
||||
const textFields: (keyof CardPinCreatePayload)[] = [
|
||||
'status', 'note', 'card_type', 'card_number',
|
||||
'province', 'branch',
|
||||
'first_name', 'last_name', 'father_name',
|
||||
'birth_date', 'phone',
|
||||
'passport_series', 'passport_number',
|
||||
]
|
||||
"status",
|
||||
"note",
|
||||
"card_type",
|
||||
"card_number",
|
||||
"province",
|
||||
"branch",
|
||||
"first_name",
|
||||
"last_name",
|
||||
"father_name",
|
||||
"birth_date",
|
||||
"phone",
|
||||
"passport_series",
|
||||
"passport_number",
|
||||
];
|
||||
|
||||
for (const key of textFields) {
|
||||
const val = payload[key]
|
||||
const val = payload[key];
|
||||
if (val !== null && val !== undefined) {
|
||||
form.append(key, String(val))
|
||||
form.append(key, String(val));
|
||||
}
|
||||
}
|
||||
|
||||
const fileFields: (keyof CardPinCreatePayload)[] = [
|
||||
'passport_file_1', 'passport_file_2', 'passport_file_3', 'passport_file_4',
|
||||
]
|
||||
const fileFields: (keyof CardPinCreatePayload)[] = ["passport_file_1", "passport_file_2", "passport_file_3", "passport_file_4"];
|
||||
|
||||
for (const key of fileFields) {
|
||||
const file = payload[key]
|
||||
if (file instanceof File) form.append(key, file)
|
||||
const file = payload[key];
|
||||
if (file instanceof File) form.append(key, file);
|
||||
}
|
||||
|
||||
return form
|
||||
}
|
||||
return form;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, useCallback, useMemo, useEffect } from 'react'
|
||||
import { useState, useCallback, useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import { CreditCard, User, FileText } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
@@ -9,6 +10,8 @@ import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
|
||||
import type { CardPinItem, CardPinCreatePayload } from '@/features/cardPins/api/cardPinApi'
|
||||
import { validateStep, DEFAULT_FORM_VALUES } from '@/features/cardPins/schemas/cardPin.schema'
|
||||
import type { CardPinFormData } from '@/features/cardPins/schemas/cardPin.schema'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -19,28 +22,6 @@ interface CardPinFormProps {
|
||||
isSubmitting: boolean
|
||||
}
|
||||
|
||||
interface FormState {
|
||||
status: string
|
||||
note: string
|
||||
card_type: string
|
||||
card_number: string
|
||||
province: string
|
||||
branch: string
|
||||
first_name: string
|
||||
last_name: string
|
||||
father_name: string
|
||||
birth_date: string
|
||||
phone: string
|
||||
passport_series: string
|
||||
passport_number: string
|
||||
passport_file_1: File | null
|
||||
passport_file_2: File | null
|
||||
passport_file_3: File | null
|
||||
passport_file_4: File | null
|
||||
}
|
||||
|
||||
type FormErrors = Partial<Record<keyof FormState, string>>
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
const STATUS_OPTIONS = [
|
||||
@@ -71,32 +52,17 @@ const PROVINCE_OPTIONS = [
|
||||
{ value: 'ahal', label: 'Ahal' },
|
||||
]
|
||||
|
||||
const INITIAL_STATE: FormState = {
|
||||
status: 'pending', note: '', card_type: '', card_number: '',
|
||||
province: '', branch: '', first_name: '', last_name: '', father_name: '',
|
||||
birth_date: '', phone: '', passport_series: '', passport_number: '',
|
||||
passport_file_1: null, passport_file_2: null,
|
||||
passport_file_3: null, passport_file_4: null,
|
||||
}
|
||||
// ─── Form errors helper ──────────────────────────────────────────────────────
|
||||
|
||||
function mapToFormState(data: CardPinItem): FormState {
|
||||
return {
|
||||
status: data.status ?? 'pending',
|
||||
note: data.note ?? '',
|
||||
card_type: data.card_type ?? '',
|
||||
card_number: data.card_number ?? '',
|
||||
province: data.province ?? '',
|
||||
branch: data.branch ?? '',
|
||||
first_name: data.first_name ?? '',
|
||||
last_name: data.last_name ?? '',
|
||||
father_name: data.father_name ?? '',
|
||||
birth_date: data.birth_date ?? '',
|
||||
phone: data.phone ?? '',
|
||||
passport_series: data.passport_series ?? '',
|
||||
passport_number: data.passport_number ?? '',
|
||||
passport_file_1: null, passport_file_2: null,
|
||||
passport_file_3: null, passport_file_4: null,
|
||||
type FlatErrors = Partial<Record<keyof CardPinFormData, 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 CardPinFormData] = msg
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ─── Step definitions ─────────────────────────────────────────────────────────
|
||||
@@ -107,7 +73,7 @@ interface StepDef {
|
||||
titleFallback: string
|
||||
subtitle: string
|
||||
icon: LucideIcon
|
||||
validate: (form: FormState, mode: 'create' | 'edit') => FormErrors
|
||||
validate: (form: CardPinFormData, mode: 'create' | 'edit') => FlatErrors
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
@@ -117,15 +83,7 @@ const STEPS: StepDef[] = [
|
||||
titleFallback: 'Kart',
|
||||
subtitle: 'Görnüş & lokasiýa',
|
||||
icon: CreditCard,
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.status) e.status = 'Status hökmany'
|
||||
if (!form.card_type) e.card_type = 'Kart görnüşi hökmany'
|
||||
if (!form.card_number) e.card_number = 'Kart belgisi hökmany'
|
||||
if (!form.province) e.province = 'Welaýat hökmany'
|
||||
if (!form.branch) e.branch = 'Şahamça hökmany'
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(0, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'personal',
|
||||
@@ -133,14 +91,7 @@ const STEPS: StepDef[] = [
|
||||
titleFallback: 'Şahsy',
|
||||
subtitle: 'Maglumatlar',
|
||||
icon: User,
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.first_name) e.first_name = 'Ady hökmany'
|
||||
if (!form.last_name) e.last_name = 'Familiýasy hökmany'
|
||||
if (!form.birth_date) e.birth_date = 'Doglan güni hökmany'
|
||||
if (!form.phone) e.phone = 'Telefon hökmany'
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(1, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'passport',
|
||||
@@ -148,18 +99,7 @@ const STEPS: StepDef[] = [
|
||||
titleFallback: 'Pasport',
|
||||
subtitle: 'Resminamalar',
|
||||
icon: FileText,
|
||||
validate: (form, mode) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.passport_series) e.passport_series = 'Pasport seriýasy hökmany'
|
||||
if (!form.passport_number) e.passport_number = 'Pasport belgisi hökmany'
|
||||
if (mode === 'create') {
|
||||
if (!form.passport_file_1) e.passport_file_1 = 'Pasport (sahypa 1) hökmany'
|
||||
if (!form.passport_file_2) e.passport_file_2 = 'Pasport (2-3-nji sahypa) hökmany'
|
||||
if (!form.passport_file_3) e.passport_file_3 = 'Pasport (8-9 sahypa) hökmany'
|
||||
if (!form.passport_file_4) e.passport_file_4 = 'Pasport (32-nji sahypa) hökmany'
|
||||
}
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(2, form, mode),
|
||||
},
|
||||
]
|
||||
|
||||
@@ -210,9 +150,9 @@ function BentoCard({
|
||||
// ─── Shared step content props ────────────────────────────────────────────────
|
||||
|
||||
interface StepContentProps {
|
||||
form: FormState
|
||||
errors: FormErrors
|
||||
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
|
||||
form: CardPinFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof CardPinFormData>(k: K, v: CardPinFormData[K]) => void
|
||||
}
|
||||
|
||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||
@@ -457,17 +397,22 @@ export function CardPinForm({ mode, initialData, onSubmit, isSubmitting }: CardP
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const [form, setForm] = useState<FormState>(() => initialData ? mapToFormState(initialData) : INITIAL_STATE)
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors,
|
||||
} = useForm<CardPinFormData>({
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
|
||||
const [currentStep, setCurrentStep] = useState(0)
|
||||
const [visited, setVisited] = useState<Set<number>>(
|
||||
() => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set<number>(),
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (initialData) setForm(mapToFormState(initialData))
|
||||
}, [initialData])
|
||||
|
||||
// ── Computed step errors ───────────────────────────────────────────────────
|
||||
|
||||
const stepsWithErrors = useMemo(() => {
|
||||
@@ -480,10 +425,10 @@ export function CardPinForm({ mode, initialData, onSubmit, isSubmitting }: CardP
|
||||
|
||||
// ── set helper ─────────────────────────────────────────────────────────────
|
||||
|
||||
const set = useCallback(<K extends keyof FormState>(key: K, value: FormState[K]) => {
|
||||
setForm((prev) => ({ ...prev, [key]: value }))
|
||||
setErrors((prev) => ({ ...prev, [key]: undefined }))
|
||||
}, [])
|
||||
const set = useCallback(<K extends keyof CardPinFormData>(key: K, value: CardPinFormData[K]) => {
|
||||
(setValue as (name: K, val: CardPinFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
|
||||
const stepProps = useMemo(() => ({ form, errors, set }), [form, errors, set])
|
||||
|
||||
@@ -496,25 +441,21 @@ export function CardPinForm({ mode, initialData, onSubmit, isSubmitting }: CardP
|
||||
markVisited(currentStep)
|
||||
const errs = STEPS[currentStep].validate(form, mode)
|
||||
if (Object.keys(errs).length > 0) {
|
||||
setErrors(errs)
|
||||
toast.error('Dogry maglumat girizmegiňizi haýyş edýäris.')
|
||||
return
|
||||
}
|
||||
setErrors({})
|
||||
setCurrentStep(currentStep + 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
|
||||
const handleBack = () => {
|
||||
markVisited(currentStep)
|
||||
setErrors({})
|
||||
setCurrentStep(currentStep - 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
|
||||
const handleGoTo = (i: number) => {
|
||||
markVisited(currentStep)
|
||||
setErrors({})
|
||||
setCurrentStep(i)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
@@ -524,14 +465,14 @@ export function CardPinForm({ mode, initialData, onSubmit, isSubmitting }: CardP
|
||||
const handleSubmit = () => {
|
||||
setVisited(new Set(STEPS.map((_, i) => i)))
|
||||
|
||||
const allErrors: FormErrors = {}
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode))
|
||||
const values = getValues()
|
||||
const allErrors: FlatErrors = {}
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(values, mode))
|
||||
|
||||
if (Object.keys(allErrors).length > 0) {
|
||||
setErrors(allErrors)
|
||||
toast.error('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(values, mode)).length > 0) {
|
||||
setCurrentStep(i)
|
||||
break
|
||||
}
|
||||
@@ -540,23 +481,23 @@ export function CardPinForm({ mode, initialData, onSubmit, isSubmitting }: CardP
|
||||
}
|
||||
|
||||
onSubmit({
|
||||
status: form.status as CardPinCreatePayload['status'],
|
||||
note: form.note,
|
||||
card_type: form.card_type,
|
||||
card_number: form.card_number,
|
||||
province: form.province,
|
||||
branch: form.branch,
|
||||
first_name: form.first_name,
|
||||
last_name: form.last_name,
|
||||
father_name: form.father_name,
|
||||
birth_date: form.birth_date,
|
||||
phone: form.phone,
|
||||
passport_series: form.passport_series,
|
||||
passport_number: form.passport_number,
|
||||
passport_file_1: form.passport_file_1,
|
||||
passport_file_2: form.passport_file_2,
|
||||
passport_file_3: form.passport_file_3,
|
||||
passport_file_4: form.passport_file_4,
|
||||
status: values.status as CardPinCreatePayload['status'],
|
||||
note: values.note ?? '',
|
||||
card_type: values.card_type,
|
||||
card_number: values.card_number,
|
||||
province: values.province,
|
||||
branch: values.branch,
|
||||
first_name: values.first_name,
|
||||
last_name: values.last_name,
|
||||
father_name: values.father_name ?? '',
|
||||
birth_date: values.birth_date,
|
||||
phone: values.phone,
|
||||
passport_series: values.passport_series,
|
||||
passport_number: values.passport_number,
|
||||
passport_file_1: values.passport_file_1,
|
||||
passport_file_2: values.passport_file_2,
|
||||
passport_file_3: values.passport_file_3,
|
||||
passport_file_4: values.passport_file_4,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -613,4 +554,22 @@ export function CardPinForm({ mode, initialData, onSubmit, isSubmitting }: CardP
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function mapInitial(data: CardPinItem): Partial<CardPinFormData> {
|
||||
return {
|
||||
status: data.status ?? 'pending',
|
||||
note: data.note ?? '',
|
||||
card_type: data.card_type ?? '',
|
||||
card_number: data.card_number ?? '',
|
||||
province: data.province ?? '',
|
||||
branch: data.branch ?? '',
|
||||
first_name: data.first_name ?? '',
|
||||
last_name: data.last_name ?? '',
|
||||
father_name: data.father_name ?? '',
|
||||
birth_date: data.birth_date ?? '',
|
||||
phone: data.phone ?? '',
|
||||
passport_series: data.passport_series ?? '',
|
||||
passport_number: data.passport_number ?? '',
|
||||
}
|
||||
}
|
||||
|
||||
91
src/features/cardPins/schemas/cardPin.schema.ts
Normal file
91
src/features/cardPins/schemas/cardPin.schema.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
const fileRequired = z.custom<File>((val) => val instanceof File, 'Faýl hökmany')
|
||||
|
||||
export const cardPinFormSchema = z.object({
|
||||
status: z.string().min(1, 'Status hökmany'),
|
||||
note: z.string().optional(),
|
||||
card_type: z.string().min(1, 'Kart görnüşi hökmany'),
|
||||
card_number: z.string().min(1, 'Kart belgisi hökmany'),
|
||||
province: z.string().min(1, 'Welaýat hökmany'),
|
||||
branch: z.string().min(1, 'Şahamça hökmany'),
|
||||
first_name: z.string().min(1, 'Ady hökmany'),
|
||||
last_name: z.string().min(1, 'Familiýasy hökmany'),
|
||||
father_name: z.string().optional(),
|
||||
birth_date: z.string().min(1, 'Doglan güni hökmany'),
|
||||
phone: z.string().min(1, 'Telefon hökmany'),
|
||||
passport_series: z.string().min(1, 'Pasport seriýasy hökmany'),
|
||||
passport_number: z.string().min(1, 'Pasport belgisi hökmany'),
|
||||
passport_file_1: z.custom<File | null>().nullable(),
|
||||
passport_file_2: z.custom<File | null>().nullable(),
|
||||
passport_file_3: z.custom<File | null>().nullable(),
|
||||
passport_file_4: z.custom<File | null>().nullable(),
|
||||
})
|
||||
|
||||
export type CardPinFormData = z.infer<typeof cardPinFormSchema>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: CardPinFormData = {
|
||||
status: 'pending',
|
||||
note: '',
|
||||
card_type: '',
|
||||
card_number: '',
|
||||
province: '',
|
||||
branch: '',
|
||||
first_name: '',
|
||||
last_name: '',
|
||||
father_name: '',
|
||||
birth_date: '',
|
||||
phone: '',
|
||||
passport_series: '',
|
||||
passport_number: '',
|
||||
passport_file_1: null,
|
||||
passport_file_2: null,
|
||||
passport_file_3: null,
|
||||
passport_file_4: null,
|
||||
}
|
||||
|
||||
export const stepSchemas: Record<number, z.ZodType<Partial<CardPinFormData>>> = {
|
||||
0: cardPinFormSchema.pick({
|
||||
status: true, card_type: true, card_number: true, province: true, branch: true,
|
||||
}),
|
||||
1: cardPinFormSchema.pick({
|
||||
first_name: true, last_name: true, birth_date: true, phone: true,
|
||||
}),
|
||||
2: z.object({
|
||||
passport_series: z.string().min(1, 'Pasport seriýasy hökmany'),
|
||||
passport_number: z.string().min(1, 'Pasport belgisi hökmany'),
|
||||
passport_file_1: fileRequired,
|
||||
passport_file_2: fileRequired,
|
||||
passport_file_3: fileRequired,
|
||||
passport_file_4: fileRequired,
|
||||
}),
|
||||
}
|
||||
|
||||
export function validateStep(
|
||||
stepIndex: number,
|
||||
form: CardPinFormData,
|
||||
mode: 'create' | 'edit',
|
||||
): Partial<Record<keyof CardPinFormData, string>> {
|
||||
if (stepIndex === 2 && mode === 'edit') {
|
||||
const schema = cardPinFormSchema.pick({ passport_series: true, passport_number: true })
|
||||
const result = schema.safeParse(form)
|
||||
if (result.success) return {}
|
||||
const errors: Partial<Record<keyof CardPinFormData, string>> = {}
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof CardPinFormData
|
||||
if (!errors[key]) errors[key] = issue.message
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
const schema = stepSchemas[stepIndex]
|
||||
const result = schema.safeParse(form)
|
||||
if (result.success) return {}
|
||||
|
||||
const errors: Partial<Record<keyof CardPinFormData, string>> = {}
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof CardPinFormData
|
||||
if (!errors[key]) errors[key] = issue.message
|
||||
}
|
||||
return errors
|
||||
}
|
||||
@@ -1,64 +1,30 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useCallback, useMemo } 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 { CardReason, CreateCardReasonPayload } from '../api/cardReasonsApi'
|
||||
import type { CardReason } from '../api/cardReasonsApi'
|
||||
import { useCreateCardReason, useUpdateCardReason } from '../hooks/useCardReasons'
|
||||
import { cardReasonFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardReason.schema'
|
||||
import type { CardReasonFormData } from '../schemas/cardReason.schema'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
// ─── Form errors helper ──────────────────────────────────────────────────────
|
||||
|
||||
interface FormErrors {
|
||||
nameTk?: string
|
||||
nameRu?: string
|
||||
nameEn?: string
|
||||
value?: string
|
||||
}
|
||||
type FlatErrors = Partial<Record<keyof CardReasonFormData, string>>
|
||||
|
||||
interface FormState {
|
||||
nameTk: string
|
||||
nameRu: string
|
||||
nameEn: string
|
||||
value: string
|
||||
description: string
|
||||
isActive: boolean
|
||||
}
|
||||
|
||||
interface CardReasonFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CardReason
|
||||
CardReasonId?: number
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function buildInitialState(data?: CardReason): FormState {
|
||||
if (!data) {
|
||||
return { nameTk: '', nameRu: '', nameEn: '', value: '', description: '', isActive: true }
|
||||
}
|
||||
return {
|
||||
nameTk: data.name.tk,
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
value: String(data.value),
|
||||
description: data.description ?? '',
|
||||
isActive: data.isActive,
|
||||
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 CardReasonFormData] = msg
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function validate(form: FormState, t: (k: string, fb: string) => string): FormErrors {
|
||||
const errors: FormErrors = {}
|
||||
if (!form.nameTk.trim())
|
||||
errors.nameTk = t('validation.required', 'Hökmany meýdan')
|
||||
if (!form.nameRu.trim())
|
||||
errors.nameRu = t('validation.required', 'Hökmany meýdan')
|
||||
if (!form.nameEn.trim())
|
||||
errors.nameEn = t('validation.required', 'Hökmany meýdan')
|
||||
if (!form.value.trim() || isNaN(Number(form.value)) || Number(form.value) < 0)
|
||||
errors.value = t('validation.invalidNumber', 'Dogry san giriziň')
|
||||
return errors
|
||||
}
|
||||
type FormErrors = FlatErrors
|
||||
|
||||
// ─── Lang Tab ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -72,6 +38,23 @@ const LANG_TABS: { key: LangKey; label: string }[] = [
|
||||
|
||||
// ─── CardReasonForm ─────────────────────────────────────────────────────────────
|
||||
|
||||
interface CardReasonFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CardReason
|
||||
CardReasonId?: number
|
||||
}
|
||||
|
||||
function mapInitial(data: CardReason): CardReasonFormData {
|
||||
return {
|
||||
nameTk: data.name.tk,
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
value: String(data.value),
|
||||
description: data.description ?? '',
|
||||
isActive: data.isActive,
|
||||
}
|
||||
}
|
||||
|
||||
export function CardReasonForm({ mode, initialData, CardReasonId }: CardReasonFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
@@ -81,32 +64,29 @@ export function CardReasonForm({ mode, initialData, CardReasonId }: CardReasonFo
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors,
|
||||
} = useForm<CardReasonFormData>({
|
||||
resolver: zodResolver(cardReasonFormSchema),
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
|
||||
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
||||
const [form, setForm] = useState<FormState>(() => buildInitialState(initialData))
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
|
||||
// Sync form when initialData arrives (edit mode data fetch)
|
||||
useEffect(() => {
|
||||
if (initialData) setForm(buildInitialState(initialData))
|
||||
}, [initialData])
|
||||
|
||||
const set = (key: keyof FormState) => (value: string | boolean) =>
|
||||
setForm((prev) => ({ ...prev, [key]: value }))
|
||||
const set = useCallback(<K extends keyof CardReasonFormData>(key: K, value: CardReasonFormData[K]) => {
|
||||
(setValue as (name: K, val: CardReasonFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
|
||||
const handleSubmit = () => {
|
||||
const errs = validate(form, t)
|
||||
if (Object.keys(errs).length > 0) {
|
||||
setErrors(errs)
|
||||
return
|
||||
}
|
||||
setErrors({})
|
||||
const values = getValues()
|
||||
const result = cardReasonFormSchema.safeParse(values)
|
||||
if (!result.success) return
|
||||
|
||||
const payload: CreateCardReasonPayload = {
|
||||
name: { tk: form.nameTk, ru: form.nameRu, en: form.nameEn },
|
||||
value: Number(form.value),
|
||||
description: form.description.trim() || null,
|
||||
isActive: form.isActive,
|
||||
}
|
||||
const payload = buildPayload(values)
|
||||
|
||||
if (mode === 'create') {
|
||||
createMutation.mutate(payload, {
|
||||
@@ -157,7 +137,7 @@ export function CardReasonForm({ mode, initialData, CardReasonId }: CardReasonFo
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form[nameFieldKey]}
|
||||
onChange={set(nameFieldKey)}
|
||||
onChange={(v) => set(nameFieldKey, v)}
|
||||
placeholder={t('CardReasons.fields.name', 'Ady')}
|
||||
error={errors[nameErrorKey]}
|
||||
/>
|
||||
@@ -172,7 +152,7 @@ export function CardReasonForm({ mode, initialData, CardReasonId }: CardReasonFo
|
||||
<FormInput
|
||||
type="number"
|
||||
value={form.value}
|
||||
onChange={set('value')}
|
||||
onChange={(v) => set('value', v)}
|
||||
placeholder={t('CardReasons.fields.value', 'Baha')}
|
||||
error={errors.value}
|
||||
/>
|
||||
@@ -186,7 +166,7 @@ export function CardReasonForm({ mode, initialData, CardReasonId }: CardReasonFo
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.description}
|
||||
onChange={set('description')}
|
||||
onChange={(v) => set('description', v)}
|
||||
placeholder={t('CardReasons.fields.description', 'Bellikler')}
|
||||
/>
|
||||
</div>
|
||||
@@ -198,7 +178,7 @@ export function CardReasonForm({ mode, initialData, CardReasonId }: CardReasonFo
|
||||
</span>
|
||||
<Checkbox
|
||||
checked={form.isActive}
|
||||
onCheckedChange={(checked) => set('isActive')(!!checked)}
|
||||
onCheckedChange={(checked) => set('isActive', !!checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -215,4 +195,4 @@ export function CardReasonForm({ mode, initialData, CardReasonId }: CardReasonFo
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
34
src/features/cardReasons/schemas/cardReason.schema.ts
Normal file
34
src/features/cardReasons/schemas/cardReason.schema.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateCardReasonPayload } from '../api/cardReasonsApi'
|
||||
|
||||
export const cardReasonFormSchema = z.object({
|
||||
nameTk: z.string().min(1, 'Hökmany meýdan'),
|
||||
nameRu: z.string().min(1, 'Hökmany meýdan'),
|
||||
nameEn: z.string().min(1, 'Hökmany meýdan'),
|
||||
value: z.string().min(1, 'Dogry san giriziň').refine(
|
||||
(v) => !isNaN(Number(v)) && Number(v) >= 0,
|
||||
{ message: 'Dogry san giriziň' },
|
||||
),
|
||||
description: z.string().optional(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
|
||||
export type CardReasonFormData = z.infer<typeof cardReasonFormSchema>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: CardReasonFormData = {
|
||||
nameTk: '',
|
||||
nameRu: '',
|
||||
nameEn: '',
|
||||
value: '',
|
||||
description: '',
|
||||
isActive: true,
|
||||
}
|
||||
|
||||
export function buildPayload(data: CardReasonFormData): CreateCardReasonPayload {
|
||||
return {
|
||||
name: { tk: data.nameTk, ru: data.nameRu, en: data.nameEn },
|
||||
value: Number(data.value),
|
||||
description: data.description?.trim() || null,
|
||||
isActive: data.isActive,
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import {apiClient} from '@/lib/api/client'
|
||||
import apiClient from '@/lib/api/client'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, useCallback, useMemo, useEffect } from 'react'
|
||||
import { useState, useCallback, useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import { CreditCard, User, FileText } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
@@ -8,8 +9,10 @@ import type { LucideIcon } from 'lucide-react'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
|
||||
import type { CardRequisite, CardRequisiteStatus, CreateCardRequisitePayload } from '../api/cardRequisitesApi'
|
||||
import type { CardRequisite } from '../api/cardRequisitesApi'
|
||||
import { useCreateCardRequisite, useUpdateCardRequisite } from '../hooks/useCardRequisites'
|
||||
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardRequisite.schema'
|
||||
import type { CardRequisiteFormData } from '../schemas/cardRequisite.schema'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -19,29 +22,16 @@ interface CardRequisiteFormProps {
|
||||
cardRequisiteId?: string
|
||||
}
|
||||
|
||||
interface FormState {
|
||||
status: string
|
||||
note: string
|
||||
card_type: string
|
||||
card_number: string
|
||||
card_expiry_month: string
|
||||
card_expiry_year: string
|
||||
province_id: string
|
||||
branch_id: string
|
||||
first_name: string
|
||||
last_name: string
|
||||
middle_name: string
|
||||
birth_date: string
|
||||
phone: string
|
||||
passport_series: string
|
||||
passport_number: string
|
||||
passport_page1: File | null
|
||||
passport_page2_3: File | null
|
||||
passport_page8_9: File | null
|
||||
passport_page32: File | null
|
||||
}
|
||||
type FlatErrors = Partial<Record<keyof CardRequisiteFormData, string>>
|
||||
|
||||
type FormErrors = Partial<Record<keyof FormState, 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 CardRequisiteFormData] = msg
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -95,16 +85,7 @@ const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => {
|
||||
return { value: year, label: year }
|
||||
})
|
||||
|
||||
const INITIAL_STATE: FormState = {
|
||||
status: 'pending', note: '', card_type: '', card_number: '',
|
||||
card_expiry_month: '', card_expiry_year: '', province_id: '', branch_id: '',
|
||||
first_name: '', last_name: '', middle_name: '', birth_date: '', phone: '',
|
||||
passport_series: '', passport_number: '',
|
||||
passport_page1: null, passport_page2_3: null,
|
||||
passport_page8_9: null, passport_page32: null,
|
||||
}
|
||||
|
||||
function mapToFormState(data: CardRequisite): FormState {
|
||||
function mapInitial(data: CardRequisite): CardRequisiteFormData {
|
||||
return {
|
||||
status: data.status ?? 'pending',
|
||||
note: data.note ?? '',
|
||||
@@ -134,7 +115,7 @@ interface StepDef {
|
||||
titleFallback: string
|
||||
subtitle: string
|
||||
icon: LucideIcon
|
||||
validate: (form: FormState, mode: 'create' | 'edit') => FormErrors
|
||||
validate: (form: CardRequisiteFormData, mode: 'create' | 'edit') => FlatErrors
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
@@ -144,17 +125,7 @@ const STEPS: StepDef[] = [
|
||||
titleFallback: 'Kart',
|
||||
subtitle: 'Görnüş & lokasiýa',
|
||||
icon: CreditCard,
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.status) e.status = 'Status hökmanydyr'
|
||||
if (!form.card_type) e.card_type = 'Görnüşi hökmanydyr'
|
||||
if (!form.card_number) e.card_number = 'Kart belgisi hökmanydyr'
|
||||
if (!form.card_expiry_month) e.card_expiry_month = 'Möhleti (aý) hökmanydyr'
|
||||
if (!form.card_expiry_year) e.card_expiry_year = 'Möhleti (ýyl) hökmanydyr'
|
||||
if (!form.province_id) e.province_id = 'Welaýat hökmanydyr'
|
||||
if (!form.branch_id) e.branch_id = 'Şahamça hökmanydyr'
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(0, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'personal',
|
||||
@@ -162,14 +133,7 @@ const STEPS: StepDef[] = [
|
||||
titleFallback: 'Şahsy',
|
||||
subtitle: 'At & telefon',
|
||||
icon: User,
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.first_name) e.first_name = 'Ady hökmanydyr'
|
||||
if (!form.last_name) e.last_name = 'Familiýasy hökmanydyr'
|
||||
if (!form.birth_date) e.birth_date = 'Doglan güni hökmanydyr'
|
||||
if (!form.phone) e.phone = 'Telefon hökmanydyr'
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(1, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'passport',
|
||||
@@ -177,18 +141,7 @@ const STEPS: StepDef[] = [
|
||||
titleFallback: 'Pasport',
|
||||
subtitle: 'Resminamalar',
|
||||
icon: FileText,
|
||||
validate: (form, mode) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.passport_series) e.passport_series = 'Pasport seriýasy hökmanydyr'
|
||||
if (!form.passport_number) e.passport_number = 'Pasport belgisi hökmanydyr'
|
||||
if (mode === 'create') {
|
||||
if (!form.passport_page1) e.passport_page1 = 'Hökmanydyr'
|
||||
if (!form.passport_page2_3) e.passport_page2_3 = 'Hökmanydyr'
|
||||
if (!form.passport_page8_9) e.passport_page8_9 = 'Hökmanydyr'
|
||||
if (!form.passport_page32) e.passport_page32 = 'Hökmanydyr'
|
||||
}
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(2, form, mode),
|
||||
},
|
||||
]
|
||||
|
||||
@@ -239,9 +192,9 @@ function BentoCard({
|
||||
// ─── Shared step content props ────────────────────────────────────────────────
|
||||
|
||||
interface StepContentProps {
|
||||
form: FormState
|
||||
errors: FormErrors
|
||||
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
|
||||
form: CardRequisiteFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof CardRequisiteFormData>(k: K, v: CardRequisiteFormData[K]) => void
|
||||
}
|
||||
|
||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||
@@ -524,17 +477,20 @@ export function CardRequisiteForm({
|
||||
const updateMutation = useUpdateCardRequisite(cardRequisiteId ?? '')
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const [form, setForm] = useState<FormState>(() => initialData ? mapToFormState(initialData) : INITIAL_STATE)
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors,
|
||||
} = useForm<CardRequisiteFormData>({
|
||||
defaultValues: initialData ? mapInitial(initialData) : DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
|
||||
const [currentStep, setCurrentStep] = useState(0)
|
||||
const [visited, setVisited] = useState<Set<number>>(
|
||||
() => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set<number>(),
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (initialData) setForm(mapToFormState(initialData))
|
||||
}, [initialData])
|
||||
|
||||
// ── Computed step errors ───────────────────────────────────────────────────
|
||||
|
||||
const stepsWithErrors = useMemo(() => {
|
||||
@@ -547,10 +503,10 @@ export function CardRequisiteForm({
|
||||
|
||||
// ── set helper ─────────────────────────────────────────────────────────────
|
||||
|
||||
const set = useCallback(<K extends keyof FormState>(key: K, value: FormState[K]) => {
|
||||
setForm((prev) => ({ ...prev, [key]: value }))
|
||||
setErrors((prev) => ({ ...prev, [key]: undefined }))
|
||||
}, [])
|
||||
const set = useCallback(<K extends keyof CardRequisiteFormData>(key: K, value: CardRequisiteFormData[K]) => {
|
||||
(setValue as (name: K, val: CardRequisiteFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
|
||||
const stepProps = useMemo(() => ({ form, errors, set }), [form, errors, set])
|
||||
|
||||
@@ -563,25 +519,21 @@ export function CardRequisiteForm({
|
||||
markVisited(currentStep)
|
||||
const errs = STEPS[currentStep].validate(form, mode)
|
||||
if (Object.keys(errs).length > 0) {
|
||||
setErrors(errs)
|
||||
toast.error(t('Fix errors', 'Dogry maglumat girizmegiňizi haýyş edýäris.'))
|
||||
return
|
||||
}
|
||||
setErrors({})
|
||||
setCurrentStep(currentStep + 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
|
||||
const handleBack = () => {
|
||||
markVisited(currentStep)
|
||||
setErrors({})
|
||||
setCurrentStep(currentStep - 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
|
||||
const handleGoTo = (i: number) => {
|
||||
markVisited(currentStep)
|
||||
setErrors({})
|
||||
setCurrentStep(i)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
@@ -596,11 +548,10 @@ export function CardRequisiteForm({
|
||||
const handleSubmit = async () => {
|
||||
setVisited(new Set(STEPS.map((_, i) => i)))
|
||||
|
||||
const allErrors: FormErrors = {}
|
||||
const allErrors: FlatErrors = {}
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode))
|
||||
|
||||
if (Object.keys(allErrors).length > 0) {
|
||||
setErrors(allErrors)
|
||||
toast.error(t('Fix errors', '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) {
|
||||
@@ -611,27 +562,7 @@ export function CardRequisiteForm({
|
||||
return
|
||||
}
|
||||
|
||||
const payload: CreateCardRequisitePayload = {
|
||||
status: form.status as CardRequisiteStatus,
|
||||
note: form.note || undefined,
|
||||
card_type: form.card_type,
|
||||
card_number: form.card_number,
|
||||
card_expiry_month: form.card_expiry_month,
|
||||
card_expiry_year: form.card_expiry_year,
|
||||
province_id: form.province_id,
|
||||
branch_id: form.branch_id,
|
||||
first_name: form.first_name,
|
||||
last_name: form.last_name,
|
||||
middle_name: form.middle_name || undefined,
|
||||
birth_date: form.birth_date,
|
||||
phone: form.phone,
|
||||
passport_series: form.passport_series,
|
||||
passport_number: form.passport_number,
|
||||
...(form.passport_page1 && { passport_page1: form.passport_page1 }),
|
||||
...(form.passport_page2_3 && { passport_page2_3: form.passport_page2_3 }),
|
||||
...(form.passport_page8_9 && { passport_page8_9: form.passport_page8_9 }),
|
||||
...(form.passport_page32 && { passport_page32: form.passport_page32 }),
|
||||
}
|
||||
const payload = buildPayload(getValues())
|
||||
|
||||
if (mode === 'create') {
|
||||
await createMutation.mutateAsync(payload)
|
||||
|
||||
112
src/features/cardRequisites/schemas/cardRequisite.schema.ts
Normal file
112
src/features/cardRequisites/schemas/cardRequisite.schema.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
import { z } from 'zod'
|
||||
import type { CardRequisiteStatus, CreateCardRequisitePayload } from '../api/cardRequisitesApi'
|
||||
|
||||
const fileRequired = z.custom<File>((val) => val instanceof File, 'Faýl hökmany')
|
||||
|
||||
export const cardRequisiteFormSchema = z.object({
|
||||
status: z.string().min(1, 'Status hökmanydyr'),
|
||||
note: z.string().optional(),
|
||||
card_type: z.string().min(1, 'Görnüşi hökmanydyr'),
|
||||
card_number: z.string().min(1, 'Kart belgisi hökmanydyr'),
|
||||
card_expiry_month: z.string().min(1, 'Möhleti (aý) hökmanydyr'),
|
||||
card_expiry_year: z.string().min(1, 'Möhleti (ýyl) hökmanydyr'),
|
||||
province_id: z.string().min(1, 'Welaýat hökmanydyr'),
|
||||
branch_id: z.string().min(1, 'Şahamça hökmanydyr'),
|
||||
first_name: z.string().min(1, 'Ady hökmanydyr'),
|
||||
last_name: z.string().min(1, 'Familiýasy hökmanydyr'),
|
||||
middle_name: z.string().optional(),
|
||||
birth_date: z.string().min(1, 'Doglan güni hökmanydyr'),
|
||||
phone: z.string().min(1, 'Telefon hökmanydyr'),
|
||||
passport_series: z.string().min(1, 'Pasport seriýasy hökmanydyr'),
|
||||
passport_number: z.string().min(1, 'Pasport belgisi hökmanydyr'),
|
||||
passport_page1: z.custom<File | null>().nullable(),
|
||||
passport_page2_3: z.custom<File | null>().nullable(),
|
||||
passport_page8_9: z.custom<File | null>().nullable(),
|
||||
passport_page32: z.custom<File | null>().nullable(),
|
||||
})
|
||||
|
||||
export type CardRequisiteFormData = z.infer<typeof cardRequisiteFormSchema>
|
||||
|
||||
export const stepSchemas: Record<number, z.ZodType<Partial<CardRequisiteFormData>>> = {
|
||||
0: cardRequisiteFormSchema.pick({
|
||||
status: true, card_type: true, card_number: true,
|
||||
card_expiry_month: true, card_expiry_year: true,
|
||||
province_id: true, branch_id: true,
|
||||
}),
|
||||
1: cardRequisiteFormSchema.pick({
|
||||
first_name: true, last_name: true, birth_date: true, phone: true,
|
||||
}),
|
||||
2: z.object({
|
||||
passport_series: z.string().min(1, 'Pasport seriýasy hökmanydyr'),
|
||||
passport_number: z.string().min(1, 'Pasport belgisi hökmanydyr'),
|
||||
passport_page1: fileRequired,
|
||||
passport_page2_3: fileRequired,
|
||||
passport_page8_9: fileRequired,
|
||||
passport_page32: fileRequired,
|
||||
}),
|
||||
}
|
||||
|
||||
export function validateStep(
|
||||
stepIndex: number,
|
||||
form: CardRequisiteFormData,
|
||||
mode: 'create' | 'edit',
|
||||
): Partial<Record<keyof CardRequisiteFormData, string>> {
|
||||
if (stepIndex === 2 && mode === 'edit') {
|
||||
const schema = z.object({
|
||||
passport_series: z.string().min(1, 'Pasport seriýasy hökmanydyr'),
|
||||
passport_number: z.string().min(1, 'Pasport belgisi hökmanydyr'),
|
||||
})
|
||||
const result = schema.safeParse(form)
|
||||
if (result.success) return {}
|
||||
const errors: Partial<Record<keyof CardRequisiteFormData, string>> = {}
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof CardRequisiteFormData
|
||||
if (!errors[key]) errors[key] = issue.message
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
const schema = stepSchemas[stepIndex]
|
||||
if (!schema) return {}
|
||||
const result = schema.safeParse(form)
|
||||
if (result.success) return {}
|
||||
const errors: Partial<Record<keyof CardRequisiteFormData, string>> = {}
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof CardRequisiteFormData
|
||||
if (!errors[key]) errors[key] = issue.message
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
export const DEFAULT_FORM_VALUES: CardRequisiteFormData = {
|
||||
status: 'pending', note: '', card_type: '', card_number: '',
|
||||
card_expiry_month: '', card_expiry_year: '', province_id: '', branch_id: '',
|
||||
first_name: '', last_name: '', middle_name: '', birth_date: '', phone: '',
|
||||
passport_series: '', passport_number: '',
|
||||
passport_page1: null, passport_page2_3: null,
|
||||
passport_page8_9: null, passport_page32: null,
|
||||
}
|
||||
|
||||
export function buildPayload(data: CardRequisiteFormData): CreateCardRequisitePayload {
|
||||
return {
|
||||
status: data.status as CardRequisiteStatus,
|
||||
note: data.note || undefined,
|
||||
card_type: data.card_type,
|
||||
card_number: data.card_number,
|
||||
card_expiry_month: data.card_expiry_month,
|
||||
card_expiry_year: data.card_expiry_year,
|
||||
province_id: data.province_id,
|
||||
branch_id: data.branch_id,
|
||||
first_name: data.first_name,
|
||||
last_name: data.last_name,
|
||||
middle_name: data.middle_name || undefined,
|
||||
birth_date: data.birth_date,
|
||||
phone: data.phone,
|
||||
passport_series: data.passport_series,
|
||||
passport_number: data.passport_number,
|
||||
...(data.passport_page1 && { passport_page1: data.passport_page1 }),
|
||||
...(data.passport_page2_3 && { passport_page2_3: data.passport_page2_3 }),
|
||||
...(data.passport_page8_9 && { passport_page8_9: data.passport_page8_9 }),
|
||||
...(data.passport_page32 && { passport_page32: data.passport_page32 }),
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import {apiClient} from '@/lib/api/client'
|
||||
import apiClient from '@/lib/api/client'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useMemo } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import type { CardTransaction } from '../api/cardTransactionsApi'
|
||||
import { useCreateCardTransaction, useUpdateCardTransaction } from '../hooks/useCardTransactions'
|
||||
import { cardTransactionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardTransaction.schema'
|
||||
import type { CardTransactionFormData } from '../schemas/cardTransaction.schema'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -14,22 +17,6 @@ interface CardTransactionFormProps {
|
||||
cardTransactionId?: number
|
||||
}
|
||||
|
||||
interface FormState {
|
||||
passport_series: string
|
||||
passport_number: string
|
||||
card_number: string
|
||||
card_expiry_month: string
|
||||
card_expiry_year: string
|
||||
}
|
||||
|
||||
interface FormErrors {
|
||||
passport_series?: string
|
||||
passport_number?: string
|
||||
card_number?: string
|
||||
card_expiry_month?: string
|
||||
card_expiry_year?: string
|
||||
}
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
const PASSPORT_SERIES_OPTIONS = [
|
||||
@@ -50,31 +37,17 @@ const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => {
|
||||
return { value: year, label: year }
|
||||
})
|
||||
|
||||
const EMPTY_FORM: FormState = {
|
||||
passport_series: '',
|
||||
passport_number: '',
|
||||
card_number: '',
|
||||
card_expiry_month: '',
|
||||
card_expiry_year: '',
|
||||
}
|
||||
// ─── Form errors helper ───────────────────────────────────────────────────────
|
||||
|
||||
// ─── Validation ───────────────────────────────────────────────────────────────
|
||||
type FlatErrors = Partial<Record<keyof CardTransactionFormData, string>>
|
||||
|
||||
function validate(form: FormState, t: (k: string, fallback: string) => string): FormErrors {
|
||||
const errors: FormErrors = {}
|
||||
|
||||
if (!form.passport_series)
|
||||
errors.passport_series = t('Passport series is required', 'Pasport seriýasy hökmanydyr')
|
||||
if (!form.passport_number)
|
||||
errors.passport_number = t('Passport number is required', 'Pasport belgisi hökmanydyr')
|
||||
if (!form.card_number)
|
||||
errors.card_number = t('Card number is required', 'Kart belgisi hökmanydyr')
|
||||
if (!form.card_expiry_month)
|
||||
errors.card_expiry_month = t('Expiry month is required', 'Möhleti (aý) hökmanydyr')
|
||||
if (!form.card_expiry_year)
|
||||
errors.card_expiry_year = t('Expiry year is required', 'Möhleti (ýyl) hökmanydyr')
|
||||
|
||||
return errors
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof CardTransactionFormData] = msg
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ─── Component ────────────────────────────────────────────────────────────────
|
||||
@@ -87,44 +60,42 @@ export function CardTransactionForm({
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const [form, setForm] = useState<FormState>(EMPTY_FORM)
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, setError,
|
||||
} = useForm<CardTransactionFormData>({
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...initialData }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
|
||||
const createMutation = useCreateCardTransaction()
|
||||
const updateMutation = useUpdateCardTransaction(cardTransactionId ?? 0)
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
// Populate form when editing
|
||||
useEffect(() => {
|
||||
if (mode === 'edit' && initialData) {
|
||||
setForm({
|
||||
passport_series: initialData.passport_series,
|
||||
passport_number: initialData.passport_number,
|
||||
card_number: initialData.card_number,
|
||||
card_expiry_month: initialData.card_expiry_month,
|
||||
card_expiry_year: initialData.card_expiry_year,
|
||||
})
|
||||
}
|
||||
}, [mode, initialData])
|
||||
|
||||
const setField = (field: keyof FormState) => (value: string) => {
|
||||
setForm((prev) => ({ ...prev, [field]: value }))
|
||||
if (errors[field]) setErrors((prev) => ({ ...prev, [field]: undefined }))
|
||||
const setField = (field: keyof CardTransactionFormData) => (value: string) => {
|
||||
setValue(field, value)
|
||||
clearErrors(field)
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const validationErrors = validate(form, t)
|
||||
if (Object.keys(validationErrors).length > 0) {
|
||||
setErrors(validationErrors)
|
||||
const result = cardTransactionFormSchema.safeParse(getValues())
|
||||
if (!result.success) {
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof CardTransactionFormData
|
||||
setError(key, { message: issue.message })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (mode === 'create') {
|
||||
await createMutation.mutateAsync(form)
|
||||
await createMutation.mutateAsync(buildPayload(result.data))
|
||||
navigate('/card-transactions')
|
||||
} else {
|
||||
await updateMutation.mutateAsync(form)
|
||||
await updateMutation.mutateAsync(buildPayload(result.data))
|
||||
navigate(`/card-transactions/${cardTransactionId}`)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateCardTransactionPayload } from '../api/cardTransactionsApi'
|
||||
|
||||
export const cardTransactionFormSchema = z.object({
|
||||
passport_series: z.string().min(1, 'Passport series is required'),
|
||||
passport_number: z.string().min(1, 'Passport number is required'),
|
||||
card_number: z.string().min(1, 'Card number is required'),
|
||||
card_expiry_month: z.string().min(1, 'Expiry month is required'),
|
||||
card_expiry_year: z.string().min(1, 'Expiry year is required'),
|
||||
})
|
||||
|
||||
export type CardTransactionFormData = z.infer<typeof cardTransactionFormSchema>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: CardTransactionFormData = {
|
||||
passport_series: '',
|
||||
passport_number: '',
|
||||
card_number: '',
|
||||
card_expiry_month: '',
|
||||
card_expiry_year: '',
|
||||
}
|
||||
|
||||
export function buildPayload(data: CardTransactionFormData): CreateCardTransactionPayload {
|
||||
return {
|
||||
passport_series: data.passport_series,
|
||||
passport_number: data.passport_number,
|
||||
card_number: data.card_number,
|
||||
card_expiry_month: data.card_expiry_month,
|
||||
card_expiry_year: data.card_expiry_year,
|
||||
}
|
||||
}
|
||||
@@ -1,30 +1,18 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useCallback, useMemo } 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 { CardType, CreateCardTypePayload } from '../api/cardTypesApi'
|
||||
import type { CardType } from '../api/cardTypesApi'
|
||||
import { useCreateCardType, useUpdateCardType } from '../hooks/useCardTypes'
|
||||
import { cardTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardType.schema'
|
||||
import type { CardTypeFormData } from '../schemas/cardType.schema'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface FormErrors {
|
||||
nameTk?: string
|
||||
nameRu?: string
|
||||
nameEn?: string
|
||||
value?: string
|
||||
}
|
||||
|
||||
interface FormState {
|
||||
nameTk: string
|
||||
nameRu: string
|
||||
nameEn: string
|
||||
value: string
|
||||
description: string
|
||||
isActive: boolean
|
||||
}
|
||||
|
||||
export interface CardTypeFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CardType
|
||||
@@ -41,10 +29,7 @@ const LANG_TABS: { key: LangKey; label: string }[] = [
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function buildInitialState(data?: CardType): FormState {
|
||||
if (!data) {
|
||||
return { nameTk: '', nameRu: '', nameEn: '', value: '', description: '', isActive: true }
|
||||
}
|
||||
function mapInitial(data: CardType): CardTypeFormData {
|
||||
return {
|
||||
nameTk: data.name.tk,
|
||||
nameRu: data.name.ru,
|
||||
@@ -55,14 +40,15 @@ function buildInitialState(data?: CardType): FormState {
|
||||
}
|
||||
}
|
||||
|
||||
function validate(form: FormState, t: (k: string, fb: string) => string): FormErrors {
|
||||
const errors: FormErrors = {}
|
||||
if (!form.nameTk.trim()) errors.nameTk = t('validation.required', 'Hökmany meýdan')
|
||||
if (!form.nameRu.trim()) errors.nameRu = t('validation.required', 'Hökmany meýdan')
|
||||
if (!form.nameEn.trim()) errors.nameEn = t('validation.required', 'Hökmany meýdan')
|
||||
if (!form.value.trim() || isNaN(Number(form.value)) || Number(form.value) < 0)
|
||||
errors.value = t('validation.invalidNumber', 'Dogry san giriziň')
|
||||
return errors
|
||||
type FlatErrors = Partial<Record<keyof CardTypeFormData, 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 CardTypeFormData] = msg
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ─── CardTypeForm ─────────────────────────────────────────────────────────────
|
||||
@@ -77,30 +63,40 @@ export function CardTypeForm({ mode, initialData, cardTypeId }: CardTypeFormProp
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
||||
const [form, setForm] = useState<FormState>(() => buildInitialState(initialData))
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
|
||||
useEffect(() => {
|
||||
if (initialData) setForm(buildInitialState(initialData))
|
||||
}, [initialData])
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
trigger,
|
||||
getValues,
|
||||
} = useForm<CardTypeFormData>({
|
||||
resolver: zodResolver(cardTypeFormSchema),
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
const set = (key: keyof FormState) => (value: string | boolean) =>
|
||||
setForm((prev) => ({ ...prev, [key]: value }))
|
||||
const form = watch()
|
||||
const errors = useMemo(
|
||||
() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>),
|
||||
[rhfErrors],
|
||||
)
|
||||
|
||||
const handleSubmit = () => {
|
||||
const errs = validate(form, t)
|
||||
if (Object.keys(errs).length > 0) {
|
||||
setErrors(errs)
|
||||
return
|
||||
}
|
||||
setErrors({})
|
||||
const set = useCallback(
|
||||
(key: keyof CardTypeFormData) => (value: string | boolean) => {
|
||||
(setValue as (k: keyof CardTypeFormData, v: string | boolean) => void)(key, value)
|
||||
clearErrors(key)
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
)
|
||||
|
||||
const payload: CreateCardTypePayload = {
|
||||
name: { tk: form.nameTk, ru: form.nameRu, en: form.nameEn },
|
||||
value: Number(form.value),
|
||||
description: form.description.trim() || null,
|
||||
isActive: form.isActive,
|
||||
}
|
||||
const handleSubmit = useCallback(async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
|
||||
const payload = buildPayload(getValues())
|
||||
|
||||
if (mode === 'create') {
|
||||
createMutation.mutate(payload, {
|
||||
@@ -109,16 +105,16 @@ export function CardTypeForm({ mode, initialData, cardTypeId }: CardTypeFormProp
|
||||
} else if (cardTypeId !== undefined) {
|
||||
updateMutation.mutate(
|
||||
{ id: cardTypeId, ...payload },
|
||||
{ onSuccess: () => navigate('/settings/card/card-types') }
|
||||
{ onSuccess: () => navigate('/settings/card/card-types') },
|
||||
)
|
||||
}
|
||||
}
|
||||
}, [mode, cardTypeId, createMutation, updateMutation, navigate, trigger, getValues])
|
||||
|
||||
const nameFieldKey = `name${activeLang.charAt(0).toUpperCase() + activeLang.slice(1)}` as
|
||||
| 'nameTk'
|
||||
| 'nameRu'
|
||||
| 'nameEn'
|
||||
const nameErrorKey = nameFieldKey as keyof FormErrors
|
||||
const nameErrorKey = nameFieldKey as keyof FlatErrors
|
||||
|
||||
return (
|
||||
<div>
|
||||
|
||||
34
src/features/cardTypes/schemas/cardType.schema.ts
Normal file
34
src/features/cardTypes/schemas/cardType.schema.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateCardTypePayload } from '../api/cardTypesApi'
|
||||
|
||||
export const cardTypeFormSchema = z.object({
|
||||
nameTk: z.string().min(1, 'Hökmany meýdan'),
|
||||
nameRu: z.string().min(1, 'Hökmany meýdan'),
|
||||
nameEn: z.string().min(1, 'Hökmany meýdan'),
|
||||
value: z.string().refine(
|
||||
(v) => v.trim() !== '' && !isNaN(Number(v)) && Number(v) >= 0,
|
||||
'Dogry san giriziň',
|
||||
),
|
||||
description: z.string().optional(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
|
||||
export type CardTypeFormData = z.infer<typeof cardTypeFormSchema>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: CardTypeFormData = {
|
||||
nameTk: '',
|
||||
nameRu: '',
|
||||
nameEn: '',
|
||||
value: '',
|
||||
description: '',
|
||||
isActive: true,
|
||||
}
|
||||
|
||||
export function buildPayload(data: CardTypeFormData): CreateCardTypePayload {
|
||||
return {
|
||||
name: { tk: data.nameTk, ru: data.nameRu, en: data.nameEn },
|
||||
value: Number(data.value),
|
||||
description: (data.description ?? '').trim() || null,
|
||||
isActive: data.isActive,
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,15 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { useCreateClient, useUpdateClient } from '../hooks/useClients'
|
||||
import type { Client, CreateClientPayload, UpdateClientPayload } from '../api/clientsApi'
|
||||
import { clientFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/client.schema'
|
||||
import type { ClientFormData } from '../schemas/client.schema'
|
||||
import type { Client } from '../api/clientsApi'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -15,20 +19,17 @@ interface ClientFormProps {
|
||||
clientId?: number
|
||||
}
|
||||
|
||||
interface FormState {
|
||||
username: string
|
||||
name: string
|
||||
phone: string
|
||||
email: string
|
||||
password: string
|
||||
isActive: boolean
|
||||
}
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
interface FormErrors {
|
||||
username?: string
|
||||
name?: string
|
||||
phone?: string
|
||||
password?: string
|
||||
type FlatErrors = Partial<Record<keyof ClientFormData, 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 ClientFormData] = msg
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ─── ClientForm ───────────────────────────────────────────────────────────────
|
||||
@@ -42,78 +43,54 @@ export function ClientForm({ mode, initialData, clientId }: ClientFormProps) {
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
// ── Form state ──────────────────────────────────────────────────────────────
|
||||
const [form, setForm] = useState<FormState>({
|
||||
username: '',
|
||||
name: '',
|
||||
phone: '',
|
||||
email: '',
|
||||
password: '',
|
||||
isActive: true,
|
||||
const schema = useMemo(() => clientFormSchema(mode), [mode])
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
} = useForm<ClientFormData>({
|
||||
resolver: zodResolver(schema as any),
|
||||
defaultValues: initialData
|
||||
? {
|
||||
...DEFAULT_FORM_VALUES,
|
||||
username: initialData.username,
|
||||
name: initialData.name,
|
||||
phone: initialData.phone ?? '',
|
||||
email: initialData.email ?? '',
|
||||
password: '',
|
||||
isActive: initialData.isActive,
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
|
||||
// Populate form in edit mode
|
||||
useEffect(() => {
|
||||
if (mode === 'edit' && initialData) {
|
||||
setForm({
|
||||
username: initialData.username ?? '',
|
||||
name: initialData.name ?? '',
|
||||
phone: initialData.phone ?? '',
|
||||
email: initialData.email ?? '',
|
||||
password: '',
|
||||
isActive: initialData.isActive ?? true,
|
||||
})
|
||||
}
|
||||
}, [mode, initialData])
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────────
|
||||
const set = (field: keyof FormState) => (value: string) =>
|
||||
setForm((prev) => ({ ...prev, [field]: value }))
|
||||
|
||||
const validate = (): boolean => {
|
||||
const next: FormErrors = {}
|
||||
if (!form.username.trim())
|
||||
next.username = t('clients.errors.usernameRequired', 'Ulanyjy ady hökmany')
|
||||
if (!form.name.trim())
|
||||
next.name = t('clients.errors.nameRequired', 'Ady hökmany')
|
||||
if (!form.phone.trim())
|
||||
next.phone = t('clients.errors.phoneRequired', 'Telefon hökmany')
|
||||
if (mode === 'create' && !form.password.trim())
|
||||
next.password = t('clients.errors.passwordRequired', 'Açar sözi hökmany')
|
||||
setErrors(next)
|
||||
return Object.keys(next).length === 0
|
||||
const setField = <K extends keyof ClientFormData>(key: K, value: ClientFormData[K]) => {
|
||||
;(setValue as (name: K, val: ClientFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}
|
||||
|
||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
||||
const handleSubmit = () => {
|
||||
if (!validate()) return
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
|
||||
const data = getValues()
|
||||
|
||||
if (mode === 'create') {
|
||||
const payload: CreateClientPayload = {
|
||||
username: form.username.trim(),
|
||||
name: form.name.trim(),
|
||||
phone: form.phone.trim(),
|
||||
email: form.email.trim() || undefined,
|
||||
password: form.password,
|
||||
isActive: form.isActive,
|
||||
}
|
||||
const payload = buildPayload(data)
|
||||
createMutation.mutate(payload, {
|
||||
onSuccess: () => navigate('/clients'),
|
||||
})
|
||||
} else {
|
||||
const payload: UpdateClientPayload = {
|
||||
username: form.username.trim(),
|
||||
name: form.name.trim(),
|
||||
phone: form.phone.trim(),
|
||||
email: form.email.trim() || undefined,
|
||||
isActive: form.isActive,
|
||||
}
|
||||
if (form.password.trim()) {
|
||||
payload.password = form.password
|
||||
}
|
||||
updateMutation.mutate(payload, {
|
||||
updateMutation.mutate({
|
||||
username: data.username.trim(),
|
||||
name: data.name.trim(),
|
||||
phone: data.phone.trim(),
|
||||
email: data.email.trim() || undefined,
|
||||
isActive: data.isActive,
|
||||
...(data.password.trim() ? { password: data.password } : {}),
|
||||
}, {
|
||||
onSuccess: () => navigate(`/clients/${clientId}`),
|
||||
})
|
||||
}
|
||||
@@ -131,7 +108,7 @@ export function ClientForm({ mode, initialData, clientId }: ClientFormProps) {
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.username}
|
||||
onChange={set('username')}
|
||||
onChange={(v) => setField('username', v)}
|
||||
placeholder={t('clients.fields.username', 'Ulanyjy ady')}
|
||||
error={errors.username}
|
||||
disabled={isPending}
|
||||
@@ -148,7 +125,7 @@ export function ClientForm({ mode, initialData, clientId }: ClientFormProps) {
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.name}
|
||||
onChange={set('name')}
|
||||
onChange={(v) => setField('name', v)}
|
||||
placeholder={t('clients.fields.name', 'Ady')}
|
||||
error={errors.name}
|
||||
disabled={isPending}
|
||||
@@ -165,7 +142,7 @@ export function ClientForm({ mode, initialData, clientId }: ClientFormProps) {
|
||||
<FormInput
|
||||
type="phone"
|
||||
value={form.phone}
|
||||
onChange={set('phone')}
|
||||
onChange={(v) => setField('phone', v)}
|
||||
error={errors.phone}
|
||||
disabled={isPending}
|
||||
className="max-w-lg"
|
||||
@@ -180,7 +157,7 @@ export function ClientForm({ mode, initialData, clientId }: ClientFormProps) {
|
||||
<FormInput
|
||||
type="email"
|
||||
value={form.email}
|
||||
onChange={set('email')}
|
||||
onChange={(v) => setField('email', v)}
|
||||
placeholder={t('clients.fields.email', 'E-poçta')}
|
||||
disabled={isPending}
|
||||
className="max-w-lg"
|
||||
@@ -197,7 +174,7 @@ export function ClientForm({ mode, initialData, clientId }: ClientFormProps) {
|
||||
<FormInput
|
||||
type="password"
|
||||
value={form.password}
|
||||
onChange={set('password')}
|
||||
onChange={(v) => setField('password', v)}
|
||||
placeholder={
|
||||
mode === 'edit'
|
||||
? t('clients.fields.passwordEditHint', 'Üýtgetmek üçin täze açar söz giriziň')
|
||||
@@ -221,7 +198,7 @@ export function ClientForm({ mode, initialData, clientId }: ClientFormProps) {
|
||||
</span>
|
||||
<Checkbox
|
||||
checked={form.isActive}
|
||||
onCheckedChange={(v) => setForm((prev) => ({ ...prev, isActive: !!v }))}
|
||||
onCheckedChange={(v) => setField('isActive', !!v)}
|
||||
disabled={isPending}
|
||||
className="data-[state=checked]:bg-primary data-[state=checked]:border-primary"
|
||||
/>
|
||||
|
||||
41
src/features/clients/schemas/client.schema.ts
Normal file
41
src/features/clients/schemas/client.schema.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateClientPayload } from '../api/clientsApi'
|
||||
|
||||
const baseSchema = z.object({
|
||||
username: z.string().min(1, 'Ulanyjy ady hökmany'),
|
||||
name: z.string().min(1, 'Ady hökmany'),
|
||||
phone: z.string().min(1, 'Telefon hökmany'),
|
||||
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, 'Açar sözi hökmany'),
|
||||
})
|
||||
: baseSchema
|
||||
}
|
||||
|
||||
export type ClientFormData = z.infer<typeof baseSchema>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: ClientFormData = {
|
||||
username: '',
|
||||
name: '',
|
||||
phone: '',
|
||||
email: '',
|
||||
password: '',
|
||||
isActive: true,
|
||||
}
|
||||
|
||||
export function buildPayload(data: ClientFormData): CreateClientPayload {
|
||||
return {
|
||||
username: data.username.trim(),
|
||||
name: data.name.trim(),
|
||||
phone: data.phone.trim(),
|
||||
email: data.email.trim() || undefined,
|
||||
password: data.password,
|
||||
isActive: data.isActive,
|
||||
}
|
||||
}
|
||||
@@ -1,51 +1,38 @@
|
||||
// features/currencyRates/components/CurrencyRateForm.tsx
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useCallback, useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { CURRENCY_OPTIONS, type CurrencyCode, type CurrencyRate } from '../api/currencyRatesApi'
|
||||
import { CURRENCY_OPTIONS, type CurrencyRate } from '../api/currencyRatesApi'
|
||||
import { useCreateCurrencyRate, useUpdateCurrencyRate } from '../hooks/useCurrencyRates'
|
||||
import {
|
||||
currencyRateFormSchema,
|
||||
DEFAULT_FORM_VALUES,
|
||||
buildPayload,
|
||||
type CurrencyRateFormData,
|
||||
} from '../schemas/currencyRate.schema'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface FormState {
|
||||
currencyFrom: string
|
||||
currencyTo: string
|
||||
value: string
|
||||
}
|
||||
|
||||
interface FormErrors {
|
||||
currencyFrom?: string
|
||||
currencyTo?: string
|
||||
value?: string
|
||||
}
|
||||
|
||||
export interface CurrencyRateFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CurrencyRate
|
||||
rateId?: number
|
||||
}
|
||||
|
||||
// ─── Validation ───────────────────────────────────────────────────────────────
|
||||
type FlatErrors = Partial<Record<keyof CurrencyRateFormData, string>>
|
||||
|
||||
function validate(form: FormState, t: (key: string, fallback: string) => string): FormErrors {
|
||||
const errors: FormErrors = {}
|
||||
|
||||
if (!form.currencyFrom) {
|
||||
errors.currencyFrom = t('currencyRates.errors.currencyFromRequired', 'Walýuta saýlaň')
|
||||
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 CurrencyRateFormData] = msg
|
||||
}
|
||||
if (!form.currencyTo) {
|
||||
errors.currencyTo = t('currencyRates.errors.currencyToRequired', 'Walýuta saýlaň')
|
||||
}
|
||||
if (!form.value.trim()) {
|
||||
errors.value = t('currencyRates.errors.valueRequired', 'Bahany giriziň')
|
||||
} else if (isNaN(Number(form.value)) || Number(form.value) <= 0) {
|
||||
errors.value = t('currencyRates.errors.valueInvalid', 'Baha 0-dan uly bolmaly')
|
||||
}
|
||||
|
||||
return errors
|
||||
return result
|
||||
}
|
||||
|
||||
// ─── CurrencyRateForm ─────────────────────────────────────────────────────────
|
||||
@@ -54,47 +41,48 @@ export function CurrencyRateForm({ mode, initialData, rateId }: CurrencyRateForm
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const [form, setForm] = useState<FormState>({
|
||||
currencyFrom: initialData?.currencyFrom ?? '',
|
||||
currencyTo: initialData?.currencyTo ?? '',
|
||||
value: initialData?.value != null ? String(initialData.value) : '',
|
||||
})
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
|
||||
const createMutation = useCreateCurrencyRate()
|
||||
const updateMutation = useUpdateCurrencyRate(rateId ?? 0)
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
// Sync form when initialData loads (edit mode)
|
||||
useEffect(() => {
|
||||
if (mode === 'edit' && initialData) {
|
||||
setForm({
|
||||
currencyFrom: initialData.currencyFrom,
|
||||
currencyTo: initialData.currencyTo,
|
||||
value: String(initialData.value),
|
||||
})
|
||||
}
|
||||
}, [mode, initialData])
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
trigger,
|
||||
getValues,
|
||||
} = useForm<CurrencyRateFormData>({
|
||||
resolver: zodResolver(currencyRateFormSchema),
|
||||
defaultValues: initialData
|
||||
? {
|
||||
currencyFrom: initialData.currencyFrom,
|
||||
currencyTo: initialData.currencyTo,
|
||||
value: String(initialData.value),
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
const setField = (field: keyof FormState) => (val: string) => {
|
||||
setForm((prev) => ({ ...prev, [field]: val }))
|
||||
// Clear error on change
|
||||
if (errors[field]) setErrors((prev) => ({ ...prev, [field]: undefined }))
|
||||
}
|
||||
const form = watch()
|
||||
const errors = useMemo(
|
||||
() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>),
|
||||
[rhfErrors],
|
||||
)
|
||||
|
||||
const setField = useCallback(
|
||||
(key: keyof CurrencyRateFormData) => (value: string) => {
|
||||
setValue(key, value)
|
||||
clearErrors(key)
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
)
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const validationErrors = validate(form, t)
|
||||
if (Object.keys(validationErrors).length > 0) {
|
||||
setErrors(validationErrors)
|
||||
return
|
||||
}
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
|
||||
const payload = {
|
||||
currencyFrom: form.currencyFrom as CurrencyCode,
|
||||
currencyTo: form.currencyTo as CurrencyCode,
|
||||
value: Number(form.value),
|
||||
}
|
||||
const payload = buildPayload(getValues())
|
||||
|
||||
if (mode === 'create') {
|
||||
await createMutation.mutateAsync(payload)
|
||||
|
||||
27
src/features/currencyRates/schemas/currencyRate.schema.ts
Normal file
27
src/features/currencyRates/schemas/currencyRate.schema.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateCurrencyRatePayload, CurrencyCode } from '../api/currencyRatesApi'
|
||||
|
||||
export const currencyRateFormSchema = z.object({
|
||||
currencyFrom: z.string().min(1, 'Hökmany meýdan'),
|
||||
currencyTo: z.string().min(1, 'Hökmany meýdan'),
|
||||
value: z
|
||||
.string()
|
||||
.min(1, 'Hökmany meýdan')
|
||||
.refine((v) => !isNaN(Number(v)) && Number(v) > 0, 'Baha 0-dan uly bolmaly'),
|
||||
})
|
||||
|
||||
export type CurrencyRateFormData = z.infer<typeof currencyRateFormSchema>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: CurrencyRateFormData = {
|
||||
currencyFrom: '',
|
||||
currencyTo: '',
|
||||
value: '',
|
||||
}
|
||||
|
||||
export function buildPayload(data: CurrencyRateFormData): CreateCurrencyRatePayload {
|
||||
return {
|
||||
currencyFrom: data.currencyFrom as CurrencyCode,
|
||||
currencyTo: data.currencyTo as CurrencyCode,
|
||||
value: Number(data.value),
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,27 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useCallback, useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import type { District, CreateDistrictPayload } from '../api/districtsApi'
|
||||
import type { District } from '../api/districtsApi'
|
||||
import { useCreateDistrict, useUpdateDistrict } from '../hooks/useDistricts'
|
||||
import { districtFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/district.schema'
|
||||
import type { DistrictFormData } from '../schemas/district.schema'
|
||||
|
||||
interface FormErrors {
|
||||
nameTk?: string
|
||||
nameRu?: string
|
||||
nameEn?: string
|
||||
type FlatErrors = Partial<Record<keyof DistrictFormData, 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 DistrictFormData] = msg
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
interface FormState {
|
||||
nameTk: string
|
||||
nameRu: string
|
||||
nameEn: string
|
||||
description: string
|
||||
isActive: boolean
|
||||
}
|
||||
type FormErrors = FlatErrors
|
||||
|
||||
export interface DistrictFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
@@ -35,10 +37,7 @@ const LANG_TABS: { key: LangKey; label: string }[] = [
|
||||
{ key: 'en', label: 'English' },
|
||||
]
|
||||
|
||||
function buildInitialState(data?: District): FormState {
|
||||
if (!data) {
|
||||
return { nameTk: '', nameRu: '', nameEn: '', description: '', isActive: true }
|
||||
}
|
||||
function mapInitial(data: District): DistrictFormData {
|
||||
return {
|
||||
nameTk: data.name.tk,
|
||||
nameRu: data.name.ru,
|
||||
@@ -48,14 +47,6 @@ function buildInitialState(data?: District): FormState {
|
||||
}
|
||||
}
|
||||
|
||||
function validate(form: FormState, t: (k: string, fb: string) => string): FormErrors {
|
||||
const errors: FormErrors = {}
|
||||
if (!form.nameTk.trim()) errors.nameTk = t('validation.required', 'Hökmany meýdan')
|
||||
if (!form.nameRu.trim()) errors.nameRu = t('validation.required', 'Hökmany meýdan')
|
||||
if (!form.nameEn.trim()) errors.nameEn = t('validation.required', 'Hökmany meýdan')
|
||||
return errors
|
||||
}
|
||||
|
||||
export function DistrictForm({ mode, initialData, districtId }: DistrictFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
@@ -65,30 +56,29 @@ export function DistrictForm({ mode, initialData, districtId }: DistrictFormProp
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors,
|
||||
} = useForm<DistrictFormData>({
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
|
||||
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
||||
const [form, setForm] = useState<FormState>(() => buildInitialState(initialData))
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
|
||||
useEffect(() => {
|
||||
if (initialData) setForm(buildInitialState(initialData))
|
||||
}, [initialData])
|
||||
|
||||
const set = (key: keyof FormState) => (value: string | boolean) =>
|
||||
setForm((prev) => ({ ...prev, [key]: value }))
|
||||
const set = useCallback(<K extends keyof DistrictFormData>(key: K) =>
|
||||
(value: DistrictFormData[K]) => {
|
||||
(setValue as (name: K, val: DistrictFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
|
||||
const handleSubmit = () => {
|
||||
const errs = validate(form, t)
|
||||
if (Object.keys(errs).length > 0) {
|
||||
setErrors(errs)
|
||||
return
|
||||
}
|
||||
setErrors({})
|
||||
const values = getValues()
|
||||
const result = districtFormSchema.safeParse(values)
|
||||
if (!result.success) return
|
||||
|
||||
const payload: CreateDistrictPayload = {
|
||||
name: { tk: form.nameTk, ru: form.nameRu, en: form.nameEn },
|
||||
description: form.description.trim() || null,
|
||||
isActive: form.isActive,
|
||||
}
|
||||
const payload = buildPayload(values)
|
||||
|
||||
if (mode === 'create') {
|
||||
createMutation.mutate(payload, {
|
||||
|
||||
28
src/features/districts/schemas/district.schema.ts
Normal file
28
src/features/districts/schemas/district.schema.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateDistrictPayload } from '../api/districtsApi'
|
||||
|
||||
export const districtFormSchema = z.object({
|
||||
nameTk: z.string().min(1, 'Hökmany meýdan'),
|
||||
nameRu: z.string().min(1, 'Hökmany meýdan'),
|
||||
nameEn: z.string().min(1, 'Hökmany meýdan'),
|
||||
description: z.string().optional(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
|
||||
export type DistrictFormData = z.infer<typeof districtFormSchema>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: DistrictFormData = {
|
||||
nameTk: '',
|
||||
nameRu: '',
|
||||
nameEn: '',
|
||||
description: '',
|
||||
isActive: true,
|
||||
}
|
||||
|
||||
export function buildPayload(data: DistrictFormData): CreateDistrictPayload {
|
||||
return {
|
||||
name: { tk: data.nameTk, ru: data.nameRu, en: data.nameEn },
|
||||
description: data.description?.trim() || null,
|
||||
isActive: data.isActive,
|
||||
}
|
||||
}
|
||||
@@ -1,412 +1,509 @@
|
||||
import { apiClient } from '@/lib/api/client'
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export type LoanOrderMobileStatus =
|
||||
| 'GARAŞYLÝAR'
|
||||
| 'KANAGATLANDYRYLAN'
|
||||
| 'RED_EDILDI'
|
||||
| 'IŞLENÝÄR'
|
||||
export type LoanOrderMobileStatus = "GARAŞYLÝAR" | "KANAGATLANDYRYLAN" | "RED_EDILDI" | "IŞLENÝÄR";
|
||||
|
||||
export interface LoanOrderMobile {
|
||||
id: string
|
||||
loanType: string
|
||||
createdAt: string
|
||||
region: string
|
||||
branch: string
|
||||
firstName: string
|
||||
lastName: string
|
||||
phone: string
|
||||
status: LoanOrderMobileStatus
|
||||
createdBy?: string
|
||||
id: string;
|
||||
loanType: string;
|
||||
createdAt: string;
|
||||
region: string;
|
||||
branch: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
phone: string;
|
||||
status: LoanOrderMobileStatus;
|
||||
createdBy?: string;
|
||||
|
||||
// ── Detail fields ─────────────────────────────────────────────────────────
|
||||
patronicName?: string | null
|
||||
education?: string | null
|
||||
marriageStatus?: string | null
|
||||
dateOfBirth?: string | null
|
||||
residence?: string | null
|
||||
currentResidence?: string | null
|
||||
patronicName?: string | null;
|
||||
education?: string | null;
|
||||
marriageStatus?: string | null;
|
||||
dateOfBirth?: string | null;
|
||||
residence?: string | null;
|
||||
currentResidence?: string | null;
|
||||
|
||||
// Passport
|
||||
passportSerie?: string | null
|
||||
passportNumber?: string | null
|
||||
passportDateOfIssue?: string | null
|
||||
passportGivenBy?: string | null
|
||||
bornPlace?: string | null
|
||||
passportPage1Url?: string | null
|
||||
passportPage23Url?: string | null
|
||||
passportPage89Url?: string | null
|
||||
passportPage32Url?: string | null
|
||||
passportSerie?: string | null;
|
||||
passportNumber?: string | null;
|
||||
passportDateOfIssue?: string | null;
|
||||
passportGivenBy?: string | null;
|
||||
bornPlace?: string | null;
|
||||
passportPage1Url?: string | null;
|
||||
passportPage23Url?: string | null;
|
||||
passportPage89Url?: string | null;
|
||||
passportPage32Url?: string | null;
|
||||
|
||||
// Contact
|
||||
email?: string | null
|
||||
phoneAdditional?: string | null
|
||||
homePhone?: string | null
|
||||
email?: string | null;
|
||||
phoneAdditional?: string | null;
|
||||
homePhone?: string | null;
|
||||
|
||||
// Employment
|
||||
workCompany?: string | null
|
||||
workHrPhone?: string | null
|
||||
workRegion?: string | null
|
||||
workProvince?: string | null
|
||||
position?: string | null
|
||||
salary?: number | null
|
||||
workStartedAt?: string | null
|
||||
workCompany?: string | null;
|
||||
workHrPhone?: string | null;
|
||||
workRegion?: string | null;
|
||||
workProvince?: string | null;
|
||||
position?: string | null;
|
||||
salary?: number | null;
|
||||
workStartedAt?: string | null;
|
||||
|
||||
// New fields
|
||||
note?: string | null
|
||||
loanAmount?: number | null
|
||||
loanHistory?: string | null
|
||||
note?: string | null;
|
||||
loanAmount?: number | null;
|
||||
loanHistory?: string | null;
|
||||
|
||||
// Card (Zähmet haky)
|
||||
cardNumber?: string | null
|
||||
cardName?: string | null
|
||||
cardExpMonth?: string | null
|
||||
cardExpYear?: string | null
|
||||
cardNumber?: string | null;
|
||||
cardName?: string | null;
|
||||
cardExpMonth?: string | null;
|
||||
cardExpYear?: string | null;
|
||||
|
||||
// Guarantor (Zamun)
|
||||
guarantor1Name?: string | null
|
||||
guarantor1Surname?: string | null
|
||||
guarantor1Patronic?: string | null
|
||||
guarantor1PassportSerie?: string | null
|
||||
guarantor1PassportNumber?: string | null
|
||||
guarantor1CardNumber?: string | null
|
||||
guarantor1CardName?: string | null
|
||||
guarantor1CardExpMonth?: string | null
|
||||
guarantor1CardExpYear?: string | null
|
||||
guarantor1Salary?: number | null
|
||||
guarantor1Name?: string | null;
|
||||
guarantor1Surname?: string | null;
|
||||
guarantor1Patronic?: string | null;
|
||||
guarantor1PassportSerie?: string | null;
|
||||
guarantor1PassportNumber?: string | null;
|
||||
guarantor1CardNumber?: string | null;
|
||||
guarantor1CardName?: string | null;
|
||||
guarantor1CardExpMonth?: string | null;
|
||||
guarantor1CardExpYear?: string | null;
|
||||
guarantor1Salary?: number | null;
|
||||
}
|
||||
|
||||
export interface LoanOrderMobilePayload {
|
||||
status: string
|
||||
loanType: string
|
||||
region: string
|
||||
branch: string
|
||||
firstName: string
|
||||
lastName: string
|
||||
patronicName?: string
|
||||
education: string
|
||||
marriageStatus: string
|
||||
dateOfBirth: string
|
||||
residence: string
|
||||
currentResidence?: string
|
||||
passportSerie: string
|
||||
passportNumber: string
|
||||
passportDateOfIssue: string
|
||||
passportGivenBy: string
|
||||
bornPlace?: string
|
||||
email?: string
|
||||
phone: string
|
||||
phoneAdditional?: string
|
||||
homePhone?: string
|
||||
workCompany: string
|
||||
workHrPhone?: string
|
||||
workRegion?: string
|
||||
workProvince?: string
|
||||
position: string
|
||||
salary: number
|
||||
workStartedAt: string
|
||||
status: string;
|
||||
loanType: string;
|
||||
region: string;
|
||||
branch: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
patronicName?: string;
|
||||
education: string;
|
||||
marriageStatus: string;
|
||||
dateOfBirth: string;
|
||||
residence: string;
|
||||
currentResidence?: string;
|
||||
passportSerie: string;
|
||||
passportNumber: string;
|
||||
passportDateOfIssue: string;
|
||||
passportGivenBy: string;
|
||||
bornPlace?: string;
|
||||
email?: string;
|
||||
phone: string;
|
||||
phoneAdditional?: string;
|
||||
homePhone?: string;
|
||||
workCompany: string;
|
||||
workHrPhone?: string;
|
||||
workRegion?: string;
|
||||
workProvince?: string;
|
||||
position: string;
|
||||
salary: number;
|
||||
workStartedAt: string;
|
||||
|
||||
note?: string
|
||||
loanAmount?: number
|
||||
loanHistory?: string
|
||||
note?: string;
|
||||
loanAmount?: number;
|
||||
loanHistory?: string;
|
||||
|
||||
cardNumber?: string
|
||||
cardName?: string
|
||||
cardExpMonth?: string
|
||||
cardExpYear?: string
|
||||
cardNumber?: string;
|
||||
cardName?: string;
|
||||
cardExpMonth?: string;
|
||||
cardExpYear?: string;
|
||||
|
||||
guarantor1Name?: string
|
||||
guarantor1Surname?: string
|
||||
guarantor1Patronic?: string
|
||||
guarantor1PassportSerie?: string
|
||||
guarantor1PassportNumber?: string
|
||||
guarantor1CardNumber?: string
|
||||
guarantor1CardName?: string
|
||||
guarantor1CardExpMonth?: string
|
||||
guarantor1CardExpYear?: string
|
||||
guarantor1Salary?: number
|
||||
guarantor1Name?: string;
|
||||
guarantor1Surname?: string;
|
||||
guarantor1Patronic?: string;
|
||||
guarantor1PassportSerie?: string;
|
||||
guarantor1PassportNumber?: string;
|
||||
guarantor1CardNumber?: string;
|
||||
guarantor1CardName?: string;
|
||||
guarantor1CardExpMonth?: string;
|
||||
guarantor1CardExpYear?: string;
|
||||
guarantor1Salary?: number;
|
||||
}
|
||||
|
||||
export interface LoanOrderMobileListParams {
|
||||
search?: string
|
||||
region?: string
|
||||
status?: LoanOrderMobileStatus
|
||||
branch?: string
|
||||
archived?: string
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string;
|
||||
region?: string;
|
||||
status?: LoanOrderMobileStatus;
|
||||
branch?: string;
|
||||
archived?: string;
|
||||
page?: number;
|
||||
perPage?: number;
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
data: T[]
|
||||
total: number
|
||||
data: T[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
// ─── Mock Data ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_DATA: LoanOrderMobile[] = [
|
||||
{
|
||||
id: 'LOM-0001', loanType: 'Sarp ediş karzy', createdAt: '2025-01-15 09:42',
|
||||
region: 'Aşgabat', branch: 'Merkezi şahamça',
|
||||
firstName: 'Oraz', lastName: 'Annaýew', phone: '+99361123456', status: 'GARAŞYLÝAR',
|
||||
note: 'Müşderi dokumentleri tassyklamady',
|
||||
loanAmount: 15000, loanHistory: 'positive',
|
||||
patronicName: 'Myradowiç', education: 'high', marriageStatus: 'MARRIED',
|
||||
dateOfBirth: '1992-04-18',
|
||||
residence: 'Aşgabat, Bitarap Türkmenistan şaýoly, 15',
|
||||
currentResidence: 'Aşgabat, Garaşsyzlyk köçesi, 5',
|
||||
passportSerie: 'I', passportNumber: '123456',
|
||||
passportDateOfIssue: '2015-03-10',
|
||||
passportGivenBy: 'Aşgabat şäheriniň Içeri işler müdirligi',
|
||||
bornPlace: 'Aşgabat şäheri',
|
||||
email: 'oraz.annayew@email.com',
|
||||
phoneAdditional: '+99365443322',
|
||||
workCompany: 'Türkmennebit', workHrPhone: '+99312456789',
|
||||
workRegion: 'Aşgabat', workProvince: 'Büzmeýin etraby',
|
||||
position: 'Inžener', salary: 2500, workStartedAt: '2018-06-01',
|
||||
cardNumber: '4111111111111111', cardName: 'ORAZ ANNAÝEW',
|
||||
cardExpMonth: '12', cardExpYear: '2027',
|
||||
guarantor1Name: 'Berdi', guarantor1Surname: 'Berdiýew',
|
||||
guarantor1Patronic: 'Annagulyýewiç',
|
||||
guarantor1PassportSerie: 'II', guarantor1PassportNumber: '654321',
|
||||
guarantor1CardNumber: '4222222222222222', guarantor1CardName: 'BERDI BERDIÝEW',
|
||||
guarantor1CardExpMonth: '06', guarantor1CardExpYear: '2026', guarantor1Salary: 3000,
|
||||
id: "LOM-0001",
|
||||
loanType: "Sarp ediş karzy",
|
||||
createdAt: "2025-01-15 09:42",
|
||||
region: "Aşgabat",
|
||||
branch: "Merkezi şahamça",
|
||||
firstName: "Oraz",
|
||||
lastName: "Annaýew",
|
||||
phone: "+99361123456",
|
||||
status: "GARAŞYLÝAR",
|
||||
note: "Müşderi dokumentleri tassyklamady",
|
||||
loanAmount: 15000,
|
||||
loanHistory: "positive",
|
||||
patronicName: "Myradowiç",
|
||||
education: "high",
|
||||
marriageStatus: "MARRIED",
|
||||
dateOfBirth: "1992-04-18",
|
||||
residence: "Aşgabat, Bitarap Türkmenistan şaýoly, 15",
|
||||
currentResidence: "Aşgabat, Garaşsyzlyk köçesi, 5",
|
||||
passportSerie: "I",
|
||||
passportNumber: "123456",
|
||||
passportDateOfIssue: "2015-03-10",
|
||||
passportGivenBy: "Aşgabat şäheriniň Içeri işler müdirligi",
|
||||
bornPlace: "Aşgabat şäheri",
|
||||
email: "oraz.annayew@email.com",
|
||||
phoneAdditional: "+99365443322",
|
||||
workCompany: "Türkmennebit",
|
||||
workHrPhone: "+99312456789",
|
||||
workRegion: "Aşgabat",
|
||||
workProvince: "Büzmeýin etraby",
|
||||
position: "Inžener",
|
||||
salary: 2500,
|
||||
workStartedAt: "2018-06-01",
|
||||
cardNumber: "4111111111111111",
|
||||
cardName: "ORAZ ANNAÝEW",
|
||||
cardExpMonth: "12",
|
||||
cardExpYear: "2027",
|
||||
guarantor1Name: "Berdi",
|
||||
guarantor1Surname: "Berdiýew",
|
||||
guarantor1Patronic: "Annagulyýewiç",
|
||||
guarantor1PassportSerie: "II",
|
||||
guarantor1PassportNumber: "654321",
|
||||
guarantor1CardNumber: "4222222222222222",
|
||||
guarantor1CardName: "BERDI BERDIÝEW",
|
||||
guarantor1CardExpMonth: "06",
|
||||
guarantor1CardExpYear: "2026",
|
||||
guarantor1Salary: 3000,
|
||||
},
|
||||
{
|
||||
id: 'LOM-0002', loanType: 'Awtoulag karzy', createdAt: '2025-01-18 11:05',
|
||||
region: 'Ahal', branch: 'Änew şahamçasy',
|
||||
firstName: 'Merjen', lastName: 'Hudaýewa', phone: '+99362234567', status: 'KANAGATLANDYRYLAN',
|
||||
loanAmount: 30000, loanHistory: 'new',
|
||||
patronicName: 'Myratowna', education: 'masters', marriageStatus: 'SINGLE',
|
||||
dateOfBirth: '1995-11-20',
|
||||
residence: 'Änew şäher, Garaşsyzlyk köçesi, 10',
|
||||
passportSerie: 'I', passportNumber: '789012',
|
||||
passportDateOfIssue: '2018-07-22',
|
||||
passportGivenBy: 'Ahal welaýatynyň Içeri işler müdirligi',
|
||||
bornPlace: 'Änew şäheri',
|
||||
email: 'merjen.hudayewa@email.com',
|
||||
workCompany: 'Änew etrap hasap bölümi', position: 'Hasapçy',
|
||||
salary: 1800, workStartedAt: '2019-03-15',
|
||||
cardNumber: '4333333333333333', cardName: 'MERJEN HUDAÝEWA',
|
||||
cardExpMonth: '09', cardExpYear: '2028',
|
||||
guarantor1Name: 'Merdan', guarantor1Surname: 'Merdanow',
|
||||
guarantor1PassportSerie: 'I', guarantor1PassportNumber: '345678',
|
||||
guarantor1CardNumber: '4444444444444444', guarantor1CardName: 'MERDAN MERDANOW',
|
||||
guarantor1CardExpMonth: '03', guarantor1CardExpYear: '2025', guarantor1Salary: 2200,
|
||||
id: "LOM-0002",
|
||||
loanType: "Awtoulag karzy",
|
||||
createdAt: "2025-01-18 11:05",
|
||||
region: "Ahal",
|
||||
branch: "Änew şahamçasy",
|
||||
firstName: "Merjen",
|
||||
lastName: "Hudaýewa",
|
||||
phone: "+99362234567",
|
||||
status: "KANAGATLANDYRYLAN",
|
||||
loanAmount: 30000,
|
||||
loanHistory: "new",
|
||||
patronicName: "Myratowna",
|
||||
education: "masters",
|
||||
marriageStatus: "SINGLE",
|
||||
dateOfBirth: "1995-11-20",
|
||||
residence: "Änew şäher, Garaşsyzlyk köçesi, 10",
|
||||
passportSerie: "I",
|
||||
passportNumber: "789012",
|
||||
passportDateOfIssue: "2018-07-22",
|
||||
passportGivenBy: "Ahal welaýatynyň Içeri işler müdirligi",
|
||||
bornPlace: "Änew şäheri",
|
||||
email: "merjen.hudayewa@email.com",
|
||||
workCompany: "Änew etrap hasap bölümi",
|
||||
position: "Hasapçy",
|
||||
salary: 1800,
|
||||
workStartedAt: "2019-03-15",
|
||||
cardNumber: "4333333333333333",
|
||||
cardName: "MERJEN HUDAÝEWA",
|
||||
cardExpMonth: "09",
|
||||
cardExpYear: "2028",
|
||||
guarantor1Name: "Merdan",
|
||||
guarantor1Surname: "Merdanow",
|
||||
guarantor1PassportSerie: "I",
|
||||
guarantor1PassportNumber: "345678",
|
||||
guarantor1CardNumber: "4444444444444444",
|
||||
guarantor1CardName: "MERDAN MERDANOW",
|
||||
guarantor1CardExpMonth: "03",
|
||||
guarantor1CardExpYear: "2025",
|
||||
guarantor1Salary: 2200,
|
||||
},
|
||||
{
|
||||
id: 'LOM-0003', loanType: 'Ipoteka karzy', createdAt: '2025-01-20 14:30',
|
||||
region: 'Balkan', branch: 'Balkanabat şahamçasy',
|
||||
firstName: 'Serdar', lastName: 'Durdyýew', phone: '+99363345678', status: 'IŞLENÝÄR',
|
||||
loanAmount: 50000, loanHistory: 'positive',
|
||||
patronicName: 'Annagylyjowiç', education: 'high', marriageStatus: 'MARRIED',
|
||||
dateOfBirth: '1988-07-12',
|
||||
residence: 'Balkanabat, Magtymguly köçesi, 25',
|
||||
passportSerie: 'II', passportNumber: '456123',
|
||||
passportDateOfIssue: '2016-05-18',
|
||||
passportGivenBy: 'Balkan welaýatynyň Içeri işler müdirligi',
|
||||
email: 'serdar.durdyyew@email.com',
|
||||
workCompany: 'Balkan nebit', position: 'Operator',
|
||||
salary: 3200, workStartedAt: '2015-09-01',
|
||||
cardNumber: '4555555555555555', cardName: 'SERDAR DURDYÝEW',
|
||||
cardExpMonth: '04', cardExpYear: '2029',
|
||||
guarantor1Name: 'Döwran', guarantor1Surname: 'Döwranow',
|
||||
guarantor1PassportSerie: 'I', guarantor1PassportNumber: '789456',
|
||||
guarantor1CardNumber: '4666666666666666', guarantor1CardName: 'DÖWRAN DÖWRANOW',
|
||||
guarantor1CardExpMonth: '11', guarantor1CardExpYear: '2027', guarantor1Salary: 3500,
|
||||
id: "LOM-0003",
|
||||
loanType: "Ipoteka karzy",
|
||||
createdAt: "2025-01-20 14:30",
|
||||
region: "Balkan",
|
||||
branch: "Balkanabat şahamçasy",
|
||||
firstName: "Serdar",
|
||||
lastName: "Durdyýew",
|
||||
phone: "+99363345678",
|
||||
status: "IŞLENÝÄR",
|
||||
loanAmount: 50000,
|
||||
loanHistory: "positive",
|
||||
patronicName: "Annagylyjowiç",
|
||||
education: "high",
|
||||
marriageStatus: "MARRIED",
|
||||
dateOfBirth: "1988-07-12",
|
||||
residence: "Balkanabat, Magtymguly köçesi, 25",
|
||||
passportSerie: "II",
|
||||
passportNumber: "456123",
|
||||
passportDateOfIssue: "2016-05-18",
|
||||
passportGivenBy: "Balkan welaýatynyň Içeri işler müdirligi",
|
||||
email: "serdar.durdyyew@email.com",
|
||||
workCompany: "Balkan nebit",
|
||||
position: "Operator",
|
||||
salary: 3200,
|
||||
workStartedAt: "2015-09-01",
|
||||
cardNumber: "4555555555555555",
|
||||
cardName: "SERDAR DURDYÝEW",
|
||||
cardExpMonth: "04",
|
||||
cardExpYear: "2029",
|
||||
guarantor1Name: "Döwran",
|
||||
guarantor1Surname: "Döwranow",
|
||||
guarantor1PassportSerie: "I",
|
||||
guarantor1PassportNumber: "789456",
|
||||
guarantor1CardNumber: "4666666666666666",
|
||||
guarantor1CardName: "DÖWRAN DÖWRANOW",
|
||||
guarantor1CardExpMonth: "11",
|
||||
guarantor1CardExpYear: "2027",
|
||||
guarantor1Salary: 3500,
|
||||
},
|
||||
{
|
||||
id: 'LOM-0004', loanType: 'Telekeçilik karzy', createdAt: '2025-01-22 08:15',
|
||||
region: 'Lebap', branch: 'Türkmenabat şahamçasy',
|
||||
firstName: 'Aýna', lastName: 'Meredowa', phone: '+99365456789', status: 'RED_EDILDI',
|
||||
id: "LOM-0004",
|
||||
loanType: "Telekeçilik karzy",
|
||||
createdAt: "2025-01-22 08:15",
|
||||
region: "Lebap",
|
||||
branch: "Türkmenabat şahamçasy",
|
||||
firstName: "Aýna",
|
||||
lastName: "Meredowa",
|
||||
phone: "+99365456789",
|
||||
status: "RED_EDILDI",
|
||||
loanAmount: 25000,
|
||||
patronicName: 'Begenjowna', education: 'high', marriageStatus: 'DIVORCED',
|
||||
dateOfBirth: '1991-02-28',
|
||||
residence: 'Türkmenabat, Lebap köçesi, 8',
|
||||
passportSerie: 'I', passportNumber: '321654',
|
||||
passportDateOfIssue: '2017-11-05',
|
||||
passportGivenBy: 'Lebap welaýatynyň Içeri işler müdirligi',
|
||||
workCompany: 'Hususy telekeçi', position: 'Telekeçi',
|
||||
salary: 4000, workStartedAt: '2020-01-10',
|
||||
cardNumber: '4777777777777777', cardName: 'AÝNA MEREDOWA',
|
||||
cardExpMonth: '07', cardExpYear: '2026',
|
||||
patronicName: "Begenjowna",
|
||||
education: "high",
|
||||
marriageStatus: "DIVORCED",
|
||||
dateOfBirth: "1991-02-28",
|
||||
residence: "Türkmenabat, Lebap köçesi, 8",
|
||||
passportSerie: "I",
|
||||
passportNumber: "321654",
|
||||
passportDateOfIssue: "2017-11-05",
|
||||
passportGivenBy: "Lebap welaýatynyň Içeri işler müdirligi",
|
||||
workCompany: "Hususy telekeçi",
|
||||
position: "Telekeçi",
|
||||
salary: 4000,
|
||||
workStartedAt: "2020-01-10",
|
||||
cardNumber: "4777777777777777",
|
||||
cardName: "AÝNA MEREDOWA",
|
||||
cardExpMonth: "07",
|
||||
cardExpYear: "2026",
|
||||
},
|
||||
{
|
||||
id: 'LOM-0005', loanType: 'Sarp ediş karzy', createdAt: '2025-01-25 16:00',
|
||||
region: 'Mary', branch: 'Mary-1 şahamçasy',
|
||||
firstName: 'Begmyrat', lastName: 'Oraz', phone: '+99366567890', status: 'GARAŞYLÝAR',
|
||||
loanAmount: 8000, loanHistory: 'new',
|
||||
patronicName: 'Annageldiwiç', education: 'middle', marriageStatus: 'SINGLE',
|
||||
dateOfBirth: '2000-08-15',
|
||||
residence: 'Mary şäher, Saýat köçesi, 3',
|
||||
passportSerie: 'I', passportNumber: '567890',
|
||||
passportDateOfIssue: '2020-01-20',
|
||||
passportGivenBy: 'Mary welaýatynyň Içeri işler müdirligi',
|
||||
workCompany: 'Mary gurluşyk', position: 'Işçi',
|
||||
salary: 1200, workStartedAt: '2022-06-01',
|
||||
id: "LOM-0005",
|
||||
loanType: "Sarp ediş karzy",
|
||||
createdAt: "2025-01-25 16:00",
|
||||
region: "Mary",
|
||||
branch: "Mary-1 şahamçasy",
|
||||
firstName: "Begmyrat",
|
||||
lastName: "Oraz",
|
||||
phone: "+99366567890",
|
||||
status: "GARAŞYLÝAR",
|
||||
loanAmount: 8000,
|
||||
loanHistory: "new",
|
||||
patronicName: "Annageldiwiç",
|
||||
education: "middle",
|
||||
marriageStatus: "SINGLE",
|
||||
dateOfBirth: "2000-08-15",
|
||||
residence: "Mary şäher, Saýat köçesi, 3",
|
||||
passportSerie: "I",
|
||||
passportNumber: "567890",
|
||||
passportDateOfIssue: "2020-01-20",
|
||||
passportGivenBy: "Mary welaýatynyň Içeri işler müdirligi",
|
||||
workCompany: "Mary gurluşyk",
|
||||
position: "Işçi",
|
||||
salary: 1200,
|
||||
workStartedAt: "2022-06-01",
|
||||
},
|
||||
{
|
||||
id: 'LOM-0006', loanType: 'Bilim karzy', createdAt: '2025-01-28 10:20',
|
||||
region: 'Daşoguz', branch: 'Daşoguz şahamçasy',
|
||||
firstName: 'Gülälek', lastName: 'Saparowa', phone: '+99361678901', status: 'KANAGATLANDYRYLAN',
|
||||
id: "LOM-0006",
|
||||
loanType: "Bilim karzy",
|
||||
createdAt: "2025-01-28 10:20",
|
||||
region: "Daşoguz",
|
||||
branch: "Daşoguz şahamçasy",
|
||||
firstName: "Gülälek",
|
||||
lastName: "Saparowa",
|
||||
phone: "+99361678901",
|
||||
status: "KANAGATLANDYRYLAN",
|
||||
loanAmount: 12000,
|
||||
patronicName: 'Mämmedowna', education: 'phd', marriageStatus: 'MARRIED',
|
||||
dateOfBirth: '1985-12-03',
|
||||
residence: 'Daşoguz, Gurbansoltan eje köçesi, 12',
|
||||
passportSerie: 'II', passportNumber: '901234',
|
||||
passportDateOfIssue: '2014-08-30',
|
||||
passportGivenBy: 'Daşoguz welaýatynyň Içeri işler müdirligi',
|
||||
email: 'gulalek.saparowa@email.com',
|
||||
workCompany: 'Daşoguz uniwersiteti', position: 'Mugallym',
|
||||
salary: 2000, workStartedAt: '2016-09-01',
|
||||
cardNumber: '4888888888888888', cardName: 'GÜLÄLEK SAPAROWA',
|
||||
cardExpMonth: '02', cardExpYear: '2028',
|
||||
guarantor1Name: 'Maksat', guarantor1Surname: 'Saparow',
|
||||
guarantor1PassportSerie: 'I', guarantor1PassportNumber: '112233',
|
||||
guarantor1CardNumber: '4999999999999999', guarantor1CardName: 'MAKSAT SAPAROW',
|
||||
guarantor1CardExpMonth: '10', guarantor1CardExpYear: '2027', guarantor1Salary: 2500,
|
||||
patronicName: "Mämmedowna",
|
||||
education: "phd",
|
||||
marriageStatus: "MARRIED",
|
||||
dateOfBirth: "1985-12-03",
|
||||
residence: "Daşoguz, Gurbansoltan eje köçesi, 12",
|
||||
passportSerie: "II",
|
||||
passportNumber: "901234",
|
||||
passportDateOfIssue: "2014-08-30",
|
||||
passportGivenBy: "Daşoguz welaýatynyň Içeri işler müdirligi",
|
||||
email: "gulalek.saparowa@email.com",
|
||||
workCompany: "Daşoguz uniwersiteti",
|
||||
position: "Mugallym",
|
||||
salary: 2000,
|
||||
workStartedAt: "2016-09-01",
|
||||
cardNumber: "4888888888888888",
|
||||
cardName: "GÜLÄLEK SAPAROWA",
|
||||
cardExpMonth: "02",
|
||||
cardExpYear: "2028",
|
||||
guarantor1Name: "Maksat",
|
||||
guarantor1Surname: "Saparow",
|
||||
guarantor1PassportSerie: "I",
|
||||
guarantor1PassportNumber: "112233",
|
||||
guarantor1CardNumber: "4999999999999999",
|
||||
guarantor1CardName: "MAKSAT SAPAROW",
|
||||
guarantor1CardExpMonth: "10",
|
||||
guarantor1CardExpYear: "2027",
|
||||
guarantor1Salary: 2500,
|
||||
},
|
||||
{
|
||||
id: 'LOM-0007', loanType: 'Awtoulag karzy', createdAt: '2025-02-01 13:45',
|
||||
region: 'Aşgabat', branch: 'Garaşsyzlyk şahamçasy',
|
||||
firstName: 'Myrat', lastName: 'Ataýew', phone: '+99362789012', status: 'IŞLENÝÄR',
|
||||
id: "LOM-0007",
|
||||
loanType: "Awtoulag karzy",
|
||||
createdAt: "2025-02-01 13:45",
|
||||
region: "Aşgabat",
|
||||
branch: "Garaşsyzlyk şahamçasy",
|
||||
firstName: "Myrat",
|
||||
lastName: "Ataýew",
|
||||
phone: "+99362789012",
|
||||
status: "IŞLENÝÄR",
|
||||
loanAmount: 35000,
|
||||
patronicName: 'Batyrowiç', education: 'high', marriageStatus: 'MARRIED',
|
||||
dateOfBirth: '1989-09-22',
|
||||
residence: 'Aşgabat, Çandybil köçesi, 45',
|
||||
passportSerie: 'I', passportNumber: '334455',
|
||||
passportDateOfIssue: '2015-12-12',
|
||||
passportGivenBy: 'Aşgabat şäheriniň Içeri işler müdirligi',
|
||||
workCompany: 'Türkmenhowaýollar', position: 'Sürüji',
|
||||
salary: 2800, workStartedAt: '2017-04-01',
|
||||
cardNumber: '4111111111112222', cardName: 'MYRAT ATAÝEW',
|
||||
cardExpMonth: '08', cardExpYear: '2027',
|
||||
patronicName: "Batyrowiç",
|
||||
education: "high",
|
||||
marriageStatus: "MARRIED",
|
||||
dateOfBirth: "1989-09-22",
|
||||
residence: "Aşgabat, Çandybil köçesi, 45",
|
||||
passportSerie: "I",
|
||||
passportNumber: "334455",
|
||||
passportDateOfIssue: "2015-12-12",
|
||||
passportGivenBy: "Aşgabat şäheriniň Içeri işler müdirligi",
|
||||
workCompany: "Türkmenhowaýollar",
|
||||
position: "Sürüji",
|
||||
salary: 2800,
|
||||
workStartedAt: "2017-04-01",
|
||||
cardNumber: "4111111111112222",
|
||||
cardName: "MYRAT ATAÝEW",
|
||||
cardExpMonth: "08",
|
||||
cardExpYear: "2027",
|
||||
},
|
||||
]
|
||||
];
|
||||
|
||||
let mockStore = [...MOCK_DATA]
|
||||
let nextId = 8
|
||||
let mockStore = [...MOCK_DATA];
|
||||
let nextId = 8;
|
||||
|
||||
const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms))
|
||||
const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
function applyMockFilters(
|
||||
params: LoanOrderMobileListParams,
|
||||
): PaginatedResponse<LoanOrderMobile> {
|
||||
const page = params.page ?? 1
|
||||
const perPage = params.perPage ?? 25
|
||||
function applyMockFilters(params: LoanOrderMobileListParams): PaginatedResponse<LoanOrderMobile> {
|
||||
const page = params.page ?? 1;
|
||||
const perPage = params.perPage ?? 25;
|
||||
|
||||
let result = [...mockStore]
|
||||
let result = [...mockStore];
|
||||
|
||||
if (params.search) {
|
||||
const q = params.search.toLowerCase()
|
||||
const q = params.search.toLowerCase();
|
||||
result = result.filter(
|
||||
(r) =>
|
||||
r.firstName.toLowerCase().includes(q) ||
|
||||
r.lastName.toLowerCase().includes(q) ||
|
||||
r.phone.includes(q) ||
|
||||
r.id.toLowerCase().includes(q),
|
||||
)
|
||||
);
|
||||
}
|
||||
if (params.region) result = result.filter((r) => r.region === params.region)
|
||||
if (params.status) result = result.filter((r) => r.status === params.status)
|
||||
if (params.branch) result = result.filter((r) => r.branch === params.branch)
|
||||
if (params.region) result = result.filter((r) => r.region === params.region);
|
||||
if (params.status) result = result.filter((r) => r.status === params.status);
|
||||
if (params.branch) result = result.filter((r) => r.branch === params.branch);
|
||||
|
||||
const total = result.length
|
||||
const start = (page - 1) * perPage
|
||||
const total = result.length;
|
||||
const start = (page - 1) * perPage;
|
||||
|
||||
return { data: result.slice(start, start + perPage), total }
|
||||
return { data: result.slice(start, start + perPage), total };
|
||||
}
|
||||
|
||||
// ─── API Functions ─────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchLoanOrderMobiles(
|
||||
params: LoanOrderMobileListParams,
|
||||
): Promise<PaginatedResponse<LoanOrderMobile>> {
|
||||
export async function fetchLoanOrderMobiles(params: LoanOrderMobileListParams): Promise<PaginatedResponse<LoanOrderMobile>> {
|
||||
if (true) {
|
||||
await delay(500)
|
||||
return applyMockFilters(params)
|
||||
await delay(500);
|
||||
return applyMockFilters(params);
|
||||
}
|
||||
const { data } = await apiClient.get<PaginatedResponse<LoanOrderMobile>>(
|
||||
'/loan-order-mobiles',
|
||||
{ params },
|
||||
)
|
||||
return data
|
||||
const { data } = await apiClient.get<PaginatedResponse<LoanOrderMobile>>("/loan-order-mobiles", { params });
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function deleteLoanOrderMobile(id: string): Promise<void> {
|
||||
await delay(300)
|
||||
mockStore = mockStore.filter((r) => r.id !== id)
|
||||
await delay(300);
|
||||
mockStore = mockStore.filter((r) => r.id !== id);
|
||||
}
|
||||
|
||||
export async function getLoanOrderMobileById(id: string): Promise<LoanOrderMobile> {
|
||||
await delay(300)
|
||||
const order = mockStore.find((r) => r.id === id)
|
||||
if (!order) throw new Error('Not found')
|
||||
return { ...order }
|
||||
await delay(300);
|
||||
const order = mockStore.find((r) => r.id === id);
|
||||
if (!order) throw new Error("Not found");
|
||||
return { ...order };
|
||||
}
|
||||
|
||||
export async function createLoanOrderMobile(
|
||||
payload: LoanOrderMobilePayload
|
||||
): Promise<LoanOrderMobile> {
|
||||
await delay(500)
|
||||
export async function createLoanOrderMobile(payload: LoanOrderMobilePayload): Promise<LoanOrderMobile> {
|
||||
await delay(500);
|
||||
const newOrder: LoanOrderMobile = {
|
||||
...payload,
|
||||
id: `LOM-${String(nextId++).padStart(4, '0')}`,
|
||||
createdAt: new Date().toISOString().slice(0, 16).replace('T', ' '),
|
||||
id: `LOM-${String(nextId++).padStart(4, "0")}`,
|
||||
createdAt: new Date().toISOString().slice(0, 16).replace("T", " "),
|
||||
status: payload.status as LoanOrderMobileStatus,
|
||||
}
|
||||
mockStore = [newOrder, ...mockStore]
|
||||
return newOrder
|
||||
};
|
||||
mockStore = [newOrder, ...mockStore];
|
||||
return newOrder;
|
||||
}
|
||||
|
||||
export async function updateLoanOrderMobile(
|
||||
id: string,
|
||||
payload: Partial<LoanOrderMobilePayload>
|
||||
): Promise<LoanOrderMobile> {
|
||||
await delay(500)
|
||||
const idx = mockStore.findIndex((r) => r.id === id)
|
||||
if (idx === -1) throw new Error('Not found')
|
||||
const updated = { ...mockStore[idx], ...payload } as LoanOrderMobile
|
||||
mockStore = mockStore.map((r) => (r.id === id ? updated : r))
|
||||
return updated
|
||||
export async function updateLoanOrderMobile(id: string, payload: Partial<LoanOrderMobilePayload>): Promise<LoanOrderMobile> {
|
||||
await delay(500);
|
||||
const idx = mockStore.findIndex((r) => r.id === id);
|
||||
if (idx === -1) throw new Error("Not found");
|
||||
const updated = { ...mockStore[idx], ...payload } as LoanOrderMobile;
|
||||
mockStore = mockStore.map((r) => (r.id === id ? updated : r));
|
||||
return updated;
|
||||
}
|
||||
|
||||
// ─── Branch options by region ─────────────────────────────────────────────────
|
||||
|
||||
export const BRANCHES_BY_REGION_MOBILE: Record<string, { value: string; label: string }[]> = {
|
||||
'Aşgabat': [
|
||||
{ value: 'Merkezi şahamça', label: 'Merkezi şahamça' },
|
||||
{ value: 'Garaşsyzlyk şahamçasy', label: 'Garaşsyzlyk şahamçasy' },
|
||||
{ value: 'Bitarap şahamça', label: 'Bitarap şahamça' },
|
||||
{ value: 'Aşgabat-1 şahamçasy', label: 'Aşgabat-1 şahamçasy' },
|
||||
Aşgabat: [
|
||||
{ value: "Merkezi şahamça", label: "Merkezi şahamça" },
|
||||
{ value: "Garaşsyzlyk şahamçasy", label: "Garaşsyzlyk şahamçasy" },
|
||||
{ value: "Bitarap şahamça", label: "Bitarap şahamça" },
|
||||
{ value: "Aşgabat-1 şahamçasy", label: "Aşgabat-1 şahamçasy" },
|
||||
],
|
||||
'Ahal': [
|
||||
{ value: 'Änew şahamçasy', label: 'Änew şahamçasy' },
|
||||
{ value: 'Gökdepe şahamçasy', label: 'Gökdepe şahamçasy' },
|
||||
{ value: 'Tejen şahamçasy', label: 'Tejen şahamçasy' },
|
||||
Ahal: [
|
||||
{ value: "Änew şahamçasy", label: "Änew şahamçasy" },
|
||||
{ value: "Gökdepe şahamçasy", label: "Gökdepe şahamçasy" },
|
||||
{ value: "Tejen şahamçasy", label: "Tejen şahamçasy" },
|
||||
],
|
||||
'Balkan': [
|
||||
{ value: 'Balkanabat şahamçasy', label: 'Balkanabat şahamçasy' },
|
||||
{ value: 'Türkmenbaşy şahamçasy', label: 'Türkmenbaşy şahamçasy' },
|
||||
{ value: 'Bereket şahamçasy', label: 'Bereket şahamçasy' },
|
||||
Balkan: [
|
||||
{ value: "Balkanabat şahamçasy", label: "Balkanabat şahamçasy" },
|
||||
{ value: "Türkmenbaşy şahamçasy", label: "Türkmenbaşy şahamçasy" },
|
||||
{ value: "Bereket şahamçasy", label: "Bereket şahamçasy" },
|
||||
],
|
||||
'Daşoguz': [
|
||||
{ value: 'Daşoguz şahamçasy', label: 'Daşoguz şahamçasy' },
|
||||
{ value: 'Akdepe şahamçasy', label: 'Akdepe şahamçasy' },
|
||||
{ value: 'Boldumsaz şahamçasy', label: 'Boldumsaz şahamçasy' },
|
||||
Daşoguz: [
|
||||
{ value: "Daşoguz şahamçasy", label: "Daşoguz şahamçasy" },
|
||||
{ value: "Akdepe şahamçasy", label: "Akdepe şahamçasy" },
|
||||
{ value: "Boldumsaz şahamçasy", label: "Boldumsaz şahamçasy" },
|
||||
],
|
||||
'Lebap': [
|
||||
{ value: 'Türkmenabat şahamçasy', label: 'Türkmenabat şahamçasy' },
|
||||
{ value: 'Seýdi şahamçasy', label: 'Seýdi şahamçasy' },
|
||||
{ value: 'Kerki şahamçasy', label: 'Kerki şahamçasy' },
|
||||
Lebap: [
|
||||
{ value: "Türkmenabat şahamçasy", label: "Türkmenabat şahamçasy" },
|
||||
{ value: "Seýdi şahamçasy", label: "Seýdi şahamçasy" },
|
||||
{ value: "Kerki şahamçasy", label: "Kerki şahamçasy" },
|
||||
],
|
||||
'Mary': [
|
||||
{ value: 'Mary-1 şahamçasy', label: 'Mary-1 şahamçasy' },
|
||||
{ value: 'Mary-2 şahamçasy', label: 'Mary-2 şahamçasy' },
|
||||
{ value: 'Baýramaly şahamçasy', label: 'Baýramaly şahamçasy' },
|
||||
Mary: [
|
||||
{ value: "Mary-1 şahamçasy", label: "Mary-1 şahamçasy" },
|
||||
{ value: "Mary-2 şahamçasy", label: "Mary-2 şahamçasy" },
|
||||
{ value: "Baýramaly şahamçasy", label: "Baýramaly şahamçasy" },
|
||||
],
|
||||
'Arkadag': [
|
||||
{ value: 'Arkadag şahamçasy', label: 'Arkadag şahamçasy' },
|
||||
],
|
||||
}
|
||||
Arkadag: [{ value: "Arkadag şahamçasy", label: "Arkadag şahamçasy" }],
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, useCallback, useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
FileText,
|
||||
@@ -19,9 +20,10 @@ import {
|
||||
} from "@/features/loanOrderMobiles/hooks/useLoanOrderMobiles";
|
||||
import type {
|
||||
LoanOrderMobile,
|
||||
LoanOrderMobilePayload,
|
||||
} from "@/features/loanOrderMobiles/api/loanOrderMobilesApi";
|
||||
import { BRANCHES_BY_REGION_MOBILE } from "@/features/loanOrderMobiles/api/loanOrderMobilesApi";
|
||||
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from "@/features/loanOrderMobiles/schemas/loanOrderMobile.schema";
|
||||
import type { LoanOrderMobileFormData } from "@/features/loanOrderMobiles/schemas/loanOrderMobile.schema";
|
||||
|
||||
// ─── Static options ───────────────────────────────────────────────────────────
|
||||
|
||||
@@ -127,129 +129,17 @@ function BentoCard({
|
||||
);
|
||||
}
|
||||
|
||||
// ─── FormState ────────────────────────────────────────────────────────────────
|
||||
// ─── Form errors helper ──────────────────────────────────────────────────────
|
||||
|
||||
interface FormState {
|
||||
status: string;
|
||||
loanType: string;
|
||||
region: string;
|
||||
branch: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
patronicName: string;
|
||||
education: string;
|
||||
marriageStatus: string;
|
||||
dateOfBirth: string;
|
||||
residence: string;
|
||||
currentResidence: string;
|
||||
passportSerie: string;
|
||||
passportNumber: string;
|
||||
passportDateOfIssue: string;
|
||||
passportGivenBy: string;
|
||||
bornPlace: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
phoneAdditional: string;
|
||||
homePhone: string;
|
||||
workCompany: string;
|
||||
workHrPhone: string;
|
||||
workRegion: string;
|
||||
workProvince: string;
|
||||
position: string;
|
||||
salary: string;
|
||||
workStartedAt: string;
|
||||
passportPage1: File | null;
|
||||
passportPage23: File | null;
|
||||
passportPage89: File | null;
|
||||
passportPage32: File | null;
|
||||
note: string;
|
||||
loanAmount: string;
|
||||
loanHistory: string;
|
||||
cardNumber: string;
|
||||
cardName: string;
|
||||
cardExpMonth: string;
|
||||
cardExpYear: string;
|
||||
guarantor1Name: string;
|
||||
guarantor1Surname: string;
|
||||
guarantor1Patronic: string;
|
||||
guarantor1PassportSerie: string;
|
||||
guarantor1PassportNumber: string;
|
||||
guarantor1CardNumber: string;
|
||||
guarantor1CardName: string;
|
||||
guarantor1CardExpMonth: string;
|
||||
guarantor1CardExpYear: string;
|
||||
guarantor1Salary: string;
|
||||
}
|
||||
type FlatErrors = Partial<Record<keyof LoanOrderMobileFormData, string>>
|
||||
|
||||
type FormErrors = Partial<Record<keyof FormState, string>>;
|
||||
|
||||
const INITIAL_STATE: FormState = {
|
||||
status: "GARAŞYLÝAR", loanType: "", region: "Aşgabat", branch: "",
|
||||
firstName: "", lastName: "", patronicName: "", education: "",
|
||||
marriageStatus: "", dateOfBirth: "", residence: "", currentResidence: "",
|
||||
passportSerie: "", passportNumber: "", passportDateOfIssue: "",
|
||||
passportGivenBy: "", bornPlace: "", email: "", phone: "",
|
||||
phoneAdditional: "", homePhone: "", workCompany: "", workHrPhone: "",
|
||||
workRegion: "Aşgabat", workProvince: "", position: "", salary: "",
|
||||
workStartedAt: "", passportPage1: null, passportPage23: null,
|
||||
passportPage89: null, passportPage32: null, note: "", loanAmount: "",
|
||||
loanHistory: "", cardNumber: "", cardName: "", cardExpMonth: "", cardExpYear: "",
|
||||
guarantor1Name: "", guarantor1Surname: "", guarantor1Patronic: "",
|
||||
guarantor1PassportSerie: "", guarantor1PassportNumber: "",
|
||||
guarantor1CardNumber: "", guarantor1CardName: "",
|
||||
guarantor1CardExpMonth: "", guarantor1CardExpYear: "", guarantor1Salary: "",
|
||||
};
|
||||
|
||||
function mapToFormState(order: LoanOrderMobile): FormState {
|
||||
return {
|
||||
status: order.status ?? "GARAŞYLÝAR",
|
||||
loanType: order.loanType ?? "",
|
||||
region: order.region ?? "Aşgabat",
|
||||
branch: order.branch ?? "",
|
||||
firstName: order.firstName ?? "",
|
||||
lastName: order.lastName ?? "",
|
||||
patronicName: order.patronicName ?? "",
|
||||
education: order.education ?? "",
|
||||
marriageStatus: order.marriageStatus ?? "",
|
||||
dateOfBirth: order.dateOfBirth ?? "",
|
||||
residence: order.residence ?? "",
|
||||
currentResidence: order.currentResidence ?? "",
|
||||
passportSerie: order.passportSerie ?? "",
|
||||
passportNumber: order.passportNumber ?? "",
|
||||
passportDateOfIssue: order.passportDateOfIssue ?? "",
|
||||
passportGivenBy: order.passportGivenBy ?? "",
|
||||
bornPlace: order.bornPlace ?? "",
|
||||
email: order.email ?? "",
|
||||
phone: order.phone ?? "",
|
||||
phoneAdditional: order.phoneAdditional ?? "",
|
||||
homePhone: order.homePhone ?? "",
|
||||
workCompany: order.workCompany ?? "",
|
||||
workHrPhone: order.workHrPhone ?? "",
|
||||
workRegion: order.workRegion ?? "Aşgabat",
|
||||
workProvince: order.workProvince ?? "",
|
||||
position: order.position ?? "",
|
||||
salary: order.salary != null ? String(order.salary) : "",
|
||||
workStartedAt: order.workStartedAt ?? "",
|
||||
passportPage1: null, passportPage23: null,
|
||||
passportPage89: null, passportPage32: null,
|
||||
note: order.note ?? "",
|
||||
loanAmount: order.loanAmount != null ? String(order.loanAmount) : "",
|
||||
loanHistory: order.loanHistory ?? "",
|
||||
cardNumber: order.cardNumber ?? "",
|
||||
cardName: order.cardName ?? "",
|
||||
cardExpMonth: order.cardExpMonth ?? "",
|
||||
cardExpYear: order.cardExpYear ?? "",
|
||||
guarantor1Name: order.guarantor1Name ?? "",
|
||||
guarantor1Surname: order.guarantor1Surname ?? "",
|
||||
guarantor1Patronic: order.guarantor1Patronic ?? "",
|
||||
guarantor1PassportSerie: order.guarantor1PassportSerie ?? "",
|
||||
guarantor1PassportNumber: order.guarantor1PassportNumber ?? "",
|
||||
guarantor1CardNumber: order.guarantor1CardNumber ?? "",
|
||||
guarantor1CardName: order.guarantor1CardName ?? "",
|
||||
guarantor1CardExpMonth: order.guarantor1CardExpMonth ?? "",
|
||||
guarantor1CardExpYear: order.guarantor1CardExpYear ?? "",
|
||||
guarantor1Salary: order.guarantor1Salary != null ? String(order.guarantor1Salary) : "",
|
||||
};
|
||||
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 LoanOrderMobileFormData] = msg
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ─── Step definitions ─────────────────────────────────────────────────────────
|
||||
@@ -259,8 +149,7 @@ interface StepDef {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
icon: LucideIcon;
|
||||
fields: Array<keyof FormState>;
|
||||
validate: (form: FormState, mode: "create" | "edit") => FormErrors;
|
||||
validate: (form: LoanOrderMobileFormData, mode: "create" | "edit") => FlatErrors;
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
@@ -269,113 +158,44 @@ const STEPS: StepDef[] = [
|
||||
title: "Karz",
|
||||
subtitle: "Görnüş, möçber & lokasiýa",
|
||||
icon: FileText,
|
||||
fields: ["loanType", "loanAmount", "region", "branch"],
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {};
|
||||
if (!form.loanType) e.loanType = "Karz görnüşi — hökmany";
|
||||
if (!form.loanAmount) e.loanAmount = "Karz möçberi — hökmany";
|
||||
if (!form.region) e.region = "Welaýat — hökmany";
|
||||
if (!form.branch) e.branch = "Şahamça — hökmany";
|
||||
return e;
|
||||
},
|
||||
validate: (form, mode) => validateStep(0, form, mode),
|
||||
},
|
||||
{
|
||||
id: "personal",
|
||||
title: "Şahsy & Pasport",
|
||||
subtitle: "Şahsyýet & pasport",
|
||||
icon: User,
|
||||
fields: [
|
||||
"firstName", "lastName", "education", "marriageStatus",
|
||||
"dateOfBirth", "residence", "passportSerie", "passportNumber",
|
||||
"passportDateOfIssue", "passportGivenBy",
|
||||
],
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {};
|
||||
if (!form.firstName) e.firstName = "Ady — hökmany";
|
||||
if (!form.lastName) e.lastName = "Familiýasy — hökmany";
|
||||
if (!form.education) e.education = "Bilimi — hökmany";
|
||||
if (!form.marriageStatus) e.marriageStatus = "Maşgala ýagdaýy — hökmany";
|
||||
if (!form.dateOfBirth) e.dateOfBirth = "Doglan güni — hökmany";
|
||||
if (!form.residence) e.residence = "Ýazgy edilen salgy — hökmany";
|
||||
if (!form.passportSerie) e.passportSerie = "Pasport seriýasy — hökmany";
|
||||
if (!form.passportNumber) e.passportNumber = "Pasport belgisi — hökmany";
|
||||
if (!form.passportDateOfIssue) e.passportDateOfIssue = "Pasport berlen senesi — hökmany";
|
||||
if (!form.passportGivenBy) e.passportGivenBy = "Kim tarapyndan berildi — hökmany";
|
||||
return e;
|
||||
},
|
||||
validate: (form, mode) => validateStep(1, form, mode),
|
||||
},
|
||||
{
|
||||
id: "contact",
|
||||
title: "Habarlaşmak & Iş",
|
||||
subtitle: "Telefon & iş",
|
||||
icon: Phone,
|
||||
fields: ["phone", "workCompany", "position", "salary", "workStartedAt"],
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {};
|
||||
if (!form.phone) {
|
||||
e.phone = "Telefon — hökmany";
|
||||
} else if (form.phone.replace(/\D/g, "").length < 8) {
|
||||
e.phone = "Telefon belgisi nädogry";
|
||||
}
|
||||
if (!form.workCompany) e.workCompany = "Kärhananyň ady — hökmany";
|
||||
if (!form.position) e.position = "Wezipe — hökmany";
|
||||
if (!form.salary) e.salary = "Zähmet haky — hökmany";
|
||||
if (!form.workStartedAt) e.workStartedAt = "Işe başlan wagty — hökmany";
|
||||
return e;
|
||||
},
|
||||
validate: (form, mode) => validateStep(2, form, mode),
|
||||
},
|
||||
{
|
||||
id: "card",
|
||||
title: "Kart & Zamun",
|
||||
subtitle: "Töleg & zamun",
|
||||
icon: CreditCard,
|
||||
fields: [
|
||||
"cardNumber", "cardName", "cardExpMonth", "cardExpYear",
|
||||
"guarantor1Name", "guarantor1Surname", "guarantor1PassportSerie",
|
||||
"guarantor1PassportNumber", "guarantor1CardNumber", "guarantor1CardName",
|
||||
"guarantor1CardExpMonth", "guarantor1CardExpYear", "guarantor1Salary",
|
||||
],
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {};
|
||||
if (!form.cardNumber) e.cardNumber = "Kart belgisi — hökmany";
|
||||
if (!form.cardName) e.cardName = "Kartdaky ady — hökmany";
|
||||
if (!form.cardExpMonth) e.cardExpMonth = "Kart möhleti (aý) — hökmany";
|
||||
if (!form.cardExpYear) e.cardExpYear = "Kart möhleti (ýyl) — hökmany";
|
||||
if (!form.guarantor1Name) e.guarantor1Name = "Zamunyň ady — hökmany";
|
||||
if (!form.guarantor1Surname) e.guarantor1Surname = "Zamunyň familiýasy — hökmany";
|
||||
if (!form.guarantor1PassportSerie) e.guarantor1PassportSerie = "Pasport seriýasy — hökmany";
|
||||
if (!form.guarantor1PassportNumber) e.guarantor1PassportNumber = "Pasport belgisi — hökmany";
|
||||
if (!form.guarantor1CardNumber) e.guarantor1CardNumber = "Kart belgisi — hökmany";
|
||||
if (!form.guarantor1CardName) e.guarantor1CardName = "Kartdaky ady — hökmany";
|
||||
if (!form.guarantor1CardExpMonth) e.guarantor1CardExpMonth = "Möhleti (aý) — hökmany";
|
||||
if (!form.guarantor1CardExpYear) e.guarantor1CardExpYear = "Möhleti (ýyl) — hökmany";
|
||||
if (!form.guarantor1Salary) e.guarantor1Salary = "Ortaca zähmet haky — hökmany";
|
||||
return e;
|
||||
},
|
||||
validate: (form, mode) => validateStep(3, form, mode),
|
||||
},
|
||||
{
|
||||
id: "files",
|
||||
title: "Faýllar & Status",
|
||||
subtitle: "Resminamalar",
|
||||
icon: Upload,
|
||||
fields: ["passportPage1", "passportPage23"],
|
||||
validate: (form, mode) => {
|
||||
const e: FormErrors = {};
|
||||
if (mode === "create") {
|
||||
if (!form.passportPage1) e.passportPage1 = "Pasport (sahypa 1) hökmany";
|
||||
if (!form.passportPage23) e.passportPage23 = "Pasport (sahypa 2-3) hökmany";
|
||||
}
|
||||
return e;
|
||||
},
|
||||
validate: (form, mode) => validateStep(4, form, mode),
|
||||
},
|
||||
];
|
||||
|
||||
// ─── Shared step content props ────────────────────────────────────────────────
|
||||
|
||||
interface StepContentProps {
|
||||
form: FormState;
|
||||
errors: FormErrors;
|
||||
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void;
|
||||
form: LoanOrderMobileFormData;
|
||||
errors: FlatErrors;
|
||||
set: <K extends keyof LoanOrderMobileFormData>(k: K, v: LoanOrderMobileFormData[K]) => void;
|
||||
}
|
||||
|
||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||
@@ -712,8 +532,13 @@ export function LoanOrderMobileForm({ mode, initialData, loanOrderId }: LoanOrde
|
||||
const updateMutation = useUpdateLoanOrderMobile();
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const [form, setForm] = useState<FormState>(() => initialData ? mapToFormState(initialData) : INITIAL_STATE);
|
||||
const [errors, setErrors] = useState<FormErrors>({});
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors,
|
||||
} = useForm<LoanOrderMobileFormData>({ defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES });
|
||||
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
const [currentStep, setCurrentStep] = useState(0);
|
||||
const [visited, setVisited] = useState<Set<number>>(
|
||||
() => mode === "edit" ? new Set(STEPS.map((_, i) => i)) : new Set<number>(),
|
||||
@@ -727,10 +552,10 @@ export function LoanOrderMobileForm({ mode, initialData, loanOrderId }: LoanOrde
|
||||
return out;
|
||||
}, [form, mode, visited]);
|
||||
|
||||
const set = useCallback(<K extends keyof FormState>(key: K, value: FormState[K]) => {
|
||||
setForm((prev) => ({ ...prev, [key]: value }));
|
||||
setErrors((prev) => ({ ...prev, [key]: undefined }));
|
||||
}, []);
|
||||
const set = useCallback(<K extends keyof LoanOrderMobileFormData>(key: K, value: LoanOrderMobileFormData[K]) => {
|
||||
(setValue as (name: K, val: LoanOrderMobileFormData[K]) => void)(key, value);
|
||||
clearErrors(key);
|
||||
}, [setValue, clearErrors]);
|
||||
|
||||
const stepProps = useMemo(() => ({ form, errors, set }), [form, errors, set]);
|
||||
|
||||
@@ -743,11 +568,9 @@ export function LoanOrderMobileForm({ mode, initialData, loanOrderId }: LoanOrde
|
||||
markVisited(currentStep);
|
||||
const errs = STEPS[currentStep].validate(form, mode);
|
||||
if (Object.keys(errs).length > 0) {
|
||||
setErrors(errs);
|
||||
toast.error("Dogry maglumat girizmegiňizi haýyş edýäris.");
|
||||
return;
|
||||
}
|
||||
setErrors({});
|
||||
if (currentStep < STEPS.length - 1) {
|
||||
setCurrentStep(currentStep + 1);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
@@ -757,7 +580,6 @@ export function LoanOrderMobileForm({ mode, initialData, loanOrderId }: LoanOrde
|
||||
const handleBack = () => {
|
||||
if (currentStep > 0) {
|
||||
markVisited(currentStep);
|
||||
setErrors({});
|
||||
setCurrentStep(currentStep - 1);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
}
|
||||
@@ -765,21 +587,19 @@ export function LoanOrderMobileForm({ mode, initialData, loanOrderId }: LoanOrde
|
||||
|
||||
const handleGoTo = (i: number) => {
|
||||
markVisited(currentStep);
|
||||
setErrors({});
|
||||
setCurrentStep(i);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
};
|
||||
|
||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = () => {
|
||||
const doSubmit = () => {
|
||||
setVisited(new Set(STEPS.map((_, i) => i)));
|
||||
|
||||
const allErrors: FormErrors = {};
|
||||
const allErrors: FlatErrors = {};
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode));
|
||||
|
||||
if (Object.keys(allErrors).length > 0) {
|
||||
setErrors(allErrors);
|
||||
toast.error("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) {
|
||||
@@ -790,53 +610,7 @@ export function LoanOrderMobileForm({ mode, initialData, loanOrderId }: LoanOrde
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: LoanOrderMobilePayload = {
|
||||
status: form.status,
|
||||
loanType: form.loanType,
|
||||
region: form.region,
|
||||
branch: form.branch,
|
||||
firstName: form.firstName,
|
||||
lastName: form.lastName,
|
||||
patronicName: form.patronicName || undefined,
|
||||
education: form.education,
|
||||
marriageStatus: form.marriageStatus,
|
||||
dateOfBirth: form.dateOfBirth,
|
||||
residence: form.residence,
|
||||
currentResidence: form.currentResidence || undefined,
|
||||
passportSerie: form.passportSerie,
|
||||
passportNumber: form.passportNumber,
|
||||
passportDateOfIssue: form.passportDateOfIssue,
|
||||
passportGivenBy: form.passportGivenBy,
|
||||
bornPlace: form.bornPlace || undefined,
|
||||
email: form.email || undefined,
|
||||
phone: form.phone,
|
||||
phoneAdditional: form.phoneAdditional || undefined,
|
||||
homePhone: form.homePhone || undefined,
|
||||
workCompany: form.workCompany,
|
||||
workHrPhone: form.workHrPhone || undefined,
|
||||
workRegion: form.workRegion || undefined,
|
||||
workProvince: form.workProvince || undefined,
|
||||
position: form.position,
|
||||
salary: Number(form.salary),
|
||||
workStartedAt: form.workStartedAt,
|
||||
note: form.note || undefined,
|
||||
loanAmount: Number(form.loanAmount) || undefined,
|
||||
loanHistory: form.loanHistory || undefined,
|
||||
cardNumber: form.cardNumber || undefined,
|
||||
cardName: form.cardName || undefined,
|
||||
cardExpMonth: form.cardExpMonth || undefined,
|
||||
cardExpYear: form.cardExpYear || undefined,
|
||||
guarantor1Name: form.guarantor1Name || undefined,
|
||||
guarantor1Surname: form.guarantor1Surname || undefined,
|
||||
guarantor1Patronic: form.guarantor1Patronic || undefined,
|
||||
guarantor1PassportSerie: form.guarantor1PassportSerie || undefined,
|
||||
guarantor1PassportNumber: form.guarantor1PassportNumber || undefined,
|
||||
guarantor1CardNumber: form.guarantor1CardNumber || undefined,
|
||||
guarantor1CardName: form.guarantor1CardName || undefined,
|
||||
guarantor1CardExpMonth: form.guarantor1CardExpMonth || undefined,
|
||||
guarantor1CardExpYear: form.guarantor1CardExpYear || undefined,
|
||||
guarantor1Salary: Number(form.guarantor1Salary) || undefined,
|
||||
};
|
||||
const payload = buildPayload(getValues());
|
||||
|
||||
if (mode === "create") {
|
||||
createMutation.mutate(payload, { onSuccess: () => navigate("/loan-order-mobiles") });
|
||||
@@ -900,7 +674,7 @@ export function LoanOrderMobileForm({ mode, initialData, loanOrderId }: LoanOrde
|
||||
onPrev={currentStep > 0 ? handleBack : undefined}
|
||||
onNext={!isLastStep ? handleNext : undefined}
|
||||
showSubmit={isLastStep}
|
||||
onSubmit={isLastStep ? handleSubmit : undefined}
|
||||
onSubmit={isLastStep ? doSubmit : undefined}
|
||||
submitLabel={
|
||||
mode === "create"
|
||||
? (t("loanOrderMobiles.createButton") || "Karz sargyt döredüň")
|
||||
@@ -913,4 +687,54 @@ export function LoanOrderMobileForm({ mode, initialData, loanOrderId }: LoanOrde
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function mapInitial(order: LoanOrderMobile): Partial<LoanOrderMobileFormData> {
|
||||
return {
|
||||
status: order.status ?? "GARAŞYLÝAR",
|
||||
loanType: order.loanType ?? "",
|
||||
region: order.region ?? "Aşgabat",
|
||||
branch: order.branch ?? "",
|
||||
firstName: order.firstName ?? "",
|
||||
lastName: order.lastName ?? "",
|
||||
patronicName: order.patronicName ?? "",
|
||||
education: order.education ?? "",
|
||||
marriageStatus: order.marriageStatus ?? "",
|
||||
dateOfBirth: order.dateOfBirth ?? "",
|
||||
residence: order.residence ?? "",
|
||||
currentResidence: order.currentResidence ?? "",
|
||||
passportSerie: order.passportSerie ?? "",
|
||||
passportNumber: order.passportNumber ?? "",
|
||||
passportDateOfIssue: order.passportDateOfIssue ?? "",
|
||||
passportGivenBy: order.passportGivenBy ?? "",
|
||||
bornPlace: order.bornPlace ?? "",
|
||||
email: order.email ?? "",
|
||||
phone: order.phone ?? "",
|
||||
phoneAdditional: order.phoneAdditional ?? "",
|
||||
homePhone: order.homePhone ?? "",
|
||||
workCompany: order.workCompany ?? "",
|
||||
workHrPhone: order.workHrPhone ?? "",
|
||||
workRegion: order.workRegion ?? "Aşgabat",
|
||||
workProvince: order.workProvince ?? "",
|
||||
position: order.position ?? "",
|
||||
salary: order.salary != null ? String(order.salary) : "",
|
||||
workStartedAt: order.workStartedAt ?? "",
|
||||
note: order.note ?? "",
|
||||
loanAmount: order.loanAmount != null ? String(order.loanAmount) : "",
|
||||
loanHistory: order.loanHistory ?? "",
|
||||
cardNumber: order.cardNumber ?? "",
|
||||
cardName: order.cardName ?? "",
|
||||
cardExpMonth: order.cardExpMonth ?? "",
|
||||
cardExpYear: order.cardExpYear ?? "",
|
||||
guarantor1Name: order.guarantor1Name ?? "",
|
||||
guarantor1Surname: order.guarantor1Surname ?? "",
|
||||
guarantor1Patronic: order.guarantor1Patronic ?? "",
|
||||
guarantor1PassportSerie: order.guarantor1PassportSerie ?? "",
|
||||
guarantor1PassportNumber: order.guarantor1PassportNumber ?? "",
|
||||
guarantor1CardNumber: order.guarantor1CardNumber ?? "",
|
||||
guarantor1CardName: order.guarantor1CardName ?? "",
|
||||
guarantor1CardExpMonth: order.guarantor1CardExpMonth ?? "",
|
||||
guarantor1CardExpYear: order.guarantor1CardExpYear ?? "",
|
||||
guarantor1Salary: order.guarantor1Salary != null ? String(order.guarantor1Salary) : "",
|
||||
};
|
||||
}
|
||||
164
src/features/loanOrderMobiles/schemas/loanOrderMobile.schema.ts
Normal file
164
src/features/loanOrderMobiles/schemas/loanOrderMobile.schema.ts
Normal file
@@ -0,0 +1,164 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
const fileRequired = z.custom<File>((val) => val instanceof File, 'Faýl hökmany')
|
||||
|
||||
export const loanOrderMobileFormSchema = z.object({
|
||||
status: z.string().min(1, 'Status — hökmany'),
|
||||
loanType: z.string().min(1, 'Karz görnüşi — hökmany'),
|
||||
region: z.string().min(1, 'Welaýat — hökmany'),
|
||||
branch: z.string().min(1, 'Şahamça — hökmany'),
|
||||
firstName: z.string().min(1, 'Ady — hökmany'),
|
||||
lastName: z.string().min(1, 'Familiýasy — hökmany'),
|
||||
patronicName: z.string().optional(),
|
||||
education: z.string().min(1, 'Bilimi — hökmany'),
|
||||
marriageStatus: z.string().min(1, 'Maşgala ýagdaýy — hökmany'),
|
||||
dateOfBirth: z.string().min(1, 'Doglan güni — hökmany'),
|
||||
residence: z.string().min(1, 'Ýazgy edilen salgy — hökmany'),
|
||||
currentResidence: z.string().optional(),
|
||||
passportSerie: z.string().min(1, 'Pasport seriýasy — hökmany'),
|
||||
passportNumber: z.string().min(1, 'Pasport belgisi — hökmany'),
|
||||
passportDateOfIssue: z.string().min(1, 'Pasport berlen senesi — hökmany'),
|
||||
passportGivenBy: z.string().min(1, 'Kim tarapyndan berildi — hökmany'),
|
||||
bornPlace: z.string().optional(),
|
||||
email: z.string().optional(),
|
||||
phone: z.string()
|
||||
.min(1, 'Telefon — hökmany')
|
||||
.refine((val) => val.replace(/\D/g, '').length >= 8, { message: 'Telefon belgisi nädogry' }),
|
||||
phoneAdditional: z.string().optional(),
|
||||
homePhone: z.string().optional(),
|
||||
workCompany: z.string().min(1, 'Kärhananyň ady — hökmany'),
|
||||
workHrPhone: z.string().optional(),
|
||||
workRegion: z.string().optional(),
|
||||
workProvince: z.string().optional(),
|
||||
position: z.string().min(1, 'Wezipe — hökmany'),
|
||||
salary: z.string().min(1, 'Zähmet haky — hökmany'),
|
||||
workStartedAt: z.string().min(1, 'Işe başlan wagty — hökmany'),
|
||||
passportPage1: z.custom<File | null>().nullable(),
|
||||
passportPage23: z.custom<File | null>().nullable(),
|
||||
passportPage89: z.custom<File | null>().nullable(),
|
||||
passportPage32: z.custom<File | null>().nullable(),
|
||||
note: z.string().optional(),
|
||||
loanAmount: z.string().min(1, 'Karz möçberi — hökmany'),
|
||||
loanHistory: z.string().optional(),
|
||||
cardNumber: z.string().min(1, 'Kart belgisi — hökmany'),
|
||||
cardName: z.string().min(1, 'Kartdaky ady — hökmany'),
|
||||
cardExpMonth: z.string().min(1, 'Kart möhleti (aý) — hökmany'),
|
||||
cardExpYear: z.string().min(1, 'Kart möhleti (ýyl) — hökmany'),
|
||||
guarantor1Name: z.string().min(1, 'Zamunyň ady — hökmany'),
|
||||
guarantor1Surname: z.string().min(1, 'Zamunyň familiýasy — hökmany'),
|
||||
guarantor1Patronic: z.string().optional(),
|
||||
guarantor1PassportSerie: z.string().min(1, 'Pasport seriýasy — hökmany'),
|
||||
guarantor1PassportNumber: z.string().min(1, 'Pasport belgisi — hökmany'),
|
||||
guarantor1CardNumber: z.string().min(1, 'Kart belgisi — hökmany'),
|
||||
guarantor1CardName: z.string().min(1, 'Kartdaky ady — hökmany'),
|
||||
guarantor1CardExpMonth: z.string().min(1, 'Möhleti (aý) — hökmany'),
|
||||
guarantor1CardExpYear: z.string().min(1, 'Möhleti (ýyl) — hökmany'),
|
||||
guarantor1Salary: z.string().min(1, 'Ortaca zähmet haky — hökmany'),
|
||||
})
|
||||
|
||||
export type LoanOrderMobileFormData = z.infer<typeof loanOrderMobileFormSchema>
|
||||
|
||||
export const stepSchemas: Record<number, z.ZodType<Partial<LoanOrderMobileFormData>>> = {
|
||||
0: loanOrderMobileFormSchema.pick({ loanType: true, loanAmount: true, region: true, branch: true }),
|
||||
1: loanOrderMobileFormSchema.pick({
|
||||
firstName: true, lastName: true, education: true,
|
||||
marriageStatus: true, dateOfBirth: true, residence: true,
|
||||
passportSerie: true, passportNumber: true,
|
||||
passportDateOfIssue: true, passportGivenBy: true,
|
||||
}),
|
||||
2: loanOrderMobileFormSchema.pick({
|
||||
phone: true, workCompany: true, position: true, salary: true, workStartedAt: true,
|
||||
}),
|
||||
3: loanOrderMobileFormSchema.pick({
|
||||
cardNumber: true, cardName: true, cardExpMonth: true, cardExpYear: true,
|
||||
guarantor1Name: true, guarantor1Surname: true,
|
||||
guarantor1PassportSerie: true, guarantor1PassportNumber: true,
|
||||
guarantor1CardNumber: true, guarantor1CardName: true,
|
||||
guarantor1CardExpMonth: true, guarantor1CardExpYear: true,
|
||||
guarantor1Salary: true,
|
||||
}),
|
||||
4: z.object({
|
||||
passportPage1: fileRequired,
|
||||
passportPage23: fileRequired,
|
||||
}),
|
||||
}
|
||||
|
||||
export function validateStep(stepIndex: number, form: LoanOrderMobileFormData, mode: 'create' | 'edit'): Partial<Record<keyof LoanOrderMobileFormData, string>> {
|
||||
if (stepIndex === 4 && mode === 'edit') return {}
|
||||
const schema = stepSchemas[stepIndex]
|
||||
const result = schema.safeParse(form)
|
||||
if (result.success) return {}
|
||||
const errors: Partial<Record<keyof LoanOrderMobileFormData, string>> = {}
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof LoanOrderMobileFormData
|
||||
if (!errors[key]) errors[key] = issue.message
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
export const DEFAULT_FORM_VALUES: LoanOrderMobileFormData = {
|
||||
status: 'GARAŞYLÝAR', loanType: '', region: 'Aşgabat', branch: '',
|
||||
firstName: '', lastName: '', patronicName: '', education: '',
|
||||
marriageStatus: '', dateOfBirth: '', residence: '', currentResidence: '',
|
||||
passportSerie: '', passportNumber: '', passportDateOfIssue: '',
|
||||
passportGivenBy: '', bornPlace: '', email: '', phone: '',
|
||||
phoneAdditional: '', homePhone: '', workCompany: '', workHrPhone: '',
|
||||
workRegion: 'Aşgabat', workProvince: '', position: '', salary: '',
|
||||
workStartedAt: '', passportPage1: null, passportPage23: null,
|
||||
passportPage89: null, passportPage32: null, note: '', loanAmount: '',
|
||||
loanHistory: '', cardNumber: '', cardName: '', cardExpMonth: '', cardExpYear: '',
|
||||
guarantor1Name: '', guarantor1Surname: '', guarantor1Patronic: '',
|
||||
guarantor1PassportSerie: '', guarantor1PassportNumber: '',
|
||||
guarantor1CardNumber: '', guarantor1CardName: '',
|
||||
guarantor1CardExpMonth: '', guarantor1CardExpYear: '', guarantor1Salary: '',
|
||||
}
|
||||
|
||||
export function buildPayload(data: LoanOrderMobileFormData) {
|
||||
return {
|
||||
status: data.status,
|
||||
loanType: data.loanType,
|
||||
region: data.region,
|
||||
branch: data.branch,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
patronicName: data.patronicName || undefined,
|
||||
education: data.education,
|
||||
marriageStatus: data.marriageStatus,
|
||||
dateOfBirth: data.dateOfBirth,
|
||||
residence: data.residence,
|
||||
currentResidence: data.currentResidence || undefined,
|
||||
passportSerie: data.passportSerie,
|
||||
passportNumber: data.passportNumber,
|
||||
passportDateOfIssue: data.passportDateOfIssue,
|
||||
passportGivenBy: data.passportGivenBy,
|
||||
bornPlace: data.bornPlace || undefined,
|
||||
email: data.email || undefined,
|
||||
phone: data.phone,
|
||||
phoneAdditional: data.phoneAdditional || undefined,
|
||||
homePhone: data.homePhone || undefined,
|
||||
workCompany: data.workCompany,
|
||||
workHrPhone: data.workHrPhone || undefined,
|
||||
workRegion: data.workRegion || undefined,
|
||||
workProvince: data.workProvince || undefined,
|
||||
position: data.position,
|
||||
salary: Number(data.salary),
|
||||
workStartedAt: data.workStartedAt,
|
||||
note: data.note || undefined,
|
||||
loanAmount: Number(data.loanAmount) || undefined,
|
||||
loanHistory: data.loanHistory || undefined,
|
||||
cardNumber: data.cardNumber || undefined,
|
||||
cardName: data.cardName || undefined,
|
||||
cardExpMonth: data.cardExpMonth || undefined,
|
||||
cardExpYear: data.cardExpYear || undefined,
|
||||
guarantor1Name: data.guarantor1Name || undefined,
|
||||
guarantor1Surname: data.guarantor1Surname || undefined,
|
||||
guarantor1Patronic: data.guarantor1Patronic || undefined,
|
||||
guarantor1PassportSerie: data.guarantor1PassportSerie || undefined,
|
||||
guarantor1PassportNumber: data.guarantor1PassportNumber || undefined,
|
||||
guarantor1CardNumber: data.guarantor1CardNumber || undefined,
|
||||
guarantor1CardName: data.guarantor1CardName || undefined,
|
||||
guarantor1CardExpMonth: data.guarantor1CardExpMonth || undefined,
|
||||
guarantor1CardExpYear: data.guarantor1CardExpYear || undefined,
|
||||
guarantor1Salary: Number(data.guarantor1Salary) || undefined,
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, useCallback, useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import {
|
||||
CircleDot, CreditCard, MapPin, User, Wallet,
|
||||
@@ -12,8 +13,10 @@ import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
|
||||
import { useCreateLoanOrder, useUpdateLoanOrder } from '@/features/loanOrders/hooks/useLoanOrders'
|
||||
import type { LoanOrder, LoanOrderPayload } from '@/features/loanOrders/api/loanOrdersApi'
|
||||
import type { LoanOrder } from '@/features/loanOrders/api/loanOrdersApi'
|
||||
import { BRANCHES_BY_REGION } from '@/features/loanOrders/api/loanOrdersApi'
|
||||
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from '@/features/loanOrders/schemas/loanOrder.schema'
|
||||
import type { LoanOrderFormData } from '@/features/loanOrders/schemas/loanOrder.schema'
|
||||
|
||||
// ─── Static options ───────────────────────────────────────────────────────────
|
||||
|
||||
@@ -75,129 +78,17 @@ const YEAR_OPTIONS = Array.from({ length: 15 }, (_, i) => ({
|
||||
label: String(new Date().getFullYear() + i),
|
||||
}))
|
||||
|
||||
// ─── FormState ────────────────────────────────────────────────────────────────
|
||||
// ─── Form errors helper ──────────────────────────────────────────────────────
|
||||
|
||||
interface FormState {
|
||||
status: string
|
||||
loanType: string
|
||||
region: string
|
||||
branch: string
|
||||
firstName: string
|
||||
lastName: string
|
||||
patronicName: string
|
||||
education: string
|
||||
marriageStatus: string
|
||||
dateOfBirth: string
|
||||
residence: string
|
||||
currentResidence: string
|
||||
passportSerie: string
|
||||
passportNumber: string
|
||||
passportDateOfIssue: string
|
||||
passportGivenBy: string
|
||||
bornPlace: string
|
||||
email: string
|
||||
phone: string
|
||||
phoneAdditional: string
|
||||
homePhone: string
|
||||
workCompany: string
|
||||
workHrPhone: string
|
||||
workRegion: string
|
||||
workProvince: string
|
||||
position: string
|
||||
salary: string
|
||||
workStartedAt: string
|
||||
passportPage1: File | null
|
||||
passportPage23: File | null
|
||||
passportPage89: File | null
|
||||
passportPage32: File | null
|
||||
note: string
|
||||
loanAmount: string
|
||||
loanHistory: string
|
||||
cardNumber: string
|
||||
cardName: string
|
||||
cardExpMonth: string
|
||||
cardExpYear: string
|
||||
guarantor1Name: string
|
||||
guarantor1Surname: string
|
||||
guarantor1Patronic: string
|
||||
guarantor1PassportSerie: string
|
||||
guarantor1PassportNumber: string
|
||||
guarantor1CardNumber: string
|
||||
guarantor1CardName: string
|
||||
guarantor1CardExpMonth: string
|
||||
guarantor1CardExpYear: string
|
||||
guarantor1Salary: string
|
||||
}
|
||||
type FlatErrors = Partial<Record<keyof LoanOrderFormData, string>>
|
||||
|
||||
type FormErrors = Partial<Record<keyof FormState, string>>
|
||||
|
||||
const INITIAL_STATE: FormState = {
|
||||
status: 'GARAŞYLÝAR', loanType: '', region: 'Aşgabat', branch: '',
|
||||
firstName: '', lastName: '', patronicName: '', education: '',
|
||||
marriageStatus: '', dateOfBirth: '', residence: '', currentResidence: '',
|
||||
passportSerie: '', passportNumber: '', passportDateOfIssue: '',
|
||||
passportGivenBy: '', bornPlace: '', email: '', phone: '',
|
||||
phoneAdditional: '', homePhone: '', workCompany: '', workHrPhone: '',
|
||||
workRegion: 'Aşgabat', workProvince: '', position: '', salary: '',
|
||||
workStartedAt: '', passportPage1: null, passportPage23: null,
|
||||
passportPage89: null, passportPage32: null, note: '', loanAmount: '',
|
||||
loanHistory: '', cardNumber: '', cardName: '', cardExpMonth: '', cardExpYear: '',
|
||||
guarantor1Name: '', guarantor1Surname: '', guarantor1Patronic: '',
|
||||
guarantor1PassportSerie: '', guarantor1PassportNumber: '',
|
||||
guarantor1CardNumber: '', guarantor1CardName: '',
|
||||
guarantor1CardExpMonth: '', guarantor1CardExpYear: '', guarantor1Salary: '',
|
||||
}
|
||||
|
||||
function mapToFormState(order: LoanOrder): FormState {
|
||||
return {
|
||||
status: order.status ?? 'GARAŞYLÝAR',
|
||||
loanType: order.loanType ?? '',
|
||||
region: order.region ?? 'Aşgabat',
|
||||
branch: order.branch ?? '',
|
||||
firstName: order.firstName ?? '',
|
||||
lastName: order.lastName ?? '',
|
||||
patronicName: order.patronicName ?? '',
|
||||
education: order.education ?? '',
|
||||
marriageStatus: order.marriageStatus ?? '',
|
||||
dateOfBirth: order.dateOfBirth ?? '',
|
||||
residence: order.residence ?? '',
|
||||
currentResidence: order.currentResidence ?? '',
|
||||
passportSerie: order.passportSerie ?? '',
|
||||
passportNumber: order.passportNumber ?? '',
|
||||
passportDateOfIssue: order.passportDateOfIssue ?? '',
|
||||
passportGivenBy: order.passportGivenBy ?? '',
|
||||
bornPlace: order.bornPlace ?? '',
|
||||
email: order.email ?? '',
|
||||
phone: order.phone ?? '',
|
||||
phoneAdditional: order.phoneAdditional ?? '',
|
||||
homePhone: order.homePhone ?? '',
|
||||
workCompany: order.workCompany ?? '',
|
||||
workHrPhone: order.workHrPhone ?? '',
|
||||
workRegion: order.workRegion ?? 'Aşgabat',
|
||||
workProvince: order.workProvince ?? '',
|
||||
position: order.position ?? '',
|
||||
salary: order.salary != null ? String(order.salary) : '',
|
||||
workStartedAt: order.workStartedAt ?? '',
|
||||
passportPage1: null, passportPage23: null,
|
||||
passportPage89: null, passportPage32: null,
|
||||
note: order.note ?? '',
|
||||
loanAmount: order.loanAmount != null ? String(order.loanAmount) : '',
|
||||
loanHistory: order.loanHistory ?? '',
|
||||
cardNumber: order.cardNumber ?? '',
|
||||
cardName: order.cardName ?? '',
|
||||
cardExpMonth: order.cardExpMonth ?? '',
|
||||
cardExpYear: order.cardExpYear ?? '',
|
||||
guarantor1Name: order.guarantor1Name ?? '',
|
||||
guarantor1Surname: order.guarantor1Surname ?? '',
|
||||
guarantor1Patronic: order.guarantor1Patronic ?? '',
|
||||
guarantor1PassportSerie: order.guarantor1PassportSerie ?? '',
|
||||
guarantor1PassportNumber: order.guarantor1PassportNumber ?? '',
|
||||
guarantor1CardNumber: order.guarantor1CardNumber ?? '',
|
||||
guarantor1CardName: order.guarantor1CardName ?? '',
|
||||
guarantor1CardExpMonth: order.guarantor1CardExpMonth ?? '',
|
||||
guarantor1CardExpYear: order.guarantor1CardExpYear ?? '',
|
||||
guarantor1Salary: order.guarantor1Salary != null ? String(order.guarantor1Salary) : '',
|
||||
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 LoanOrderFormData] = msg
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ─── Step definitions ─────────────────────────────────────────────────────────
|
||||
@@ -208,126 +99,59 @@ interface StepDef {
|
||||
titleFallback: string
|
||||
subtitle: string
|
||||
icon: LucideIcon
|
||||
validate: (form: FormState, mode: 'create' | 'edit') => FormErrors
|
||||
validate: (form: LoanOrderFormData, mode: 'create' | 'edit') => FlatErrors
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
{
|
||||
id: 'status', titleKey: 'Status', titleFallback: 'Status',
|
||||
subtitle: 'Ýagdaý we bellik', icon: CircleDot,
|
||||
validate: () => ({}),
|
||||
validate: (form, mode) => validateStep(0, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'loan', titleKey: 'Loan', titleFallback: 'Karz',
|
||||
subtitle: 'Görnüş we möçber', icon: Wallet,
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.loanType) e.loanType = 'Karz görnüşi — hökmany'
|
||||
if (!form.loanAmount) e.loanAmount = 'Karz möçberi — hökmany'
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(1, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'location', titleKey: 'Location', titleFallback: 'Lokasiýa',
|
||||
subtitle: 'Welaýat we şahamça', icon: MapPin,
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.region) e.region = 'Welaýat — hökmany'
|
||||
if (!form.branch) e.branch = 'Şahamça — hökmany'
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(2, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'personal', titleKey: 'Personal data', titleFallback: 'Şahsy maglumatlar',
|
||||
subtitle: 'At, bilim, maşgala', icon: User,
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.firstName) e.firstName = 'Ady — hökmany'
|
||||
if (!form.lastName) e.lastName = 'Familiýasy — hökmany'
|
||||
if (!form.education) e.education = 'Bilimi — hökmany'
|
||||
if (!form.marriageStatus) e.marriageStatus = 'Maşgala ýagdaýy — hökmany'
|
||||
if (!form.dateOfBirth) e.dateOfBirth = 'Doglan güni — hökmany'
|
||||
if (!form.residence) e.residence = 'Ýazgy edilen salgy — hökmany'
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(3, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'card', titleKey: 'Card (Salary)', titleFallback: 'Kart (Zähmet haky)',
|
||||
subtitle: 'Zähmet haky karty', icon: CreditCard,
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.cardNumber) e.cardNumber = 'Kart belgisi — hökmany'
|
||||
if (!form.cardName) e.cardName = 'Kartdaky ady — hökmany'
|
||||
if (!form.cardExpMonth) e.cardExpMonth = 'Kart möhleti (aý) — hökmany'
|
||||
if (!form.cardExpYear) e.cardExpYear = 'Kart möhleti (ýyl) — hökmany'
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(4, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'passport', titleKey: 'Passport', titleFallback: 'Pasport',
|
||||
subtitle: 'Seriýa, belgisi, senesi', icon: FileText,
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.passportSerie) e.passportSerie = 'Pasport seriýasy — hökmany'
|
||||
if (!form.passportNumber) e.passportNumber = 'Pasport belgisi — hökmany'
|
||||
if (!form.passportDateOfIssue) e.passportDateOfIssue = 'Pasport berlen senesi — hökmany'
|
||||
if (!form.passportGivenBy) e.passportGivenBy = 'Kim tarapyndan berildi — hökmany'
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(5, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'contact', titleKey: 'Contact data', titleFallback: 'Habarlaşmak',
|
||||
subtitle: 'Telefon we e-poçta', icon: Phone,
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.phone) {
|
||||
e.phone = 'Telefon — hökmany'
|
||||
} else if (form.phone.replace(/\D/g, '').length < 8) {
|
||||
e.phone = 'Telefon belgisi nädogry'
|
||||
}
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(6, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'job', titleKey: 'Job', titleFallback: 'Iş',
|
||||
subtitle: 'Kärhana we wezipe', icon: Briefcase,
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.workCompany) e.workCompany = 'Kärhananyň ady — hökmany'
|
||||
if (!form.position) e.position = 'Wezipe — hökmany'
|
||||
if (!form.salary) e.salary = 'Zähmet haky — hökmany'
|
||||
if (!form.workStartedAt) e.workStartedAt = 'Işe başlan wagty — hökmany'
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(7, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'files', titleKey: 'Passport files', titleFallback: 'Pasport faýllar',
|
||||
subtitle: 'Pasport suratlary', icon: FolderOpen,
|
||||
validate: (form, mode) => {
|
||||
const e: FormErrors = {}
|
||||
if (mode === 'create') {
|
||||
if (!form.passportPage1) e.passportPage1 = 'Pasport (sahypa 1) hökmany'
|
||||
if (!form.passportPage23) e.passportPage23 = 'Pasport (sahypa 2-3) hökmany'
|
||||
}
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(8, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'guarantor', titleKey: '1. Guarantor', titleFallback: '1. Zamun',
|
||||
subtitle: 'Zamun maglumatlary', icon: ShieldCheck,
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.guarantor1Name) e.guarantor1Name = 'Zamunyň ady — hökmany'
|
||||
if (!form.guarantor1Surname) e.guarantor1Surname = 'Zamunyň familiýasy — hökmany'
|
||||
if (!form.guarantor1PassportSerie) e.guarantor1PassportSerie = 'Pasport seriýasy — hökmany'
|
||||
if (!form.guarantor1PassportNumber) e.guarantor1PassportNumber = 'Pasport belgisi — hökmany'
|
||||
if (!form.guarantor1CardNumber) e.guarantor1CardNumber = 'Kart belgisi — hökmany'
|
||||
if (!form.guarantor1CardName) e.guarantor1CardName = 'Kartdaky ady — hökmany'
|
||||
if (!form.guarantor1CardExpMonth) e.guarantor1CardExpMonth = 'Möhleti (aý) — hökmany'
|
||||
if (!form.guarantor1CardExpYear) e.guarantor1CardExpYear = 'Möhleti (ýyl) — hökmany'
|
||||
if (!form.guarantor1Salary) e.guarantor1Salary = 'Ortaca zähmet haky — hökmany'
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(9, form, mode),
|
||||
},
|
||||
]
|
||||
|
||||
@@ -378,9 +202,9 @@ function BentoCard({
|
||||
// ─── Shared step content props ────────────────────────────────────────────────
|
||||
|
||||
interface StepContentProps {
|
||||
form: FormState
|
||||
errors: FormErrors
|
||||
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
|
||||
form: LoanOrderFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof LoanOrderFormData>(k: K, v: LoanOrderFormData[K]) => void
|
||||
}
|
||||
|
||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||
@@ -750,8 +574,13 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP
|
||||
const updateMutation = useUpdateLoanOrder()
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const [form, setForm] = useState<FormState>(() => initialData ? mapToFormState(initialData) : INITIAL_STATE)
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors,
|
||||
} = useForm<LoanOrderFormData>({ defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES })
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
|
||||
const [currentStep, setCurrentStep] = useState(0)
|
||||
const [visited, setVisited] = useState<Set<number>>(
|
||||
() => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set<number>(),
|
||||
@@ -765,10 +594,10 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP
|
||||
return out
|
||||
}, [form, mode, visited])
|
||||
|
||||
const set = useCallback(<K extends keyof FormState>(key: K, value: FormState[K]) => {
|
||||
setForm((prev) => ({ ...prev, [key]: value }))
|
||||
setErrors((prev) => ({ ...prev, [key]: undefined }))
|
||||
}, [])
|
||||
const set = useCallback(<K extends keyof LoanOrderFormData>(key: K, value: LoanOrderFormData[K]) => {
|
||||
(setValue as (name: K, val: LoanOrderFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
|
||||
const stepProps = useMemo(() => ({ form, errors, set }), [form, errors, set])
|
||||
|
||||
@@ -781,11 +610,9 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP
|
||||
markVisited(currentStep)
|
||||
const errs = STEPS[currentStep].validate(form, mode)
|
||||
if (Object.keys(errs).length > 0) {
|
||||
setErrors(errs)
|
||||
toast.error('Dogry maglumat girizmegiňizi haýyş edýäris.')
|
||||
return
|
||||
}
|
||||
setErrors({})
|
||||
if (currentStep < STEPS.length - 1) {
|
||||
setCurrentStep(currentStep + 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
@@ -795,7 +622,6 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP
|
||||
const handleBack = () => {
|
||||
if (currentStep > 0) {
|
||||
markVisited(currentStep)
|
||||
setErrors({})
|
||||
setCurrentStep(currentStep - 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
@@ -803,21 +629,19 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP
|
||||
|
||||
const handleGoTo = (i: number) => {
|
||||
markVisited(currentStep)
|
||||
setErrors({})
|
||||
setCurrentStep(i)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
|
||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = () => {
|
||||
const doSubmit = () => {
|
||||
setVisited(new Set(STEPS.map((_, i) => i)))
|
||||
|
||||
const allErrors: FormErrors = {}
|
||||
const allErrors: FlatErrors = {}
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode))
|
||||
|
||||
if (Object.keys(allErrors).length > 0) {
|
||||
setErrors(allErrors)
|
||||
toast.error('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) {
|
||||
@@ -827,53 +651,7 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP
|
||||
return
|
||||
}
|
||||
|
||||
const payload: LoanOrderPayload = {
|
||||
status: form.status,
|
||||
loanType: form.loanType,
|
||||
region: form.region,
|
||||
branch: form.branch,
|
||||
firstName: form.firstName,
|
||||
lastName: form.lastName,
|
||||
patronicName: form.patronicName || undefined,
|
||||
education: form.education,
|
||||
marriageStatus: form.marriageStatus,
|
||||
dateOfBirth: form.dateOfBirth,
|
||||
residence: form.residence,
|
||||
currentResidence: form.currentResidence || undefined,
|
||||
passportSerie: form.passportSerie,
|
||||
passportNumber: form.passportNumber,
|
||||
passportDateOfIssue: form.passportDateOfIssue,
|
||||
passportGivenBy: form.passportGivenBy,
|
||||
bornPlace: form.bornPlace || undefined,
|
||||
email: form.email || undefined,
|
||||
phone: form.phone,
|
||||
phoneAdditional: form.phoneAdditional || undefined,
|
||||
homePhone: form.homePhone || undefined,
|
||||
workCompany: form.workCompany,
|
||||
workHrPhone: form.workHrPhone || undefined,
|
||||
workRegion: form.workRegion || undefined,
|
||||
workProvince: form.workProvince || undefined,
|
||||
position: form.position,
|
||||
salary: Number(form.salary),
|
||||
workStartedAt: form.workStartedAt,
|
||||
note: form.note || undefined,
|
||||
loanAmount: Number(form.loanAmount) || undefined,
|
||||
loanHistory: form.loanHistory || undefined,
|
||||
cardNumber: form.cardNumber || undefined,
|
||||
cardName: form.cardName || undefined,
|
||||
cardExpMonth: form.cardExpMonth || undefined,
|
||||
cardExpYear: form.cardExpYear || undefined,
|
||||
guarantor1Name: form.guarantor1Name || undefined,
|
||||
guarantor1Surname: form.guarantor1Surname || undefined,
|
||||
guarantor1Patronic: form.guarantor1Patronic || undefined,
|
||||
guarantor1PassportSerie: form.guarantor1PassportSerie || undefined,
|
||||
guarantor1PassportNumber: form.guarantor1PassportNumber || undefined,
|
||||
guarantor1CardNumber: form.guarantor1CardNumber || undefined,
|
||||
guarantor1CardName: form.guarantor1CardName || undefined,
|
||||
guarantor1CardExpMonth: form.guarantor1CardExpMonth || undefined,
|
||||
guarantor1CardExpYear: form.guarantor1CardExpYear || undefined,
|
||||
guarantor1Salary: Number(form.guarantor1Salary) || undefined,
|
||||
}
|
||||
const payload = buildPayload(getValues())
|
||||
|
||||
if (mode === 'create') {
|
||||
createMutation.mutate(payload, { onSuccess: () => navigate('/loan-orders') })
|
||||
@@ -942,7 +720,7 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP
|
||||
onPrev={currentStep > 0 ? handleBack : undefined}
|
||||
onNext={!isLastStep ? handleNext : undefined}
|
||||
showSubmit={isLastStep}
|
||||
onSubmit={isLastStep ? handleSubmit : undefined}
|
||||
onSubmit={isLastStep ? doSubmit : undefined}
|
||||
submitLabel={
|
||||
mode === 'create'
|
||||
? (t('loanOrderMobiles.createButton') || 'Karz sargyt döredüň')
|
||||
@@ -955,4 +733,54 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function mapInitial(order: LoanOrder): Partial<LoanOrderFormData> {
|
||||
return {
|
||||
status: order.status ?? 'GARAŞYLÝAR',
|
||||
loanType: order.loanType ?? '',
|
||||
region: order.region ?? 'Aşgabat',
|
||||
branch: order.branch ?? '',
|
||||
firstName: order.firstName ?? '',
|
||||
lastName: order.lastName ?? '',
|
||||
patronicName: order.patronicName ?? '',
|
||||
education: order.education ?? '',
|
||||
marriageStatus: order.marriageStatus ?? '',
|
||||
dateOfBirth: order.dateOfBirth ?? '',
|
||||
residence: order.residence ?? '',
|
||||
currentResidence: order.currentResidence ?? '',
|
||||
passportSerie: order.passportSerie ?? '',
|
||||
passportNumber: order.passportNumber ?? '',
|
||||
passportDateOfIssue: order.passportDateOfIssue ?? '',
|
||||
passportGivenBy: order.passportGivenBy ?? '',
|
||||
bornPlace: order.bornPlace ?? '',
|
||||
email: order.email ?? '',
|
||||
phone: order.phone ?? '',
|
||||
phoneAdditional: order.phoneAdditional ?? '',
|
||||
homePhone: order.homePhone ?? '',
|
||||
workCompany: order.workCompany ?? '',
|
||||
workHrPhone: order.workHrPhone ?? '',
|
||||
workRegion: order.workRegion ?? 'Aşgabat',
|
||||
workProvince: order.workProvince ?? '',
|
||||
position: order.position ?? '',
|
||||
salary: order.salary != null ? String(order.salary) : '',
|
||||
workStartedAt: order.workStartedAt ?? '',
|
||||
note: order.note ?? '',
|
||||
loanAmount: order.loanAmount != null ? String(order.loanAmount) : '',
|
||||
loanHistory: order.loanHistory ?? '',
|
||||
cardNumber: order.cardNumber ?? '',
|
||||
cardName: order.cardName ?? '',
|
||||
cardExpMonth: order.cardExpMonth ?? '',
|
||||
cardExpYear: order.cardExpYear ?? '',
|
||||
guarantor1Name: order.guarantor1Name ?? '',
|
||||
guarantor1Surname: order.guarantor1Surname ?? '',
|
||||
guarantor1Patronic: order.guarantor1Patronic ?? '',
|
||||
guarantor1PassportSerie: order.guarantor1PassportSerie ?? '',
|
||||
guarantor1PassportNumber: order.guarantor1PassportNumber ?? '',
|
||||
guarantor1CardNumber: order.guarantor1CardNumber ?? '',
|
||||
guarantor1CardName: order.guarantor1CardName ?? '',
|
||||
guarantor1CardExpMonth: order.guarantor1CardExpMonth ?? '',
|
||||
guarantor1CardExpYear: order.guarantor1CardExpYear ?? '',
|
||||
guarantor1Salary: order.guarantor1Salary != null ? String(order.guarantor1Salary) : '',
|
||||
}
|
||||
}
|
||||
171
src/features/loanOrders/schemas/loanOrder.schema.ts
Normal file
171
src/features/loanOrders/schemas/loanOrder.schema.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
const fileRequired = z.custom<File>((val) => val instanceof File, 'Faýl hökmany')
|
||||
|
||||
export const loanOrderFormSchema = z.object({
|
||||
status: z.string().min(1, 'Status — hökmany'),
|
||||
loanType: z.string().min(1, 'Karz görnüşi — hökmany'),
|
||||
region: z.string().min(1, 'Welaýat — hökmany'),
|
||||
branch: z.string().min(1, 'Şahamça — hökmany'),
|
||||
firstName: z.string().min(1, 'Ady — hökmany'),
|
||||
lastName: z.string().min(1, 'Familiýasy — hökmany'),
|
||||
patronicName: z.string().optional(),
|
||||
education: z.string().min(1, 'Bilimi — hökmany'),
|
||||
marriageStatus: z.string().min(1, 'Maşgala ýagdaýy — hökmany'),
|
||||
dateOfBirth: z.string().min(1, 'Doglan güni — hökmany'),
|
||||
residence: z.string().min(1, 'Ýazgy edilen salgy — hökmany'),
|
||||
currentResidence: z.string().optional(),
|
||||
passportSerie: z.string().min(1, 'Pasport seriýasy — hökmany'),
|
||||
passportNumber: z.string().min(1, 'Pasport belgisi — hökmany'),
|
||||
passportDateOfIssue: z.string().min(1, 'Pasport berlen senesi — hökmany'),
|
||||
passportGivenBy: z.string().min(1, 'Kim tarapyndan berildi — hökmany'),
|
||||
bornPlace: z.string().optional(),
|
||||
email: z.string().optional(),
|
||||
phone: z.string()
|
||||
.min(1, 'Telefon — hökmany')
|
||||
.refine((val) => val.replace(/\D/g, '').length >= 8, { message: 'Telefon belgisi nädogry' }),
|
||||
phoneAdditional: z.string().optional(),
|
||||
homePhone: z.string().optional(),
|
||||
workCompany: z.string().min(1, 'Kärhananyň ady — hökmany'),
|
||||
workHrPhone: z.string().optional(),
|
||||
workRegion: z.string().optional(),
|
||||
workProvince: z.string().optional(),
|
||||
position: z.string().min(1, 'Wezipe — hökmany'),
|
||||
salary: z.string().min(1, 'Zähmet haky — hökmany'),
|
||||
workStartedAt: z.string().min(1, 'Işe başlan wagty — hökmany'),
|
||||
passportPage1: z.custom<File | null>().nullable(),
|
||||
passportPage23: z.custom<File | null>().nullable(),
|
||||
passportPage89: z.custom<File | null>().nullable(),
|
||||
passportPage32: z.custom<File | null>().nullable(),
|
||||
note: z.string().optional(),
|
||||
loanAmount: z.string().min(1, 'Karz möçberi — hökmany'),
|
||||
loanHistory: z.string().optional(),
|
||||
cardNumber: z.string().min(1, 'Kart belgisi — hökmany'),
|
||||
cardName: z.string().min(1, 'Kartdaky ady — hökmany'),
|
||||
cardExpMonth: z.string().min(1, 'Kart möhleti (aý) — hökmany'),
|
||||
cardExpYear: z.string().min(1, 'Kart möhleti (ýyl) — hökmany'),
|
||||
guarantor1Name: z.string().min(1, 'Zamunyň ady — hökmany'),
|
||||
guarantor1Surname: z.string().min(1, 'Zamunyň familiýasy — hökmany'),
|
||||
guarantor1Patronic: z.string().optional(),
|
||||
guarantor1PassportSerie: z.string().min(1, 'Pasport seriýasy — hökmany'),
|
||||
guarantor1PassportNumber: z.string().min(1, 'Pasport belgisi — hökmany'),
|
||||
guarantor1CardNumber: z.string().min(1, 'Kart belgisi — hökmany'),
|
||||
guarantor1CardName: z.string().min(1, 'Kartdaky ady — hökmany'),
|
||||
guarantor1CardExpMonth: z.string().min(1, 'Möhleti (aý) — hökmany'),
|
||||
guarantor1CardExpYear: z.string().min(1, 'Möhleti (ýyl) — hökmany'),
|
||||
guarantor1Salary: z.string().min(1, 'Ortaca zähmet haky — hökmany'),
|
||||
})
|
||||
|
||||
export type LoanOrderFormData = z.infer<typeof loanOrderFormSchema>
|
||||
|
||||
export const stepSchemas: Record<number, z.ZodType<Partial<LoanOrderFormData>>> = {
|
||||
0: loanOrderFormSchema.pick({ status: true }),
|
||||
1: loanOrderFormSchema.pick({ loanType: true, loanAmount: true }),
|
||||
2: loanOrderFormSchema.pick({ region: true, branch: true }),
|
||||
3: loanOrderFormSchema.pick({
|
||||
firstName: true, lastName: true, education: true,
|
||||
marriageStatus: true, dateOfBirth: true, residence: true,
|
||||
}),
|
||||
4: loanOrderFormSchema.pick({
|
||||
cardNumber: true, cardName: true, cardExpMonth: true, cardExpYear: true,
|
||||
}),
|
||||
5: loanOrderFormSchema.pick({
|
||||
passportSerie: true, passportNumber: true,
|
||||
passportDateOfIssue: true, passportGivenBy: true,
|
||||
}),
|
||||
6: loanOrderFormSchema.pick({ phone: true }),
|
||||
7: loanOrderFormSchema.pick({
|
||||
workCompany: true, position: true, salary: true, workStartedAt: true,
|
||||
}),
|
||||
8: z.object({
|
||||
passportPage1: fileRequired,
|
||||
passportPage23: fileRequired,
|
||||
}),
|
||||
9: loanOrderFormSchema.pick({
|
||||
guarantor1Name: true, guarantor1Surname: true,
|
||||
guarantor1PassportSerie: true, guarantor1PassportNumber: true,
|
||||
guarantor1CardNumber: true, guarantor1CardName: true,
|
||||
guarantor1CardExpMonth: true, guarantor1CardExpYear: true,
|
||||
guarantor1Salary: true,
|
||||
}),
|
||||
}
|
||||
|
||||
export function validateStep(stepIndex: number, form: LoanOrderFormData, mode: 'create' | 'edit'): Partial<Record<keyof LoanOrderFormData, string>> {
|
||||
if (stepIndex === 8 && mode === 'edit') return {}
|
||||
const schema = stepSchemas[stepIndex]
|
||||
const result = schema.safeParse(form)
|
||||
if (result.success) return {}
|
||||
const errors: Partial<Record<keyof LoanOrderFormData, string>> = {}
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof LoanOrderFormData
|
||||
if (!errors[key]) errors[key] = issue.message
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
export const DEFAULT_FORM_VALUES: LoanOrderFormData = {
|
||||
status: 'GARAŞYLÝAR', loanType: '', region: 'Aşgabat', branch: '',
|
||||
firstName: '', lastName: '', patronicName: '', education: '',
|
||||
marriageStatus: '', dateOfBirth: '', residence: '', currentResidence: '',
|
||||
passportSerie: '', passportNumber: '', passportDateOfIssue: '',
|
||||
passportGivenBy: '', bornPlace: '', email: '', phone: '',
|
||||
phoneAdditional: '', homePhone: '', workCompany: '', workHrPhone: '',
|
||||
workRegion: 'Aşgabat', workProvince: '', position: '', salary: '',
|
||||
workStartedAt: '', passportPage1: null, passportPage23: null,
|
||||
passportPage89: null, passportPage32: null, note: '', loanAmount: '',
|
||||
loanHistory: '', cardNumber: '', cardName: '', cardExpMonth: '', cardExpYear: '',
|
||||
guarantor1Name: '', guarantor1Surname: '', guarantor1Patronic: '',
|
||||
guarantor1PassportSerie: '', guarantor1PassportNumber: '',
|
||||
guarantor1CardNumber: '', guarantor1CardName: '',
|
||||
guarantor1CardExpMonth: '', guarantor1CardExpYear: '', guarantor1Salary: '',
|
||||
}
|
||||
|
||||
export function buildPayload(data: LoanOrderFormData) {
|
||||
return {
|
||||
status: data.status,
|
||||
loanType: data.loanType,
|
||||
region: data.region,
|
||||
branch: data.branch,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
patronicName: data.patronicName || undefined,
|
||||
education: data.education,
|
||||
marriageStatus: data.marriageStatus,
|
||||
dateOfBirth: data.dateOfBirth,
|
||||
residence: data.residence,
|
||||
currentResidence: data.currentResidence || undefined,
|
||||
passportSerie: data.passportSerie,
|
||||
passportNumber: data.passportNumber,
|
||||
passportDateOfIssue: data.passportDateOfIssue,
|
||||
passportGivenBy: data.passportGivenBy,
|
||||
bornPlace: data.bornPlace || undefined,
|
||||
email: data.email || undefined,
|
||||
phone: data.phone,
|
||||
phoneAdditional: data.phoneAdditional || undefined,
|
||||
homePhone: data.homePhone || undefined,
|
||||
workCompany: data.workCompany,
|
||||
workHrPhone: data.workHrPhone || undefined,
|
||||
workRegion: data.workRegion || undefined,
|
||||
workProvince: data.workProvince || undefined,
|
||||
position: data.position,
|
||||
salary: Number(data.salary),
|
||||
workStartedAt: data.workStartedAt,
|
||||
note: data.note || undefined,
|
||||
loanAmount: Number(data.loanAmount) || undefined,
|
||||
loanHistory: data.loanHistory || undefined,
|
||||
cardNumber: data.cardNumber || undefined,
|
||||
cardName: data.cardName || undefined,
|
||||
cardExpMonth: data.cardExpMonth || undefined,
|
||||
cardExpYear: data.cardExpYear || undefined,
|
||||
guarantor1Name: data.guarantor1Name || undefined,
|
||||
guarantor1Surname: data.guarantor1Surname || undefined,
|
||||
guarantor1Patronic: data.guarantor1Patronic || undefined,
|
||||
guarantor1PassportSerie: data.guarantor1PassportSerie || undefined,
|
||||
guarantor1PassportNumber: data.guarantor1PassportNumber || undefined,
|
||||
guarantor1CardNumber: data.guarantor1CardNumber || undefined,
|
||||
guarantor1CardName: data.guarantor1CardName || undefined,
|
||||
guarantor1CardExpMonth: data.guarantor1CardExpMonth || undefined,
|
||||
guarantor1CardExpYear: data.guarantor1CardExpYear || undefined,
|
||||
guarantor1Salary: Number(data.guarantor1Salary) || undefined,
|
||||
}
|
||||
}
|
||||
@@ -1,84 +1,73 @@
|
||||
import { apiClient } from '@/lib/api/client'
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface LoanPaidOffLetter {
|
||||
id: number
|
||||
passportSeries: string
|
||||
passportNumber: string
|
||||
loanAccount: string
|
||||
issuedAt: string
|
||||
id: number;
|
||||
passportSeries: string;
|
||||
passportNumber: string;
|
||||
loanAccount: string;
|
||||
issuedAt: string;
|
||||
}
|
||||
|
||||
export interface LoanPaidOffLetterListParams {
|
||||
search?: string
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string;
|
||||
page?: number;
|
||||
perPage?: number;
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
data: T[]
|
||||
total: number
|
||||
data: T[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
// ─── Mock Data ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const USE_MOCK = true
|
||||
const USE_MOCK = true;
|
||||
|
||||
const MOCK_DATA: LoanPaidOffLetter[] = [
|
||||
{ id: 1, passportSeries: 'TM', passportNumber: 'A123456', loanAccount: 'LOAN-2024-001', issuedAt: '2025-01-10' },
|
||||
{ id: 2, passportSeries: 'TM', passportNumber: 'B234567', loanAccount: 'LOAN-2024-002', issuedAt: '2025-01-14' },
|
||||
{ id: 3, passportSeries: 'TM', passportNumber: 'C345678', loanAccount: 'LOAN-2024-003', issuedAt: '2025-01-17' },
|
||||
{ id: 4, passportSeries: 'TM', passportNumber: 'D456789', loanAccount: 'LOAN-2023-115', issuedAt: '2025-01-20' },
|
||||
{ id: 5, passportSeries: 'TM', passportNumber: 'E567890', loanAccount: 'LOAN-2023-116', issuedAt: '2025-01-23' },
|
||||
{ id: 6, passportSeries: 'TM', passportNumber: 'F678901', loanAccount: 'LOAN-2024-044', issuedAt: '2025-01-27' },
|
||||
{ id: 7, passportSeries: 'TM', passportNumber: 'G789012', loanAccount: 'LOAN-2024-055', issuedAt: '2025-02-01' },
|
||||
{ id: 8, passportSeries: 'TM', passportNumber: 'H890123', loanAccount: 'LOAN-2024-066', issuedAt: '2025-02-05' },
|
||||
{ id: 9, passportSeries: 'TM', passportNumber: 'I901234', loanAccount: 'LOAN-2024-077', issuedAt: '2025-02-09' },
|
||||
{ id: 10, passportSeries: 'TM', passportNumber: 'J012345', loanAccount: 'LOAN-2024-088', issuedAt: '2025-02-12' },
|
||||
]
|
||||
{ id: 1, passportSeries: "TM", passportNumber: "A123456", loanAccount: "LOAN-2024-001", issuedAt: "2025-01-10" },
|
||||
{ id: 2, passportSeries: "TM", passportNumber: "B234567", loanAccount: "LOAN-2024-002", issuedAt: "2025-01-14" },
|
||||
{ id: 3, passportSeries: "TM", passportNumber: "C345678", loanAccount: "LOAN-2024-003", issuedAt: "2025-01-17" },
|
||||
{ id: 4, passportSeries: "TM", passportNumber: "D456789", loanAccount: "LOAN-2023-115", issuedAt: "2025-01-20" },
|
||||
{ id: 5, passportSeries: "TM", passportNumber: "E567890", loanAccount: "LOAN-2023-116", issuedAt: "2025-01-23" },
|
||||
{ id: 6, passportSeries: "TM", passportNumber: "F678901", loanAccount: "LOAN-2024-044", issuedAt: "2025-01-27" },
|
||||
{ id: 7, passportSeries: "TM", passportNumber: "G789012", loanAccount: "LOAN-2024-055", issuedAt: "2025-02-01" },
|
||||
{ id: 8, passportSeries: "TM", passportNumber: "H890123", loanAccount: "LOAN-2024-066", issuedAt: "2025-02-05" },
|
||||
{ id: 9, passportSeries: "TM", passportNumber: "I901234", loanAccount: "LOAN-2024-077", issuedAt: "2025-02-09" },
|
||||
{ id: 10, passportSeries: "TM", passportNumber: "J012345", loanAccount: "LOAN-2024-088", issuedAt: "2025-02-12" },
|
||||
];
|
||||
|
||||
function applyMockFilters(
|
||||
params: LoanPaidOffLetterListParams,
|
||||
): PaginatedResponse<LoanPaidOffLetter> {
|
||||
let result = [...MOCK_DATA]
|
||||
function applyMockFilters(params: LoanPaidOffLetterListParams): PaginatedResponse<LoanPaidOffLetter> {
|
||||
let result = [...MOCK_DATA];
|
||||
|
||||
if (params.search) {
|
||||
const q = params.search.toLowerCase()
|
||||
result = result.filter(
|
||||
(r) =>
|
||||
r.passportNumber.toLowerCase().includes(q) ||
|
||||
r.loanAccount.toLowerCase().includes(q),
|
||||
)
|
||||
const q = params.search.toLowerCase();
|
||||
result = result.filter((r) => r.passportNumber.toLowerCase().includes(q) || r.loanAccount.toLowerCase().includes(q));
|
||||
}
|
||||
|
||||
const total = result.length
|
||||
const page = params.page ?? 1
|
||||
const perPage = params.perPage ?? 25
|
||||
const start = (page - 1) * perPage
|
||||
const total = result.length;
|
||||
const page = params.page ?? 1;
|
||||
const perPage = params.perPage ?? 25;
|
||||
const start = (page - 1) * perPage;
|
||||
|
||||
return { data: result.slice(start, start + perPage), total }
|
||||
return { data: result.slice(start, start + perPage), total };
|
||||
}
|
||||
|
||||
// ─── API Functions ─────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchLoanPaidOffLetters(
|
||||
params: LoanPaidOffLetterListParams,
|
||||
): Promise<PaginatedResponse<LoanPaidOffLetter>> {
|
||||
if (USE_MOCK) return applyMockFilters(params)
|
||||
export async function fetchLoanPaidOffLetters(params: LoanPaidOffLetterListParams): Promise<PaginatedResponse<LoanPaidOffLetter>> {
|
||||
if (USE_MOCK) return applyMockFilters(params);
|
||||
|
||||
const { data } = await apiClient.get<PaginatedResponse<LoanPaidOffLetter>>(
|
||||
'/loan-paid-off-letter-orders',
|
||||
{ params },
|
||||
)
|
||||
return data
|
||||
const { data } = await apiClient.get<PaginatedResponse<LoanPaidOffLetter>>("/loan-paid-off-letter-orders", { params });
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function deleteLoanPaidOffLetter(id: number): Promise<void> {
|
||||
if (USE_MOCK) {
|
||||
const idx = MOCK_DATA.findIndex((r) => r.id === id)
|
||||
if (idx !== -1) MOCK_DATA.splice(idx, 1)
|
||||
return
|
||||
const idx = MOCK_DATA.findIndex((r) => r.id === id);
|
||||
if (idx !== -1) MOCK_DATA.splice(idx, 1);
|
||||
return;
|
||||
}
|
||||
await apiClient.delete(`/loan-paid-off-letter-orders/${id}`)
|
||||
}
|
||||
await apiClient.delete(`/loan-paid-off-letter-orders/${id}`);
|
||||
}
|
||||
|
||||
@@ -1,97 +1,86 @@
|
||||
import { apiClient } from '@/lib/api/client'
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface LoanRemaining {
|
||||
id: number
|
||||
passportSeries: string
|
||||
passportNumber: string
|
||||
loanAccount: string
|
||||
id: number;
|
||||
passportSeries: string;
|
||||
passportNumber: string;
|
||||
loanAccount: string;
|
||||
}
|
||||
|
||||
export type LoanRemainingPayload = Omit<LoanRemaining, 'id'>
|
||||
export type LoanRemainingPayload = Omit<LoanRemaining, "id">;
|
||||
|
||||
export interface LoanRemainingListParams {
|
||||
search?: string
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string;
|
||||
page?: number;
|
||||
perPage?: number;
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
data: T[]
|
||||
total: number
|
||||
data: T[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
// ─── Mock Data ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const USE_MOCK = true
|
||||
const USE_MOCK = true;
|
||||
|
||||
const MOCK_DATA: LoanRemaining[] = [
|
||||
{ id: 1, passportSeries: 'TM', passportNumber: 'A111111', loanAccount: 'NOVA-2024-001' },
|
||||
{ id: 2, passportSeries: 'TM', passportNumber: 'B222222', loanAccount: 'NOVA-2024-002' },
|
||||
{ id: 3, passportSeries: 'TM', passportNumber: 'C333333', loanAccount: 'NOVA-2023-078' },
|
||||
{ id: 4, passportSeries: 'TM', passportNumber: 'D444444', loanAccount: 'NOVA-2023-079' },
|
||||
{ id: 5, passportSeries: 'TM', passportNumber: 'E555555', loanAccount: 'NOVA-2024-033' },
|
||||
{ id: 6, passportSeries: 'TM', passportNumber: 'F666666', loanAccount: 'NOVA-2024-034' },
|
||||
{ id: 7, passportSeries: 'TM', passportNumber: 'G777777', loanAccount: 'NOVA-2024-051' },
|
||||
{ id: 8, passportSeries: 'TM', passportNumber: 'H888888', loanAccount: 'NOVA-2024-052' },
|
||||
{ id: 9, passportSeries: 'TM', passportNumber: 'I999999', loanAccount: 'NOVA-2024-063' },
|
||||
{ id: 10, passportSeries: 'TM', passportNumber: 'J000000', loanAccount: 'NOVA-2024-064' },
|
||||
]
|
||||
{ id: 1, passportSeries: "TM", passportNumber: "A111111", loanAccount: "NOVA-2024-001" },
|
||||
{ id: 2, passportSeries: "TM", passportNumber: "B222222", loanAccount: "NOVA-2024-002" },
|
||||
{ id: 3, passportSeries: "TM", passportNumber: "C333333", loanAccount: "NOVA-2023-078" },
|
||||
{ id: 4, passportSeries: "TM", passportNumber: "D444444", loanAccount: "NOVA-2023-079" },
|
||||
{ id: 5, passportSeries: "TM", passportNumber: "E555555", loanAccount: "NOVA-2024-033" },
|
||||
{ id: 6, passportSeries: "TM", passportNumber: "F666666", loanAccount: "NOVA-2024-034" },
|
||||
{ id: 7, passportSeries: "TM", passportNumber: "G777777", loanAccount: "NOVA-2024-051" },
|
||||
{ id: 8, passportSeries: "TM", passportNumber: "H888888", loanAccount: "NOVA-2024-052" },
|
||||
{ id: 9, passportSeries: "TM", passportNumber: "I999999", loanAccount: "NOVA-2024-063" },
|
||||
{ id: 10, passportSeries: "TM", passportNumber: "J000000", loanAccount: "NOVA-2024-064" },
|
||||
];
|
||||
|
||||
function applyMockFilters(
|
||||
params: LoanRemainingListParams,
|
||||
): PaginatedResponse<LoanRemaining> {
|
||||
let result = [...MOCK_DATA]
|
||||
function applyMockFilters(params: LoanRemainingListParams): PaginatedResponse<LoanRemaining> {
|
||||
let result = [...MOCK_DATA];
|
||||
|
||||
if (params.search) {
|
||||
const q = params.search.toLowerCase()
|
||||
result = result.filter(
|
||||
(r) =>
|
||||
r.passportNumber.toLowerCase().includes(q) ||
|
||||
r.loanAccount.toLowerCase().includes(q),
|
||||
)
|
||||
const q = params.search.toLowerCase();
|
||||
result = result.filter((r) => r.passportNumber.toLowerCase().includes(q) || r.loanAccount.toLowerCase().includes(q));
|
||||
}
|
||||
|
||||
const total = result.length
|
||||
const page = params.page ?? 1
|
||||
const perPage = params.perPage ?? 25
|
||||
const start = (page - 1) * perPage
|
||||
const total = result.length;
|
||||
const page = params.page ?? 1;
|
||||
const perPage = params.perPage ?? 25;
|
||||
const start = (page - 1) * perPage;
|
||||
|
||||
return { data: result.slice(start, start + perPage), total }
|
||||
return { data: result.slice(start, start + perPage), total };
|
||||
}
|
||||
|
||||
// ─── API Functions ─────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchLoanRemaining(
|
||||
params: LoanRemainingListParams,
|
||||
): Promise<PaginatedResponse<LoanRemaining>> {
|
||||
if (USE_MOCK) return applyMockFilters(params)
|
||||
export async function fetchLoanRemaining(params: LoanRemainingListParams): Promise<PaginatedResponse<LoanRemaining>> {
|
||||
if (USE_MOCK) return applyMockFilters(params);
|
||||
|
||||
const { data } = await apiClient.get<PaginatedResponse<LoanRemaining>>(
|
||||
'/nova-loan-remaining-orders',
|
||||
{ params },
|
||||
)
|
||||
return data
|
||||
const { data } = await apiClient.get<PaginatedResponse<LoanRemaining>>("/nova-loan-remaining-orders", { params });
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function deleteLoanRemaining(id: number): Promise<void> {
|
||||
if (USE_MOCK) {
|
||||
const idx = MOCK_DATA.findIndex((r) => r.id === id)
|
||||
if (idx !== -1) MOCK_DATA.splice(idx, 1)
|
||||
return
|
||||
const idx = MOCK_DATA.findIndex((r) => r.id === id);
|
||||
if (idx !== -1) MOCK_DATA.splice(idx, 1);
|
||||
return;
|
||||
}
|
||||
await apiClient.delete(`/nova-loan-remaining-orders/${id}`)
|
||||
await apiClient.delete(`/nova-loan-remaining-orders/${id}`);
|
||||
}
|
||||
|
||||
export async function fetchLoanRemainingById(id: number): Promise<LoanRemaining> {
|
||||
if (USE_MOCK) {
|
||||
const item = MOCK_DATA.find((r) => r.id === id)
|
||||
if (!item) throw new Error('Not found')
|
||||
return item
|
||||
const item = MOCK_DATA.find((r) => r.id === id);
|
||||
if (!item) throw new Error("Not found");
|
||||
return item;
|
||||
}
|
||||
const { data } = await apiClient.get<LoanRemaining>(`/nova-loan-remaining-orders/${id}`)
|
||||
return data
|
||||
const { data } = await apiClient.get<LoanRemaining>(`/nova-loan-remaining-orders/${id}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function createLoanRemaining(payload: LoanRemainingPayload): Promise<LoanRemaining> {
|
||||
@@ -99,22 +88,22 @@ export async function createLoanRemaining(payload: LoanRemainingPayload): Promis
|
||||
const newItem: LoanRemaining = {
|
||||
id: Math.max(0, ...MOCK_DATA.map((d) => d.id)) + 1,
|
||||
...payload,
|
||||
}
|
||||
MOCK_DATA.unshift(newItem)
|
||||
return newItem
|
||||
};
|
||||
MOCK_DATA.unshift(newItem);
|
||||
return newItem;
|
||||
}
|
||||
const { data } = await apiClient.post<LoanRemaining>('/nova-loan-remaining-orders', payload)
|
||||
return data
|
||||
const { data } = await apiClient.post<LoanRemaining>("/nova-loan-remaining-orders", payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function updateLoanRemaining(id: number, payload: LoanRemainingPayload): Promise<LoanRemaining> {
|
||||
if (USE_MOCK) {
|
||||
const idx = MOCK_DATA.findIndex((r) => r.id === id)
|
||||
if (idx === -1) throw new Error('Not found')
|
||||
const updated = { ...MOCK_DATA[idx], ...payload }
|
||||
MOCK_DATA[idx] = updated
|
||||
return updated
|
||||
const idx = MOCK_DATA.findIndex((r) => r.id === id);
|
||||
if (idx === -1) throw new Error("Not found");
|
||||
const updated = { ...MOCK_DATA[idx], ...payload };
|
||||
MOCK_DATA[idx] = updated;
|
||||
return updated;
|
||||
}
|
||||
const { data } = await apiClient.put<LoanRemaining>(`/nova-loan-remaining-orders/${id}`, payload)
|
||||
return data
|
||||
}
|
||||
const { data } = await apiClient.put<LoanRemaining>(`/nova-loan-remaining-orders/${id}`, payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useEffect } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { toast } from 'sonner'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
@@ -10,10 +12,13 @@ import {
|
||||
useCreateLoanRemaining,
|
||||
useUpdateLoanRemaining,
|
||||
} from '../hooks/useLoanRemaining'
|
||||
import type {
|
||||
LoanRemaining,
|
||||
LoanRemainingPayload,
|
||||
} from '../api/loanRemainingApi'
|
||||
import type { LoanRemaining } from '../api/loanRemainingApi'
|
||||
import {
|
||||
loanRemainingFormSchema,
|
||||
type LoanRemainingFormData,
|
||||
DEFAULT_FORM_VALUES,
|
||||
buildPayload,
|
||||
} from '../schemas/loanRemaining.schema'
|
||||
|
||||
interface LoanRemainingFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
@@ -21,20 +26,6 @@ interface LoanRemainingFormProps {
|
||||
loanRemainingId?: string
|
||||
}
|
||||
|
||||
interface FormState {
|
||||
passportSeries: string
|
||||
passportNumber: string
|
||||
loanAccount: string
|
||||
}
|
||||
|
||||
type FormErrors = Partial<Record<keyof FormState, string>>
|
||||
|
||||
const INITIAL_STATE: FormState = {
|
||||
passportSeries: '',
|
||||
passportNumber: '',
|
||||
loanAccount: '',
|
||||
}
|
||||
|
||||
export function LoanRemainingForm({
|
||||
mode,
|
||||
initialData,
|
||||
@@ -48,66 +39,30 @@ export function LoanRemainingForm({
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const [form, setForm] = useState<FormState>(() =>
|
||||
mode === 'edit' && initialData
|
||||
? {
|
||||
passportSeries: initialData.passportSeries,
|
||||
passportNumber: initialData.passportNumber,
|
||||
loanAccount: initialData.loanAccount,
|
||||
}
|
||||
: INITIAL_STATE
|
||||
)
|
||||
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
const [submitted, setSubmitted] = useState(false)
|
||||
const {
|
||||
handleSubmit,
|
||||
watch,
|
||||
setValue,
|
||||
reset,
|
||||
formState: { errors },
|
||||
} = useForm<LoanRemainingFormData>({
|
||||
resolver: zodResolver(loanRemainingFormSchema),
|
||||
defaultValues: DEFAULT_FORM_VALUES,
|
||||
mode: 'onSubmit',
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (mode === 'edit' && initialData) {
|
||||
setForm({
|
||||
reset({
|
||||
passportSeries: initialData.passportSeries,
|
||||
passportNumber: initialData.passportNumber,
|
||||
loanAccount: initialData.loanAccount,
|
||||
})
|
||||
}
|
||||
}, [mode, initialData])
|
||||
}, [mode, initialData, reset])
|
||||
|
||||
const set = useCallback(
|
||||
<K extends keyof FormState>(key: K, value: FormState[K]) => {
|
||||
setForm((prev) => ({ ...prev, [key]: value }))
|
||||
if (submitted) {
|
||||
setErrors((prev) => ({ ...prev, [key]: undefined }))
|
||||
}
|
||||
},
|
||||
[submitted]
|
||||
)
|
||||
|
||||
const validate = (): boolean => {
|
||||
const newErrors: FormErrors = {}
|
||||
|
||||
if (!form.passportSeries.trim()) {
|
||||
newErrors.passportSeries = t('common.required', 'Hökman doldurylmaly')
|
||||
}
|
||||
if (!form.passportNumber.trim()) {
|
||||
newErrors.passportNumber = t('common.required', 'Hökman doldurylmaly')
|
||||
}
|
||||
if (!form.loanAccount.trim()) {
|
||||
newErrors.loanAccount = t('common.required', 'Hökman doldurylmaly')
|
||||
}
|
||||
|
||||
setErrors(newErrors)
|
||||
return Object.keys(newErrors).length === 0
|
||||
}
|
||||
|
||||
const handleSubmit = (e?: React.FormEvent) => {
|
||||
e?.preventDefault()
|
||||
setSubmitted(true)
|
||||
|
||||
if (!validate()) {
|
||||
toast.error(t('common.errors.fillRequired', 'Hökman doldurylmaly öýjükleri dolduryň'))
|
||||
return
|
||||
}
|
||||
|
||||
const payload: LoanRemainingPayload = form
|
||||
const onSubmit = (data: LoanRemainingFormData) => {
|
||||
const payload = buildPayload(data)
|
||||
|
||||
if (mode === 'create') {
|
||||
createMutation.mutate(payload, {
|
||||
@@ -132,36 +87,40 @@ export function LoanRemainingForm({
|
||||
}
|
||||
}
|
||||
|
||||
const onError = () => {
|
||||
toast.error(t('common.errors.fillRequired', 'Hökman doldurylmaly öýjükleri dolduryň'))
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<form onSubmit={handleSubmit(onSubmit, onError)} className="space-y-6">
|
||||
<div className="bg-card border border-border rounded-xl p-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<FormInput
|
||||
label={t('loanRemaining.columns.passportSeries', 'Pasport seriýasy')}
|
||||
required
|
||||
value={form.passportSeries}
|
||||
onChange={(v) => set('passportSeries', v)}
|
||||
value={watch('passportSeries')}
|
||||
onChange={(v) => setValue('passportSeries', v)}
|
||||
placeholder={t('loanRemaining.placeholders.passportSeries', 'TM')}
|
||||
error={errors.passportSeries}
|
||||
error={errors.passportSeries?.message}
|
||||
/>
|
||||
|
||||
<FormInput
|
||||
label={t('loanRemaining.columns.passportNumber', 'Pasport belgisi')}
|
||||
required
|
||||
value={form.passportNumber}
|
||||
onChange={(v) => set('passportNumber', v)}
|
||||
value={watch('passportNumber')}
|
||||
onChange={(v) => setValue('passportNumber', v)}
|
||||
placeholder="A123456"
|
||||
error={errors.passportNumber}
|
||||
error={errors.passportNumber?.message}
|
||||
/>
|
||||
|
||||
<div className="md:col-span-2">
|
||||
<FormInput
|
||||
label={t('loanRemaining.columns.loanAccount', 'Karz hasaby')}
|
||||
required
|
||||
value={form.loanAccount}
|
||||
onChange={(v) => set('loanAccount', v)}
|
||||
value={watch('loanAccount')}
|
||||
onChange={(v) => setValue('loanAccount', v)}
|
||||
placeholder="NOVA-..."
|
||||
error={errors.loanAccount}
|
||||
error={errors.loanAccount?.message}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -169,7 +128,7 @@ export function LoanRemainingForm({
|
||||
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onSubmit={handleSubmit(onSubmit, onError)}
|
||||
onCancel={() => navigate('/loan-remaining')}
|
||||
submitLabel={mode === 'create'
|
||||
? t('common.create', 'Döret')
|
||||
|
||||
25
src/features/loanRemaining/schemas/loanRemaining.schema.ts
Normal file
25
src/features/loanRemaining/schemas/loanRemaining.schema.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const loanRemainingFormSchema = z.object({
|
||||
passportSeries: z.string().min(1, 'Hökman doldurylmaly'),
|
||||
passportNumber: z.string().min(1, 'Hökman doldurylmaly'),
|
||||
loanAccount: z.string().min(1, 'Hökman doldurylmaly'),
|
||||
})
|
||||
|
||||
export type LoanRemainingFormData = z.infer<typeof loanRemainingFormSchema>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: LoanRemainingFormData = {
|
||||
passportSeries: '',
|
||||
passportNumber: '',
|
||||
loanAccount: '',
|
||||
}
|
||||
|
||||
export function buildPayload(
|
||||
data: LoanRemainingFormData,
|
||||
): { passportSeries: string; passportNumber: string; loanAccount: string } {
|
||||
return {
|
||||
passportSeries: data.passportSeries,
|
||||
passportNumber: data.passportNumber,
|
||||
loanAccount: data.loanAccount,
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,16 @@
|
||||
// features/loanTypes/components/LoanTypeForm.tsx
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useCallback, useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { useCreateLoanType, useUpdateLoanType } from '../hooks/useLoanTypes'
|
||||
import type { LoanType, CreateLoanTypePayload } from '../api/loanTypesApi'
|
||||
import type { LoanType } from '../api/loanTypesApi'
|
||||
import { loanTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/loanType.schema'
|
||||
import type { LoanTypeFormData } from '../schemas/loanType.schema'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -20,12 +22,29 @@ interface LoanTypeFormProps {
|
||||
loanTypeId?: number
|
||||
}
|
||||
|
||||
interface FormErrors {
|
||||
nameTk?: string
|
||||
nameRu?: string
|
||||
nameEn?: string
|
||||
tax?: string
|
||||
loanTerm?: string
|
||||
type FlatErrors = Partial<Record<keyof LoanTypeFormData, 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 LoanTypeFormData] = msg
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function mapInitial(data: LoanType): LoanTypeFormData {
|
||||
return {
|
||||
nameTk: data.name.tk,
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
notesTk: data.notes?.tk ?? '',
|
||||
notesRu: data.notes?.ru ?? '',
|
||||
notesEn: data.notes?.en ?? '',
|
||||
tax: String(data.tax),
|
||||
loanTerm: String(data.loanTerm),
|
||||
isActive: data.isActive,
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Language Tab ─────────────────────────────────────────────────────────────
|
||||
@@ -38,25 +57,6 @@ const LANG_TABS: { key: Lang; label: string }[] = [
|
||||
{ key: 'en', label: 'English' },
|
||||
]
|
||||
|
||||
// ─── Validation ───────────────────────────────────────────────────────────────
|
||||
|
||||
function validate(
|
||||
nameTk: string,
|
||||
nameRu: string,
|
||||
nameEn: string,
|
||||
tax: string,
|
||||
loanTerm: string,
|
||||
t: (key: string, fallback: string) => string
|
||||
): FormErrors {
|
||||
const errors: FormErrors = {}
|
||||
if (!nameTk.trim()) errors.nameTk = t('validation.required', 'Hökmany meýdan')
|
||||
if (!nameRu.trim()) errors.nameRu = t('validation.required', 'Hökmany meýdan')
|
||||
if (!nameEn.trim()) errors.nameEn = t('validation.required', 'Hökmany meýdan')
|
||||
if (!tax || Number(tax) <= 0) errors.tax = t('validation.positiveNumber', 'Oňyn san gerek')
|
||||
if (!loanTerm || Number(loanTerm) <= 0) errors.loanTerm = t('validation.positiveNumber', 'Oňyn san gerek')
|
||||
return errors
|
||||
}
|
||||
|
||||
// ─── LoanTypeForm ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProps) {
|
||||
@@ -68,53 +68,42 @@ export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProp
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
// ── State ──────────────────────────────────────────────────────────────────
|
||||
const [activeLang, setActiveLang] = useState<Lang>('tk')
|
||||
const [nameTk, setNameTk] = useState('')
|
||||
const [nameRu, setNameRu] = useState('')
|
||||
const [nameEn, setNameEn] = useState('')
|
||||
const [notesTk, setNotesTk] = useState('')
|
||||
const [notesRu, setNotesRu] = useState('')
|
||||
const [notesEn, setNotesEn] = useState('')
|
||||
const [tax, setTax] = useState('')
|
||||
const [loanTerm, setLoanTerm] = useState('')
|
||||
const [isActive, setIsActive] = useState(true)
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
|
||||
// ── Populate on edit ───────────────────────────────────────────────────────
|
||||
useEffect(() => {
|
||||
if (mode === 'edit' && initialData) {
|
||||
setNameTk(initialData.name.tk)
|
||||
setNameRu(initialData.name.ru)
|
||||
setNameEn(initialData.name.en)
|
||||
setNotesTk(initialData.notes?.tk ?? '')
|
||||
setNotesRu(initialData.notes?.ru ?? '')
|
||||
setNotesEn(initialData.notes?.en ?? '')
|
||||
setTax(String(initialData.tax))
|
||||
setLoanTerm(String(initialData.loanTerm))
|
||||
setIsActive(initialData.isActive)
|
||||
}
|
||||
}, [mode, initialData])
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
trigger,
|
||||
getValues,
|
||||
} = useForm<LoanTypeFormData>({
|
||||
resolver: zodResolver(loanTypeFormSchema),
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(
|
||||
() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>),
|
||||
[rhfErrors],
|
||||
)
|
||||
|
||||
const set = useCallback(
|
||||
(key: keyof LoanTypeFormData) => (value: string | boolean) => {
|
||||
(setValue as (k: keyof LoanTypeFormData, v: string | boolean) => void)(key, value)
|
||||
clearErrors(key)
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
)
|
||||
|
||||
// ── Submit ─────────────────────────────────────────────────────────────────
|
||||
const handleSubmit = async () => {
|
||||
const validationErrors = validate(nameTk, nameRu, nameEn, tax, loanTerm, t)
|
||||
if (Object.keys(validationErrors).length > 0) {
|
||||
setErrors(validationErrors)
|
||||
return
|
||||
}
|
||||
setErrors({})
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
|
||||
const payload: CreateLoanTypePayload = {
|
||||
name: { tk: nameTk.trim(), ru: nameRu.trim(), en: nameEn.trim() },
|
||||
tax: Number(tax),
|
||||
loanTerm: Number(loanTerm),
|
||||
notes:
|
||||
notesTk.trim() || notesRu.trim() || notesEn.trim()
|
||||
? { tk: notesTk.trim(), ru: notesRu.trim(), en: notesEn.trim() }
|
||||
: null,
|
||||
isActive,
|
||||
}
|
||||
const payload = buildPayload(getValues())
|
||||
|
||||
if (mode === 'create') {
|
||||
const result = await createMutation.mutateAsync(payload)
|
||||
@@ -129,15 +118,15 @@ export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProp
|
||||
|
||||
// ── Name fields per lang ───────────────────────────────────────────────────
|
||||
const nameFields: Record<Lang, { value: string; onChange: (v: string) => void; error?: string }> = {
|
||||
tk: { value: nameTk, onChange: setNameTk, error: errors.nameTk },
|
||||
ru: { value: nameRu, onChange: setNameRu, error: errors.nameRu },
|
||||
en: { value: nameEn, onChange: setNameEn, error: errors.nameEn },
|
||||
tk: { value: form.nameTk, onChange: set('nameTk'), error: errors.nameTk },
|
||||
ru: { value: form.nameRu, onChange: set('nameRu'), error: errors.nameRu },
|
||||
en: { value: form.nameEn, onChange: set('nameEn'), error: errors.nameEn },
|
||||
}
|
||||
|
||||
const notesFields: Record<Lang, { value: string; onChange: (v: string) => void }> = {
|
||||
tk: { value: notesTk, onChange: setNotesTk },
|
||||
ru: { value: notesRu, onChange: setNotesRu },
|
||||
en: { value: notesEn, onChange: setNotesEn },
|
||||
tk: { value: form.notesTk ?? '', onChange: set('notesTk') },
|
||||
ru: { value: form.notesRu ?? '', onChange: set('notesRu') },
|
||||
en: { value: form.notesEn ?? '', onChange: set('notesEn') },
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
@@ -187,8 +176,8 @@ export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProp
|
||||
</span>
|
||||
<FormInput
|
||||
type="number"
|
||||
value={tax}
|
||||
onChange={setTax}
|
||||
value={form.tax}
|
||||
onChange={set('tax')}
|
||||
placeholder={t('loanTypes.fields.tax', 'Salgyt')}
|
||||
error={errors.tax}
|
||||
/>
|
||||
@@ -202,8 +191,8 @@ export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProp
|
||||
</span>
|
||||
<FormInput
|
||||
type="number"
|
||||
value={loanTerm}
|
||||
onChange={setLoanTerm}
|
||||
value={form.loanTerm}
|
||||
onChange={set('loanTerm')}
|
||||
placeholder={t('loanTypes.fields.loanTerm', 'Karz möhleti')}
|
||||
error={errors.loanTerm}
|
||||
/>
|
||||
@@ -230,10 +219,11 @@ export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProp
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="isActive"
|
||||
checked={isActive}
|
||||
checked={form.isActive}
|
||||
onCheckedChange={(checked) => set('isActive')(!!checked)}
|
||||
/>
|
||||
<Label htmlFor="isActive" className="text-sm text-foreground cursor-pointer">
|
||||
{isActive
|
||||
{form.isActive
|
||||
? t('common.active', 'Işjeň')
|
||||
: t('common.inactive', 'Işjeň däl')}
|
||||
</Label>
|
||||
@@ -253,4 +243,4 @@ export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProp
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
47
src/features/loanTypes/schemas/loanType.schema.ts
Normal file
47
src/features/loanTypes/schemas/loanType.schema.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateLoanTypePayload } from '../api/loanTypesApi'
|
||||
|
||||
export const loanTypeFormSchema = z.object({
|
||||
nameTk: z.string().min(1, 'Hökmany meýdan'),
|
||||
nameRu: z.string().min(1, 'Hökmany meýdan'),
|
||||
nameEn: z.string().min(1, 'Hökmany meýdan'),
|
||||
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,
|
||||
'Oňyn san gerek',
|
||||
),
|
||||
loanTerm: z.string().refine(
|
||||
(v) => v.trim() !== '' && !isNaN(Number(v)) && Number(v) > 0,
|
||||
'Oňyn san gerek',
|
||||
),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
|
||||
export type LoanTypeFormData = z.infer<typeof loanTypeFormSchema>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: LoanTypeFormData = {
|
||||
nameTk: '',
|
||||
nameRu: '',
|
||||
nameEn: '',
|
||||
notesTk: '',
|
||||
notesRu: '',
|
||||
notesEn: '',
|
||||
tax: '',
|
||||
loanTerm: '',
|
||||
isActive: true,
|
||||
}
|
||||
|
||||
export function buildPayload(data: LoanTypeFormData): CreateLoanTypePayload {
|
||||
return {
|
||||
name: { tk: data.nameTk.trim(), ru: data.nameRu.trim(), en: data.nameEn.trim() },
|
||||
tax: Number(data.tax),
|
||||
loanTerm: Number(data.loanTerm),
|
||||
notes:
|
||||
(data.notesTk ?? '').trim() || (data.notesRu ?? '').trim() || (data.notesEn ?? '').trim()
|
||||
? { tk: (data.notesTk ?? '').trim(), ru: (data.notesRu ?? '').trim(), en: (data.notesEn ?? '').trim() }
|
||||
: null,
|
||||
isActive: data.isActive,
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,15 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useMemo } 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 { useCreateOperator, useUpdateOperator } from '../hooks/useOperators'
|
||||
import type { Operator, CreateOperatorPayload, UpdateOperatorPayload } from '../api/operatorsApi'
|
||||
import { operatorFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/operator.schema'
|
||||
import type { OperatorFormData } from '../schemas/operator.schema'
|
||||
import type { Operator } from '../api/operatorsApi'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -15,19 +19,17 @@ interface OperatorFormProps {
|
||||
operatorId?: number
|
||||
}
|
||||
|
||||
interface FormState {
|
||||
username: string
|
||||
name: string
|
||||
phone: string
|
||||
email: string
|
||||
password: string
|
||||
isActive: boolean
|
||||
}
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
interface FormErrors {
|
||||
username?: string
|
||||
name?: string
|
||||
password?: string
|
||||
type FlatErrors = Partial<Record<keyof OperatorFormData, 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 OperatorFormData] = msg
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ─── OperatorForm ─────────────────────────────────────────────────────────────
|
||||
@@ -41,76 +43,54 @@ export function OperatorForm({ mode, initialData, operatorId }: OperatorFormProp
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
// ── Form state ──────────────────────────────────────────────────────────────
|
||||
const [form, setForm] = useState<FormState>({
|
||||
username: '',
|
||||
name: '',
|
||||
phone: '',
|
||||
email: '',
|
||||
password: '',
|
||||
isActive: true,
|
||||
const schema = useMemo(() => operatorFormSchema(mode), [mode])
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
} = useForm<OperatorFormData>({
|
||||
resolver: zodResolver(schema as any),
|
||||
defaultValues: initialData
|
||||
? {
|
||||
...DEFAULT_FORM_VALUES,
|
||||
username: initialData.username,
|
||||
name: initialData.name,
|
||||
phone: initialData.phone ?? '',
|
||||
email: initialData.email ?? '',
|
||||
password: '',
|
||||
isActive: initialData.isActive,
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
|
||||
// Populate form in edit mode
|
||||
useEffect(() => {
|
||||
if (mode === 'edit' && initialData) {
|
||||
setForm({
|
||||
username: initialData.username ?? '',
|
||||
name: initialData.name ?? '',
|
||||
phone: initialData.phone ?? '',
|
||||
email: initialData.email ?? '',
|
||||
password: '',
|
||||
isActive: initialData.isActive ?? true,
|
||||
})
|
||||
}
|
||||
}, [mode, initialData])
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────────
|
||||
const set = (field: keyof FormState) => (value: string) =>
|
||||
setForm((prev) => ({ ...prev, [field]: value }))
|
||||
|
||||
const validate = (): boolean => {
|
||||
const next: FormErrors = {}
|
||||
if (!form.username.trim())
|
||||
next.username = t('operators.errors.usernameRequired', 'Ulanyjy ady hökmany')
|
||||
if (!form.name.trim())
|
||||
next.name = t('operators.errors.nameRequired', 'Ady hökmany')
|
||||
if (mode === 'create' && !form.password.trim())
|
||||
next.password = t('operators.errors.passwordRequired', 'Açar sözi hökmany')
|
||||
setErrors(next)
|
||||
return Object.keys(next).length === 0
|
||||
const setField = <K extends keyof OperatorFormData>(key: K, value: OperatorFormData[K]) => {
|
||||
;(setValue as (name: K, val: OperatorFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}
|
||||
|
||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
||||
const handleSubmit = () => {
|
||||
if (!validate()) return
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
|
||||
const data = getValues()
|
||||
|
||||
if (mode === 'create') {
|
||||
const payload: CreateOperatorPayload = {
|
||||
username: form.username.trim(),
|
||||
name: form.name.trim(),
|
||||
phone: form.phone.trim() || undefined,
|
||||
email: form.email.trim() || undefined,
|
||||
password: form.password,
|
||||
isActive: form.isActive,
|
||||
}
|
||||
const payload = buildPayload(data)
|
||||
createMutation.mutate(payload, {
|
||||
onSuccess: () => navigate('/operators'),
|
||||
})
|
||||
} else {
|
||||
const payload: UpdateOperatorPayload = {
|
||||
username: form.username.trim(),
|
||||
name: form.name.trim(),
|
||||
phone: form.phone.trim() || undefined,
|
||||
email: form.email.trim() || undefined,
|
||||
isActive: form.isActive,
|
||||
}
|
||||
if (form.password.trim()) {
|
||||
payload.password = form.password
|
||||
}
|
||||
updateMutation.mutate(payload, {
|
||||
updateMutation.mutate({
|
||||
username: data.username.trim(),
|
||||
name: data.name.trim(),
|
||||
phone: data.phone.trim() || undefined,
|
||||
email: data.email.trim() || undefined,
|
||||
isActive: data.isActive,
|
||||
...(data.password.trim() ? { password: data.password } : {}),
|
||||
}, {
|
||||
onSuccess: () => navigate(`/operators/${operatorId}`),
|
||||
})
|
||||
}
|
||||
@@ -128,7 +108,7 @@ export function OperatorForm({ mode, initialData, operatorId }: OperatorFormProp
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.username}
|
||||
onChange={set('username')}
|
||||
onChange={(v) => setField('username', v)}
|
||||
placeholder={t('operators.fields.username', 'Ulanyjy ady')}
|
||||
error={errors.username}
|
||||
disabled={isPending}
|
||||
@@ -145,7 +125,7 @@ export function OperatorForm({ mode, initialData, operatorId }: OperatorFormProp
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.name}
|
||||
onChange={set('name')}
|
||||
onChange={(v) => setField('name', v)}
|
||||
placeholder={t('operators.fields.name', 'Ady')}
|
||||
error={errors.name}
|
||||
disabled={isPending}
|
||||
@@ -161,7 +141,7 @@ export function OperatorForm({ mode, initialData, operatorId }: OperatorFormProp
|
||||
<FormInput
|
||||
type="phone"
|
||||
value={form.phone}
|
||||
onChange={set('phone')}
|
||||
onChange={(v) => setField('phone', v)}
|
||||
disabled={isPending}
|
||||
className="max-w-lg"
|
||||
/>
|
||||
@@ -175,7 +155,7 @@ export function OperatorForm({ mode, initialData, operatorId }: OperatorFormProp
|
||||
<FormInput
|
||||
type="email"
|
||||
value={form.email}
|
||||
onChange={set('email')}
|
||||
onChange={(v) => setField('email', v)}
|
||||
placeholder={t('operators.fields.email', 'E-poçta')}
|
||||
disabled={isPending}
|
||||
className="max-w-lg"
|
||||
@@ -192,7 +172,7 @@ export function OperatorForm({ mode, initialData, operatorId }: OperatorFormProp
|
||||
<FormInput
|
||||
type="password"
|
||||
value={form.password}
|
||||
onChange={set('password')}
|
||||
onChange={(v) => setField('password', v)}
|
||||
placeholder={
|
||||
mode === 'edit'
|
||||
? t('operators.fields.passwordEditHint', 'Üýtgetmek üçin täze açar söz giriziň')
|
||||
@@ -219,7 +199,7 @@ export function OperatorForm({ mode, initialData, operatorId }: OperatorFormProp
|
||||
</span>
|
||||
<Checkbox
|
||||
checked={form.isActive}
|
||||
onCheckedChange={(v) => setForm((prev) => ({ ...prev, isActive: !!v }))}
|
||||
onCheckedChange={(v) => setField('isActive', !!v)}
|
||||
disabled={isPending}
|
||||
className="data-[state=checked]:bg-primary data-[state=checked]:border-primary"
|
||||
/>
|
||||
@@ -237,4 +217,4 @@ export function OperatorForm({ mode, initialData, operatorId }: OperatorFormProp
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
41
src/features/operators/schemas/operator.schema.ts
Normal file
41
src/features/operators/schemas/operator.schema.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateOperatorPayload } from '../api/operatorsApi'
|
||||
|
||||
const baseSchema = z.object({
|
||||
username: z.string().min(1, 'Ulanyjy ady hökmany'),
|
||||
name: z.string().min(1, 'Ady hökmany'),
|
||||
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, 'Açar sözi hökmany'),
|
||||
})
|
||||
: baseSchema
|
||||
}
|
||||
|
||||
export type OperatorFormData = z.infer<typeof baseSchema>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: OperatorFormData = {
|
||||
username: '',
|
||||
name: '',
|
||||
phone: '',
|
||||
email: '',
|
||||
password: '',
|
||||
isActive: true,
|
||||
}
|
||||
|
||||
export function buildPayload(data: OperatorFormData): CreateOperatorPayload {
|
||||
return {
|
||||
username: data.username.trim(),
|
||||
name: data.name.trim(),
|
||||
phone: data.phone.trim() || undefined,
|
||||
email: data.email.trim() || undefined,
|
||||
password: data.password,
|
||||
isActive: data.isActive,
|
||||
}
|
||||
}
|
||||
@@ -158,7 +158,7 @@ export interface CreateCardOrderPayload {
|
||||
|
||||
export interface UpdateCardOrderPayload extends Partial<CreateCardOrderPayload> {}
|
||||
|
||||
import {apiClient} from '@/lib/api/client'
|
||||
import apiClient from '@/lib/api/client'
|
||||
|
||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
||||
const USE_MOCK = true
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useState, useCallback, useMemo, useEffect } from 'react'
|
||||
import { useState, useCallback, useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { toast } from 'sonner'
|
||||
import { CreditCard, User, FileText, Upload } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
@@ -21,6 +22,8 @@ import {
|
||||
useCreateCardOrder,
|
||||
useUpdateCardOrder,
|
||||
} from '../hooks/useOrderNewCard'
|
||||
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/orderNewCard.schema'
|
||||
import type { OrderNewCardFormData } from '../schemas/orderNewCard.schema'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -32,72 +35,17 @@ interface CardOrderFormProps {
|
||||
onCancel?: () => void
|
||||
}
|
||||
|
||||
interface FormState {
|
||||
isPaid: boolean
|
||||
status: CardOrderStatus | ''
|
||||
note: string
|
||||
issuanceReasonId: string
|
||||
cardTypeId: string
|
||||
provinceId: string
|
||||
branchId: string
|
||||
firstName: string
|
||||
lastName: string
|
||||
middleName: string
|
||||
formerLastName: string
|
||||
birthDate: string
|
||||
phone: string
|
||||
phoneExtra: string
|
||||
citizenship: string
|
||||
registeredAddress: string
|
||||
currentAddress: string
|
||||
workplace: string
|
||||
passportSeriesId: string
|
||||
passportNumber: string
|
||||
passportIssueDate: string
|
||||
passportIssuedBy: string
|
||||
passportBirthPlace: string
|
||||
passportPage1: File | null
|
||||
passportPage23: File | null
|
||||
passportPage89: File | null
|
||||
passportPage32: File | null
|
||||
termsAccepted: boolean
|
||||
}
|
||||
// ─── Form errors helper ──────────────────────────────────────────────────────
|
||||
|
||||
type FormErrors = Partial<Record<keyof FormState, string>>
|
||||
type FlatErrors = Partial<Record<keyof OrderNewCardFormData, string>>
|
||||
|
||||
// ─── Initial state ────────────────────────────────────────────────────────────
|
||||
|
||||
function getInitialState(data?: CardOrder): FormState {
|
||||
return {
|
||||
isPaid: data?.isPaid ?? false,
|
||||
status: data?.status ?? '',
|
||||
note: data?.note ?? '',
|
||||
issuanceReasonId: data?.issuanceReasonId ? String(data.issuanceReasonId) : '',
|
||||
cardTypeId: data?.cardTypeId ? String(data.cardTypeId) : '',
|
||||
provinceId: data?.provinceId ? String(data.provinceId) : '',
|
||||
branchId: data?.branchId ? String(data.branchId) : '',
|
||||
firstName: data?.firstName ?? '',
|
||||
lastName: data?.lastName ?? '',
|
||||
middleName: data?.middleName ?? '',
|
||||
formerLastName: data?.formerLastName ?? '',
|
||||
birthDate: data?.birthDate ?? '',
|
||||
phone: data?.phone ?? '',
|
||||
phoneExtra: data?.phoneExtra ?? '',
|
||||
citizenship: data?.citizenship ?? 'Turkmenistan',
|
||||
registeredAddress: data?.registeredAddress ?? '',
|
||||
currentAddress: data?.currentAddress ?? '',
|
||||
workplace: data?.workplace ?? '',
|
||||
passportSeriesId: data?.passportSeriesId ? String(data.passportSeriesId) : '',
|
||||
passportNumber: data?.passportNumber ?? '',
|
||||
passportIssueDate: data?.passportIssueDate ?? '',
|
||||
passportIssuedBy: data?.passportIssuedBy ?? '',
|
||||
passportBirthPlace: data?.passportBirthPlace ?? '',
|
||||
passportPage1: null,
|
||||
passportPage23: null,
|
||||
passportPage89: null,
|
||||
passportPage32: null,
|
||||
termsAccepted: false,
|
||||
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 OrderNewCardFormData] = msg
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ─── Step definitions ─────────────────────────────────────────────────────────
|
||||
@@ -108,7 +56,7 @@ interface StepDef {
|
||||
titleFallback: string
|
||||
subtitle: string
|
||||
icon: LucideIcon
|
||||
validate: (form: FormState, mode: 'create' | 'edit') => FormErrors
|
||||
validate: (form: OrderNewCardFormData, mode: 'create' | 'edit') => FlatErrors
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
@@ -118,15 +66,7 @@ const STEPS: StepDef[] = [
|
||||
titleFallback: 'Kart',
|
||||
subtitle: 'Görnüş & lokasiýa',
|
||||
icon: CreditCard,
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.status) e.status = 'Status — hökmany'
|
||||
if (!form.issuanceReasonId) e.issuanceReasonId = 'Kartyň çykarylmagynyň sebäbi — hökmany'
|
||||
if (!form.cardTypeId) e.cardTypeId = 'Kart görnüşi — hökmany'
|
||||
if (!form.provinceId) e.provinceId = 'Welaýat — hökmany'
|
||||
if (!form.branchId) e.branchId = 'Şahamça — hökmany'
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(0, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'personal',
|
||||
@@ -134,18 +74,7 @@ const STEPS: StepDef[] = [
|
||||
titleFallback: 'Şahsy',
|
||||
subtitle: 'Maglumatlar',
|
||||
icon: User,
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.firstName) e.firstName = 'Ady — hökmany'
|
||||
if (!form.lastName) e.lastName = 'Familiýasy — hökmany'
|
||||
if (!form.birthDate) e.birthDate = 'Doglan güni — hökmany'
|
||||
if (!form.phone) e.phone = 'Telefon — hökmany'
|
||||
if (!form.citizenship) e.citizenship = 'Raýatlyk — hökmany'
|
||||
if (!form.registeredAddress) e.registeredAddress = 'Ýazgy edilen salgy — hökmany'
|
||||
if (!form.currentAddress) e.currentAddress = 'Häzirki ýaşaýyş ýeri — hökmany'
|
||||
if (!form.workplace) e.workplace = 'Işleýän ýeri — hökmany'
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(1, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'passport',
|
||||
@@ -153,15 +82,7 @@ const STEPS: StepDef[] = [
|
||||
titleFallback: 'Pasport',
|
||||
subtitle: 'Resmi maglumat',
|
||||
icon: FileText,
|
||||
validate: (form) => {
|
||||
const e: FormErrors = {}
|
||||
if (!form.passportSeriesId) e.passportSeriesId = 'Pasport seriýasy — hökmany'
|
||||
if (!form.passportNumber) e.passportNumber = 'Pasport belgisi — hökmany'
|
||||
if (!form.passportIssueDate) e.passportIssueDate = 'Pasport berlen senesi — hökmany'
|
||||
if (!form.passportIssuedBy) e.passportIssuedBy = 'Kim tarapyndan berildi — hökmany'
|
||||
if (!form.passportBirthPlace) e.passportBirthPlace = 'Doglan ýeri — hökmany'
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(2, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'files',
|
||||
@@ -169,17 +90,7 @@ const STEPS: StepDef[] = [
|
||||
titleFallback: 'Faýllar',
|
||||
subtitle: 'Ýüklemek & Tassyklamak',
|
||||
icon: Upload,
|
||||
validate: (form, mode) => {
|
||||
const e: FormErrors = {}
|
||||
if (mode === 'create') {
|
||||
if (!form.passportPage1) e.passportPage1 = 'Pasport (sahypa 1) — hökmany'
|
||||
if (!form.passportPage23) e.passportPage23 = 'Pasport (2-3-nji sahypa) — hökmany'
|
||||
if (!form.passportPage89) e.passportPage89 = 'Pasport (8-9 sahypa) — hökmany'
|
||||
if (!form.passportPage32) e.passportPage32 = 'Pasport (32-nji sahypa) — hökmany'
|
||||
if (!form.termsAccepted) e.termsAccepted = 'Şertnama bilen razylaşmaly'
|
||||
}
|
||||
return e
|
||||
},
|
||||
validate: (form, mode) => validateStep(3, form, mode),
|
||||
},
|
||||
]
|
||||
|
||||
@@ -230,9 +141,9 @@ function BentoCard({
|
||||
// ─── Shared step content props ────────────────────────────────────────────────
|
||||
|
||||
interface StepContentProps {
|
||||
form: FormState
|
||||
errors: FormErrors
|
||||
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
|
||||
form: OrderNewCardFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof OrderNewCardFormData>(k: K, v: OrderNewCardFormData[K]) => void
|
||||
}
|
||||
|
||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||
@@ -642,17 +553,20 @@ export function CardOrderForm({
|
||||
const updateMutation = useUpdateCardOrder(cardOrderId ?? '')
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const [form, setForm] = useState<FormState>(() => getInitialState(initialData))
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors,
|
||||
} = useForm<OrderNewCardFormData>({
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
|
||||
const [currentStep, setCurrentStep] = useState(0)
|
||||
const [visited, setVisited] = useState<Set<number>>(
|
||||
() => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set<number>(),
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (initialData) setForm(getInitialState(initialData))
|
||||
}, [initialData])
|
||||
|
||||
// ── Lookup data ────────────────────────────────────────────────────────────
|
||||
|
||||
const { data: reasons = [] } = useCardIssuanceReasons()
|
||||
@@ -695,10 +609,10 @@ export function CardOrderForm({
|
||||
|
||||
// ── set helper ─────────────────────────────────────────────────────────────
|
||||
|
||||
const set = useCallback(<K extends keyof FormState>(key: K, value: FormState[K]) => {
|
||||
setForm((prev) => ({ ...prev, [key]: value }))
|
||||
setErrors((prev) => ({ ...prev, [key]: undefined }))
|
||||
}, [])
|
||||
const set = useCallback(<K extends keyof OrderNewCardFormData>(key: K, value: OrderNewCardFormData[K]) => {
|
||||
(setValue as (name: K, val: OrderNewCardFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
|
||||
const stepProps = useMemo(() => ({ form, errors, set }), [form, errors, set])
|
||||
|
||||
@@ -711,39 +625,38 @@ export function CardOrderForm({
|
||||
markVisited(currentStep)
|
||||
const errs = STEPS[currentStep].validate(form, mode)
|
||||
if (Object.keys(errs).length > 0) {
|
||||
setErrors(errs)
|
||||
toast.error(t('validation.fixErrors', 'Dogry maglumat girizmegiňizi haýyş edýäris.'))
|
||||
return
|
||||
}
|
||||
setErrors({})
|
||||
setCurrentStep(currentStep + 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
if (currentStep < STEPS.length - 1) {
|
||||
setCurrentStep(currentStep + 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
}
|
||||
|
||||
const handleBack = () => {
|
||||
markVisited(currentStep)
|
||||
setErrors({})
|
||||
setCurrentStep(currentStep - 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
if (currentStep > 0) {
|
||||
markVisited(currentStep)
|
||||
setCurrentStep(currentStep - 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
}
|
||||
|
||||
const handleGoTo = (i: number) => {
|
||||
markVisited(currentStep)
|
||||
setErrors({})
|
||||
setCurrentStep(i)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
|
||||
// ── Submit ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const doSubmit = async () => {
|
||||
setVisited(new Set(STEPS.map((_, i) => i)))
|
||||
|
||||
const allErrors: FormErrors = {}
|
||||
const allErrors: FlatErrors = {}
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode))
|
||||
|
||||
if (Object.keys(allErrors).length > 0) {
|
||||
setErrors(allErrors)
|
||||
toast.error(t('validation.fixErrors', '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) {
|
||||
@@ -754,35 +667,7 @@ export function CardOrderForm({
|
||||
return
|
||||
}
|
||||
|
||||
const payload = {
|
||||
isPaid: form.isPaid,
|
||||
status: form.status as CardOrderStatus,
|
||||
note: form.note || null,
|
||||
issuanceReasonId: Number(form.issuanceReasonId),
|
||||
cardTypeId: Number(form.cardTypeId),
|
||||
provinceId: Number(form.provinceId),
|
||||
branchId: Number(form.branchId),
|
||||
firstName: form.firstName,
|
||||
lastName: form.lastName,
|
||||
middleName: form.middleName || null,
|
||||
formerLastName: form.formerLastName || null,
|
||||
birthDate: form.birthDate,
|
||||
phone: form.phone,
|
||||
phoneExtra: form.phoneExtra || null,
|
||||
citizenship: form.citizenship,
|
||||
registeredAddress: form.registeredAddress,
|
||||
currentAddress: form.currentAddress,
|
||||
workplace: form.workplace,
|
||||
passportSeriesId: Number(form.passportSeriesId),
|
||||
passportNumber: form.passportNumber,
|
||||
passportIssueDate: form.passportIssueDate,
|
||||
passportIssuedBy: form.passportIssuedBy,
|
||||
passportBirthPlace: form.passportBirthPlace,
|
||||
...(form.passportPage1 && { passportPage1: form.passportPage1 }),
|
||||
...(form.passportPage23 && { passportPage23: form.passportPage23 }),
|
||||
...(form.passportPage89 && { passportPage89: form.passportPage89 }),
|
||||
...(form.passportPage32 && { passportPage32: form.passportPage32 }),
|
||||
}
|
||||
const payload = buildPayload(getValues())
|
||||
|
||||
try {
|
||||
if (mode === 'edit') {
|
||||
@@ -852,7 +737,7 @@ export function CardOrderForm({
|
||||
onPrev={currentStep > 0 ? handleBack : undefined}
|
||||
onNext={!isLastStep ? handleNext : undefined}
|
||||
showSubmit={isLastStep}
|
||||
onSubmit={isLastStep ? handleSubmit : undefined}
|
||||
onSubmit={isLastStep ? doSubmit : undefined}
|
||||
submitLabel={
|
||||
mode === 'create'
|
||||
? (t('cardOrder.submit') || 'Kart sargyt dörediň')
|
||||
@@ -865,4 +750,32 @@ export function CardOrderForm({
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function mapInitial(data: CardOrder): Partial<OrderNewCardFormData> {
|
||||
return {
|
||||
isPaid: data.isPaid,
|
||||
status: data.status,
|
||||
note: data.note ?? '',
|
||||
issuanceReasonId: String(data.issuanceReasonId),
|
||||
cardTypeId: String(data.cardTypeId),
|
||||
provinceId: String(data.provinceId),
|
||||
branchId: String(data.branchId),
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
middleName: data.middleName ?? '',
|
||||
formerLastName: data.formerLastName ?? '',
|
||||
birthDate: data.birthDate,
|
||||
phone: data.phone,
|
||||
phoneExtra: data.phoneExtra ?? '',
|
||||
citizenship: data.citizenship,
|
||||
registeredAddress: data.registeredAddress,
|
||||
currentAddress: data.currentAddress,
|
||||
workplace: data.workplace,
|
||||
passportSeriesId: String(data.passportSeriesId),
|
||||
passportNumber: data.passportNumber,
|
||||
passportIssueDate: data.passportIssueDate,
|
||||
passportIssuedBy: data.passportIssuedBy,
|
||||
passportBirthPlace: data.passportBirthPlace,
|
||||
}
|
||||
}
|
||||
138
src/features/orderNewCard/schemas/orderNewCard.schema.ts
Normal file
138
src/features/orderNewCard/schemas/orderNewCard.schema.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import { z } from 'zod'
|
||||
import type { CardOrderStatus } from '../api/orderNewCardApi'
|
||||
|
||||
const fileRequired = z.custom<File>((val) => val instanceof File, 'Faýl hökmany')
|
||||
|
||||
export const orderNewCardFormSchema = z.object({
|
||||
isPaid: z.boolean(),
|
||||
status: z.string().min(1, 'Status — hökmany'),
|
||||
note: z.string().optional(),
|
||||
issuanceReasonId: z.string().min(1, 'Kartyň çykarylmagynyň sebäbi — hökmany'),
|
||||
cardTypeId: z.string().min(1, 'Kart görnüşi — hökmany'),
|
||||
provinceId: z.string().min(1, 'Welaýat — hökmany'),
|
||||
branchId: z.string().min(1, 'Şahamça — hökmany'),
|
||||
firstName: z.string().min(1, 'Ady — hökmany'),
|
||||
lastName: z.string().min(1, 'Familiýasy — hökmany'),
|
||||
middleName: z.string().optional(),
|
||||
formerLastName: z.string().optional(),
|
||||
birthDate: z.string().min(1, 'Doglan güni — hökmany'),
|
||||
phone: z.string().min(1, 'Telefon — hökmany'),
|
||||
phoneExtra: z.string().optional(),
|
||||
citizenship: z.string().min(1, 'Raýatlyk — hökmany'),
|
||||
registeredAddress: z.string().min(1, 'Ýazgy edilen salgy — hökmany'),
|
||||
currentAddress: z.string().min(1, 'Häzirki ýaşaýyş ýeri — hökmany'),
|
||||
workplace: z.string().min(1, 'Işleýän ýeri — hökmany'),
|
||||
passportSeriesId: z.string().min(1, 'Pasport seriýasy — hökmany'),
|
||||
passportNumber: z.string().min(1, 'Pasport belgisi — hökmany'),
|
||||
passportIssueDate: z.string().min(1, 'Pasport berlen senesi — hökmany'),
|
||||
passportIssuedBy: z.string().min(1, 'Kim tarapyndan berildi — hökmany'),
|
||||
passportBirthPlace: z.string().min(1, 'Doglan ýeri — hökmany'),
|
||||
passportPage1: z.custom<File | null>().nullable(),
|
||||
passportPage23: z.custom<File | null>().nullable(),
|
||||
passportPage89: z.custom<File | null>().nullable(),
|
||||
passportPage32: z.custom<File | null>().nullable(),
|
||||
termsAccepted: z.boolean(),
|
||||
})
|
||||
|
||||
export type OrderNewCardFormData = z.infer<typeof orderNewCardFormSchema>
|
||||
|
||||
export const stepSchemas: Record<number, z.ZodType<Partial<OrderNewCardFormData>>> = {
|
||||
0: orderNewCardFormSchema.pick({
|
||||
status: true, issuanceReasonId: true, cardTypeId: true, provinceId: true, branchId: true,
|
||||
}),
|
||||
1: orderNewCardFormSchema.pick({
|
||||
firstName: true, lastName: true, birthDate: true, phone: true, citizenship: true,
|
||||
registeredAddress: true, currentAddress: true, workplace: true,
|
||||
}),
|
||||
2: orderNewCardFormSchema.pick({
|
||||
passportSeriesId: true, passportNumber: true, passportIssueDate: true,
|
||||
passportIssuedBy: true, passportBirthPlace: true,
|
||||
}),
|
||||
3: z.object({
|
||||
passportPage1: fileRequired,
|
||||
passportPage23: fileRequired,
|
||||
passportPage89: fileRequired,
|
||||
passportPage32: fileRequired,
|
||||
termsAccepted: z.literal(true, { message: 'Şertnama bilen razylaşmaly' }),
|
||||
}),
|
||||
}
|
||||
|
||||
export function validateStep(
|
||||
stepIndex: number,
|
||||
form: OrderNewCardFormData,
|
||||
mode: 'create' | 'edit',
|
||||
): Partial<Record<keyof OrderNewCardFormData, string>> {
|
||||
if (stepIndex === 3 && mode === 'edit') return {}
|
||||
const schema = stepSchemas[stepIndex]
|
||||
const result = schema.safeParse(form)
|
||||
if (result.success) return {}
|
||||
const errors: Partial<Record<keyof OrderNewCardFormData, string>> = {}
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof OrderNewCardFormData
|
||||
if (!errors[key]) errors[key] = issue.message
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
export const DEFAULT_FORM_VALUES: OrderNewCardFormData = {
|
||||
isPaid: false,
|
||||
status: '',
|
||||
note: '',
|
||||
issuanceReasonId: '',
|
||||
cardTypeId: '',
|
||||
provinceId: '',
|
||||
branchId: '',
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
middleName: '',
|
||||
formerLastName: '',
|
||||
birthDate: '',
|
||||
phone: '',
|
||||
phoneExtra: '',
|
||||
citizenship: 'Turkmenistan',
|
||||
registeredAddress: '',
|
||||
currentAddress: '',
|
||||
workplace: '',
|
||||
passportSeriesId: '',
|
||||
passportNumber: '',
|
||||
passportIssueDate: '',
|
||||
passportIssuedBy: '',
|
||||
passportBirthPlace: '',
|
||||
passportPage1: null,
|
||||
passportPage23: null,
|
||||
passportPage89: null,
|
||||
passportPage32: null,
|
||||
termsAccepted: false,
|
||||
}
|
||||
|
||||
export function buildPayload(data: OrderNewCardFormData) {
|
||||
return {
|
||||
isPaid: data.isPaid,
|
||||
status: data.status as CardOrderStatus,
|
||||
note: data.note || null,
|
||||
issuanceReasonId: Number(data.issuanceReasonId),
|
||||
cardTypeId: Number(data.cardTypeId),
|
||||
provinceId: Number(data.provinceId),
|
||||
branchId: Number(data.branchId),
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
middleName: data.middleName || null,
|
||||
formerLastName: data.formerLastName || null,
|
||||
birthDate: data.birthDate,
|
||||
phone: data.phone,
|
||||
phoneExtra: data.phoneExtra || null,
|
||||
citizenship: data.citizenship,
|
||||
registeredAddress: data.registeredAddress,
|
||||
currentAddress: data.currentAddress,
|
||||
workplace: data.workplace,
|
||||
passportSeriesId: Number(data.passportSeriesId),
|
||||
passportNumber: data.passportNumber,
|
||||
passportIssueDate: data.passportIssueDate,
|
||||
passportIssuedBy: data.passportIssuedBy,
|
||||
passportBirthPlace: data.passportBirthPlace,
|
||||
...(data.passportPage1 && { passportPage1: data.passportPage1 }),
|
||||
...(data.passportPage23 && { passportPage23: data.passportPage23 }),
|
||||
...(data.passportPage89 && { passportPage89: data.passportPage89 }),
|
||||
...(data.passportPage32 && { passportPage32: data.passportPage32 }),
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, useMemo, 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 { useEditor, EditorContent } from '@tiptap/react'
|
||||
import StarterKit from '@tiptap/starter-kit'
|
||||
import Link from '@tiptap/extension-link'
|
||||
@@ -23,7 +25,9 @@ import { cn } from '@/lib/utils'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { useCreateRequiredDocument, useUpdateRequiredDocument } from '../hooks/useRequiredDocuments'
|
||||
import type { LoanDocument, LoanDocumentPayload, LoanDocumentTranslation } from '../api/requiredDocumentsApi'
|
||||
import { requiredDocumentFormSchema, DEFAULT_FORM_VALUES, buildPayload, mapInitial } from '../schemas/requiredDocument.schema'
|
||||
import type { RequiredDocumentFormData } from '../schemas/requiredDocument.schema'
|
||||
import type { LoanDocument, LoanDocumentTranslation } from '../api/requiredDocumentsApi'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -166,9 +170,31 @@ function LangTabs({ active, onChange }: LangTabsProps) {
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Empty translation ────────────────────────────────────────────────────────
|
||||
// ─── Error helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
const emptyTranslation = (): LoanDocumentTranslation => ({ tk: '', ru: '', en: '' })
|
||||
type LegacyErrorKey = `name_${Locale}` | `desc_${Locale}`
|
||||
|
||||
const RHF_TO_LEGACY_KEY: Record<string, LegacyErrorKey> = {
|
||||
nameTk: 'name_tk',
|
||||
nameRu: 'name_ru',
|
||||
nameEn: 'name_en',
|
||||
descTk: 'desc_tk',
|
||||
descRu: 'desc_ru',
|
||||
descEn: 'desc_en',
|
||||
}
|
||||
|
||||
function flattenErrors(
|
||||
errors: Record<string, { message?: string } | undefined>,
|
||||
): Partial<Record<LegacyErrorKey, string>> {
|
||||
const result: Partial<Record<LegacyErrorKey, string>> = {}
|
||||
for (const [key, err] of Object.entries(errors)) {
|
||||
const legacyKey = RHF_TO_LEGACY_KEY[key]
|
||||
if (legacyKey && err?.message) {
|
||||
result[legacyKey] = err.message
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ─── RequiredDocumentForm ─────────────────────────────────────────────────────────
|
||||
|
||||
@@ -176,57 +202,78 @@ export function RequiredDocumentForm({ mode, initialData, requiredDocumentId }:
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
// Per-field locale tabs
|
||||
// Per-field locale tabs (UI only, not form state)
|
||||
const [nameLang, setNameLang] = useState<Locale>('tk')
|
||||
const [descLang, setDescLang] = useState<Locale>('tk')
|
||||
|
||||
// Form state
|
||||
const [name, setName] = useState<LoanDocumentTranslation>(
|
||||
initialData?.name ?? emptyTranslation()
|
||||
)
|
||||
const [description, setDescription] = useState<LoanDocumentTranslation>(
|
||||
initialData?.description ?? emptyTranslation()
|
||||
)
|
||||
|
||||
// Errors
|
||||
const [errors, setErrors] = useState<Partial<Record<`name_${Locale}` | `desc_${Locale}`, string>>>({})
|
||||
|
||||
// Sync initial data on edit mode load
|
||||
useEffect(() => {
|
||||
if (initialData) {
|
||||
setName(initialData.name)
|
||||
setDescription(initialData.description)
|
||||
}
|
||||
}, [initialData])
|
||||
|
||||
const createMutation = useCreateRequiredDocument()
|
||||
const updateMutation = useUpdateRequiredDocument(requiredDocumentId ?? 0)
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
// ── Validation ──────────────────────────────────────────────────────────────
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
trigger,
|
||||
} = useForm<RequiredDocumentFormData>({
|
||||
resolver: zodResolver(requiredDocumentFormSchema),
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
const validate = (): boolean => {
|
||||
const errs: typeof errors = {}
|
||||
LOCALES.forEach(({ code }) => {
|
||||
if (!name[code].trim()) {
|
||||
errs[`name_${code}`] = t('validation.required', 'Bu meýdan hökmany')
|
||||
}
|
||||
if (!description[code].replace(/<[^>]*>/g, '').trim()) {
|
||||
errs[`desc_${code}`] = t('validation.required', 'Bu meýdan hökmany')
|
||||
}
|
||||
})
|
||||
setErrors(errs)
|
||||
return Object.keys(errs).length === 0
|
||||
}
|
||||
const form = watch()
|
||||
const errors = useMemo(
|
||||
() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>),
|
||||
[rhfErrors],
|
||||
)
|
||||
|
||||
// Derive LoanDocumentTranslation objects so the JSX stays unchanged
|
||||
const name: LoanDocumentTranslation = useMemo(
|
||||
() => ({ tk: form.nameTk, ru: form.nameRu, en: form.nameEn }),
|
||||
[form.nameTk, form.nameRu, form.nameEn],
|
||||
)
|
||||
|
||||
const description: LoanDocumentTranslation = useMemo(
|
||||
() => ({ tk: form.descTk, ru: form.descRu, en: form.descEn }),
|
||||
[form.descTk, form.descRu, form.descEn],
|
||||
)
|
||||
|
||||
// Functional setter that matches React's useState(prev => …) signature
|
||||
const setName = useCallback(
|
||||
(updater: (prev: LoanDocumentTranslation) => LoanDocumentTranslation) => {
|
||||
const current = getValues()
|
||||
const prev: LoanDocumentTranslation = { tk: current.nameTk, ru: current.nameRu, en: current.nameEn }
|
||||
const next = updater(prev)
|
||||
setValue('nameTk', next.tk)
|
||||
setValue('nameRu', next.ru)
|
||||
setValue('nameEn', next.en)
|
||||
},
|
||||
[setValue, getValues],
|
||||
)
|
||||
|
||||
const setDescription = useCallback(
|
||||
(updater: (prev: LoanDocumentTranslation) => LoanDocumentTranslation) => {
|
||||
const current = getValues()
|
||||
const prev: LoanDocumentTranslation = { tk: current.descTk, ru: current.descRu, en: current.descEn }
|
||||
const next = updater(prev)
|
||||
setValue('descTk', next.tk)
|
||||
setValue('descRu', next.ru)
|
||||
setValue('descEn', next.en)
|
||||
},
|
||||
[setValue, getValues],
|
||||
)
|
||||
|
||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = async (e?: React.FormEvent) => {
|
||||
e?.preventDefault()
|
||||
if (!validate()) return
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
|
||||
const payload: LoanDocumentPayload = { name, description }
|
||||
const payload = buildPayload(getValues())
|
||||
|
||||
if (mode === 'create') {
|
||||
await createMutation.mutateAsync(payload)
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { z } from 'zod'
|
||||
import type { LoanDocument, LoanDocumentPayload } from '../api/requiredDocumentsApi'
|
||||
|
||||
export const requiredDocumentFormSchema = z.object({
|
||||
nameTk: z.string().min(1, 'Hökmany meýdan'),
|
||||
nameRu: z.string().min(1, 'Hökmany meýdan'),
|
||||
nameEn: z.string().min(1, 'Hökmany meýdan'),
|
||||
descTk: z.string().min(1, 'Hökmany meýdan'),
|
||||
descRu: z.string().min(1, 'Hökmany meýdan'),
|
||||
descEn: z.string().min(1, 'Hökmany meýdan'),
|
||||
})
|
||||
|
||||
export type RequiredDocumentFormData = z.infer<typeof requiredDocumentFormSchema>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: RequiredDocumentFormData = {
|
||||
nameTk: '',
|
||||
nameRu: '',
|
||||
nameEn: '',
|
||||
descTk: '',
|
||||
descRu: '',
|
||||
descEn: '',
|
||||
}
|
||||
|
||||
export function buildPayload(data: RequiredDocumentFormData): LoanDocumentPayload {
|
||||
return {
|
||||
name: { tk: data.nameTk.trim(), ru: data.nameRu.trim(), en: data.nameEn.trim() },
|
||||
description: { tk: data.descTk.trim(), ru: data.descRu.trim(), en: data.descEn.trim() },
|
||||
}
|
||||
}
|
||||
|
||||
export function mapInitial(data: LoanDocument): RequiredDocumentFormData {
|
||||
return {
|
||||
nameTk: data.name.tk,
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
descTk: data.description.tk,
|
||||
descRu: data.description.ru,
|
||||
descEn: data.description.en,
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import { User, MapPin, IdCard, CreditCard, Files } from 'lucide-react'
|
||||
|
||||
@@ -16,9 +17,14 @@ import {
|
||||
SAHAMCALAR,
|
||||
STATUSES,
|
||||
type SberPaymentOrder,
|
||||
type SberPaymentFormData,
|
||||
type PaymentStatus,
|
||||
} from '@/features/sberPayments/api/sberPaymentsApi'
|
||||
import {
|
||||
validateStep,
|
||||
DEFAULT_FORM_VALUES,
|
||||
buildPayload,
|
||||
type SberPaymentFormData,
|
||||
} from '@/features/sberPayments/schemas/sberPayment.schema'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -28,6 +34,19 @@ interface SberPaymentFormProps {
|
||||
orderId?: string
|
||||
}
|
||||
|
||||
type FlatErrors = Partial<Record<keyof SberPaymentFormData, string>>
|
||||
|
||||
// ─── Flatten RHF errors ──────────────────────────────────────────────────────
|
||||
|
||||
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 SberPaymentFormData] = msg
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ─── Document lists ───────────────────────────────────────────────────────────
|
||||
|
||||
type AcceptedDocKey =
|
||||
@@ -60,95 +79,6 @@ const SENT_DOCS: { key: SentDocKey; label: string }[] = [
|
||||
]
|
||||
|
||||
|
||||
// ─── FormState ────────────────────────────────────────────────────────────────
|
||||
|
||||
interface FormState extends SberPaymentFormData {
|
||||
client_id: string
|
||||
// file fields
|
||||
acc_sberbank_card: File | null
|
||||
acc_enrollment: File | null
|
||||
acc_summons: File | null
|
||||
acc_passport_tm: File | null
|
||||
acc_zagran_passport: File | null
|
||||
acc_visa_page: File | null
|
||||
acc_entry_stamp: File | null
|
||||
acc_school_letter: File | null
|
||||
snt_passport_tm: File | null
|
||||
snt_zagran_passport: File | null
|
||||
snt_entry_stamp: File | null
|
||||
snt_relation_doc: File | null
|
||||
snt_new_passport_series: File | null
|
||||
snt_old_passport_series: File | null
|
||||
}
|
||||
|
||||
type FormErrors = Partial<Record<keyof FormState, string>>
|
||||
|
||||
// ─── Default state ────────────────────────────────────────────────────────────
|
||||
|
||||
const defaultState: FormState = {
|
||||
client_id: '',
|
||||
welayat: '',
|
||||
sahamca: '',
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
phone: '',
|
||||
email: '',
|
||||
address: '',
|
||||
status: 'GARASYLYYAR',
|
||||
bellik: '',
|
||||
accountNumber: '',
|
||||
passportSeries: '',
|
||||
passportNumber: '',
|
||||
fullName: '',
|
||||
acc_sberbank_card: null,
|
||||
acc_enrollment: null,
|
||||
acc_summons: null,
|
||||
acc_passport_tm: null,
|
||||
acc_zagran_passport: null,
|
||||
acc_visa_page: null,
|
||||
acc_entry_stamp: null,
|
||||
acc_school_letter: null,
|
||||
snt_passport_tm: null,
|
||||
snt_zagran_passport: null,
|
||||
snt_entry_stamp: null,
|
||||
snt_relation_doc: null,
|
||||
snt_new_passport_series: null,
|
||||
snt_old_passport_series: null,
|
||||
}
|
||||
|
||||
// ─── Step definitions ─────────────────────────────────────────────────────────
|
||||
|
||||
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 STEP_REQUIRED: Partial<Record<StepId, (keyof FormState)[]>> = {
|
||||
general: ['status'],
|
||||
location: ['welayat', 'sahamca'],
|
||||
personal: ['firstName', 'lastName', 'phone', 'address'],
|
||||
payment: ['passportSeries', 'passportNumber', 'fullName', 'accountNumber'],
|
||||
}
|
||||
|
||||
const ERROR_LABELS: Partial<Record<keyof FormState, string>> = {
|
||||
status: 'Status hökmany',
|
||||
welayat: 'Welaýat hökmany',
|
||||
sahamca: 'Şahamça hökmany',
|
||||
firstName: 'Ady hökmany',
|
||||
lastName: 'Familiýasy hökmany',
|
||||
phone: 'Telefon hökmany',
|
||||
address: 'Salgy hökmany',
|
||||
passportSeries:'Pasport seriýasy hökmany',
|
||||
passportNumber:'Pasport nomeri hökmany',
|
||||
fullName: 'Doly ady hökmany',
|
||||
accountNumber: 'Goýum hasaby hökmany',
|
||||
}
|
||||
|
||||
// ─── Bento primitives ─────────────────────────────────────────────────────────
|
||||
|
||||
function BentoGrid({ cols = 2, children }: { cols?: 1 | 2; children: React.ReactNode }) {
|
||||
@@ -189,9 +119,9 @@ function BentoCard({
|
||||
function StepGeneral({
|
||||
form, errors, set,
|
||||
}: {
|
||||
form: FormState
|
||||
errors: FormErrors
|
||||
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
|
||||
form: SberPaymentFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||
}) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
@@ -236,9 +166,9 @@ function StepGeneral({
|
||||
function StepLocation({
|
||||
form, errors, set,
|
||||
}: {
|
||||
form: FormState
|
||||
errors: FormErrors
|
||||
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
|
||||
form: SberPaymentFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||
}) {
|
||||
const branches = form.welayat ? (SAHAMCALAR[form.welayat] ?? []) : []
|
||||
|
||||
@@ -280,9 +210,9 @@ function StepLocation({
|
||||
function StepPersonal({
|
||||
form, errors, set,
|
||||
}: {
|
||||
form: FormState
|
||||
errors: FormErrors
|
||||
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
|
||||
form: SberPaymentFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||
}) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
@@ -343,9 +273,9 @@ function StepPersonal({
|
||||
function StepPayment({
|
||||
form, errors, set,
|
||||
}: {
|
||||
form: FormState
|
||||
errors: FormErrors
|
||||
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
|
||||
form: SberPaymentFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||
}) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
@@ -403,8 +333,8 @@ function StepPayment({
|
||||
function StepDocs({
|
||||
form, set,
|
||||
}: {
|
||||
form: FormState
|
||||
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
|
||||
form: SberPaymentFormData
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||
}) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
@@ -441,6 +371,38 @@ function StepDocs({
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Step definitions ─────────────────────────────────────────────────────────
|
||||
|
||||
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' },
|
||||
]
|
||||
|
||||
// ─── Initial data mapper ──────────────────────────────────────────────────────
|
||||
|
||||
function mapInitialData(data: SberPaymentOrder): Partial<SberPaymentFormData> {
|
||||
return {
|
||||
welayat: data.welayat,
|
||||
sahamca: data.sahamca,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
phone: data.phone,
|
||||
email: data.email,
|
||||
address: data.address,
|
||||
status: data.status,
|
||||
bellik: data.bellik,
|
||||
accountNumber: data.accountNumber,
|
||||
passportSeries: data.passportSeries,
|
||||
passportNumber: data.passportNumber,
|
||||
fullName: data.fullName,
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Main component ───────────────────────────────────────────────────────────
|
||||
|
||||
export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormProps) {
|
||||
@@ -449,58 +411,36 @@ export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormP
|
||||
const updateMutation = useUpdateSberPayment()
|
||||
const isLoading = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const [form, setForm] = useState<FormState>(defaultState)
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors,
|
||||
} = useForm<SberPaymentFormData>({
|
||||
defaultValues: mode === 'edit' && initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitialData(initialData) }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
|
||||
const [currentStep, setCurrentStep] = useState(0)
|
||||
const [stepStatuses, setStepStatuses] = useState<StepStatus[]>(
|
||||
STEPS.map((_, i) => (i === 0 ? 'active' : 'idle')),
|
||||
() => mode === 'edit'
|
||||
? STEPS.map((_, i) => (i === 0 ? 'active' : i < 4 ? 'done' : 'idle'))
|
||||
: STEPS.map((_, i) => (i === 0 ? 'active' : 'idle')),
|
||||
)
|
||||
|
||||
// ── Populate in edit mode ──
|
||||
useEffect(() => {
|
||||
if (mode === 'edit' && initialData) {
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
welayat: initialData.welayat,
|
||||
sahamca: initialData.sahamca,
|
||||
firstName: initialData.firstName,
|
||||
lastName: initialData.lastName,
|
||||
phone: initialData.phone,
|
||||
email: initialData.email,
|
||||
address: initialData.address,
|
||||
status: initialData.status,
|
||||
bellik: initialData.bellik,
|
||||
accountNumber: initialData.accountNumber,
|
||||
passportSeries: initialData.passportSeries,
|
||||
passportNumber: initialData.passportNumber,
|
||||
fullName: initialData.fullName,
|
||||
}))
|
||||
// Let user jump freely to any step in edit mode
|
||||
setStepStatuses(STEPS.map((_, i) => (i === 0 ? 'active' : i < 4 ? 'done' : 'idle')))
|
||||
}
|
||||
}, [mode, initialData])
|
||||
|
||||
// ── Field setter ──
|
||||
const set = <K extends keyof FormState>(key: K, value: FormState[K]) => {
|
||||
setForm((prev) => ({ ...prev, [key]: value }))
|
||||
if (errors[key]) setErrors((prev) => ({ ...prev, [key]: undefined }))
|
||||
const set = <K extends keyof SberPaymentFormData>(key: K, value: SberPaymentFormData[K]) => {
|
||||
(setValue as (name: K, val: SberPaymentFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}
|
||||
|
||||
// ── Step validation ──
|
||||
const validateStep = (stepId: StepId): FormErrors => {
|
||||
const fields = STEP_REQUIRED[stepId] ?? []
|
||||
const errs: FormErrors = {}
|
||||
fields.forEach((f) => {
|
||||
if (!form[f]) errs[f] = ERROR_LABELS[f] ?? 'Hökmany'
|
||||
})
|
||||
return errs
|
||||
}
|
||||
|
||||
const validateAll = (): FormErrors => {
|
||||
const errs: FormErrors = {}
|
||||
Object.entries(ERROR_LABELS).forEach(([k, msg]) => {
|
||||
if (!form[k as keyof FormState]) errs[k as keyof FormState] = msg
|
||||
})
|
||||
const doValidateAll = (): FlatErrors => {
|
||||
const errs: FlatErrors = {}
|
||||
for (let i = 0; i <= 3; i++) {
|
||||
Object.assign(errs, validateStep(i, form, mode))
|
||||
}
|
||||
return errs
|
||||
}
|
||||
|
||||
@@ -518,15 +458,13 @@ export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormP
|
||||
}
|
||||
return next
|
||||
})
|
||||
setErrors({})
|
||||
clearErrors()
|
||||
setCurrentStep(idx)
|
||||
}
|
||||
|
||||
const handleNext = () => {
|
||||
const stepId = STEPS[currentStep].id
|
||||
const stepErrors = validateStep(stepId)
|
||||
const stepErrors = validateStep(currentStep, form, mode)
|
||||
if (Object.keys(stepErrors).length > 0) {
|
||||
setErrors(stepErrors)
|
||||
setStepStatuses((prev) => {
|
||||
const next = [...prev]; next[currentStep] = 'error'; return next
|
||||
})
|
||||
@@ -541,28 +479,13 @@ export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormP
|
||||
|
||||
// ── Submit ──
|
||||
const handleSubmit = async () => {
|
||||
const allErrors = validateAll()
|
||||
const allErrors = doValidateAll()
|
||||
if (Object.keys(allErrors).length > 0) {
|
||||
setErrors(allErrors)
|
||||
toast.error('Meýdanlary dolduryň')
|
||||
return
|
||||
}
|
||||
try {
|
||||
const payload: SberPaymentFormData = {
|
||||
welayat: form.welayat,
|
||||
sahamca: form.sahamca,
|
||||
firstName: form.firstName,
|
||||
lastName: form.lastName,
|
||||
phone: form.phone,
|
||||
email: form.email,
|
||||
address: form.address,
|
||||
status: form.status,
|
||||
bellik: form.bellik,
|
||||
accountNumber: form.accountNumber,
|
||||
passportSeries: form.passportSeries,
|
||||
passportNumber: form.passportNumber,
|
||||
fullName: form.fullName,
|
||||
}
|
||||
const payload = buildPayload(getValues())
|
||||
if (mode === 'create') {
|
||||
await createMutation.mutateAsync(payload)
|
||||
toast.success('Töleg üstünlikli döredildi')
|
||||
@@ -628,4 +551,4 @@ export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormP
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
126
src/features/sberPayments/schemas/sberPayment.schema.ts
Normal file
126
src/features/sberPayments/schemas/sberPayment.schema.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateSberPaymentPayload, PaymentStatus } from '@/features/sberPayments/api/sberPaymentsApi'
|
||||
|
||||
// ─── File helper ─────────────────────────────────────────────────────
|
||||
|
||||
const fileField = z.custom<File | null>((val) => val === null || val instanceof File).nullable()
|
||||
|
||||
// ─── Full form schema ─────────────────────────────────────────────────
|
||||
|
||||
export const sberPaymentFormSchema = z.object({
|
||||
// From SberPaymentFormData
|
||||
welayat: z.string().min(1, 'Welaýat hökmany'),
|
||||
sahamca: z.string().min(1, 'Şahamça hökmany'),
|
||||
firstName: z.string().min(1, 'Ady hökmany'),
|
||||
lastName: z.string().min(1, 'Familiýasy hökmany'),
|
||||
phone: z.string().min(1, 'Telefon hökmany'),
|
||||
email: z.string(),
|
||||
address: z.string().min(1, 'Salgy hökmany'),
|
||||
status: z.string().min(1, 'Status hökmany'),
|
||||
bellik: z.string(),
|
||||
accountNumber: z.string().min(1, 'Goýum hasaby hökmany'),
|
||||
passportSeries: z.string().min(1, 'Pasport seriýasy hökmany'),
|
||||
passportNumber: z.string().min(1, 'Pasport nomeri hökmany'),
|
||||
fullName: z.string().min(1, 'Doly ady hökmany'),
|
||||
// Client id
|
||||
client_id: z.string().optional(),
|
||||
// File fields
|
||||
acc_sberbank_card: fileField,
|
||||
acc_enrollment: fileField,
|
||||
acc_summons: fileField,
|
||||
acc_passport_tm: fileField,
|
||||
acc_zagran_passport: fileField,
|
||||
acc_visa_page: fileField,
|
||||
acc_entry_stamp: fileField,
|
||||
acc_school_letter: fileField,
|
||||
snt_passport_tm: fileField,
|
||||
snt_zagran_passport: fileField,
|
||||
snt_entry_stamp: fileField,
|
||||
snt_relation_doc: fileField,
|
||||
snt_new_passport_series: fileField,
|
||||
snt_old_passport_series: fileField,
|
||||
})
|
||||
|
||||
export type SberPaymentFormData = z.infer<typeof sberPaymentFormSchema>
|
||||
|
||||
// ─── Step schemas ─────────────────────────────────────────────────────
|
||||
|
||||
export const stepSchemas: Record<number, z.ZodType<Partial<SberPaymentFormData>>> = {
|
||||
0: sberPaymentFormSchema.pick({ status: true }),
|
||||
1: sberPaymentFormSchema.pick({ welayat: true, sahamca: true }),
|
||||
2: sberPaymentFormSchema.pick({ firstName: true, lastName: true, phone: true, address: true }),
|
||||
3: sberPaymentFormSchema.pick({ passportSeries: true, passportNumber: true, fullName: true, accountNumber: true }),
|
||||
}
|
||||
|
||||
// ─── validateStep ─────────────────────────────────────────────────────
|
||||
|
||||
export function validateStep(
|
||||
stepIndex: number,
|
||||
form: SberPaymentFormData,
|
||||
mode: 'create' | 'edit',
|
||||
): Partial<Record<keyof SberPaymentFormData, string>> {
|
||||
void mode
|
||||
const schema = stepSchemas[stepIndex]
|
||||
if (!schema) return {}
|
||||
const result = schema.safeParse(form)
|
||||
if (result.success) return {}
|
||||
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
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
// ─── Default values ───────────────────────────────────────────────────
|
||||
|
||||
export const DEFAULT_FORM_VALUES: SberPaymentFormData = {
|
||||
client_id: '',
|
||||
welayat: '',
|
||||
sahamca: '',
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
phone: '',
|
||||
email: '',
|
||||
address: '',
|
||||
status: 'GARASYLYYAR',
|
||||
bellik: '',
|
||||
accountNumber: '',
|
||||
passportSeries: '',
|
||||
passportNumber: '',
|
||||
fullName: '',
|
||||
acc_sberbank_card: null,
|
||||
acc_enrollment: null,
|
||||
acc_summons: null,
|
||||
acc_passport_tm: null,
|
||||
acc_zagran_passport: null,
|
||||
acc_visa_page: null,
|
||||
acc_entry_stamp: null,
|
||||
acc_school_letter: null,
|
||||
snt_passport_tm: null,
|
||||
snt_zagran_passport: null,
|
||||
snt_entry_stamp: null,
|
||||
snt_relation_doc: null,
|
||||
snt_new_passport_series: null,
|
||||
snt_old_passport_series: null,
|
||||
}
|
||||
|
||||
// ─── buildPayload ─────────────────────────────────────────────────────
|
||||
|
||||
export function buildPayload(data: SberPaymentFormData): CreateSberPaymentPayload {
|
||||
return {
|
||||
welayat: data.welayat,
|
||||
sahamca: data.sahamca,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
phone: data.phone,
|
||||
email: data.email,
|
||||
address: data.address,
|
||||
status: data.status as PaymentStatus,
|
||||
bellik: data.bellik,
|
||||
accountNumber: data.accountNumber,
|
||||
passportSeries: data.passportSeries,
|
||||
passportNumber: data.passportNumber,
|
||||
fullName: data.fullName,
|
||||
}
|
||||
}
|
||||
@@ -1,151 +1,151 @@
|
||||
import { apiClient } from '@/lib/api/client'
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export type IntlPaymentStatus = 'pending' | 'approved' | 'rejected'
|
||||
export type CurrencyType = 'visa' | 'mastercard'
|
||||
export type IntlPaymentStatus = "pending" | "approved" | "rejected";
|
||||
export type CurrencyType = "visa" | "mastercard";
|
||||
|
||||
export interface IntlPaymentItem {
|
||||
id: string
|
||||
client_id: string
|
||||
client_label: string
|
||||
currency_type: CurrencyType
|
||||
currency_type_label: string
|
||||
created_at: string
|
||||
province: string
|
||||
province_label: string
|
||||
branch: string
|
||||
branch_label: string
|
||||
status: IntlPaymentStatus
|
||||
note: string | null
|
||||
id: string;
|
||||
client_id: string;
|
||||
client_label: string;
|
||||
currency_type: CurrencyType;
|
||||
currency_type_label: string;
|
||||
created_at: string;
|
||||
province: string;
|
||||
province_label: string;
|
||||
branch: string;
|
||||
branch_label: string;
|
||||
status: IntlPaymentStatus;
|
||||
note: string | null;
|
||||
|
||||
// Şahsy maglumatlar
|
||||
passport_first_name: string
|
||||
passport_last_name: string
|
||||
phone: string
|
||||
email: string | null
|
||||
home_address: string | null
|
||||
passport_first_name: string;
|
||||
passport_last_name: string;
|
||||
phone: string;
|
||||
email: string | null;
|
||||
home_address: string | null;
|
||||
|
||||
// Töleg upgradyjynyň maglumatlary
|
||||
passport_series: string
|
||||
passport_number: string
|
||||
payer_full_name: string
|
||||
payer_account_number: string
|
||||
passport_series: string;
|
||||
passport_number: string;
|
||||
payer_full_name: string;
|
||||
payer_account_number: string;
|
||||
|
||||
// Töleg kabul edijiniň maglumatlary
|
||||
receiver_info: string
|
||||
receiver_info: string;
|
||||
|
||||
// Kabul ediji talyp boyunca resminamalar (9 sany)
|
||||
doc_sberbank_account: string | null // file url
|
||||
doc_school_enrollment: string | null
|
||||
doc_summons: string | null
|
||||
doc_passport_tm: string | null
|
||||
doc_foreign_passport: string | null
|
||||
doc_foreign_passport_copy: string | null
|
||||
doc_exit_permission: string | null
|
||||
doc_school_foreign_info: string | null
|
||||
doc_school_departure_info: string | null
|
||||
doc_sberbank_account: string | null; // file url
|
||||
doc_school_enrollment: string | null;
|
||||
doc_summons: string | null;
|
||||
doc_passport_tm: string | null;
|
||||
doc_foreign_passport: string | null;
|
||||
doc_foreign_passport_copy: string | null;
|
||||
doc_exit_permission: string | null;
|
||||
doc_school_foreign_info: string | null;
|
||||
doc_school_departure_info: string | null;
|
||||
|
||||
// Upgradyý boyunca resminamalar (6 sany)
|
||||
upd_doc_passport_tm: string | null
|
||||
upd_doc_foreign_passport: string | null
|
||||
upd_doc_visa: string | null
|
||||
upd_doc_acceptance_letter: string | null
|
||||
upd_doc_passport_biometric: string | null
|
||||
upd_doc_passport_old: string | null
|
||||
upd_doc_passport_tm: string | null;
|
||||
upd_doc_foreign_passport: string | null;
|
||||
upd_doc_visa: string | null;
|
||||
upd_doc_acceptance_letter: string | null;
|
||||
upd_doc_passport_biometric: string | null;
|
||||
upd_doc_passport_old: string | null;
|
||||
|
||||
created_by: string
|
||||
created_by_label: string
|
||||
created_by: string;
|
||||
created_by_label: string;
|
||||
}
|
||||
|
||||
export interface IntlPaymentListParams {
|
||||
page?: number
|
||||
per_page?: number
|
||||
search?: string
|
||||
status?: IntlPaymentStatus | ''
|
||||
month?: string
|
||||
province?: string
|
||||
page?: number;
|
||||
per_page?: number;
|
||||
search?: string;
|
||||
status?: IntlPaymentStatus | "";
|
||||
month?: string;
|
||||
province?: string;
|
||||
}
|
||||
|
||||
export interface IntlPaymentListResponse {
|
||||
data: IntlPaymentItem[]
|
||||
data: IntlPaymentItem[];
|
||||
meta: {
|
||||
current_page: number
|
||||
last_page: number
|
||||
per_page: number
|
||||
total: number
|
||||
}
|
||||
current_page: number;
|
||||
last_page: number;
|
||||
per_page: number;
|
||||
total: number;
|
||||
};
|
||||
}
|
||||
|
||||
export type IntlPaymentCreatePayload = {
|
||||
client_id: string
|
||||
status: IntlPaymentStatus
|
||||
note: string
|
||||
currency_type: CurrencyType
|
||||
province: string
|
||||
branch: string
|
||||
client_id: string;
|
||||
status: IntlPaymentStatus;
|
||||
note: string;
|
||||
currency_type: CurrencyType;
|
||||
province: string;
|
||||
branch: string;
|
||||
|
||||
passport_first_name: string
|
||||
passport_last_name: string
|
||||
phone: string
|
||||
email: string
|
||||
home_address: string
|
||||
passport_first_name: string;
|
||||
passport_last_name: string;
|
||||
phone: string;
|
||||
email: string;
|
||||
home_address: string;
|
||||
|
||||
passport_series: string
|
||||
passport_number: string
|
||||
payer_full_name: string
|
||||
payer_account_number: string
|
||||
passport_series: string;
|
||||
passport_number: string;
|
||||
payer_full_name: string;
|
||||
payer_account_number: string;
|
||||
|
||||
receiver_info: string
|
||||
receiver_info: string;
|
||||
|
||||
// kabul ediji docs
|
||||
doc_sberbank_account: File | null
|
||||
doc_school_enrollment: File | null
|
||||
doc_summons: File | null
|
||||
doc_passport_tm: File | null
|
||||
doc_foreign_passport: File | null
|
||||
doc_foreign_passport_copy: File | null
|
||||
doc_exit_permission: File | null
|
||||
doc_school_foreign_info: File | null
|
||||
doc_school_departure_info: File | null
|
||||
doc_sberbank_account: File | null;
|
||||
doc_school_enrollment: File | null;
|
||||
doc_summons: File | null;
|
||||
doc_passport_tm: File | null;
|
||||
doc_foreign_passport: File | null;
|
||||
doc_foreign_passport_copy: File | null;
|
||||
doc_exit_permission: File | null;
|
||||
doc_school_foreign_info: File | null;
|
||||
doc_school_departure_info: File | null;
|
||||
|
||||
// upgradyý docs
|
||||
upd_doc_passport_tm: File | null
|
||||
upd_doc_foreign_passport: File | null
|
||||
upd_doc_visa: File | null
|
||||
upd_doc_acceptance_letter: File | null
|
||||
upd_doc_passport_biometric: File | null
|
||||
upd_doc_passport_old: File | null
|
||||
}
|
||||
upd_doc_passport_tm: File | null;
|
||||
upd_doc_foreign_passport: File | null;
|
||||
upd_doc_visa: File | null;
|
||||
upd_doc_acceptance_letter: File | null;
|
||||
upd_doc_passport_biometric: File | null;
|
||||
upd_doc_passport_old: File | null;
|
||||
};
|
||||
|
||||
export type IntlPaymentUpdatePayload = IntlPaymentCreatePayload
|
||||
export type IntlPaymentUpdatePayload = IntlPaymentCreatePayload;
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_INTL_PAYMENTS: IntlPaymentItem[] = [
|
||||
{
|
||||
id: '1',
|
||||
client_id: '1',
|
||||
client_label: 'Jelaletdin',
|
||||
currency_type: 'visa',
|
||||
currency_type_label: 'Visa',
|
||||
created_at: '2024-05-07 12:00',
|
||||
province: 'ashgabat',
|
||||
province_label: 'Aşgabat',
|
||||
branch: '1',
|
||||
branch_label: 'Merkezi şahamça',
|
||||
status: 'pending',
|
||||
note: 'Test sargyt',
|
||||
passport_first_name: 'Aman',
|
||||
passport_last_name: 'Amanow',
|
||||
phone: '99365123456',
|
||||
email: 'aman@example.com',
|
||||
home_address: 'Aşgabat ş., Magtymguly şaýoly 1',
|
||||
passport_series: 'I-MR',
|
||||
passport_number: '123456',
|
||||
payer_full_name: 'Aman Amanow',
|
||||
payer_account_number: '1234567890123456',
|
||||
receiver_info: 'Test Receiver',
|
||||
id: "1",
|
||||
client_id: "1",
|
||||
client_label: "Jelaletdin",
|
||||
currency_type: "visa",
|
||||
currency_type_label: "Visa",
|
||||
created_at: "2024-05-07 12:00",
|
||||
province: "ashgabat",
|
||||
province_label: "Aşgabat",
|
||||
branch: "1",
|
||||
branch_label: "Merkezi şahamça",
|
||||
status: "pending",
|
||||
note: "Test sargyt",
|
||||
passport_first_name: "Aman",
|
||||
passport_last_name: "Amanow",
|
||||
phone: "99365123456",
|
||||
email: "aman@example.com",
|
||||
home_address: "Aşgabat ş., Magtymguly şaýoly 1",
|
||||
passport_series: "I-MR",
|
||||
passport_number: "123456",
|
||||
payer_full_name: "Aman Amanow",
|
||||
payer_account_number: "1234567890123456",
|
||||
receiver_info: "Test Receiver",
|
||||
doc_sberbank_account: null,
|
||||
doc_school_enrollment: null,
|
||||
doc_summons: null,
|
||||
@@ -161,10 +161,10 @@ const MOCK_INTL_PAYMENTS: IntlPaymentItem[] = [
|
||||
upd_doc_acceptance_letter: null,
|
||||
upd_doc_passport_biometric: null,
|
||||
upd_doc_passport_old: null,
|
||||
created_by: '1',
|
||||
created_by_label: 'Admin',
|
||||
created_by: "1",
|
||||
created_by_label: "Admin",
|
||||
},
|
||||
]
|
||||
];
|
||||
|
||||
export const intlPaymentApi = {
|
||||
list: async (params: IntlPaymentListParams): Promise<IntlPaymentListResponse> => {
|
||||
@@ -175,70 +175,91 @@ export const intlPaymentApi = {
|
||||
last_page: 1,
|
||||
per_page: params.per_page || 25,
|
||||
total: MOCK_INTL_PAYMENTS.length,
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
const { data } = await apiClient.get('/intl-payments/visa-master', { params })
|
||||
return data
|
||||
const { data } = await apiClient.get("/intl-payments/visa-master", { params });
|
||||
return data;
|
||||
},
|
||||
|
||||
getById: async (id: string): Promise<IntlPaymentItem> => {
|
||||
const mock = MOCK_INTL_PAYMENTS.find(p => p.id === id)
|
||||
if (mock) return mock
|
||||
const mock = MOCK_INTL_PAYMENTS.find((p) => p.id === id);
|
||||
if (mock) return mock;
|
||||
|
||||
const { data } = await apiClient.get(`/intl-payments/visa-master/${id}`)
|
||||
return data
|
||||
const { data } = await apiClient.get(`/intl-payments/visa-master/${id}`);
|
||||
return data;
|
||||
},
|
||||
|
||||
create: (payload: IntlPaymentCreatePayload): Promise<IntlPaymentItem> => {
|
||||
const form = buildFormData(payload)
|
||||
const form = buildFormData(payload);
|
||||
return apiClient
|
||||
.post('/intl-payments/visa-master', form, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
.post("/intl-payments/visa-master", form, {
|
||||
headers: { "Content-Type": "multipart/form-data" },
|
||||
})
|
||||
.then((r) => r.data)
|
||||
.then((r) => r.data);
|
||||
},
|
||||
|
||||
update: (id: string, payload: IntlPaymentUpdatePayload): Promise<IntlPaymentItem> => {
|
||||
const form = buildFormData(payload)
|
||||
form.append('_method', 'PUT')
|
||||
const form = buildFormData(payload);
|
||||
form.append("_method", "PUT");
|
||||
return apiClient
|
||||
.post(`/intl-payments/visa-master/${id}`, form, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
headers: { "Content-Type": "multipart/form-data" },
|
||||
})
|
||||
.then((r) => r.data)
|
||||
.then((r) => r.data);
|
||||
},
|
||||
|
||||
delete: (id: string): Promise<void> =>
|
||||
apiClient.delete(`/intl-payments/visa-master/${id}`).then((r) => r.data),
|
||||
}
|
||||
delete: (id: string): Promise<void> => apiClient.delete(`/intl-payments/visa-master/${id}`).then((r) => r.data),
|
||||
};
|
||||
|
||||
// ─── Helper ───────────────────────────────────────────────────────────────────
|
||||
|
||||
const TEXT_FIELDS: (keyof IntlPaymentCreatePayload)[] = [
|
||||
'client_id', 'status', 'note', 'currency_type', 'province', 'branch',
|
||||
'passport_first_name', 'passport_last_name', 'phone', 'email', 'home_address',
|
||||
'passport_series', 'passport_number', 'payer_full_name', 'payer_account_number',
|
||||
'receiver_info',
|
||||
]
|
||||
"client_id",
|
||||
"status",
|
||||
"note",
|
||||
"currency_type",
|
||||
"province",
|
||||
"branch",
|
||||
"passport_first_name",
|
||||
"passport_last_name",
|
||||
"phone",
|
||||
"email",
|
||||
"home_address",
|
||||
"passport_series",
|
||||
"passport_number",
|
||||
"payer_full_name",
|
||||
"payer_account_number",
|
||||
"receiver_info",
|
||||
];
|
||||
|
||||
const FILE_FIELDS: (keyof IntlPaymentCreatePayload)[] = [
|
||||
'doc_sberbank_account', 'doc_school_enrollment', 'doc_summons',
|
||||
'doc_passport_tm', 'doc_foreign_passport', 'doc_foreign_passport_copy',
|
||||
'doc_exit_permission', 'doc_school_foreign_info', 'doc_school_departure_info',
|
||||
'upd_doc_passport_tm', 'upd_doc_foreign_passport', 'upd_doc_visa',
|
||||
'upd_doc_acceptance_letter', 'upd_doc_passport_biometric', 'upd_doc_passport_old',
|
||||
]
|
||||
"doc_sberbank_account",
|
||||
"doc_school_enrollment",
|
||||
"doc_summons",
|
||||
"doc_passport_tm",
|
||||
"doc_foreign_passport",
|
||||
"doc_foreign_passport_copy",
|
||||
"doc_exit_permission",
|
||||
"doc_school_foreign_info",
|
||||
"doc_school_departure_info",
|
||||
"upd_doc_passport_tm",
|
||||
"upd_doc_foreign_passport",
|
||||
"upd_doc_visa",
|
||||
"upd_doc_acceptance_letter",
|
||||
"upd_doc_passport_biometric",
|
||||
"upd_doc_passport_old",
|
||||
];
|
||||
|
||||
function buildFormData(payload: IntlPaymentCreatePayload): FormData {
|
||||
const form = new FormData()
|
||||
const form = new FormData();
|
||||
for (const key of TEXT_FIELDS) {
|
||||
const val = payload[key]
|
||||
if (val !== null && val !== undefined) form.append(key, String(val))
|
||||
const val = payload[key];
|
||||
if (val !== null && val !== undefined) form.append(key, String(val));
|
||||
}
|
||||
for (const key of FILE_FIELDS) {
|
||||
const file = payload[key]
|
||||
if (file instanceof File) form.append(key, file)
|
||||
const file = payload[key];
|
||||
if (file instanceof File) form.append(key, file);
|
||||
}
|
||||
return form
|
||||
return form;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { z } from 'zod'
|
||||
import type { IntlPaymentCreatePayload, IntlPaymentStatus, CurrencyType } from '../api/visaMasterPaymentsApi'
|
||||
|
||||
const fileField = z.custom<File | null>().nullable()
|
||||
|
||||
export const visaMasterPaymentFormSchema = z.object({
|
||||
client_id: z.string().min(1, 'Ulanyjy hökmany'),
|
||||
status: z.string().min(1, 'Status hökmany'),
|
||||
note: z.string().optional().default(''),
|
||||
currency_type: z.string().min(1, 'Ýüztumanyň görnüşi hökmany'),
|
||||
province: z.string().min(1, 'Welaýat hökmany'),
|
||||
branch: z.string().min(1, 'Şahamça hökmany'),
|
||||
passport_first_name: z.string().min(1, 'Ady hökmany'),
|
||||
passport_last_name: z.string().min(1, 'Familiýasy hökmany'),
|
||||
phone: z.string().min(1, 'Telefon hökmany'),
|
||||
email: z.string().optional().default(''),
|
||||
home_address: z.string().optional().default(''),
|
||||
passport_series: z.string().min(1, 'Pasport seriýasy hökmany'),
|
||||
passport_number: z.string().min(1, 'Pasport nomeri hökmany'),
|
||||
payer_full_name: z.string().min(1, 'Doly ady hökmany'),
|
||||
payer_account_number: z.string().min(1, 'Goşun hasaby hökmany'),
|
||||
receiver_info: z.string().min(1, 'Kabul edijiniň maglumatlary hökmany'),
|
||||
doc_sberbank_account: fileField,
|
||||
doc_school_enrollment: fileField,
|
||||
doc_summons: fileField,
|
||||
doc_passport_tm: fileField,
|
||||
doc_foreign_passport: fileField,
|
||||
doc_foreign_passport_copy: fileField,
|
||||
doc_exit_permission: fileField,
|
||||
doc_school_foreign_info: fileField,
|
||||
doc_school_departure_info: fileField,
|
||||
upd_doc_passport_tm: fileField,
|
||||
upd_doc_foreign_passport: fileField,
|
||||
upd_doc_visa: fileField,
|
||||
upd_doc_acceptance_letter: fileField,
|
||||
upd_doc_passport_biometric: fileField,
|
||||
upd_doc_passport_old: fileField,
|
||||
})
|
||||
|
||||
export type IntlPaymentFormData = z.infer<typeof visaMasterPaymentFormSchema>
|
||||
|
||||
export const stepSchemas: Record<number, z.ZodType<Partial<IntlPaymentFormData>>> = {
|
||||
0: visaMasterPaymentFormSchema.pick({ client_id: true, status: true, currency_type: true }),
|
||||
1: visaMasterPaymentFormSchema.pick({ province: true, branch: true }),
|
||||
2: visaMasterPaymentFormSchema.pick({ passport_first_name: true, passport_last_name: true, phone: true }),
|
||||
3: visaMasterPaymentFormSchema.pick({
|
||||
passport_series: true, passport_number: true,
|
||||
payer_full_name: true, payer_account_number: true, receiver_info: true,
|
||||
}),
|
||||
4: z.object({}),
|
||||
}
|
||||
|
||||
export function validateStep(
|
||||
stepIndex: number,
|
||||
form: IntlPaymentFormData,
|
||||
mode: 'create' | 'edit',
|
||||
): Partial<Record<keyof IntlPaymentFormData, string>> {
|
||||
void mode
|
||||
const schema = stepSchemas[stepIndex]
|
||||
const result = schema.safeParse(form)
|
||||
if (result.success) return {}
|
||||
const errors: Partial<Record<keyof IntlPaymentFormData, string>> = {}
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof IntlPaymentFormData
|
||||
if (!errors[key]) errors[key] = issue.message
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
export const DEFAULT_FORM_VALUES: IntlPaymentFormData = {
|
||||
client_id: '', status: 'pending', note: '', currency_type: '',
|
||||
province: '', branch: '',
|
||||
passport_first_name: '', passport_last_name: '', phone: '',
|
||||
email: '', home_address: '',
|
||||
passport_series: '', passport_number: '',
|
||||
payer_full_name: '', payer_account_number: '', receiver_info: '',
|
||||
doc_sberbank_account: null, doc_school_enrollment: null,
|
||||
doc_summons: null, doc_passport_tm: null,
|
||||
doc_foreign_passport: null, doc_foreign_passport_copy: null,
|
||||
doc_exit_permission: null, doc_school_foreign_info: null,
|
||||
doc_school_departure_info: null,
|
||||
upd_doc_passport_tm: null, upd_doc_foreign_passport: null,
|
||||
upd_doc_visa: null, upd_doc_acceptance_letter: null,
|
||||
upd_doc_passport_biometric: null, upd_doc_passport_old: null,
|
||||
}
|
||||
|
||||
export function buildPayload(data: IntlPaymentFormData): IntlPaymentCreatePayload {
|
||||
return {
|
||||
...data,
|
||||
status: data.status as IntlPaymentStatus,
|
||||
currency_type: data.currency_type as CurrencyType,
|
||||
}
|
||||
}
|
||||
@@ -1,54 +1,51 @@
|
||||
// features/visaMasterSettings/components/VisaMasterSettingForm.tsx
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useCallback, useMemo } 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 { type VisaMasterSetting } from '../api/visaMasterSberSettingsApi'
|
||||
import type { VisaMasterSetting } from '../api/visaMasterSberSettingsApi'
|
||||
import {
|
||||
useCreateVisaMasterSetting,
|
||||
useUpdateVisaMasterSetting,
|
||||
} from '../hooks/useVisaMasterSettings'
|
||||
import {
|
||||
visaMasterSettingFormSchema,
|
||||
DEFAULT_FORM_VALUES,
|
||||
buildPayload,
|
||||
} from '../schemas/visaMasterSberSetting.schema'
|
||||
import type { VisaMasterSettingFormData } from '../schemas/visaMasterSberSetting.schema'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface FormState {
|
||||
kod: string
|
||||
ady: string
|
||||
yazgy: string
|
||||
}
|
||||
|
||||
interface FormErrors {
|
||||
kod?: string
|
||||
ady?: string
|
||||
yazgy?: string
|
||||
}
|
||||
|
||||
export interface VisaMasterSettingFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: VisaMasterSetting
|
||||
settingId?: number
|
||||
}
|
||||
|
||||
// ─── Validation ───────────────────────────────────────────────────────────────
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function validate(
|
||||
form: FormState,
|
||||
t: (key: string, fallback: string) => string
|
||||
): FormErrors {
|
||||
const errors: FormErrors = {}
|
||||
function mapInitial(data: VisaMasterSetting): VisaMasterSettingFormData {
|
||||
return {
|
||||
kod: data.kod,
|
||||
ady: data.ady,
|
||||
yazgy: data.yazgy,
|
||||
}
|
||||
}
|
||||
|
||||
if (!form.kod.trim())
|
||||
errors.kod = t('visaMasterSettings.errors.kodRequired', 'Kod giriziň')
|
||||
type FlatErrors = Partial<Record<keyof VisaMasterSettingFormData, string>>
|
||||
|
||||
if (!form.ady.trim())
|
||||
errors.ady = t('visaMasterSettings.errors.adyRequired', 'Ady giriziň')
|
||||
|
||||
if (!form.yazgy.trim())
|
||||
errors.yazgy = t('visaMasterSettings.errors.yazgyRequired', 'Yazgy giriziň')
|
||||
|
||||
return errors
|
||||
function flattenErrors(
|
||||
errors: Record<string, { message?: string } | undefined>
|
||||
): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof VisaMasterSettingFormData] = msg
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ─── VisaMasterSettingForm ────────────────────────────────────────────────────
|
||||
@@ -61,42 +58,44 @@ export function VisaMasterSettingForm({
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const [form, setForm] = useState<FormState>({
|
||||
kod: initialData?.kod ?? '',
|
||||
ady: initialData?.ady ?? '',
|
||||
yazgy: initialData?.yazgy ?? '',
|
||||
})
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
|
||||
const createMutation = useCreateVisaMasterSetting()
|
||||
const updateMutation = useUpdateVisaMasterSetting(settingId ?? 0)
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
// Sync when initialData arrives (edit mode async fetch)
|
||||
useEffect(() => {
|
||||
if (mode === 'edit' && initialData) {
|
||||
setForm({
|
||||
kod: initialData.kod,
|
||||
ady: initialData.ady,
|
||||
yazgy: initialData.yazgy,
|
||||
})
|
||||
}
|
||||
}, [mode, initialData])
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
trigger,
|
||||
getValues,
|
||||
} = useForm<VisaMasterSettingFormData>({
|
||||
resolver: zodResolver(visaMasterSettingFormSchema),
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
|
||||
const setField = (field: keyof FormState) => (val: string) => {
|
||||
setForm((prev) => ({ ...prev, [field]: val }))
|
||||
if (errors[field]) setErrors((prev) => ({ ...prev, [field]: undefined }))
|
||||
}
|
||||
const form = watch()
|
||||
const errors = useMemo(
|
||||
() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>),
|
||||
[rhfErrors],
|
||||
)
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const validationErrors = validate(form, t)
|
||||
if (Object.keys(validationErrors).length > 0) {
|
||||
setErrors(validationErrors)
|
||||
return
|
||||
}
|
||||
const set = useCallback(
|
||||
(key: keyof VisaMasterSettingFormData) => (value: string) => {
|
||||
setValue(key, value)
|
||||
clearErrors(key)
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
)
|
||||
|
||||
const payload = { kod: form.kod.trim(), ady: form.ady.trim(), yazgy: form.yazgy.trim() }
|
||||
const handleSubmit = useCallback(async () => {
|
||||
const isValid = await trigger()
|
||||
if (!isValid) return
|
||||
|
||||
const payload = buildPayload(getValues())
|
||||
|
||||
if (mode === 'create') {
|
||||
await createMutation.mutateAsync(payload)
|
||||
@@ -105,7 +104,7 @@ export function VisaMasterSettingForm({
|
||||
await updateMutation.mutateAsync(payload)
|
||||
navigate('/resources/visa-master-settings')
|
||||
}
|
||||
}
|
||||
}, [mode, createMutation, updateMutation, navigate, trigger, getValues])
|
||||
|
||||
const handleCancel = () => navigate('/resources/visa-master-settings')
|
||||
|
||||
@@ -122,7 +121,7 @@ export function VisaMasterSettingForm({
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.kod}
|
||||
onChange={setField('kod')}
|
||||
onChange={set('kod')}
|
||||
placeholder={t('visaMasterSettings.fields.kod', 'Kod')}
|
||||
error={errors.kod}
|
||||
disabled={isPending}
|
||||
@@ -138,7 +137,7 @@ export function VisaMasterSettingForm({
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.ady}
|
||||
onChange={setField('ady')}
|
||||
onChange={set('ady')}
|
||||
placeholder={t('visaMasterSettings.fields.ady', 'Ady')}
|
||||
error={errors.ady}
|
||||
disabled={isPending}
|
||||
@@ -154,7 +153,7 @@ export function VisaMasterSettingForm({
|
||||
<FormInput
|
||||
type="textarea"
|
||||
value={form.yazgy}
|
||||
onChange={setField('yazgy')}
|
||||
onChange={set('yazgy')}
|
||||
placeholder={t('visaMasterSettings.fields.yazgy', 'Yazgy')}
|
||||
error={errors.yazgy}
|
||||
disabled={isPending}
|
||||
@@ -174,4 +173,4 @@ export function VisaMasterSettingForm({
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { z } from 'zod'
|
||||
import type { VisaMasterSettingPayload } from '../api/visaMasterSberSettingsApi'
|
||||
|
||||
export const visaMasterSettingFormSchema = z.object({
|
||||
kod: z.string().min(1, 'Hökmany meýdan'),
|
||||
ady: z.string().min(1, 'Hökmany meýdan'),
|
||||
yazgy: z.string().min(1, 'Hökmany meýdan'),
|
||||
})
|
||||
|
||||
export type VisaMasterSettingFormData = z.infer<typeof visaMasterSettingFormSchema>
|
||||
|
||||
export const DEFAULT_FORM_VALUES: VisaMasterSettingFormData = {
|
||||
kod: '',
|
||||
ady: '',
|
||||
yazgy: '',
|
||||
}
|
||||
|
||||
export function buildPayload(data: VisaMasterSettingFormData): VisaMasterSettingPayload {
|
||||
return {
|
||||
kod: data.kod.trim(),
|
||||
ady: data.ady.trim(),
|
||||
yazgy: data.yazgy.trim(),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user