added lang support to create pages
This commit is contained in:
1 parent
35164d16d3
commit
a0ed9a702c
34 files changed
+1456
-639
No files matched your search
@@ -1,4 +1,4 @@
|
|||||||
import { useMemo } from 'react'
|
import { useMemo, useEffect, useCallback } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from 'react-hook-form'
|
||||||
@@ -36,7 +36,11 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
|||||||
// ─── UserForm ─────────────────────────────────────────────────────────────────
|
// ─── UserForm ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function UserForm({ mode, initialData, userId }: UserFormProps) {
|
export function UserForm({ mode, initialData, userId }: UserFormProps) {
|
||||||
const { t } = useTranslation()
|
const { t: _t, i18n } = useTranslation()
|
||||||
|
const t: (key: string, fallback?: string) => string = useCallback(
|
||||||
|
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||||
|
[_t],
|
||||||
|
)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const createUser = useCreateUser()
|
const createUser = useCreateUser()
|
||||||
@@ -44,7 +48,7 @@ export function UserForm({ mode, initialData, userId }: UserFormProps) {
|
|||||||
|
|
||||||
const isPending = createUser.isPending || updateUser.isPending
|
const isPending = createUser.isPending || updateUser.isPending
|
||||||
|
|
||||||
const schema = useMemo(() => allUserFormSchema(mode), [mode])
|
const schema = useMemo(() => allUserFormSchema(mode, t), [mode, t, i18n.language])
|
||||||
|
|
||||||
const {
|
const {
|
||||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||||
@@ -72,6 +76,14 @@ export function UserForm({ mode, initialData, userId }: UserFormProps) {
|
|||||||
clearErrors(key)
|
clearErrors(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Re-validate on language change ──
|
||||||
|
useEffect(() => {
|
||||||
|
if (Object.keys(rhfErrors).length > 0) {
|
||||||
|
trigger()
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [i18n.language])
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
const isValid = await trigger()
|
const isValid = await trigger()
|
||||||
if (!isValid) return
|
if (!isValid) return
|
||||||
|
|||||||
@@ -1,39 +1,39 @@
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import i18next from 'i18next'
|
|
||||||
import type { CreateUserPayload } from '../api/allUsersApi'
|
import type { CreateUserPayload } from '../api/allUsersApi'
|
||||||
|
|
||||||
const t = i18next.t.bind(i18next)
|
export function allUserFormSchema(
|
||||||
|
mode: 'create' | 'edit',
|
||||||
|
t: (key: string, fallback?: string) => string,
|
||||||
|
) {
|
||||||
|
const baseSchema = z.object({
|
||||||
|
username: z.string()
|
||||||
|
.min(1, t('validation.required', 'validation.required'))
|
||||||
|
.min(3, t('validation.minLength', 'validation.minLength')),
|
||||||
|
name: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
phone: z.string()
|
||||||
|
.min(1, t('validation.required', 'validation.required'))
|
||||||
|
.regex(/^\d[\d\s-]{6,}$/, t('validation.invalidPhone', 'validation.invalidPhone')),
|
||||||
|
email: z.string()
|
||||||
|
.refine(
|
||||||
|
(v) => !v || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),
|
||||||
|
t('validation.invalidEmail', 'validation.invalidEmail'),
|
||||||
|
)
|
||||||
|
.default(''),
|
||||||
|
password: z.string(),
|
||||||
|
phoneVerified: z.boolean(),
|
||||||
|
isActive: z.boolean(),
|
||||||
|
})
|
||||||
|
|
||||||
const baseSchema = z.object({
|
|
||||||
username: z.string()
|
|
||||||
.min(1, t('validation.required', 'Ulanyjy ady hökmany'))
|
|
||||||
.min(3, t('validation.minLength', 'Ulanyjy ady iň az 3 harp bolmaly')),
|
|
||||||
name: z.string().min(1, t('validation.required', 'Ady hökmany')),
|
|
||||||
phone: z.string()
|
|
||||||
.min(1, t('validation.required', 'Telefon hökmany'))
|
|
||||||
.regex(/^\d[\d\s-]{6,}$/, t('validation.invalidPhone', 'Nädogry telefon formaty')),
|
|
||||||
email: z.string()
|
|
||||||
.refine(
|
|
||||||
(v) => !v || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),
|
|
||||||
t('validation.invalidEmail', 'Nädogry e-poçta formaty'),
|
|
||||||
)
|
|
||||||
.default(''),
|
|
||||||
password: z.string(),
|
|
||||||
phoneVerified: z.boolean(),
|
|
||||||
isActive: z.boolean(),
|
|
||||||
})
|
|
||||||
|
|
||||||
export function allUserFormSchema(mode: 'create' | 'edit') {
|
|
||||||
return mode === 'create'
|
return mode === 'create'
|
||||||
? baseSchema.extend({
|
? baseSchema.extend({
|
||||||
password: z.string()
|
password: z.string()
|
||||||
.min(1, t('validation.required', 'Açar sözi hökmany'))
|
.min(1, t('validation.required', 'validation.required'))
|
||||||
.min(6, t('validation.minLength', 'Açar sözi iň az 6 harp bolmaly')),
|
.min(6, t('validation.minLength', 'validation.minLength')),
|
||||||
})
|
})
|
||||||
: baseSchema
|
: baseSchema
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AllUserFormData = z.infer<typeof baseSchema>
|
export type AllUserFormData = z.infer<ReturnType<typeof allUserFormSchema>>
|
||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: AllUserFormData = {
|
export const DEFAULT_FORM_VALUES: AllUserFormData = {
|
||||||
username: '',
|
username: '',
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { useState, useCallback, useMemo } from 'react'
|
import { useState, useCallback, useMemo, useEffect } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from 'react-hook-form'
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
import { ChevronLeft, ChevronRight, Loader2, Building2, MapPin, Clock } from 'lucide-react'
|
import { ChevronLeft, ChevronRight, Loader2, Building2, MapPin, Clock } from 'lucide-react'
|
||||||
import type { LucideIcon } from 'lucide-react'
|
import type { LucideIcon } from 'lucide-react'
|
||||||
@@ -12,7 +13,7 @@ import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
|
|||||||
import { useCreateBranch, useUpdateBranch } from '@/features/branches/hooks/useBranches'
|
import { useCreateBranch, useUpdateBranch } from '@/features/branches/hooks/useBranches'
|
||||||
import type { Branch } from '@/features/branches/api/branchesApi'
|
import type { Branch } from '@/features/branches/api/branchesApi'
|
||||||
import { getDistrictOptions } from '@/features/branches/api/branchesApi'
|
import { getDistrictOptions } from '@/features/branches/api/branchesApi'
|
||||||
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from '@/features/branches/schemas/branch.schema'
|
import { createBranchFormSchema, validateStep, DEFAULT_FORM_VALUES, buildPayload } from '@/features/branches/schemas/branch.schema'
|
||||||
import type { BranchFormData } from '@/features/branches/schemas/branch.schema'
|
import type { BranchFormData } from '@/features/branches/schemas/branch.schema'
|
||||||
|
|
||||||
type FlatErrors = Partial<Record<keyof BranchFormData, string>>
|
type FlatErrors = Partial<Record<keyof BranchFormData, string>>
|
||||||
@@ -43,7 +44,7 @@ interface StepDef {
|
|||||||
shortLabel: string
|
shortLabel: string
|
||||||
icon: LucideIcon
|
icon: LucideIcon
|
||||||
subtitle: string
|
subtitle: string
|
||||||
validate: (form: BranchFormData, mode: 'create' | 'edit') => FlatErrors
|
validate: (form: BranchFormData, mode: 'create' | 'edit', t: (key: string, fallback?: string) => string) => FlatErrors
|
||||||
}
|
}
|
||||||
|
|
||||||
const STEPS: StepDef[] = [
|
const STEPS: StepDef[] = [
|
||||||
@@ -54,7 +55,7 @@ const STEPS: StepDef[] = [
|
|||||||
shortLabel: 'Esasy',
|
shortLabel: 'Esasy',
|
||||||
icon: Building2,
|
icon: Building2,
|
||||||
subtitle: 'Ady, kody, etrapy',
|
subtitle: 'Ady, kody, etrapy',
|
||||||
validate: (form, mode) => validateStep(0, form, mode),
|
validate: (form, mode, t) => validateStep(0, form, mode, t),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'address',
|
id: 'address',
|
||||||
@@ -63,7 +64,7 @@ const STEPS: StepDef[] = [
|
|||||||
shortLabel: 'Salgy',
|
shortLabel: 'Salgy',
|
||||||
icon: MapPin,
|
icon: MapPin,
|
||||||
subtitle: 'Salgy, telefon, e-poçta',
|
subtitle: 'Salgy, telefon, e-poçta',
|
||||||
validate: (form, mode) => validateStep(1, form, mode),
|
validate: (form, mode, t) => validateStep(1, form, mode, t),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'hours',
|
id: 'hours',
|
||||||
@@ -72,10 +73,16 @@ const STEPS: StepDef[] = [
|
|||||||
shortLabel: 'Wagt',
|
shortLabel: 'Wagt',
|
||||||
icon: Clock,
|
icon: Clock,
|
||||||
subtitle: 'Iş wagty we bellikler',
|
subtitle: 'Iş wagty we bellikler',
|
||||||
validate: (form, mode) => validateStep(2, form, mode),
|
validate: (form, mode, t) => validateStep(2, form, mode, t),
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
|
const STEP_FIELDS: Record<number, (keyof BranchFormData)[]> = {
|
||||||
|
0: ['nameTk', 'nameRu', 'nameEn', 'code', 'districtId', 'isActive'],
|
||||||
|
1: ['addressTk', 'addressRu', 'addressEn', 'phone', 'email'],
|
||||||
|
2: ['workingHours', 'description'],
|
||||||
|
}
|
||||||
|
|
||||||
interface StepContentProps {
|
interface StepContentProps {
|
||||||
form: BranchFormData
|
form: BranchFormData
|
||||||
errors: FlatErrors
|
errors: FlatErrors
|
||||||
@@ -264,7 +271,11 @@ function mapInitial(data: Branch): Partial<BranchFormData> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function BranchForm({ mode, initialData, branchId }: BranchFormProps) {
|
export function BranchForm({ mode, initialData, branchId }: BranchFormProps) {
|
||||||
const { t } = useTranslation()
|
const { t: _t, i18n } = useTranslation()
|
||||||
|
const t: (key: string, fallback?: string) => string = useCallback(
|
||||||
|
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||||
|
[_t],
|
||||||
|
)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const createMutation = useCreateBranch()
|
const createMutation = useCreateBranch()
|
||||||
@@ -273,9 +284,14 @@ export function BranchForm({ mode, initialData, branchId }: BranchFormProps) {
|
|||||||
|
|
||||||
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
||||||
|
|
||||||
|
const schema = useMemo(() => createBranchFormSchema(t), [t, i18n.language])
|
||||||
|
|
||||||
const {
|
const {
|
||||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors,
|
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||||
} = useForm<BranchFormData>({ defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES })
|
} = useForm<BranchFormData>({
|
||||||
|
resolver: zodResolver(schema),
|
||||||
|
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||||
|
})
|
||||||
|
|
||||||
const form = watch()
|
const form = watch()
|
||||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||||
@@ -284,14 +300,15 @@ export function BranchForm({ mode, initialData, branchId }: BranchFormProps) {
|
|||||||
const [visited, setVisited] = useState<Set<number>>(
|
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 [isValidated, setIsValidated] = useState(false)
|
||||||
|
|
||||||
const stepsWithErrors = useMemo(() => {
|
const stepsWithErrors = useMemo(() => {
|
||||||
const out = new Set<number>()
|
const out = new Set<number>()
|
||||||
visited.forEach((i) => {
|
visited.forEach((i) => {
|
||||||
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) out.add(i)
|
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) out.add(i)
|
||||||
})
|
})
|
||||||
return out
|
return out
|
||||||
}, [form, mode, visited])
|
}, [form, mode, visited, t])
|
||||||
|
|
||||||
const set = useCallback(<K extends keyof BranchFormData>(key: K, value: BranchFormData[K]) => {
|
const set = useCallback(<K extends keyof BranchFormData>(key: K, value: BranchFormData[K]) => {
|
||||||
(setValue as (name: K, val: BranchFormData[K]) => void)(key, value)
|
(setValue as (name: K, val: BranchFormData[K]) => void)(key, value)
|
||||||
@@ -303,10 +320,25 @@ export function BranchForm({ mode, initialData, branchId }: BranchFormProps) {
|
|||||||
const markVisited = (i: number) =>
|
const markVisited = (i: number) =>
|
||||||
setVisited((prev) => new Set([...prev, i]))
|
setVisited((prev) => new Set([...prev, i]))
|
||||||
|
|
||||||
const handleNext = () => {
|
// ── Re-validate on language change ──
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isValidated) return
|
||||||
|
|
||||||
|
const visitedFields = Array.from(visited).flatMap((stepIdx) => STEP_FIELDS[stepIdx] || [])
|
||||||
|
if (visitedFields.length > 0) {
|
||||||
|
trigger(visitedFields)
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [i18n.language, isValidated])
|
||||||
|
|
||||||
|
const handleNext = async () => {
|
||||||
|
setIsValidated(true)
|
||||||
markVisited(currentStep)
|
markVisited(currentStep)
|
||||||
const errs = STEPS[currentStep].validate(form, mode)
|
|
||||||
if (Object.keys(errs).length > 0) {
|
const fields = STEP_FIELDS[currentStep] || []
|
||||||
|
const isValid = await trigger(fields)
|
||||||
|
|
||||||
|
if (!isValid) {
|
||||||
toast.error(t('common.errors.fillRequiredCorrectly', 'Dogry maglumat girizmegiňizi haýyş edýäris.'))
|
toast.error(t('common.errors.fillRequiredCorrectly', 'Dogry maglumat girizmegiňizi haýyş edýäris.'))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -330,16 +362,15 @@ export function BranchForm({ mode, initialData, branchId }: BranchFormProps) {
|
|||||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||||
}
|
}
|
||||||
|
|
||||||
const doSubmit = () => {
|
const doSubmit = async () => {
|
||||||
|
setIsValidated(true)
|
||||||
setVisited(new Set(STEPS.map((_, i) => i)))
|
setVisited(new Set(STEPS.map((_, i) => i)))
|
||||||
|
|
||||||
const allErrors: FlatErrors = {}
|
const isValid = await trigger()
|
||||||
for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode))
|
if (!isValid) {
|
||||||
|
|
||||||
if (Object.keys(allErrors).length > 0) {
|
|
||||||
toast.error(t('common.errors.requiredFieldsMissing', 'Käbir hökmany meýdanlar doldurylan däldir.'))
|
toast.error(t('common.errors.requiredFieldsMissing', 'Käbir hökmany meýdanlar doldurylan däldir.'))
|
||||||
for (let i = 0; i < STEPS.length; i++) {
|
for (let i = 0; i < STEPS.length; i++) {
|
||||||
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) {
|
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) {
|
||||||
setCurrentStep(i); break
|
setCurrentStep(i); break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,40 +1,47 @@
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import i18next from 'i18next'
|
|
||||||
import type { CreateBranchPayload } from '@/features/branches/api/branchesApi'
|
import type { CreateBranchPayload } from '@/features/branches/api/branchesApi'
|
||||||
|
|
||||||
const t = i18next.t.bind(i18next)
|
export function createBranchFormSchema(t: (key: string, fallback?: string) => string) {
|
||||||
|
return z.object({
|
||||||
|
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
code: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
districtId: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
addressTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
addressRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
addressEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
phone: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
email: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
workingHours: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
description: z.string().optional(),
|
||||||
|
isActive: z.boolean(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
export const branchFormSchema = z.object({
|
export type BranchFormData = z.infer<ReturnType<typeof createBranchFormSchema>>
|
||||||
nameTk: z.string().min(1, t('validation.required', '')),
|
|
||||||
nameRu: z.string().min(1, t('validation.required', '')),
|
|
||||||
nameEn: z.string().min(1, t('validation.required', '')),
|
|
||||||
code: z.string().min(1, t('validation.required', '')),
|
|
||||||
districtId: z.string().min(1, t('validation.required', '')),
|
|
||||||
addressTk: z.string().min(1, t('validation.required', '')),
|
|
||||||
addressRu: z.string().min(1, t('validation.required', '')),
|
|
||||||
addressEn: z.string().min(1, t('validation.required', '')),
|
|
||||||
phone: z.string().min(1, t('validation.required', '')),
|
|
||||||
email: z.string().min(1, t('validation.required', '')),
|
|
||||||
workingHours: z.string().min(1, t('validation.required', '')),
|
|
||||||
description: z.string().optional(),
|
|
||||||
isActive: z.boolean(),
|
|
||||||
})
|
|
||||||
|
|
||||||
export type BranchFormData = z.infer<typeof branchFormSchema>
|
type StepSchemas = Record<number, z.ZodType<Partial<BranchFormData>>>
|
||||||
|
|
||||||
export const stepSchemas: Record<number, z.ZodType<Partial<BranchFormData>>> = {
|
function createStepSchemas(t: (key: string, fallback?: string) => string): StepSchemas {
|
||||||
0: branchFormSchema.pick({ nameTk: true, nameRu: true, nameEn: true, code: true, districtId: true }),
|
const schema = createBranchFormSchema(t)
|
||||||
1: branchFormSchema.pick({ addressTk: true, addressRu: true, addressEn: true, phone: true, email: true }),
|
return {
|
||||||
2: branchFormSchema.pick({ workingHours: true }),
|
0: schema.pick({ nameTk: true, nameRu: true, nameEn: true, code: true, districtId: true }),
|
||||||
|
1: schema.pick({ addressTk: true, addressRu: true, addressEn: true, phone: true, email: true }),
|
||||||
|
2: schema.pick({ workingHours: true }),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function validateStep(
|
export function validateStep(
|
||||||
stepIndex: number,
|
stepIndex: number,
|
||||||
form: BranchFormData,
|
form: BranchFormData,
|
||||||
mode: 'create' | 'edit',
|
mode: 'create' | 'edit',
|
||||||
|
t: (key: string, fallback?: string) => string,
|
||||||
): Partial<Record<keyof BranchFormData, string>> {
|
): Partial<Record<keyof BranchFormData, string>> {
|
||||||
void mode
|
void mode
|
||||||
|
const stepSchemas = createStepSchemas(t)
|
||||||
const schema = stepSchemas[stepIndex]
|
const schema = stepSchemas[stepIndex]
|
||||||
|
if (!schema) return {}
|
||||||
const result = schema.safeParse(form)
|
const result = schema.safeParse(form)
|
||||||
if (result.success) return {}
|
if (result.success) return {}
|
||||||
const errors: Partial<Record<keyof BranchFormData, string>> = {}
|
const errors: Partial<Record<keyof BranchFormData, string>> = {}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useState, useCallback, useMemo } from 'react'
|
import { useState, useCallback, useMemo, useEffect } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from 'react-hook-form'
|
||||||
@@ -8,7 +8,7 @@ import { FormActions } from '@/components/formActions'
|
|||||||
import { FormInput } from '@/components/formInput'
|
import { FormInput } from '@/components/formInput'
|
||||||
import type { CardReason } from '../api/cardReasonsApi'
|
import type { CardReason } from '../api/cardReasonsApi'
|
||||||
import { useCreateCardReason, useUpdateCardReason } from '../hooks/useCardReasons'
|
import { useCreateCardReason, useUpdateCardReason } from '../hooks/useCardReasons'
|
||||||
import { cardReasonFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardReason.schema'
|
import { createCardReasonFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardReason.schema'
|
||||||
import type { CardReasonFormData } from '../schemas/cardReason.schema'
|
import type { CardReasonFormData } from '../schemas/cardReason.schema'
|
||||||
|
|
||||||
// ─── Form errors helper ──────────────────────────────────────────────────────
|
// ─── Form errors helper ──────────────────────────────────────────────────────
|
||||||
@@ -56,7 +56,11 @@ function mapInitial(data: CardReason): CardReasonFormData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function CardReasonForm({ mode, initialData, CardReasonId }: CardReasonFormProps) {
|
export function CardReasonForm({ mode, initialData, CardReasonId }: CardReasonFormProps) {
|
||||||
const { t } = useTranslation()
|
const { t: _t, i18n } = useTranslation()
|
||||||
|
const t: (key: string, fallback?: string) => string = useCallback(
|
||||||
|
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||||
|
[_t],
|
||||||
|
)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const createMutation = useCreateCardReason()
|
const createMutation = useCreateCardReason()
|
||||||
@@ -64,10 +68,12 @@ export function CardReasonForm({ mode, initialData, CardReasonId }: CardReasonFo
|
|||||||
|
|
||||||
const isPending = createMutation.isPending || updateMutation.isPending
|
const isPending = createMutation.isPending || updateMutation.isPending
|
||||||
|
|
||||||
|
const schema = useMemo(() => createCardReasonFormSchema(t), [t, i18n.language])
|
||||||
|
|
||||||
const {
|
const {
|
||||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors,
|
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||||
} = useForm<CardReasonFormData>({
|
} = useForm<CardReasonFormData>({
|
||||||
resolver: zodResolver(cardReasonFormSchema),
|
resolver: zodResolver(schema),
|
||||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -81,11 +87,17 @@ export function CardReasonForm({ mode, initialData, CardReasonId }: CardReasonFo
|
|||||||
clearErrors(key)
|
clearErrors(key)
|
||||||
}, [setValue, clearErrors])
|
}, [setValue, clearErrors])
|
||||||
|
|
||||||
const handleSubmit = () => {
|
// ── Re-validate on language change ──
|
||||||
const values = getValues()
|
useEffect(() => {
|
||||||
const result = cardReasonFormSchema.safeParse(values)
|
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||||
if (!result.success) return
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [i18n.language])
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
const isValid = await trigger()
|
||||||
|
if (!isValid) return
|
||||||
|
|
||||||
|
const values = getValues()
|
||||||
const payload = buildPayload(values)
|
const payload = buildPayload(values)
|
||||||
|
|
||||||
if (mode === 'create') {
|
if (mode === 'create') {
|
||||||
|
|||||||
@@ -1,22 +1,21 @@
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import i18next from 'i18next'
|
|
||||||
import type { CreateCardReasonPayload } from '../api/cardReasonsApi'
|
import type { CreateCardReasonPayload } from '../api/cardReasonsApi'
|
||||||
|
|
||||||
const t = i18next.t.bind(i18next)
|
export function createCardReasonFormSchema(t: (key: string, fallback?: string) => string) {
|
||||||
|
return z.object({
|
||||||
|
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
value: z.string().min(1, t('validation.invalidNumber', 'validation.invalidNumber')).refine(
|
||||||
|
(v) => !isNaN(Number(v)) && Number(v) >= 0,
|
||||||
|
{ message: t('validation.invalidNumber', 'Dogry san giriziň') },
|
||||||
|
),
|
||||||
|
description: z.string().optional(),
|
||||||
|
isActive: z.boolean(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
export const cardReasonFormSchema = z.object({
|
export type CardReasonFormData = z.infer<ReturnType<typeof createCardReasonFormSchema>>
|
||||||
nameTk: z.string().min(1, t('validation.required', '')),
|
|
||||||
nameRu: z.string().min(1, t('validation.required', '')),
|
|
||||||
nameEn: z.string().min(1, t('validation.required', '')),
|
|
||||||
value: z.string().min(1, t('validation.invalidNumber', '')).refine(
|
|
||||||
(v) => !isNaN(Number(v)) && Number(v) >= 0,
|
|
||||||
{ message: t('validation.invalidNumber', 'Dogry san giriziň') },
|
|
||||||
),
|
|
||||||
description: z.string().optional(),
|
|
||||||
isActive: z.boolean(),
|
|
||||||
})
|
|
||||||
|
|
||||||
export type CardReasonFormData = z.infer<typeof cardReasonFormSchema>
|
|
||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: CardReasonFormData = {
|
export const DEFAULT_FORM_VALUES: CardReasonFormData = {
|
||||||
nameTk: '',
|
nameTk: '',
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useState, useCallback, useMemo } from 'react'
|
import { useState, useCallback, useMemo, useEffect } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from 'react-hook-form'
|
||||||
@@ -8,7 +8,7 @@ import { FormActions } from '@/components/formActions'
|
|||||||
import { FormInput } from '@/components/formInput'
|
import { FormInput } from '@/components/formInput'
|
||||||
import type { CardType } from '../api/cardTypesApi'
|
import type { CardType } from '../api/cardTypesApi'
|
||||||
import { useCreateCardType, useUpdateCardType } from '../hooks/useCardTypes'
|
import { useCreateCardType, useUpdateCardType } from '../hooks/useCardTypes'
|
||||||
import { cardTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardType.schema'
|
import { createCardTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardType.schema'
|
||||||
import type { CardTypeFormData } from '../schemas/cardType.schema'
|
import type { CardTypeFormData } from '../schemas/cardType.schema'
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
@@ -54,7 +54,11 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
|||||||
// ─── CardTypeForm ─────────────────────────────────────────────────────────────
|
// ─── CardTypeForm ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function CardTypeForm({ mode, initialData, cardTypeId }: CardTypeFormProps) {
|
export function CardTypeForm({ mode, initialData, cardTypeId }: CardTypeFormProps) {
|
||||||
const { t } = useTranslation()
|
const { t: _t, i18n } = useTranslation()
|
||||||
|
const t: (key: string, fallback?: string) => string = useCallback(
|
||||||
|
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||||
|
[_t],
|
||||||
|
)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const createMutation = useCreateCardType()
|
const createMutation = useCreateCardType()
|
||||||
@@ -64,6 +68,8 @@ export function CardTypeForm({ mode, initialData, cardTypeId }: CardTypeFormProp
|
|||||||
|
|
||||||
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
||||||
|
|
||||||
|
const schema = useMemo(() => createCardTypeFormSchema(t), [t, i18n.language])
|
||||||
|
|
||||||
const {
|
const {
|
||||||
watch,
|
watch,
|
||||||
setValue,
|
setValue,
|
||||||
@@ -72,7 +78,7 @@ export function CardTypeForm({ mode, initialData, cardTypeId }: CardTypeFormProp
|
|||||||
trigger,
|
trigger,
|
||||||
getValues,
|
getValues,
|
||||||
} = useForm<CardTypeFormData>({
|
} = useForm<CardTypeFormData>({
|
||||||
resolver: zodResolver(cardTypeFormSchema),
|
resolver: zodResolver(schema),
|
||||||
defaultValues: initialData
|
defaultValues: initialData
|
||||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||||
: DEFAULT_FORM_VALUES,
|
: DEFAULT_FORM_VALUES,
|
||||||
@@ -92,6 +98,12 @@ export function CardTypeForm({ mode, initialData, cardTypeId }: CardTypeFormProp
|
|||||||
[setValue, clearErrors],
|
[setValue, clearErrors],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ── Re-validate on language change ──
|
||||||
|
useEffect(() => {
|
||||||
|
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [i18n.language])
|
||||||
|
|
||||||
const handleSubmit = useCallback(async () => {
|
const handleSubmit = useCallback(async () => {
|
||||||
const isValid = await trigger()
|
const isValid = await trigger()
|
||||||
if (!isValid) return
|
if (!isValid) return
|
||||||
|
|||||||
@@ -1,22 +1,21 @@
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import i18next from 'i18next'
|
|
||||||
import type { CreateCardTypePayload } from '../api/cardTypesApi'
|
import type { CreateCardTypePayload } from '../api/cardTypesApi'
|
||||||
|
|
||||||
const t = i18next.t.bind(i18next)
|
export function createCardTypeFormSchema(t: (key: string, fallback?: string) => string) {
|
||||||
|
return z.object({
|
||||||
|
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
value: z.string().refine(
|
||||||
|
(v) => v.trim() !== '' && !isNaN(Number(v)) && Number(v) >= 0,
|
||||||
|
t('validation.invalidNumber', 'Dogry san giriziň'),
|
||||||
|
),
|
||||||
|
description: z.string().optional(),
|
||||||
|
isActive: z.boolean(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
export const cardTypeFormSchema = z.object({
|
export type CardTypeFormData = z.infer<ReturnType<typeof createCardTypeFormSchema>>
|
||||||
nameTk: z.string().min(1, t('validation.required', '')),
|
|
||||||
nameRu: z.string().min(1, t('validation.required', '')),
|
|
||||||
nameEn: z.string().min(1, t('validation.required', 'Hökmany meýdan')),
|
|
||||||
value: z.string().refine(
|
|
||||||
(v) => v.trim() !== '' && !isNaN(Number(v)) && Number(v) >= 0,
|
|
||||||
t('validation.invalidNumber', 'Dogry san giriziň'),
|
|
||||||
),
|
|
||||||
description: z.string().optional(),
|
|
||||||
isActive: z.boolean(),
|
|
||||||
})
|
|
||||||
|
|
||||||
export type CardTypeFormData = z.infer<typeof cardTypeFormSchema>
|
|
||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: CardTypeFormData = {
|
export const DEFAULT_FORM_VALUES: CardTypeFormData = {
|
||||||
nameTk: '',
|
nameTk: '',
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useMemo } from 'react'
|
import { useMemo, useEffect, useCallback } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from 'react-hook-form'
|
||||||
@@ -35,7 +35,11 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
|||||||
// ─── ClientForm ───────────────────────────────────────────────────────────────
|
// ─── ClientForm ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function ClientForm({ mode, initialData, clientId }: ClientFormProps) {
|
export function ClientForm({ mode, initialData, clientId }: ClientFormProps) {
|
||||||
const { t } = useTranslation()
|
const { t: _t, i18n } = useTranslation()
|
||||||
|
const t: (key: string, fallback?: string) => string = useCallback(
|
||||||
|
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||||
|
[_t],
|
||||||
|
)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const createMutation = useCreateClient()
|
const createMutation = useCreateClient()
|
||||||
@@ -43,7 +47,7 @@ export function ClientForm({ mode, initialData, clientId }: ClientFormProps) {
|
|||||||
|
|
||||||
const isPending = createMutation.isPending || updateMutation.isPending
|
const isPending = createMutation.isPending || updateMutation.isPending
|
||||||
|
|
||||||
const schema = useMemo(() => clientFormSchema(mode), [mode])
|
const schema = useMemo(() => clientFormSchema(mode, t), [mode, t, i18n.language])
|
||||||
|
|
||||||
const {
|
const {
|
||||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||||
@@ -70,6 +74,14 @@ export function ClientForm({ mode, initialData, clientId }: ClientFormProps) {
|
|||||||
clearErrors(key)
|
clearErrors(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Re-validate on language change ──
|
||||||
|
useEffect(() => {
|
||||||
|
if (Object.keys(rhfErrors).length > 0) {
|
||||||
|
trigger()
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [i18n.language])
|
||||||
|
|
||||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
// ── Submit ──────────────────────────────────────────────────────────────────
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
const isValid = await trigger()
|
const isValid = await trigger()
|
||||||
|
|||||||
@@ -1,27 +1,27 @@
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import i18next from 'i18next'
|
|
||||||
import type { CreateClientPayload } from '../api/clientsApi'
|
import type { CreateClientPayload } from '../api/clientsApi'
|
||||||
|
|
||||||
const t = i18next.t.bind(i18next)
|
export function clientFormSchema(
|
||||||
|
mode: 'create' | 'edit',
|
||||||
|
t: (key: string, fallback?: string) => string,
|
||||||
|
) {
|
||||||
|
const baseSchema = z.object({
|
||||||
|
username: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
name: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
phone: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
email: z.string().default(''),
|
||||||
|
password: z.string(),
|
||||||
|
isActive: z.boolean(),
|
||||||
|
})
|
||||||
|
|
||||||
const baseSchema = z.object({
|
|
||||||
username: z.string().min(1, t('validation.required', '')),
|
|
||||||
name: z.string().min(1, t('validation.required', '')),
|
|
||||||
phone: z.string().min(1, t('validation.required', '')),
|
|
||||||
email: z.string().default(''),
|
|
||||||
password: z.string(),
|
|
||||||
isActive: z.boolean(),
|
|
||||||
})
|
|
||||||
|
|
||||||
export function clientFormSchema(mode: 'create' | 'edit') {
|
|
||||||
return mode === 'create'
|
return mode === 'create'
|
||||||
? baseSchema.extend({
|
? baseSchema.extend({
|
||||||
password: z.string().min(1, t('validation.required', '')),
|
password: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
})
|
})
|
||||||
: baseSchema
|
: baseSchema
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ClientFormData = z.infer<typeof baseSchema>
|
export type ClientFormData = z.infer<ReturnType<typeof clientFormSchema>>
|
||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: ClientFormData = {
|
export const DEFAULT_FORM_VALUES: ClientFormData = {
|
||||||
username: '',
|
username: '',
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// features/currencyRates/components/CurrencyRateForm.tsx
|
// features/currencyRates/components/CurrencyRateForm.tsx
|
||||||
|
|
||||||
import { useCallback, useMemo } from 'react'
|
import { useCallback, useMemo, useEffect } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from 'react-hook-form'
|
||||||
@@ -10,7 +10,7 @@ import { FormActions } from '@/components/formActions'
|
|||||||
import { CURRENCY_OPTIONS, type CurrencyRate } from '../api/currencyRatesApi'
|
import { CURRENCY_OPTIONS, type CurrencyRate } from '../api/currencyRatesApi'
|
||||||
import { useCreateCurrencyRate, useUpdateCurrencyRate } from '../hooks/useCurrencyRates'
|
import { useCreateCurrencyRate, useUpdateCurrencyRate } from '../hooks/useCurrencyRates'
|
||||||
import {
|
import {
|
||||||
currencyRateFormSchema,
|
createCurrencyRateFormSchema,
|
||||||
DEFAULT_FORM_VALUES,
|
DEFAULT_FORM_VALUES,
|
||||||
buildPayload,
|
buildPayload,
|
||||||
type CurrencyRateFormData,
|
type CurrencyRateFormData,
|
||||||
@@ -38,7 +38,11 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
|||||||
// ─── CurrencyRateForm ─────────────────────────────────────────────────────────
|
// ─── CurrencyRateForm ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function CurrencyRateForm({ mode, initialData, rateId }: CurrencyRateFormProps) {
|
export function CurrencyRateForm({ mode, initialData, rateId }: CurrencyRateFormProps) {
|
||||||
const { t } = useTranslation()
|
const { t: _t, i18n } = useTranslation()
|
||||||
|
const t: (key: string, fallback?: string) => string = useCallback(
|
||||||
|
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||||
|
[_t],
|
||||||
|
)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const createMutation = useCreateCurrencyRate()
|
const createMutation = useCreateCurrencyRate()
|
||||||
@@ -46,6 +50,8 @@ export function CurrencyRateForm({ mode, initialData, rateId }: CurrencyRateForm
|
|||||||
|
|
||||||
const isPending = createMutation.isPending || updateMutation.isPending
|
const isPending = createMutation.isPending || updateMutation.isPending
|
||||||
|
|
||||||
|
const schema = useMemo(() => createCurrencyRateFormSchema(t), [t, i18n.language])
|
||||||
|
|
||||||
const {
|
const {
|
||||||
watch,
|
watch,
|
||||||
setValue,
|
setValue,
|
||||||
@@ -54,7 +60,7 @@ export function CurrencyRateForm({ mode, initialData, rateId }: CurrencyRateForm
|
|||||||
trigger,
|
trigger,
|
||||||
getValues,
|
getValues,
|
||||||
} = useForm<CurrencyRateFormData>({
|
} = useForm<CurrencyRateFormData>({
|
||||||
resolver: zodResolver(currencyRateFormSchema),
|
resolver: zodResolver(schema),
|
||||||
defaultValues: initialData
|
defaultValues: initialData
|
||||||
? {
|
? {
|
||||||
currencyFrom: initialData.currencyFrom,
|
currencyFrom: initialData.currencyFrom,
|
||||||
@@ -70,6 +76,14 @@ export function CurrencyRateForm({ mode, initialData, rateId }: CurrencyRateForm
|
|||||||
[rhfErrors],
|
[rhfErrors],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ── Re-validate on language change ──
|
||||||
|
useEffect(() => {
|
||||||
|
if (Object.keys(rhfErrors).length > 0) {
|
||||||
|
trigger()
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [i18n.language])
|
||||||
|
|
||||||
const setField = useCallback(
|
const setField = useCallback(
|
||||||
(key: keyof CurrencyRateFormData) => (value: string) => {
|
(key: keyof CurrencyRateFormData) => (value: string) => {
|
||||||
setValue(key, value)
|
setValue(key, value)
|
||||||
|
|||||||
@@ -1,19 +1,18 @@
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import i18next from 'i18next'
|
|
||||||
import type { CreateCurrencyRatePayload, CurrencyCode } from '../api/currencyRatesApi'
|
import type { CreateCurrencyRatePayload, CurrencyCode } from '../api/currencyRatesApi'
|
||||||
|
|
||||||
const t = i18next.t.bind(i18next)
|
export function createCurrencyRateFormSchema(t: (key: string, fallback?: string) => string) {
|
||||||
|
return z.object({
|
||||||
|
currencyFrom: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
currencyTo: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
value: z
|
||||||
|
.string()
|
||||||
|
.min(1, t('validation.required', 'validation.required'))
|
||||||
|
.refine((v) => !isNaN(Number(v)) && Number(v) > 0, t('validation.valuePositive', 'validation.valuePositive')),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
export const currencyRateFormSchema = z.object({
|
export type CurrencyRateFormData = z.infer<ReturnType<typeof createCurrencyRateFormSchema>>
|
||||||
currencyFrom: z.string().min(1, t('validation.required', 'Hökmany meýdan')),
|
|
||||||
currencyTo: z.string().min(1, t('validation.required', 'Hökmany meýdan')),
|
|
||||||
value: z
|
|
||||||
.string()
|
|
||||||
.min(1, t('validation.required', 'Hökmany meýdan'))
|
|
||||||
.refine((v) => !isNaN(Number(v)) && Number(v) > 0, t('validation.valuePositive', 'Baha 0-dan uly bolmaly')),
|
|
||||||
})
|
|
||||||
|
|
||||||
export type CurrencyRateFormData = z.infer<typeof currencyRateFormSchema>
|
|
||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: CurrencyRateFormData = {
|
export const DEFAULT_FORM_VALUES: CurrencyRateFormData = {
|
||||||
currencyFrom: '',
|
currencyFrom: '',
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
import { useState, useCallback, useMemo } from 'react'
|
import { useState, useCallback, useMemo, useEffect } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from 'react-hook-form'
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
import { Checkbox } from '@/components/ui/checkbox'
|
import { Checkbox } from '@/components/ui/checkbox'
|
||||||
import { FormActions } from '@/components/formActions'
|
import { FormActions } from '@/components/formActions'
|
||||||
import { FormInput } from '@/components/formInput'
|
import { FormInput } from '@/components/formInput'
|
||||||
import type { District } from '../api/districtsApi'
|
import type { District } from '../api/districtsApi'
|
||||||
import { useCreateDistrict, useUpdateDistrict } from '../hooks/useDistricts'
|
import { useCreateDistrict, useUpdateDistrict } from '../hooks/useDistricts'
|
||||||
import { districtFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/district.schema'
|
import { createDistrictFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/district.schema'
|
||||||
import type { DistrictFormData } from '../schemas/district.schema'
|
import type { DistrictFormData } from '../schemas/district.schema'
|
||||||
|
|
||||||
type FlatErrors = Partial<Record<keyof DistrictFormData, string>>
|
type FlatErrors = Partial<Record<keyof DistrictFormData, string>>
|
||||||
@@ -48,7 +49,11 @@ function mapInitial(data: District): DistrictFormData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function DistrictForm({ mode, initialData, districtId }: DistrictFormProps) {
|
export function DistrictForm({ mode, initialData, districtId }: DistrictFormProps) {
|
||||||
const { t } = useTranslation()
|
const { t: _t, i18n } = useTranslation()
|
||||||
|
const t: (key: string, fallback?: string) => string = useCallback(
|
||||||
|
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||||
|
[_t],
|
||||||
|
)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const createMutation = useCreateDistrict()
|
const createMutation = useCreateDistrict()
|
||||||
@@ -56,9 +61,12 @@ export function DistrictForm({ mode, initialData, districtId }: DistrictFormProp
|
|||||||
|
|
||||||
const isPending = createMutation.isPending || updateMutation.isPending
|
const isPending = createMutation.isPending || updateMutation.isPending
|
||||||
|
|
||||||
|
const schema = useMemo(() => createDistrictFormSchema(t), [t, i18n.language])
|
||||||
|
|
||||||
const {
|
const {
|
||||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors,
|
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||||
} = useForm<DistrictFormData>({
|
} = useForm<DistrictFormData>({
|
||||||
|
resolver: zodResolver(schema),
|
||||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -73,12 +81,17 @@ export function DistrictForm({ mode, initialData, districtId }: DistrictFormProp
|
|||||||
clearErrors(key)
|
clearErrors(key)
|
||||||
}, [setValue, clearErrors])
|
}, [setValue, clearErrors])
|
||||||
|
|
||||||
const handleSubmit = () => {
|
// ── Re-validate on language change ──
|
||||||
const values = getValues()
|
useEffect(() => {
|
||||||
const result = districtFormSchema.safeParse(values)
|
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||||
if (!result.success) return
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [i18n.language])
|
||||||
|
|
||||||
const payload = buildPayload(values)
|
const handleSubmit = async () => {
|
||||||
|
const isValid = await trigger()
|
||||||
|
if (!isValid) return
|
||||||
|
|
||||||
|
const payload = buildPayload(getValues())
|
||||||
|
|
||||||
if (mode === 'create') {
|
if (mode === 'create') {
|
||||||
createMutation.mutate(payload, {
|
createMutation.mutate(payload, {
|
||||||
|
|||||||
@@ -1,18 +1,17 @@
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import i18next from 'i18next'
|
|
||||||
import type { CreateDistrictPayload } from '../api/districtsApi'
|
import type { CreateDistrictPayload } from '../api/districtsApi'
|
||||||
|
|
||||||
const t = i18next.t.bind(i18next)
|
export function createDistrictFormSchema(t: (key: string, fallback?: string) => string) {
|
||||||
|
return z.object({
|
||||||
|
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
description: z.string().optional(),
|
||||||
|
isActive: z.boolean(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
export const districtFormSchema = z.object({
|
export type DistrictFormData = z.infer<ReturnType<typeof createDistrictFormSchema>>
|
||||||
nameTk: z.string().min(1, t('validation.required', '')),
|
|
||||||
nameRu: z.string().min(1, t('validation.required', '')),
|
|
||||||
nameEn: z.string().min(1, t('validation.required', '')),
|
|
||||||
description: z.string().optional(),
|
|
||||||
isActive: z.boolean(),
|
|
||||||
})
|
|
||||||
|
|
||||||
export type DistrictFormData = z.infer<typeof districtFormSchema>
|
|
||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: DistrictFormData = {
|
export const DEFAULT_FORM_VALUES: DistrictFormData = {
|
||||||
nameTk: '',
|
nameTk: '',
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useState, useCallback, useMemo } from 'react'
|
import { useState, useCallback, useMemo, useEffect } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from 'react-hook-form'
|
||||||
@@ -9,7 +9,7 @@ import { FormActions } from '@/components/formActions'
|
|||||||
import { Checkbox } from '@/components/ui/checkbox'
|
import { Checkbox } from '@/components/ui/checkbox'
|
||||||
import { useCreateLoanType, useUpdateLoanType } from '../hooks/useLoanTypes'
|
import { useCreateLoanType, useUpdateLoanType } from '../hooks/useLoanTypes'
|
||||||
import type { LoanType } from '../api/loanTypesApi'
|
import type { LoanType } from '../api/loanTypesApi'
|
||||||
import { loanTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/loanType.schema'
|
import { createLoanTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/loanType.schema'
|
||||||
import type { LoanTypeFormData } from '../schemas/loanType.schema'
|
import type { LoanTypeFormData } from '../schemas/loanType.schema'
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
@@ -60,7 +60,11 @@ const LANG_TABS: { key: Lang; label: string }[] = [
|
|||||||
// ─── LoanTypeForm ─────────────────────────────────────────────────────────────
|
// ─── LoanTypeForm ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProps) {
|
export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProps) {
|
||||||
const { t } = useTranslation()
|
const { t: _t, i18n } = useTranslation()
|
||||||
|
const t: (key: string, fallback?: string) => string = useCallback(
|
||||||
|
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||||
|
[_t],
|
||||||
|
)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const createMutation = useCreateLoanType()
|
const createMutation = useCreateLoanType()
|
||||||
@@ -70,6 +74,8 @@ export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProp
|
|||||||
|
|
||||||
const [activeLang, setActiveLang] = useState<Lang>('tk')
|
const [activeLang, setActiveLang] = useState<Lang>('tk')
|
||||||
|
|
||||||
|
const schema = useMemo(() => createLoanTypeFormSchema(t), [t, i18n.language])
|
||||||
|
|
||||||
const {
|
const {
|
||||||
watch,
|
watch,
|
||||||
setValue,
|
setValue,
|
||||||
@@ -78,7 +84,7 @@ export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProp
|
|||||||
trigger,
|
trigger,
|
||||||
getValues,
|
getValues,
|
||||||
} = useForm<LoanTypeFormData>({
|
} = useForm<LoanTypeFormData>({
|
||||||
resolver: zodResolver(loanTypeFormSchema),
|
resolver: zodResolver(schema),
|
||||||
defaultValues: initialData
|
defaultValues: initialData
|
||||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||||
: DEFAULT_FORM_VALUES,
|
: DEFAULT_FORM_VALUES,
|
||||||
@@ -90,6 +96,12 @@ export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProp
|
|||||||
[rhfErrors],
|
[rhfErrors],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ── Re-validate on language change ──
|
||||||
|
useEffect(() => {
|
||||||
|
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [i18n.language])
|
||||||
|
|
||||||
const set = useCallback(
|
const set = useCallback(
|
||||||
(key: keyof LoanTypeFormData) => (value: string | boolean) => {
|
(key: keyof LoanTypeFormData) => (value: string | boolean) => {
|
||||||
(setValue as (k: keyof LoanTypeFormData, v: string | boolean) => void)(key, value)
|
(setValue as (k: keyof LoanTypeFormData, v: string | boolean) => void)(key, value)
|
||||||
|
|||||||
@@ -1,28 +1,27 @@
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import i18next from 'i18next'
|
|
||||||
import type { CreateLoanTypePayload } from '../api/loanTypesApi'
|
import type { CreateLoanTypePayload } from '../api/loanTypesApi'
|
||||||
|
|
||||||
const t = i18next.t.bind(i18next)
|
export function createLoanTypeFormSchema(t: (key: string, fallback?: string) => string) {
|
||||||
|
return z.object({
|
||||||
|
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
notesTk: z.string().optional(),
|
||||||
|
notesRu: z.string().optional(),
|
||||||
|
notesEn: z.string().optional(),
|
||||||
|
tax: z.string().refine(
|
||||||
|
(v) => v.trim() !== '' && !isNaN(Number(v)) && Number(v) > 0,
|
||||||
|
t('validation.positiveNumber', 'validation.positiveNumber'),
|
||||||
|
),
|
||||||
|
loanTerm: z.string().refine(
|
||||||
|
(v) => v.trim() !== '' && !isNaN(Number(v)) && Number(v) > 0,
|
||||||
|
t('validation.positiveNumber', 'validation.positiveNumber'),
|
||||||
|
),
|
||||||
|
isActive: z.boolean(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
export const loanTypeFormSchema = z.object({
|
export type LoanTypeFormData = z.infer<ReturnType<typeof createLoanTypeFormSchema>>
|
||||||
nameTk: z.string().min(1, t('validation.required', '')),
|
|
||||||
nameRu: z.string().min(1, t('validation.required', '')),
|
|
||||||
nameEn: z.string().min(1, t('validation.required', '')),
|
|
||||||
notesTk: z.string().optional(),
|
|
||||||
notesRu: z.string().optional(),
|
|
||||||
notesEn: z.string().optional(),
|
|
||||||
tax: z.string().refine(
|
|
||||||
(v) => v.trim() !== '' && !isNaN(Number(v)) && Number(v) > 0,
|
|
||||||
t('validation.positiveNumber', 'Oňyn san gerek'),
|
|
||||||
),
|
|
||||||
loanTerm: z.string().refine(
|
|
||||||
(v) => v.trim() !== '' && !isNaN(Number(v)) && Number(v) > 0,
|
|
||||||
t('validation.positiveNumber', 'Oňyn san gerek'),
|
|
||||||
),
|
|
||||||
isActive: z.boolean(),
|
|
||||||
})
|
|
||||||
|
|
||||||
export type LoanTypeFormData = z.infer<typeof loanTypeFormSchema>
|
|
||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: LoanTypeFormData = {
|
export const DEFAULT_FORM_VALUES: LoanTypeFormData = {
|
||||||
nameTk: '',
|
nameTk: '',
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useMemo } from 'react'
|
import { useMemo, useEffect, useCallback } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from 'react-hook-form'
|
||||||
@@ -35,7 +35,11 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
|||||||
// ─── OperatorForm ─────────────────────────────────────────────────────────────
|
// ─── OperatorForm ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function OperatorForm({ mode, initialData, operatorId }: OperatorFormProps) {
|
export function OperatorForm({ mode, initialData, operatorId }: OperatorFormProps) {
|
||||||
const { t } = useTranslation()
|
const { t: _t, i18n } = useTranslation()
|
||||||
|
const t: (key: string, fallback?: string) => string = useCallback(
|
||||||
|
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||||
|
[_t],
|
||||||
|
)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const createMutation = useCreateOperator()
|
const createMutation = useCreateOperator()
|
||||||
@@ -43,7 +47,7 @@ export function OperatorForm({ mode, initialData, operatorId }: OperatorFormProp
|
|||||||
|
|
||||||
const isPending = createMutation.isPending || updateMutation.isPending
|
const isPending = createMutation.isPending || updateMutation.isPending
|
||||||
|
|
||||||
const schema = useMemo(() => operatorFormSchema(mode), [mode])
|
const schema = useMemo(() => operatorFormSchema(mode, t), [mode, t, i18n.language])
|
||||||
|
|
||||||
const {
|
const {
|
||||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||||
@@ -70,6 +74,14 @@ export function OperatorForm({ mode, initialData, operatorId }: OperatorFormProp
|
|||||||
clearErrors(key)
|
clearErrors(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Re-validate on language change ──
|
||||||
|
useEffect(() => {
|
||||||
|
if (Object.keys(rhfErrors).length > 0) {
|
||||||
|
trigger()
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [i18n.language])
|
||||||
|
|
||||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
// ── Submit ──────────────────────────────────────────────────────────────────
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
const isValid = await trigger()
|
const isValid = await trigger()
|
||||||
|
|||||||
@@ -1,27 +1,27 @@
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import i18next from 'i18next'
|
|
||||||
import type { CreateOperatorPayload } from '../api/operatorsApi'
|
import type { CreateOperatorPayload } from '../api/operatorsApi'
|
||||||
|
|
||||||
const t = i18next.t.bind(i18next)
|
export function operatorFormSchema(
|
||||||
|
mode: 'create' | 'edit',
|
||||||
|
t: (key: string, fallback?: string) => string,
|
||||||
|
) {
|
||||||
|
const baseSchema = z.object({
|
||||||
|
username: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
name: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
phone: z.string().default(''),
|
||||||
|
email: z.string().default(''),
|
||||||
|
password: z.string(),
|
||||||
|
isActive: z.boolean(),
|
||||||
|
})
|
||||||
|
|
||||||
const baseSchema = z.object({
|
|
||||||
username: z.string().min(1, t('validation.required', '')),
|
|
||||||
name: z.string().min(1, t('validation.required', '')),
|
|
||||||
phone: z.string().default(''),
|
|
||||||
email: z.string().default(''),
|
|
||||||
password: z.string(),
|
|
||||||
isActive: z.boolean(),
|
|
||||||
})
|
|
||||||
|
|
||||||
export function operatorFormSchema(mode: 'create' | 'edit') {
|
|
||||||
return mode === 'create'
|
return mode === 'create'
|
||||||
? baseSchema.extend({
|
? baseSchema.extend({
|
||||||
password: z.string().min(1, t('validation.required', '')),
|
password: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
})
|
})
|
||||||
: baseSchema
|
: baseSchema
|
||||||
}
|
}
|
||||||
|
|
||||||
export type OperatorFormData = z.infer<typeof baseSchema>
|
export type OperatorFormData = z.infer<ReturnType<typeof operatorFormSchema>>
|
||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: OperatorFormData = {
|
export const DEFAULT_FORM_VALUES: OperatorFormData = {
|
||||||
username: '',
|
username: '',
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
import { useState } from 'react'
|
import { useState, useMemo, useEffect, useCallback } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
|
import { useForm } from 'react-hook-form'
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
import { FormInput } from '@/components/formInput'
|
import { FormInput } from '@/components/formInput'
|
||||||
import { FormActions } from '@/components/formActions'
|
import { FormActions } from '@/components/formActions'
|
||||||
import { useCreatePermission, useUpdatePermission } from '../hooks/usePermissions'
|
import { useCreatePermission, useUpdatePermission } from '../hooks/usePermissions'
|
||||||
import type { Permission, PermissionPayload } from '../api/permissionsApi'
|
import { createPermissionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/permission.schema'
|
||||||
|
import type { PermissionFormData } from '../schemas/permission.schema'
|
||||||
|
import type { Permission } from '../api/permissionsApi'
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -14,14 +18,6 @@ interface PermissionFormProps {
|
|||||||
permissionId?: number
|
permissionId?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
interface FormErrors {
|
|
||||||
code?: string
|
|
||||||
name_tk?: string
|
|
||||||
name_ru?: string
|
|
||||||
name_en?: string
|
|
||||||
guard_name?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
type LangKey = 'tk' | 'ru' | 'en'
|
type LangKey = 'tk' | 'ru' | 'en'
|
||||||
|
|
||||||
const LANG_TABS: { key: LangKey; label: string }[] = [
|
const LANG_TABS: { key: LangKey; label: string }[] = [
|
||||||
@@ -36,10 +32,25 @@ const GUARD_OPTIONS = [
|
|||||||
{ value: 'sanctum', label: 'sanctum' },
|
{ value: 'sanctum', label: 'sanctum' },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
type FlatErrors = Partial<Record<keyof PermissionFormData, string>>
|
||||||
|
|
||||||
|
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||||
|
const result: FlatErrors = {}
|
||||||
|
for (const key of Object.keys(errors)) {
|
||||||
|
const msg = errors[key]?.message
|
||||||
|
if (msg) result[key as keyof PermissionFormData] = msg
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
// ─── PermissionForm ───────────────────────────────────────────────────────────
|
// ─── PermissionForm ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function PermissionForm({ mode, initialData, permissionId }: PermissionFormProps) {
|
export function PermissionForm({ mode, initialData, permissionId }: PermissionFormProps) {
|
||||||
const { t } = useTranslation()
|
const { t: _t, i18n } = useTranslation()
|
||||||
|
const t: (key: string, fallback?: string) => string = useCallback(
|
||||||
|
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||||
|
[_t],
|
||||||
|
)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const createPermission = useCreatePermission()
|
const createPermission = useCreatePermission()
|
||||||
@@ -48,57 +59,63 @@ export function PermissionForm({ mode, initialData, permissionId }: PermissionFo
|
|||||||
const isPending = createPermission.isPending || updatePermission.isPending
|
const isPending = createPermission.isPending || updatePermission.isPending
|
||||||
|
|
||||||
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
||||||
const [errors, setErrors] = useState<FormErrors>({})
|
|
||||||
|
|
||||||
const [form, setForm] = useState<PermissionPayload>({
|
const schema = useMemo(() => createPermissionFormSchema(t), [t, i18n.language])
|
||||||
code: initialData?.code ?? '',
|
|
||||||
guard_name: initialData?.guard_name ?? 'web',
|
const {
|
||||||
name: {
|
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||||
tk: initialData?.name?.tk ?? '',
|
} = useForm<PermissionFormData>({
|
||||||
ru: initialData?.name?.ru ?? '',
|
resolver: zodResolver(schema),
|
||||||
en: initialData?.name?.en ?? '',
|
defaultValues: initialData
|
||||||
},
|
? {
|
||||||
|
...DEFAULT_FORM_VALUES,
|
||||||
|
code: initialData.code,
|
||||||
|
nameTk: initialData.name.tk,
|
||||||
|
nameRu: initialData.name.ru,
|
||||||
|
nameEn: initialData.name.en,
|
||||||
|
guard_name: initialData.guard_name,
|
||||||
|
}
|
||||||
|
: DEFAULT_FORM_VALUES,
|
||||||
})
|
})
|
||||||
|
|
||||||
// ── Helpers ────────────────────────────────────────────────────────────────
|
const form = watch()
|
||||||
|
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||||
|
|
||||||
const setField = (field: keyof Omit<PermissionPayload, 'name'>, value: string) => {
|
const setField = useCallback(
|
||||||
setForm((prev) => ({ ...prev, [field]: value }))
|
(key: keyof PermissionFormData) => (value: string) => {
|
||||||
setErrors((prev) => ({ ...prev, [field]: undefined }))
|
(setValue as (k: keyof PermissionFormData, v: string) => void)(key, value)
|
||||||
}
|
clearErrors(key)
|
||||||
|
},
|
||||||
|
[setValue, clearErrors],
|
||||||
|
)
|
||||||
|
|
||||||
const setNameField = (lang: LangKey, value: string) => {
|
const setNameField = (lang: LangKey, value: string) => {
|
||||||
setForm((prev) => ({ ...prev, name: { ...prev.name, [lang]: value } }))
|
const key = `name${lang.charAt(0).toUpperCase() + lang.slice(1)}` as 'nameTk' | 'nameRu' | 'nameEn'
|
||||||
setErrors((prev) => ({ ...prev, [`name_${lang}`]: undefined }))
|
setValue(key, value)
|
||||||
|
clearErrors(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Validation ─────────────────────────────────────────────────────────────
|
// ── Re-validate on language change ──
|
||||||
|
useEffect(() => {
|
||||||
const validate = (): boolean => {
|
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||||
const newErrors: FormErrors = {}
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [i18n.language])
|
||||||
if (!form.code.trim())
|
|
||||||
newErrors.code = t('permissions.validation.codeRequired', 'Kod hökman!')
|
|
||||||
if (!form.name.tk.trim())
|
|
||||||
newErrors.name_tk = t('permissions.validation.nameTkRequired', 'Türkmençe ady hökman!')
|
|
||||||
if (!form.guard_name.trim())
|
|
||||||
newErrors.guard_name = t('permissions.validation.guardRequired', 'Guard name hökman!')
|
|
||||||
|
|
||||||
setErrors(newErrors)
|
|
||||||
return Object.keys(newErrors).length === 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Submit ─────────────────────────────────────────────────────────────────
|
// ── Submit ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const handleSubmit = () => {
|
const handleSubmit = async () => {
|
||||||
if (!validate()) return
|
const isValid = await trigger()
|
||||||
|
if (!isValid) return
|
||||||
|
|
||||||
|
const values = getValues()
|
||||||
|
const payload = buildPayload(values)
|
||||||
|
|
||||||
if (mode === 'create') {
|
if (mode === 'create') {
|
||||||
createPermission.mutate(form, {
|
createPermission.mutate(payload, {
|
||||||
onSuccess: () => navigate('/settings/users/permissions'),
|
onSuccess: () => navigate('/settings/users/permissions'),
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
updatePermission.mutate(form, {
|
updatePermission.mutate(payload, {
|
||||||
onSuccess: () => navigate('/settings/users/permissions'),
|
onSuccess: () => navigate('/settings/users/permissions'),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -106,6 +123,9 @@ export function PermissionForm({ mode, initialData, permissionId }: PermissionFo
|
|||||||
|
|
||||||
// ── Render ─────────────────────────────────────────────────────────────────
|
// ── Render ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const activeNameKey = `name${activeLang.charAt(0).toUpperCase() + activeLang.slice(1)}` as 'nameTk' | 'nameRu' | 'nameEn'
|
||||||
|
const nameError = errors[activeNameKey]
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="bg-card border border-border rounded-xl overflow-hidden">
|
<div className="bg-card border border-border rounded-xl overflow-hidden">
|
||||||
|
|
||||||
@@ -118,7 +138,7 @@ export function PermissionForm({ mode, initialData, permissionId }: PermissionFo
|
|||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
value={form.code}
|
value={form.code}
|
||||||
onChange={(v) => setField('code', v)}
|
onChange={setField('code')}
|
||||||
placeholder={t('permissions.fields.code', 'Kod')}
|
placeholder={t('permissions.fields.code', 'Kod')}
|
||||||
error={errors.code}
|
error={errors.code}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
@@ -150,10 +170,10 @@ export function PermissionForm({ mode, initialData, permissionId }: PermissionFo
|
|||||||
</div>
|
</div>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
value={form.name[activeLang]}
|
value={form[activeNameKey]}
|
||||||
onChange={(v) => setNameField(activeLang, v)}
|
onChange={(v) => setNameField(activeLang, v)}
|
||||||
placeholder={t('permissions.fields.name', 'Ady')}
|
placeholder={t('permissions.fields.name', 'Ady')}
|
||||||
error={errors[`name_${activeLang}` as keyof FormErrors]}
|
error={nameError}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -168,7 +188,7 @@ export function PermissionForm({ mode, initialData, permissionId }: PermissionFo
|
|||||||
<FormInput
|
<FormInput
|
||||||
type="select"
|
type="select"
|
||||||
value={form.guard_name}
|
value={form.guard_name}
|
||||||
onChange={(v) => setField('guard_name', v)}
|
onChange={setField('guard_name')}
|
||||||
options={GUARD_OPTIONS}
|
options={GUARD_OPTIONS}
|
||||||
error={errors.guard_name}
|
error={errors.guard_name}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
import type { PermissionPayload } from '../api/permissionsApi'
|
||||||
|
|
||||||
|
export function createPermissionFormSchema(t: (key: string, fallback?: string) => string) {
|
||||||
|
return z.object({
|
||||||
|
code: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
guard_name: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PermissionFormData = z.infer<ReturnType<typeof createPermissionFormSchema>>
|
||||||
|
|
||||||
|
export const DEFAULT_FORM_VALUES: PermissionFormData = {
|
||||||
|
code: '',
|
||||||
|
nameTk: '',
|
||||||
|
nameRu: '',
|
||||||
|
nameEn: '',
|
||||||
|
guard_name: 'web',
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildPayload(data: PermissionFormData): PermissionPayload {
|
||||||
|
return {
|
||||||
|
code: data.code,
|
||||||
|
name: {
|
||||||
|
tk: data.nameTk,
|
||||||
|
ru: data.nameRu,
|
||||||
|
en: data.nameEn,
|
||||||
|
},
|
||||||
|
guard_name: data.guard_name,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,7 +25,7 @@ import { cn } from '@/lib/utils'
|
|||||||
import { FormInput } from '@/components/formInput'
|
import { FormInput } from '@/components/formInput'
|
||||||
import { FormActions } from '@/components/formActions'
|
import { FormActions } from '@/components/formActions'
|
||||||
import { useCreateRequiredDocument, useUpdateRequiredDocument } from '../hooks/useRequiredDocuments'
|
import { useCreateRequiredDocument, useUpdateRequiredDocument } from '../hooks/useRequiredDocuments'
|
||||||
import { requiredDocumentFormSchema, DEFAULT_FORM_VALUES, buildPayload, mapInitial } from '../schemas/requiredDocument.schema'
|
import { createRequiredDocumentFormSchema, DEFAULT_FORM_VALUES, buildPayload, mapInitial } from '../schemas/requiredDocument.schema'
|
||||||
import type { RequiredDocumentFormData } from '../schemas/requiredDocument.schema'
|
import type { RequiredDocumentFormData } from '../schemas/requiredDocument.schema'
|
||||||
import type { LoanDocument, LoanDocumentTranslation } from '../api/requiredDocumentsApi'
|
import type { LoanDocument, LoanDocumentTranslation } from '../api/requiredDocumentsApi'
|
||||||
|
|
||||||
@@ -199,7 +199,11 @@ function flattenErrors(
|
|||||||
// ─── RequiredDocumentForm ─────────────────────────────────────────────────────────
|
// ─── RequiredDocumentForm ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function RequiredDocumentForm({ mode, initialData, requiredDocumentId }: RequiredDocumentFormProps) {
|
export function RequiredDocumentForm({ mode, initialData, requiredDocumentId }: RequiredDocumentFormProps) {
|
||||||
const { t } = useTranslation()
|
const { t: _t, i18n } = useTranslation()
|
||||||
|
const t: (key: string, fallback?: string) => string = useCallback(
|
||||||
|
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||||
|
[_t],
|
||||||
|
)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
// Per-field locale tabs (UI only, not form state)
|
// Per-field locale tabs (UI only, not form state)
|
||||||
@@ -211,6 +215,8 @@ export function RequiredDocumentForm({ mode, initialData, requiredDocumentId }:
|
|||||||
|
|
||||||
const isPending = createMutation.isPending || updateMutation.isPending
|
const isPending = createMutation.isPending || updateMutation.isPending
|
||||||
|
|
||||||
|
const schema = useMemo(() => createRequiredDocumentFormSchema(t), [t, i18n.language])
|
||||||
|
|
||||||
const {
|
const {
|
||||||
watch,
|
watch,
|
||||||
setValue,
|
setValue,
|
||||||
@@ -218,7 +224,7 @@ export function RequiredDocumentForm({ mode, initialData, requiredDocumentId }:
|
|||||||
formState: { errors: rhfErrors },
|
formState: { errors: rhfErrors },
|
||||||
trigger,
|
trigger,
|
||||||
} = useForm<RequiredDocumentFormData>({
|
} = useForm<RequiredDocumentFormData>({
|
||||||
resolver: zodResolver(requiredDocumentFormSchema),
|
resolver: zodResolver(schema),
|
||||||
defaultValues: initialData
|
defaultValues: initialData
|
||||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||||
: DEFAULT_FORM_VALUES,
|
: DEFAULT_FORM_VALUES,
|
||||||
@@ -230,6 +236,12 @@ export function RequiredDocumentForm({ mode, initialData, requiredDocumentId }:
|
|||||||
[rhfErrors],
|
[rhfErrors],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ── Re-validate on language change ──
|
||||||
|
useEffect(() => {
|
||||||
|
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [i18n.language])
|
||||||
|
|
||||||
// Derive LoanDocumentTranslation objects so the JSX stays unchanged
|
// Derive LoanDocumentTranslation objects so the JSX stays unchanged
|
||||||
const name: LoanDocumentTranslation = useMemo(
|
const name: LoanDocumentTranslation = useMemo(
|
||||||
() => ({ tk: form.nameTk, ru: form.nameRu, en: form.nameEn }),
|
() => ({ tk: form.nameTk, ru: form.nameRu, en: form.nameEn }),
|
||||||
|
|||||||
@@ -1,19 +1,18 @@
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import i18next from 'i18next'
|
|
||||||
import type { LoanDocument, LoanDocumentPayload } from '../api/requiredDocumentsApi'
|
import type { LoanDocument, LoanDocumentPayload } from '../api/requiredDocumentsApi'
|
||||||
|
|
||||||
const t = i18next.t.bind(i18next)
|
export function createRequiredDocumentFormSchema(t: (key: string, fallback?: string) => string) {
|
||||||
|
return z.object({
|
||||||
|
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
descTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
descRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
descEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
export const requiredDocumentFormSchema = z.object({
|
export type RequiredDocumentFormData = z.infer<ReturnType<typeof createRequiredDocumentFormSchema>>
|
||||||
nameTk: z.string().min(1, t('validation.required', '')),
|
|
||||||
nameRu: z.string().min(1, t('validation.required', '')),
|
|
||||||
nameEn: z.string().min(1, t('validation.required', '')),
|
|
||||||
descTk: z.string().min(1, t('validation.required', '')),
|
|
||||||
descRu: z.string().min(1, t('validation.required', '')),
|
|
||||||
descEn: z.string().min(1, t('validation.required', '')),
|
|
||||||
})
|
|
||||||
|
|
||||||
export type RequiredDocumentFormData = z.infer<typeof requiredDocumentFormSchema>
|
|
||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: RequiredDocumentFormData = {
|
export const DEFAULT_FORM_VALUES: RequiredDocumentFormData = {
|
||||||
nameTk: '',
|
nameTk: '',
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
import { useState } from 'react'
|
import { useState, useMemo, useEffect, useCallback } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
|
import { useForm } from 'react-hook-form'
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
import { FormInput } from '@/components/formInput'
|
import { FormInput } from '@/components/formInput'
|
||||||
import { FormActions } from '@/components/formActions'
|
import { FormActions } from '@/components/formActions'
|
||||||
import { useCreateRole, useUpdateRole } from '../hooks/useRoles'
|
import { useCreateRole, useUpdateRole } from '../hooks/useRoles'
|
||||||
import type { Role, RolePayload } from '../api/rolesApi'
|
import { createRoleFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/role.schema'
|
||||||
|
import type { RoleFormData } from '../schemas/role.schema'
|
||||||
|
import type { Role } from '../api/rolesApi'
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -14,14 +18,6 @@ interface RoleFormProps {
|
|||||||
roleId?: number
|
roleId?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
interface FormErrors {
|
|
||||||
code?: string
|
|
||||||
name_tk?: string
|
|
||||||
name_ru?: string
|
|
||||||
name_en?: string
|
|
||||||
guard_name?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
type LangKey = 'tk' | 'ru' | 'en'
|
type LangKey = 'tk' | 'ru' | 'en'
|
||||||
|
|
||||||
const LANG_TABS: { key: LangKey; label: string }[] = [
|
const LANG_TABS: { key: LangKey; label: string }[] = [
|
||||||
@@ -36,10 +32,25 @@ const GUARD_OPTIONS = [
|
|||||||
{ value: 'sanctum', label: 'sanctum' },
|
{ value: 'sanctum', label: 'sanctum' },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
type FlatErrors = Partial<Record<keyof RoleFormData, string>>
|
||||||
|
|
||||||
|
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||||
|
const result: FlatErrors = {}
|
||||||
|
for (const key of Object.keys(errors)) {
|
||||||
|
const msg = errors[key]?.message
|
||||||
|
if (msg) result[key as keyof RoleFormData] = msg
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
// ─── RoleForm ─────────────────────────────────────────────────────────────────
|
// ─── RoleForm ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function RoleForm({ mode, initialData, roleId }: RoleFormProps) {
|
export function RoleForm({ mode, initialData, roleId }: RoleFormProps) {
|
||||||
const { t } = useTranslation()
|
const { t: _t, i18n } = useTranslation()
|
||||||
|
const t: (key: string, fallback?: string) => string = useCallback(
|
||||||
|
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||||
|
[_t],
|
||||||
|
)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const createRole = useCreateRole()
|
const createRole = useCreateRole()
|
||||||
@@ -48,57 +59,63 @@ export function RoleForm({ mode, initialData, roleId }: RoleFormProps) {
|
|||||||
const isPending = createRole.isPending || updateRole.isPending
|
const isPending = createRole.isPending || updateRole.isPending
|
||||||
|
|
||||||
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
||||||
const [errors, setErrors] = useState<FormErrors>({})
|
|
||||||
|
|
||||||
const [form, setForm] = useState<RolePayload>({
|
const schema = useMemo(() => createRoleFormSchema(t), [t, i18n.language])
|
||||||
code: initialData?.code ?? '',
|
|
||||||
guard_name: initialData?.guard_name ?? 'web',
|
const {
|
||||||
name: {
|
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||||
tk: initialData?.name?.tk ?? '',
|
} = useForm<RoleFormData>({
|
||||||
ru: initialData?.name?.ru ?? '',
|
resolver: zodResolver(schema),
|
||||||
en: initialData?.name?.en ?? '',
|
defaultValues: initialData
|
||||||
},
|
? {
|
||||||
|
...DEFAULT_FORM_VALUES,
|
||||||
|
code: initialData.code,
|
||||||
|
nameTk: initialData.name.tk,
|
||||||
|
nameRu: initialData.name.ru,
|
||||||
|
nameEn: initialData.name.en,
|
||||||
|
guard_name: initialData.guard_name,
|
||||||
|
}
|
||||||
|
: DEFAULT_FORM_VALUES,
|
||||||
})
|
})
|
||||||
|
|
||||||
// ── Helpers ────────────────────────────────────────────────────────────────
|
const form = watch()
|
||||||
|
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||||
|
|
||||||
const setField = (field: keyof Omit<RolePayload, 'name'>, value: string) => {
|
const setField = useCallback(
|
||||||
setForm((prev) => ({ ...prev, [field]: value }))
|
(key: keyof RoleFormData) => (value: string) => {
|
||||||
setErrors((prev) => ({ ...prev, [field]: undefined }))
|
(setValue as (k: keyof RoleFormData, v: string) => void)(key, value)
|
||||||
}
|
clearErrors(key)
|
||||||
|
},
|
||||||
|
[setValue, clearErrors],
|
||||||
|
)
|
||||||
|
|
||||||
const setNameField = (lang: LangKey, value: string) => {
|
const setNameField = (lang: LangKey, value: string) => {
|
||||||
setForm((prev) => ({ ...prev, name: { ...prev.name, [lang]: value } }))
|
const key = `name${lang.charAt(0).toUpperCase() + lang.slice(1)}` as 'nameTk' | 'nameRu' | 'nameEn'
|
||||||
setErrors((prev) => ({ ...prev, [`name_${lang}`]: undefined }))
|
setValue(key, value)
|
||||||
|
clearErrors(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Validation ─────────────────────────────────────────────────────────────
|
// ── Re-validate on language change ──
|
||||||
|
useEffect(() => {
|
||||||
const validate = (): boolean => {
|
if (Object.keys(rhfErrors).length > 0) trigger()
|
||||||
const newErrors: FormErrors = {}
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [i18n.language])
|
||||||
if (!form.code.trim())
|
|
||||||
newErrors.code = t('roles.validation.codeRequired', 'Kod hökman!')
|
|
||||||
if (!form.name.tk.trim())
|
|
||||||
newErrors.name_tk = t('roles.validation.nameTkRequired', 'Türkmençe ady hökman!')
|
|
||||||
if (!form.guard_name.trim())
|
|
||||||
newErrors.guard_name = t('roles.validation.guardRequired', 'Guard name hökman!')
|
|
||||||
|
|
||||||
setErrors(newErrors)
|
|
||||||
return Object.keys(newErrors).length === 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Submit ─────────────────────────────────────────────────────────────────
|
// ── Submit ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const handleSubmit = () => {
|
const handleSubmit = async () => {
|
||||||
if (!validate()) return
|
const isValid = await trigger()
|
||||||
|
if (!isValid) return
|
||||||
|
|
||||||
|
const values = getValues()
|
||||||
|
const payload = buildPayload(values)
|
||||||
|
|
||||||
if (mode === 'create') {
|
if (mode === 'create') {
|
||||||
createRole.mutate(form, {
|
createRole.mutate(payload, {
|
||||||
onSuccess: () => navigate('/settings/users/roles'),
|
onSuccess: () => navigate('/settings/users/roles'),
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
updateRole.mutate(form, {
|
updateRole.mutate(payload, {
|
||||||
onSuccess: () => navigate('/settings/users/roles'),
|
onSuccess: () => navigate('/settings/users/roles'),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -106,6 +123,9 @@ export function RoleForm({ mode, initialData, roleId }: RoleFormProps) {
|
|||||||
|
|
||||||
// ── Render ─────────────────────────────────────────────────────────────────
|
// ── Render ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const activeNameKey = `name${activeLang.charAt(0).toUpperCase() + activeLang.slice(1)}` as 'nameTk' | 'nameRu' | 'nameEn'
|
||||||
|
const nameError = activeLang === 'tk' ? errors[activeNameKey] : undefined
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="bg-card border border-border rounded-xl overflow-hidden">
|
<div className="bg-card border border-border rounded-xl overflow-hidden">
|
||||||
|
|
||||||
@@ -118,7 +138,7 @@ export function RoleForm({ mode, initialData, roleId }: RoleFormProps) {
|
|||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
value={form.code}
|
value={form.code}
|
||||||
onChange={(v) => setField('code', v)}
|
onChange={setField('code')}
|
||||||
placeholder={t('roles.fields.code', 'Kod')}
|
placeholder={t('roles.fields.code', 'Kod')}
|
||||||
error={errors.code}
|
error={errors.code}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
@@ -132,7 +152,6 @@ export function RoleForm({ mode, initialData, roleId }: RoleFormProps) {
|
|||||||
<span className="text-destructive ml-0.5">*</span>
|
<span className="text-destructive ml-0.5">*</span>
|
||||||
</span>
|
</span>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
{/* Language tabs */}
|
|
||||||
<div className="flex gap-1 justify-end">
|
<div className="flex gap-1 justify-end">
|
||||||
{LANG_TABS.map((tab) => (
|
{LANG_TABS.map((tab) => (
|
||||||
<button
|
<button
|
||||||
@@ -151,10 +170,10 @@ export function RoleForm({ mode, initialData, roleId }: RoleFormProps) {
|
|||||||
</div>
|
</div>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
value={form.name[activeLang]}
|
value={form[activeNameKey]}
|
||||||
onChange={(v) => setNameField(activeLang, v)}
|
onChange={(v) => setNameField(activeLang, v)}
|
||||||
placeholder={t('roles.fields.name', 'Ady')}
|
placeholder={t('roles.fields.name', 'Ady')}
|
||||||
error={errors[`name_${activeLang}` as keyof FormErrors]}
|
error={nameError}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -169,7 +188,7 @@ export function RoleForm({ mode, initialData, roleId }: RoleFormProps) {
|
|||||||
<FormInput
|
<FormInput
|
||||||
type="select"
|
type="select"
|
||||||
value={form.guard_name}
|
value={form.guard_name}
|
||||||
onChange={(v) => setField('guard_name', v)}
|
onChange={setField('guard_name')}
|
||||||
options={GUARD_OPTIONS}
|
options={GUARD_OPTIONS}
|
||||||
error={errors.guard_name}
|
error={errors.guard_name}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
import type { RolePayload } from '../api/rolesApi'
|
||||||
|
|
||||||
|
export function createRoleFormSchema(t: (key: string, fallback?: string) => string) {
|
||||||
|
return z.object({
|
||||||
|
code: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
guard_name: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export type RoleFormData = z.infer<ReturnType<typeof createRoleFormSchema>>
|
||||||
|
|
||||||
|
export const DEFAULT_FORM_VALUES: RoleFormData = {
|
||||||
|
code: '',
|
||||||
|
nameTk: '',
|
||||||
|
nameRu: '',
|
||||||
|
nameEn: '',
|
||||||
|
guard_name: 'web',
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildPayload(data: RoleFormData): RolePayload {
|
||||||
|
return {
|
||||||
|
code: data.code,
|
||||||
|
name: {
|
||||||
|
tk: data.nameTk,
|
||||||
|
ru: data.nameRu,
|
||||||
|
en: data.nameEn,
|
||||||
|
},
|
||||||
|
guard_name: data.guard_name,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useState, useMemo } from 'react'
|
import { useState, useMemo, useEffect, useCallback } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from 'react-hook-form'
|
||||||
@@ -59,24 +59,24 @@ type SentDocKey =
|
|||||||
| 'snt_passport_tm' | 'snt_zagran_passport' | 'snt_entry_stamp'
|
| 'snt_passport_tm' | 'snt_zagran_passport' | 'snt_entry_stamp'
|
||||||
| 'snt_relation_doc' | 'snt_new_passport_series' | 'snt_old_passport_series'
|
| 'snt_relation_doc' | 'snt_new_passport_series' | 'snt_old_passport_series'
|
||||||
|
|
||||||
const ACCEPTED_DOCS: { key: AcceptedDocKey; label: string }[] = [
|
const ACCEPTED_DOCS = (t: (key: string, fallback?: string) => string): { key: AcceptedDocKey; label: string }[] => [
|
||||||
{ key: 'acc_sberbank_card', label: 'Talýba degişli SBERBANK kartynyň rekwizitleri' },
|
{ key: 'acc_sberbank_card', label: t('sberPayments.documents.sberbankCard', 'Talýba degişli SBERBANK kartynyň rekwizitleri') },
|
||||||
{ key: 'acc_enrollment', label: 'Daşary ýurt ÝOM-da okaýandygy baradaky güwänamasy' },
|
{ key: 'acc_enrollment', label: t('sberPayments.documents.enrollment', 'Daşary ýurt ÝOM-da okaýandygy baradaky güwänamasy') },
|
||||||
{ key: 'acc_summons', label: 'Çagyrylma hatynyn göçürmesi' },
|
{ key: 'acc_summons', label: t('sberPayments.documents.summons', 'Çagyrylma hatynyn göçürmesi') },
|
||||||
{ key: 'acc_passport_tm', label: 'TM içki pasportynyň asyl görnüşi we göçürmesi' },
|
{ key: 'acc_passport_tm', label: t('sberPayments.documents.passportTm', 'TM içki pasportynyň asyl görnüşi we göçürmesi') },
|
||||||
{ key: 'acc_zagran_passport', label: 'Daşary ýurt (zagran) pasportynyň göçürmesi' },
|
{ key: 'acc_zagran_passport', label: t('sberPayments.documents.zagranPassport', 'Daşary ýurt (zagran) pasportynyň göçürmesi') },
|
||||||
{ key: 'acc_visa_page', label: 'Daşary ýurda rugsat (wizasy) bellenen sahypasynyň göçürmesi' },
|
{ key: 'acc_visa_page', label: t('sberPayments.documents.visaPage', 'Daşary ýurda rugsat (wizasy) bellenen sahypasynyň göçürmesi') },
|
||||||
{ key: 'acc_entry_stamp', label: 'Daşary ýurt döwletine girenliği baradaky ştamply sahypasynyň göçürmesi' },
|
{ key: 'acc_entry_stamp', label: t('sberPayments.documents.entryStamp', 'Daşary ýurt döwletine girenliği baradaky ştamply sahypasynyň göçürmesi') },
|
||||||
{ key: 'acc_school_letter', label: 'ÝOM-dan hat (daşary ýurt dilinde maglumatly)' },
|
{ key: 'acc_school_letter', label: t('sberPayments.documents.schoolLetter', 'ÝOM-dan hat (daşary ýurt dilinde maglumatly)') },
|
||||||
]
|
]
|
||||||
|
|
||||||
const SENT_DOCS: { key: SentDocKey; label: string }[] = [
|
const SENT_DOCS = (t: (key: string, fallback?: string) => string): { key: SentDocKey; label: string }[] => [
|
||||||
{ key: 'snt_passport_tm', label: 'Ugradyjynyň TM içki pasportynyň asyl görnüşi we göçürmesi' },
|
{ key: 'snt_passport_tm', label: t('sberPayments.documents.sentPassportTm', 'Ugradyjynyň TM içki pasportynyň asyl görnüşi we göçürmesi') },
|
||||||
{ key: 'snt_zagran_passport', label: 'Ugradyjynyň daşary ýurt pasportynyň asyl görnüşi we göçürmesi' },
|
{ key: 'snt_zagran_passport', label: t('sberPayments.documents.sentZagranPassport', 'Ugradyjynyň daşary ýurt pasportynyň asyl görnüşi we göçürmesi') },
|
||||||
{ key: 'snt_entry_stamp', label: 'Ugradyjynyň daşary döwletine girenliği ştamply sahypasynyň göçürmesi' },
|
{ key: 'snt_entry_stamp', label: t('sberPayments.documents.sentEntryStamp', 'Ugradyjynyň daşary döwletine girenliği ştamply sahypasynyň göçürmesi') },
|
||||||
{ key: 'snt_relation_doc', label: 'Ugradyjy we kabul edijiniň garyndaşlyk tassyklaýjy resminamasynyn göçürmesi' },
|
{ key: 'snt_relation_doc', label: t('sberPayments.documents.sentRelationDoc', 'Ugradyjy we kabul edijiniň garyndaşlyk tassyklaýjy resminamasynyn göçürmesi') },
|
||||||
{ key: 'snt_new_passport_series', label: 'Ugradyjy/kabul ediji täze (2015+) pasport seriýasy maglumaty' },
|
{ key: 'snt_new_passport_series', label: t('sberPayments.documents.sentNewPassportSeries', 'Ugradyjy/kabul ediji täze (2015+) pasport seriýasy maglumaty') },
|
||||||
{ key: 'snt_old_passport_series', label: 'Ugradyjy/kabul ediji köne pasport seriýasy baradaky güwänamasy' },
|
{ key: 'snt_old_passport_series', label: t('sberPayments.documents.sentOldPassportSeries', 'Ugradyjy/kabul ediji köne pasport seriýasy baradaky güwänamasy') },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@@ -118,30 +118,31 @@ function BentoCard({
|
|||||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function StepGeneral({
|
function StepGeneral({
|
||||||
form, errors, set,
|
form, errors, set, t,
|
||||||
}: {
|
}: {
|
||||||
form: SberPaymentFormData
|
form: SberPaymentFormData
|
||||||
errors: FlatErrors
|
errors: FlatErrors
|
||||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||||
|
t: (key: string, fallback?: string) => string
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<BentoGrid cols={2}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard title="Müşderi">
|
<BentoCard title={t('sberPayments.cards.musteri', 'Müşderi')}>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="searchable-select"
|
type="searchable-select"
|
||||||
label="Ulanyjy"
|
label={t('sberPayments.fields.client_id', 'Ulanyjy')}
|
||||||
value={form.client_id}
|
value={form.client_id}
|
||||||
onChange={(v) => set('client_id', v)}
|
onChange={(v) => set('client_id', v)}
|
||||||
options={[]}
|
options={[]}
|
||||||
placeholder="Saýlamak üçin basyň"
|
placeholder={t('sberPayments.placeholders.select', 'Saýlamak üçin basyň')}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
<BentoCard title="Status">
|
<BentoCard title={t('sberPayments.cards.status', 'Status')}>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="select"
|
type="select"
|
||||||
label="Status"
|
label={t('sberPayments.fields.status', 'Status')}
|
||||||
value={form.status}
|
value={form.status}
|
||||||
onChange={(v) => set('status', v as PaymentStatus)}
|
onChange={(v) => set('status', v as PaymentStatus)}
|
||||||
options={STATUSES}
|
options={STATUSES}
|
||||||
@@ -150,13 +151,13 @@ function StepGeneral({
|
|||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
<BentoCard title="Bellik" span="full">
|
<BentoCard title={t('sberPayments.cards.bellik', 'Bellik')} span="full">
|
||||||
<FormInput
|
<FormInput
|
||||||
type="textarea"
|
type="textarea"
|
||||||
label="Bellik"
|
label={t('sberPayments.fields.bellik', 'Bellik')}
|
||||||
value={form.bellik}
|
value={form.bellik}
|
||||||
onChange={(v) => set('bellik', v)}
|
onChange={(v) => set('bellik', v)}
|
||||||
placeholder="Bellik..."
|
placeholder={t('sberPayments.placeholders.bellik', 'Bellik...')}
|
||||||
rows={2}
|
rows={2}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
@@ -165,40 +166,41 @@ function StepGeneral({
|
|||||||
}
|
}
|
||||||
|
|
||||||
function StepLocation({
|
function StepLocation({
|
||||||
form, errors, set,
|
form, errors, set, t,
|
||||||
}: {
|
}: {
|
||||||
form: SberPaymentFormData
|
form: SberPaymentFormData
|
||||||
errors: FlatErrors
|
errors: FlatErrors
|
||||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||||
|
t: (key: string, fallback?: string) => string
|
||||||
}) {
|
}) {
|
||||||
const branches = form.welayat ? (SAHAMCALAR[form.welayat] ?? []) : []
|
const branches = form.welayat ? (SAHAMCALAR[form.welayat] ?? []) : []
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<BentoGrid cols={2}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard title="Welaýat">
|
<BentoCard title={t('sberPayments.cards.welayat', 'Welaýat')}>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="select"
|
type="select"
|
||||||
label="Welaýat"
|
label={t('sberPayments.fields.welayat', 'Welaýat')}
|
||||||
value={form.welayat}
|
value={form.welayat}
|
||||||
onChange={(v) => { set('welayat', v); set('sahamca', '') }}
|
onChange={(v) => { set('welayat', v); set('sahamca', '') }}
|
||||||
options={WELAYATLAR.map((w) => ({ value: w, label: w }))}
|
options={WELAYATLAR.map((w) => ({ value: w, label: w }))}
|
||||||
placeholder="Aşgabat"
|
placeholder={t('sberPayments.placeholders.welayat', 'Aşgabat')}
|
||||||
error={errors.welayat}
|
error={errors.welayat}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-xs text-muted-foreground">
|
||||||
Welaýaty saýlasaňyz şahamçalar güncellenar.
|
{t('sberPayments.hints.selectRegion', 'Welaýaty saýlasaňyz şahamçalar güncellenar.')}
|
||||||
</p>
|
</p>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
<BentoCard title="Şahamça">
|
<BentoCard title={t('sberPayments.cards.sahamca', 'Şahamça')}>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="searchable-select"
|
type="searchable-select"
|
||||||
label="Şahamça"
|
label={t('sberPayments.fields.sahamca', 'Şahamça')}
|
||||||
value={form.sahamca}
|
value={form.sahamca}
|
||||||
onChange={(v) => set('sahamca', v)}
|
onChange={(v) => set('sahamca', v)}
|
||||||
options={branches.map((b) => ({ value: b, label: b }))}
|
options={branches.map((b) => ({ value: b, label: b }))}
|
||||||
placeholder="Saýlamak üçin basyň"
|
placeholder={t('sberPayments.placeholders.select', 'Saýlamak üçin basyň')}
|
||||||
disabled={!form.welayat}
|
disabled={!form.welayat}
|
||||||
error={errors.sahamca}
|
error={errors.sahamca}
|
||||||
required
|
required
|
||||||
@@ -209,39 +211,40 @@ function StepLocation({
|
|||||||
}
|
}
|
||||||
|
|
||||||
function StepPersonal({
|
function StepPersonal({
|
||||||
form, errors, set,
|
form, errors, set, t,
|
||||||
}: {
|
}: {
|
||||||
form: SberPaymentFormData
|
form: SberPaymentFormData
|
||||||
errors: FlatErrors
|
errors: FlatErrors
|
||||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||||
|
t: (key: string, fallback?: string) => string
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<BentoGrid cols={2}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard title="At-familýa">
|
<BentoCard title={t('sberPayments.cards.atFamilia', 'At-familýa')}>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label="Pasportdaky familiýa"
|
label={t('sberPayments.fields.lastName', 'Pasportdaky familiýa')}
|
||||||
value={form.lastName}
|
value={form.lastName}
|
||||||
onChange={(v) => set('lastName', v)}
|
onChange={(v) => set('lastName', v)}
|
||||||
placeholder="NURYYEW"
|
placeholder={t('sberPayments.placeholders.lastName', 'NURYYEW')}
|
||||||
error={errors.lastName}
|
error={errors.lastName}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label="Pasportdaky ady"
|
label={t('sberPayments.fields.firstName', 'Pasportdaky ady')}
|
||||||
value={form.firstName}
|
value={form.firstName}
|
||||||
onChange={(v) => set('firstName', v)}
|
onChange={(v) => set('firstName', v)}
|
||||||
placeholder="HAÝDAR"
|
placeholder={t('sberPayments.placeholders.firstName', 'HAÝDAR')}
|
||||||
error={errors.firstName}
|
error={errors.firstName}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
<BentoCard title="Kontakt">
|
<BentoCard title={t('sberPayments.cards.kontakt', 'Kontakt')}>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="phone"
|
type="phone"
|
||||||
label="Telefon"
|
label={t('sberPayments.fields.phone', 'Telefon')}
|
||||||
value={form.phone}
|
value={form.phone}
|
||||||
onChange={(v) => set('phone', v)}
|
onChange={(v) => set('phone', v)}
|
||||||
error={errors.phone}
|
error={errors.phone}
|
||||||
@@ -249,20 +252,20 @@ function StepPersonal({
|
|||||||
/>
|
/>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="email"
|
type="email"
|
||||||
label="E-poçta"
|
label={t('sberPayments.fields.email', 'E-poçta')}
|
||||||
value={form.email}
|
value={form.email}
|
||||||
onChange={(v) => set('email', v)}
|
onChange={(v) => set('email', v)}
|
||||||
placeholder="email@example.com"
|
placeholder={t('sberPayments.placeholders.email', 'email@example.com')}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
<BentoCard title="Häzirki ýaşyş ýeri" span="full">
|
<BentoCard title={t('sberPayments.cards.yasysYeri', 'Häzirki ýaşyş ýeri')} span="full">
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label="Salgy"
|
label={t('sberPayments.fields.address', 'Salgy')}
|
||||||
value={form.address}
|
value={form.address}
|
||||||
onChange={(v) => set('address', v)}
|
onChange={(v) => set('address', v)}
|
||||||
placeholder="Köçe, jaý belgisi..."
|
placeholder={t('sberPayments.placeholders.address', 'Köçe, jaý belgisi...')}
|
||||||
error={errors.address}
|
error={errors.address}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
@@ -272,18 +275,19 @@ function StepPersonal({
|
|||||||
}
|
}
|
||||||
|
|
||||||
function StepPayment({
|
function StepPayment({
|
||||||
form, errors, set,
|
form, errors, set, t,
|
||||||
}: {
|
}: {
|
||||||
form: SberPaymentFormData
|
form: SberPaymentFormData
|
||||||
errors: FlatErrors
|
errors: FlatErrors
|
||||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||||
|
t: (key: string, fallback?: string) => string
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<BentoGrid cols={2}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard title="Pasport maglumatlary">
|
<BentoCard title={t('sberPayments.cards.pasportMaglumatlary', 'Pasport maglumatlary')}>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="searchable-select"
|
type="searchable-select"
|
||||||
label="Pasport seriýasy"
|
label={t('sberPayments.fields.passportSeries', 'Pasport seriýasy')}
|
||||||
value={form.passportSeries}
|
value={form.passportSeries}
|
||||||
onChange={(v) => set('passportSeries', v)}
|
onChange={(v) => set('passportSeries', v)}
|
||||||
options={[
|
options={[
|
||||||
@@ -292,37 +296,37 @@ function StepPayment({
|
|||||||
{ value: 'II-MC', label: 'II-MC' },
|
{ value: 'II-MC', label: 'II-MC' },
|
||||||
{ value: 'II-MD', label: 'II-MD' },
|
{ value: 'II-MD', label: 'II-MD' },
|
||||||
]}
|
]}
|
||||||
placeholder="Saýlamak üçin basyň"
|
placeholder={t('sberPayments.placeholders.select', 'Saýlamak üçin basyň')}
|
||||||
error={errors.passportSeries}
|
error={errors.passportSeries}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label="Pasport nomeri"
|
label={t('sberPayments.fields.passportNumber', 'Pasport nomeri')}
|
||||||
value={form.passportNumber}
|
value={form.passportNumber}
|
||||||
onChange={(v) => set('passportNumber', v)}
|
onChange={(v) => set('passportNumber', v)}
|
||||||
placeholder="A123456"
|
placeholder={t('sberPayments.placeholders.passportNumber', 'A123456')}
|
||||||
error={errors.passportNumber}
|
error={errors.passportNumber}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
<BentoCard title="Ugradyjy">
|
<BentoCard title={t('sberPayments.cards.ugradyjy', 'Ugradyjy')}>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label="Ady Familiýasy Atasynyň ady"
|
label={t('sberPayments.fields.fullName', 'Ady Familiýasy Atasynyň ady')}
|
||||||
value={form.fullName}
|
value={form.fullName}
|
||||||
onChange={(v) => set('fullName', v)}
|
onChange={(v) => set('fullName', v)}
|
||||||
placeholder="Doly ady..."
|
placeholder={t('sberPayments.placeholders.fullName', 'Doly ady...')}
|
||||||
error={errors.fullName}
|
error={errors.fullName}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label="Goýum hasaby"
|
label={t('sberPayments.fields.accountNumber', 'Goýum hasaby')}
|
||||||
value={form.accountNumber}
|
value={form.accountNumber}
|
||||||
onChange={(v) => set('accountNumber', v)}
|
onChange={(v) => set('accountNumber', v)}
|
||||||
placeholder="1234 5678 ..."
|
placeholder={t('sberPayments.placeholders.accountNumber', '1234 5678 ...')}
|
||||||
error={errors.accountNumber}
|
error={errors.accountNumber}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
@@ -332,16 +336,17 @@ function StepPayment({
|
|||||||
}
|
}
|
||||||
|
|
||||||
function StepDocs({
|
function StepDocs({
|
||||||
form, set,
|
form, set, t,
|
||||||
}: {
|
}: {
|
||||||
form: SberPaymentFormData
|
form: SberPaymentFormData
|
||||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||||
|
t: (key: string, fallback?: string) => string
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<BentoGrid cols={2}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard title="Kabul ediji talyp — 8 resminama">
|
<BentoCard title={t('sberPayments.cards.documentsAccepted', 'Kabul ediji talyp — 8 resminama')}>
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{ACCEPTED_DOCS.map(({ key, label }) => (
|
{ACCEPTED_DOCS(t).map(({ key, label }) => (
|
||||||
<FormInput
|
<FormInput
|
||||||
key={key}
|
key={key}
|
||||||
type="file"
|
type="file"
|
||||||
@@ -354,9 +359,9 @@ function StepDocs({
|
|||||||
</div>
|
</div>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
<BentoCard title="Ugradyjy — 6 resminama">
|
<BentoCard title={t('sberPayments.cards.documentsSent', 'Ugradyjy — 6 resminama')}>
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{SENT_DOCS.map(({ key, label }) => (
|
{SENT_DOCS(t).map(({ key, label }) => (
|
||||||
<FormInput
|
<FormInput
|
||||||
key={key}
|
key={key}
|
||||||
type="file"
|
type="file"
|
||||||
@@ -376,12 +381,12 @@ function StepDocs({
|
|||||||
|
|
||||||
type StepId = 'general' | 'location' | 'personal' | 'payment' | 'docs'
|
type StepId = 'general' | 'location' | 'personal' | 'payment' | 'docs'
|
||||||
|
|
||||||
const STEPS: { id: StepId; title: string; subtitle: string }[] = [
|
const getSteps = (t: (key: string, fallback?: string) => string): { id: StepId; title: string; subtitle: string }[] => [
|
||||||
{ id: 'general', title: 'Esasy', subtitle: 'Status, müşderi' },
|
{ id: 'general', title: t('sberPayments.steps.general.title', 'Esasy'), subtitle: t('sberPayments.steps.general.subtitle', 'Status, müşderi') },
|
||||||
{ id: 'location', title: 'Lokasiýa', subtitle: 'Welaýat, şahamça' },
|
{ id: 'location', title: t('sberPayments.steps.location.title', 'Lokasiýa'), subtitle: t('sberPayments.steps.location.subtitle', 'Welaýat, şahamça') },
|
||||||
{ id: 'personal', title: 'Şahsy', subtitle: 'Pasport, kontakt' },
|
{ id: 'personal', title: t('sberPayments.steps.personal.title', 'Şahsy'), subtitle: t('sberPayments.steps.personal.subtitle', 'Pasport, kontakt') },
|
||||||
{ id: 'payment', title: 'Töleg', subtitle: 'Hasap, ugradyjy' },
|
{ id: 'payment', title: t('sberPayments.steps.payment.title', 'Töleg'), subtitle: t('sberPayments.steps.payment.subtitle', 'Hasap, ugradyjy') },
|
||||||
{ id: 'docs', title: 'Resminamalar', subtitle: '14 resminama' },
|
{ id: 'docs', title: t('sberPayments.steps.docs.title', 'Resminamalar'), subtitle: t('sberPayments.steps.docs.subtitle', '14 resminama') },
|
||||||
]
|
]
|
||||||
|
|
||||||
// ─── Initial data mapper ──────────────────────────────────────────────────────
|
// ─── Initial data mapper ──────────────────────────────────────────────────────
|
||||||
@@ -407,7 +412,11 @@ function mapInitialData(data: SberPaymentOrder): Partial<SberPaymentFormData> {
|
|||||||
// ─── Main component ───────────────────────────────────────────────────────────
|
// ─── Main component ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormProps) {
|
export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormProps) {
|
||||||
const { t } = useTranslation()
|
const { t: _t, i18n } = useTranslation()
|
||||||
|
const t: (key: string, fallback?: string) => string = useCallback(
|
||||||
|
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||||
|
[_t],
|
||||||
|
)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const createMutation = useCreateSberPayment()
|
const createMutation = useCreateSberPayment()
|
||||||
const updateMutation = useUpdateSberPayment()
|
const updateMutation = useUpdateSberPayment()
|
||||||
@@ -422,33 +431,59 @@ export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormP
|
|||||||
})
|
})
|
||||||
|
|
||||||
const form = watch()
|
const form = watch()
|
||||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
const [validationErrors, setValidationErrors] = useState<FlatErrors>({})
|
||||||
|
|
||||||
|
const rhfFlat = useMemo(
|
||||||
|
() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>),
|
||||||
|
[rhfErrors],
|
||||||
|
)
|
||||||
|
const errors = useMemo(
|
||||||
|
() => ({ ...rhfFlat, ...validationErrors }),
|
||||||
|
[rhfFlat, validationErrors],
|
||||||
|
)
|
||||||
|
|
||||||
|
const steps = useMemo(() => getSteps(t), [i18n.language])
|
||||||
|
|
||||||
const [currentStep, setCurrentStep] = useState(0)
|
const [currentStep, setCurrentStep] = useState(0)
|
||||||
const [stepStatuses, setStepStatuses] = useState<StepStatus[]>(
|
const [stepStatuses, setStepStatuses] = useState<StepStatus[]>(
|
||||||
() => mode === 'edit'
|
() => mode === 'edit'
|
||||||
? STEPS.map((_, i) => (i === 0 ? 'active' : i < 4 ? 'done' : 'idle'))
|
? steps.map((_, i) => (i === 0 ? 'active' : i < 4 ? 'done' : 'idle'))
|
||||||
: STEPS.map((_, i) => (i === 0 ? 'active' : 'idle')),
|
: steps.map((_, i) => (i === 0 ? 'active' : 'idle')),
|
||||||
)
|
)
|
||||||
|
|
||||||
// ── Field setter ──
|
// ── Field setter ──
|
||||||
const set = <K extends keyof SberPaymentFormData>(key: K, value: SberPaymentFormData[K]) => {
|
const set = <K extends keyof SberPaymentFormData>(key: K, value: SberPaymentFormData[K]) => {
|
||||||
(setValue as (name: K, val: SberPaymentFormData[K]) => void)(key, value)
|
(setValue as (name: K, val: SberPaymentFormData[K]) => void)(key, value)
|
||||||
clearErrors(key)
|
clearErrors(key)
|
||||||
|
setValidationErrors((prev) => {
|
||||||
|
const next = { ...prev }
|
||||||
|
delete next[key]
|
||||||
|
return next
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Step validation ──
|
// ── Step validation ──
|
||||||
const doValidateAll = (): FlatErrors => {
|
const doValidateAll = (): FlatErrors => {
|
||||||
const errs: FlatErrors = {}
|
const errs: FlatErrors = {}
|
||||||
for (let i = 0; i <= 3; i++) {
|
for (let i = 0; i <= 3; i++) {
|
||||||
Object.assign(errs, validateStep(i, form, mode))
|
Object.assign(errs, validateStep(i, form, mode, t))
|
||||||
}
|
}
|
||||||
|
setValidationErrors(errs)
|
||||||
return errs
|
return errs
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Re-validate on language change ──
|
||||||
|
useEffect(() => {
|
||||||
|
const hasErrors = Object.keys(validationErrors).length > 0 || Object.keys(rhfErrors).length > 0
|
||||||
|
if (hasErrors) {
|
||||||
|
doValidateAll()
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [i18n.language])
|
||||||
|
|
||||||
// ── Navigation ──
|
// ── Navigation ──
|
||||||
const goStep = (idx: number) => {
|
const goStep = (idx: number) => {
|
||||||
if (idx < 0 || idx >= STEPS.length) return
|
if (idx < 0 || idx >= steps.length) return
|
||||||
setStepStatuses((prev) => {
|
setStepStatuses((prev) => {
|
||||||
const next = [...prev]
|
const next = [...prev]
|
||||||
if (idx > currentStep) next[currentStep] = 'done'
|
if (idx > currentStep) next[currentStep] = 'done'
|
||||||
@@ -461,18 +496,21 @@ export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormP
|
|||||||
return next
|
return next
|
||||||
})
|
})
|
||||||
clearErrors()
|
clearErrors()
|
||||||
|
setValidationErrors({})
|
||||||
setCurrentStep(idx)
|
setCurrentStep(idx)
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleNext = () => {
|
const handleNext = () => {
|
||||||
const stepErrors = validateStep(currentStep, form, mode)
|
const stepErrors = validateStep(currentStep, form, mode, t)
|
||||||
if (Object.keys(stepErrors).length > 0) {
|
if (Object.keys(stepErrors).length > 0) {
|
||||||
|
setValidationErrors(stepErrors)
|
||||||
setStepStatuses((prev) => {
|
setStepStatuses((prev) => {
|
||||||
const next = [...prev]; next[currentStep] = 'error'; return next
|
const next = [...prev]; next[currentStep] = 'error'; return next
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (currentStep === STEPS.length - 1) {
|
setValidationErrors({})
|
||||||
|
if (currentStep === steps.length - 1) {
|
||||||
handleSubmit()
|
handleSubmit()
|
||||||
} else {
|
} else {
|
||||||
goStep(currentStep + 1)
|
goStep(currentStep + 1)
|
||||||
@@ -499,7 +537,7 @@ export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormP
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ── StepBarCards data ──
|
// ── StepBarCards data ──
|
||||||
const stepCardItems: StepCardItem[] = STEPS.map((s, i) => ({
|
const stepCardItems: StepCardItem[] = steps.map((s, i) => ({
|
||||||
id: s.id,
|
id: s.id,
|
||||||
title: s.title,
|
title: s.title,
|
||||||
subtitle: s.subtitle,
|
subtitle: s.subtitle,
|
||||||
@@ -507,16 +545,18 @@ export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormP
|
|||||||
icon: ([User, MapPin, IdCard, CreditCard, Files] as const)[i],
|
icon: ([User, MapPin, IdCard, CreditCard, Files] as const)[i],
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const isLastStep = currentStep === STEPS.length - 1
|
const isLastStep = currentStep === steps.length - 1
|
||||||
|
|
||||||
const submitLabel = mode === 'create'
|
const submitLabel = mode === 'create'
|
||||||
? 'Sber töleg (talyplar üçin) dörediň'
|
? t('sberPayments.buttons.create', 'Sber töleg (talyplar üçin) dörediň')
|
||||||
: 'Ýatda sakla'
|
: t('sberPayments.buttons.update', 'Ýatda sakla')
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto space-y-6 pb-8">
|
<div className="mx-auto space-y-6 pb-8">
|
||||||
<h1 className="text-2xl font-bold text-foreground">
|
<h1 className="text-2xl font-bold text-foreground">
|
||||||
{mode === 'create' ? 'Sber töleg dörediň' : 'Sber töleg redaktirläň'}
|
{mode === 'create'
|
||||||
|
? t('sberPayments.formTitle.create', 'Sber töleg dörediň')
|
||||||
|
: t('sberPayments.formTitle.edit', 'Sber töleg redaktirläň')}
|
||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
{/* ── Step bar ──────────────────────────────────────────────────────── */}
|
{/* ── Step bar ──────────────────────────────────────────────────────── */}
|
||||||
@@ -530,11 +570,11 @@ export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormP
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* ── Step content ─────────────────────────────────────────────────── */}
|
{/* ── Step content ─────────────────────────────────────────────────── */}
|
||||||
{STEPS[currentStep].id === 'general' && <StepGeneral form={form} errors={errors} set={set} />}
|
{steps[currentStep].id === 'general' && <StepGeneral form={form} errors={errors} set={set} t={t} />}
|
||||||
{STEPS[currentStep].id === 'location' && <StepLocation form={form} errors={errors} set={set} />}
|
{steps[currentStep].id === 'location' && <StepLocation form={form} errors={errors} set={set} t={t} />}
|
||||||
{STEPS[currentStep].id === 'personal' && <StepPersonal form={form} errors={errors} set={set} />}
|
{steps[currentStep].id === 'personal' && <StepPersonal form={form} errors={errors} set={set} t={t} />}
|
||||||
{STEPS[currentStep].id === 'payment' && <StepPayment form={form} errors={errors} set={set} />}
|
{steps[currentStep].id === 'payment' && <StepPayment form={form} errors={errors} set={set} t={t} />}
|
||||||
{STEPS[currentStep].id === 'docs' && <StepDocs form={form} set={set} />}
|
{steps[currentStep].id === 'docs' && <StepDocs form={form} set={set} t={t} />}
|
||||||
|
|
||||||
{/* ── Actions ───────────────────────────────────────────────────────── */}
|
{/* ── Actions ───────────────────────────────────────────────────────── */}
|
||||||
<FormActions
|
<FormActions
|
||||||
@@ -545,7 +585,7 @@ export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormP
|
|||||||
showSubmit={isLastStep}
|
showSubmit={isLastStep}
|
||||||
onSubmit={isLastStep ? handleNext : undefined}
|
onSubmit={isLastStep ? handleNext : undefined}
|
||||||
submitLabel={submitLabel}
|
submitLabel={submitLabel}
|
||||||
loadingLabel="Ýüklenýär..."
|
loadingLabel={t('sberPayments.buttons.loading', 'Ýüklenýär...')}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,25 +1,22 @@
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import i18next from 'i18next'
|
|
||||||
import type { CreateSberPaymentPayload, PaymentStatus } from '@/features/sberPayments/api/sberPaymentsApi'
|
import type { CreateSberPaymentPayload, PaymentStatus } from '@/features/sberPayments/api/sberPaymentsApi'
|
||||||
|
|
||||||
const t = i18next.t.bind(i18next)
|
|
||||||
|
|
||||||
const fileField = z.custom<File | null>((val) => val === null || val instanceof File).nullable()
|
const fileField = z.custom<File | null>((val) => val === null || val instanceof File).nullable()
|
||||||
|
|
||||||
export const sberPaymentFormSchema = z.object({
|
export const sberPaymentFormSchema = z.object({
|
||||||
welayat: z.string().min(1, t('validation.required', '')),
|
welayat: z.string().min(1, 'validation.required'),
|
||||||
sahamca: z.string().min(1, t('validation.required', '')),
|
sahamca: z.string().min(1, 'validation.required'),
|
||||||
firstName: z.string().min(1, t('validation.required', '')),
|
firstName: z.string().min(1, 'validation.required'),
|
||||||
lastName: z.string().min(1, t('validation.required', '')),
|
lastName: z.string().min(1, 'validation.required'),
|
||||||
phone: z.string().min(1, t('validation.required', '')),
|
phone: z.string().min(1, 'validation.required'),
|
||||||
email: z.string(),
|
email: z.string(),
|
||||||
address: z.string().min(1, t('validation.required', '')),
|
address: z.string().min(1, 'validation.required'),
|
||||||
status: z.string().min(1, t('validation.required', '')),
|
status: z.string().min(1, 'validation.required'),
|
||||||
bellik: z.string(),
|
bellik: z.string(),
|
||||||
accountNumber: z.string().min(1, t('validation.required', '')),
|
accountNumber: z.string().min(1, 'validation.required'),
|
||||||
passportSeries: z.string().min(1, t('validation.required', '')),
|
passportSeries: z.string().min(1, 'validation.required'),
|
||||||
passportNumber: z.string().min(1, t('validation.required', '')),
|
passportNumber: z.string().min(1, 'validation.required'),
|
||||||
fullName: z.string().min(1, t('validation.required', '')),
|
fullName: z.string().min(1, 'validation.required'),
|
||||||
client_id: z.string().optional(),
|
client_id: z.string().optional(),
|
||||||
acc_sberbank_card: fileField,
|
acc_sberbank_card: fileField,
|
||||||
acc_enrollment: fileField,
|
acc_enrollment: fileField,
|
||||||
@@ -50,6 +47,7 @@ export function validateStep(
|
|||||||
stepIndex: number,
|
stepIndex: number,
|
||||||
form: SberPaymentFormData,
|
form: SberPaymentFormData,
|
||||||
mode: 'create' | 'edit',
|
mode: 'create' | 'edit',
|
||||||
|
t?: (key: string, fallback?: string) => string,
|
||||||
): Partial<Record<keyof SberPaymentFormData, string>> {
|
): Partial<Record<keyof SberPaymentFormData, string>> {
|
||||||
void mode
|
void mode
|
||||||
const schema = stepSchemas[stepIndex]
|
const schema = stepSchemas[stepIndex]
|
||||||
@@ -59,7 +57,10 @@ export function validateStep(
|
|||||||
const errors: Partial<Record<keyof SberPaymentFormData, string>> = {}
|
const errors: Partial<Record<keyof SberPaymentFormData, string>> = {}
|
||||||
for (const issue of result.error.issues) {
|
for (const issue of result.error.issues) {
|
||||||
const key = issue.path[0] as keyof SberPaymentFormData
|
const key = issue.path[0] as keyof SberPaymentFormData
|
||||||
if (!errors[key]) errors[key] = issue.message
|
if (!errors[key]) {
|
||||||
|
const msg = issue.message
|
||||||
|
errors[key] = t && msg.startsWith('validation.') ? t(msg, msg) : msg
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return errors
|
return errors
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useCallback, useMemo } from 'react'
|
import { useCallback, useEffect, useMemo } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from 'react-hook-form'
|
||||||
@@ -12,7 +12,7 @@ import {
|
|||||||
useUpdateVisaMasterSetting,
|
useUpdateVisaMasterSetting,
|
||||||
} from '../hooks/useVisaMasterSettings'
|
} from '../hooks/useVisaMasterSettings'
|
||||||
import {
|
import {
|
||||||
visaMasterSettingFormSchema,
|
createVisaMasterSettingFormSchema,
|
||||||
DEFAULT_FORM_VALUES,
|
DEFAULT_FORM_VALUES,
|
||||||
buildPayload,
|
buildPayload,
|
||||||
} from '../schemas/visaMasterSberSetting.schema'
|
} from '../schemas/visaMasterSberSetting.schema'
|
||||||
@@ -56,7 +56,11 @@ export function VisaMasterSettingForm({
|
|||||||
initialData,
|
initialData,
|
||||||
settingId,
|
settingId,
|
||||||
}: VisaMasterSettingFormProps) {
|
}: VisaMasterSettingFormProps) {
|
||||||
const { t } = useTranslation()
|
const { t: _t, i18n } = useTranslation()
|
||||||
|
const t: (key: string, fallback?: string) => string = useCallback(
|
||||||
|
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||||
|
[_t],
|
||||||
|
)
|
||||||
|
|
||||||
const errMsg = (msg: string | undefined) =>
|
const errMsg = (msg: string | undefined) =>
|
||||||
!msg ? undefined : msg.startsWith('validation.') ? t(msg, msg) : msg
|
!msg ? undefined : msg.startsWith('validation.') ? t(msg, msg) : msg
|
||||||
@@ -67,6 +71,12 @@ export function VisaMasterSettingForm({
|
|||||||
|
|
||||||
const isPending = createMutation.isPending || updateMutation.isPending
|
const isPending = createMutation.isPending || updateMutation.isPending
|
||||||
|
|
||||||
|
const schema = useMemo(
|
||||||
|
() => createVisaMasterSettingFormSchema(t),
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
[i18n.language],
|
||||||
|
)
|
||||||
|
|
||||||
const {
|
const {
|
||||||
watch,
|
watch,
|
||||||
setValue,
|
setValue,
|
||||||
@@ -75,7 +85,7 @@ export function VisaMasterSettingForm({
|
|||||||
trigger,
|
trigger,
|
||||||
getValues,
|
getValues,
|
||||||
} = useForm<VisaMasterSettingFormData>({
|
} = useForm<VisaMasterSettingFormData>({
|
||||||
resolver: zodResolver(visaMasterSettingFormSchema),
|
resolver: zodResolver(schema),
|
||||||
defaultValues: initialData
|
defaultValues: initialData
|
||||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||||
: DEFAULT_FORM_VALUES,
|
: DEFAULT_FORM_VALUES,
|
||||||
@@ -87,6 +97,13 @@ export function VisaMasterSettingForm({
|
|||||||
[rhfErrors],
|
[rhfErrors],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (Object.keys(rhfErrors).length > 0) {
|
||||||
|
trigger()
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [i18n.language])
|
||||||
|
|
||||||
const set = useCallback(
|
const set = useCallback(
|
||||||
(key: keyof VisaMasterSettingFormData) => (value: string) => {
|
(key: keyof VisaMasterSettingFormData) => (value: string) => {
|
||||||
setValue(key, value)
|
setValue(key, value)
|
||||||
@@ -111,7 +128,7 @@ export function VisaMasterSettingForm({
|
|||||||
await updateMutation.mutateAsync(payload)
|
await updateMutation.mutateAsync(payload)
|
||||||
navigate('/resources/visa-master-settings')
|
navigate('/resources/visa-master-settings')
|
||||||
}
|
}
|
||||||
}, [mode, createMutation, updateMutation, navigate, trigger, getValues])
|
}, [mode, createMutation, updateMutation, navigate, trigger, getValues, t])
|
||||||
|
|
||||||
const handleCancel = () => navigate('/resources/visa-master-settings')
|
const handleCancel = () => navigate('/resources/visa-master-settings')
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import type { VisaMasterSettingPayload } from '../api/visaMasterSberSettingsApi'
|
import type { VisaMasterSettingPayload } from '../api/visaMasterSberSettingsApi'
|
||||||
|
|
||||||
export const visaMasterSettingFormSchema = z.object({
|
export function createVisaMasterSettingFormSchema(
|
||||||
kod: z.string().min(1, 'validation.required'),
|
t: (key: string, fallback?: string) => string,
|
||||||
ady: z.string().min(1, 'validation.required'),
|
) {
|
||||||
yazgy: z.string().min(1, 'validation.required'),
|
return z.object({
|
||||||
})
|
kod: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
ady: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
yazgy: z.string().min(1, t('validation.required', 'validation.required')),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
export type VisaMasterSettingFormData = z.infer<typeof visaMasterSettingFormSchema>
|
export type VisaMasterSettingFormData = z.infer<ReturnType<typeof createVisaMasterSettingFormSchema>>
|
||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: VisaMasterSettingFormData = {
|
export const DEFAULT_FORM_VALUES: VisaMasterSettingFormData = {
|
||||||
kod: '',
|
kod: '',
|
||||||
|
|||||||
@@ -565,5 +565,164 @@
|
|||||||
"intlPaymentForm.placeholders.receiverInfo": "Receiver bank, account, Swift...",
|
"intlPaymentForm.placeholders.receiverInfo": "Receiver bank, account, Swift...",
|
||||||
"intlPaymentForm.placeholders.address": "Street, house number...",
|
"intlPaymentForm.placeholders.address": "Street, house number...",
|
||||||
"intlPaymentForm.hints.selectRegion": "Branches update when region is selected.",
|
"intlPaymentForm.hints.selectRegion": "Branches update when region is selected.",
|
||||||
"Fix errors": "Please fix the errors"
|
"Fix errors": "Please fix the errors",
|
||||||
|
"visaMasterSettings.title": "Visa/Master, Sber Settings",
|
||||||
|
"visaMasterSettings.fields.kod": "Code",
|
||||||
|
"visaMasterSettings.fields.ady": "Name",
|
||||||
|
"visaMasterSettings.fields.yazgy": "Text",
|
||||||
|
"visaMasterSettings.columns.kod": "CODE",
|
||||||
|
"visaMasterSettings.columns.ady": "NAME",
|
||||||
|
"visaMasterSettings.columns.yazgy": "TEXT",
|
||||||
|
"visaMasterSettings.actions.create": "Create Visa/Master, Sber setting",
|
||||||
|
"visaMasterSettings.actions.update": "Save",
|
||||||
|
"visaMasterSettings.detail.editTitle": "Edit setting",
|
||||||
|
"visaMasterSettings.notFound": "Setting not found",
|
||||||
|
"visaMasterSettings.toast.created": "Setting created",
|
||||||
|
"visaMasterSettings.toast.updated": "Setting updated",
|
||||||
|
"visaMasterSettings.toast.deleted": "Setting deleted",
|
||||||
|
"visaMasterSettings.deleteDialog.title": "Are you sure you want to delete?",
|
||||||
|
"visaMasterSettings.deleteDialog.description": "This action cannot be undone. The setting will be permanently deleted.",
|
||||||
|
"sberPayments.title": "Sber payments (for students)",
|
||||||
|
"sberPayments.formTitle.create": "Create Sber payment",
|
||||||
|
"sberPayments.formTitle.edit": "Edit Sber payment",
|
||||||
|
"sberPayments.viewTitle": "Sberbank payment",
|
||||||
|
"sberPayments.notFound": "Payment not found",
|
||||||
|
"sberPayments.loading": "Loading...",
|
||||||
|
"sberPayments.toast.created": "Payment created successfully",
|
||||||
|
"sberPayments.toast.updated": "Payment updated successfully",
|
||||||
|
"sberPayments.toast.deleted": "Payment deleted successfully",
|
||||||
|
"sberPayments.steps.general.title": "General",
|
||||||
|
"sberPayments.steps.general.subtitle": "Status, customer",
|
||||||
|
"sberPayments.steps.location.title": "Location",
|
||||||
|
"sberPayments.steps.location.subtitle": "Region, branch",
|
||||||
|
"sberPayments.steps.personal.title": "Personal",
|
||||||
|
"sberPayments.steps.personal.subtitle": "Passport, contact",
|
||||||
|
"sberPayments.steps.payment.title": "Payment",
|
||||||
|
"sberPayments.steps.payment.subtitle": "Account, sender",
|
||||||
|
"sberPayments.steps.docs.title": "Documents",
|
||||||
|
"sberPayments.steps.docs.subtitle": "14 documents",
|
||||||
|
"sberPayments.cards.musteri": "Customer",
|
||||||
|
"sberPayments.cards.status": "Status",
|
||||||
|
"sberPayments.cards.bellik": "Note",
|
||||||
|
"sberPayments.cards.welayat": "Region",
|
||||||
|
"sberPayments.cards.sahamca": "Branch",
|
||||||
|
"sberPayments.cards.atFamilia": "Name-Surname",
|
||||||
|
"sberPayments.cards.kontakt": "Contact",
|
||||||
|
"sberPayments.cards.yasysYeri": "Current residence",
|
||||||
|
"sberPayments.cards.pasportMaglumatlary": "Passport info",
|
||||||
|
"sberPayments.cards.ugradyjy": "Sender",
|
||||||
|
"sberPayments.cards.documentsAccepted": "Receiver student — 8 docs",
|
||||||
|
"sberPayments.cards.documentsSent": "Sender — 6 docs",
|
||||||
|
"sberPayments.fields.client_id": "User",
|
||||||
|
"sberPayments.fields.status": "Status",
|
||||||
|
"sberPayments.fields.bellik": "Note",
|
||||||
|
"sberPayments.fields.welayat": "Region",
|
||||||
|
"sberPayments.fields.sahamca": "Branch",
|
||||||
|
"sberPayments.fields.lastName": "Surname (as in passport)",
|
||||||
|
"sberPayments.fields.firstName": "Name (as in passport)",
|
||||||
|
"sberPayments.fields.phone": "Phone",
|
||||||
|
"sberPayments.fields.email": "Email",
|
||||||
|
"sberPayments.fields.address": "Address",
|
||||||
|
"sberPayments.fields.passportSeries": "Passport series",
|
||||||
|
"sberPayments.fields.passportNumber": "Passport number",
|
||||||
|
"sberPayments.fields.fullName": "Full name",
|
||||||
|
"sberPayments.fields.accountNumber": "Account number",
|
||||||
|
"sberPayments.placeholders.select": "Click to select",
|
||||||
|
"sberPayments.placeholders.bellik": "Note...",
|
||||||
|
"sberPayments.placeholders.welayat": "Ashgabat",
|
||||||
|
"sberPayments.placeholders.lastName": "SURNAME",
|
||||||
|
"sberPayments.placeholders.firstName": "NAME",
|
||||||
|
"sberPayments.placeholders.email": "email@example.com",
|
||||||
|
"sberPayments.placeholders.address": "Street, house number...",
|
||||||
|
"sberPayments.placeholders.passportNumber": "A123456",
|
||||||
|
"sberPayments.placeholders.fullName": "Full name...",
|
||||||
|
"sberPayments.placeholders.accountNumber": "1234 5678 ...",
|
||||||
|
"sberPayments.hints.selectRegion": "Branches update when region is selected.",
|
||||||
|
"sberPayments.documents.sberbankCard": "SBERBANK card details of the student",
|
||||||
|
"sberPayments.documents.enrollment": "Certificate of foreign university enrollment",
|
||||||
|
"sberPayments.documents.summons": "Copy of the summons",
|
||||||
|
"sberPayments.documents.passportTm": "Original and copy of TM internal passport",
|
||||||
|
"sberPayments.documents.zagranPassport": "Copy of foreign passport",
|
||||||
|
"sberPayments.documents.visaPage": "Copy of visa page",
|
||||||
|
"sberPayments.documents.entryStamp": "Copy of entry stamp page",
|
||||||
|
"sberPayments.documents.schoolLetter": "Letter from university (in foreign language)",
|
||||||
|
"sberPayments.documents.sentPassportTm": "Original and copy of sender's TM internal passport",
|
||||||
|
"sberPayments.documents.sentZagranPassport": "Copy of sender's foreign passport",
|
||||||
|
"sberPayments.documents.sentEntryStamp": "Copy of sender's entry stamp page",
|
||||||
|
"sberPayments.documents.sentRelationDoc": "Copy of relationship document between sender and receiver",
|
||||||
|
"sberPayments.documents.sentNewPassportSeries": "Sender/receiver new (2015+) passport series info",
|
||||||
|
"sberPayments.documents.sentOldPassportSeries": "Sender/receiver old passport series certificate",
|
||||||
|
"sberPayments.buttons.create": "Create Sber payment (for students)",
|
||||||
|
"sberPayments.buttons.update": "Save",
|
||||||
|
"sberPayments.buttons.loading": "Loading...",
|
||||||
|
"sberPayments.columns.id": "ID",
|
||||||
|
"sberPayments.columns.createdAt": "Created date",
|
||||||
|
"sberPayments.columns.welayat": "Region",
|
||||||
|
"sberPayments.columns.sahamca": "Branch",
|
||||||
|
"sberPayments.columns.firstName": "Name",
|
||||||
|
"sberPayments.columns.lastName": "Surname",
|
||||||
|
"sberPayments.columns.phone": "Phone",
|
||||||
|
"sberPayments.columns.status": "Status",
|
||||||
|
"sberPayments.columns.paidStatus": "Paid (this month)",
|
||||||
|
"sberPayments.filters.welayat": "Region",
|
||||||
|
"sberPayments.filters.status": "Status",
|
||||||
|
"sberPayments.list.actionLabel": "Create Sber payment (for students)",
|
||||||
|
"sberPayments.list.title": "Sber payments (for students)",
|
||||||
|
"sberPayments.list.monthLabel": "Month payment",
|
||||||
|
"sberPayments.deleteDialog.title": "Are you sure you want to delete this payment?",
|
||||||
|
"sberPayments.deleteDialog.description": "This action cannot be undone.",
|
||||||
|
"sberPayments.deleteDialog.confirm": "Delete",
|
||||||
|
"sberPayments.status.pending": "Pending",
|
||||||
|
"sberPayments.status.approved": "Approved",
|
||||||
|
"sberPayments.status.rejected": "Rejected",
|
||||||
|
"sberPayments.paidStatus.paid": "Paid",
|
||||||
|
"sberPayments.paidStatus.unpaid": "Unpaid",
|
||||||
|
"sberPayments.view.sections.main": "Main info",
|
||||||
|
"sberPayments.view.sections.location": "Location",
|
||||||
|
"sberPayments.view.sections.personal": "Personal info",
|
||||||
|
"sberPayments.view.sections.payment": "Payment",
|
||||||
|
"sberPayments.view.sections.acceptedDocs": "Receiver student documents",
|
||||||
|
"sberPayments.view.sections.sentDocs": "Sender documents",
|
||||||
|
"sberPayments.view.sections.paymentHistory": "Payment history",
|
||||||
|
"sberPayments.view.noDocuments": "No documents",
|
||||||
|
"sberPayments.view.noPaymentHistory": "No payment history matching criteria.",
|
||||||
|
"sberPayments.view.edit": "Edit",
|
||||||
|
"sberPayments.view.delete": "Delete",
|
||||||
|
"operators.title": "Operators",
|
||||||
|
"operators.detailTitle": "Operator details",
|
||||||
|
"operators.createTitle": "Create operator",
|
||||||
|
"operators.editTitle": "Edit operator",
|
||||||
|
"operators.createBtn": "Create operator",
|
||||||
|
"operators.updateBtn": "Save changes",
|
||||||
|
"operators.createSuccess": "Operator created successfully",
|
||||||
|
"operators.updateSuccess": "Operator updated successfully",
|
||||||
|
"operators.deleteSuccess": "Operator deleted successfully",
|
||||||
|
"operators.deleteTitle": "Delete operator",
|
||||||
|
"operators.deleteDescription": "Are you sure you want to delete \"{name}\"?",
|
||||||
|
"operators.deleteConfirm": "Are you sure you want to delete operator {{name}}?",
|
||||||
|
"operators.fields.username": "Username",
|
||||||
|
"operators.fields.name": "Name",
|
||||||
|
"operators.fields.phone": "Phone",
|
||||||
|
"operators.fields.email": "Email",
|
||||||
|
"operators.fields.password": "Password",
|
||||||
|
"operators.fields.passwordEditHint": "Enter a new password to change",
|
||||||
|
"operators.fields.passwordEditNote": "Leave empty to keep current password",
|
||||||
|
"operators.fields.isActive": "Active",
|
||||||
|
"operators.sections.basic": "Basic info",
|
||||||
|
"operators.sections.contact": "Contact",
|
||||||
|
"operators.sections.roles": "Roles",
|
||||||
|
"operators.sections.permissions": "Permissions",
|
||||||
|
"operators.sections.branches": "Branches",
|
||||||
|
"operators.sections.loanLimits": "Loan order limits",
|
||||||
|
"operators.sections.cardLimits": "Card order limits",
|
||||||
|
"operators.addRole": "Add role",
|
||||||
|
"operators.addPermission": "Add permission",
|
||||||
|
"operators.addBranch": "Add branch",
|
||||||
|
"operators.addLoanLimit": "Create loan order limit",
|
||||||
|
"operators.addCardLimit": "Create card order limit",
|
||||||
|
"operators.noPermissions": "No permissions match your criteria.",
|
||||||
|
"operators.noLoanLimits": "No loan order limits match your criteria.",
|
||||||
|
"operators.noCardLimits": "No card order limits match your criteria.",
|
||||||
|
"operators.roleAssigned": "Role assigned",
|
||||||
|
"operators.roleRemoved": "Role removed"
|
||||||
}
|
}
|
||||||
@@ -566,5 +566,164 @@
|
|||||||
"intlPaymentForm.placeholders.payerAccount": "1234 5678 ...",
|
"intlPaymentForm.placeholders.payerAccount": "1234 5678 ...",
|
||||||
"intlPaymentForm.placeholders.receiverInfo": "Банк получателя, счет, Swift...",
|
"intlPaymentForm.placeholders.receiverInfo": "Банк получателя, счет, Swift...",
|
||||||
"intlPaymentForm.placeholders.address": "Улица, номер дома...",
|
"intlPaymentForm.placeholders.address": "Улица, номер дома...",
|
||||||
"intlPaymentForm.hints.selectRegion": "Филиалы обновятся после выбора велаята."
|
"intlPaymentForm.hints.selectRegion": "Филиалы обновятся после выбора велаята.",
|
||||||
|
"visaMasterSettings.title": "Настройки Visa/Master, Sber",
|
||||||
|
"visaMasterSettings.fields.kod": "Код",
|
||||||
|
"visaMasterSettings.fields.ady": "Название",
|
||||||
|
"visaMasterSettings.fields.yazgy": "Текст",
|
||||||
|
"visaMasterSettings.columns.kod": "КОД",
|
||||||
|
"visaMasterSettings.columns.ady": "НАЗВАНИЕ",
|
||||||
|
"visaMasterSettings.columns.yazgy": "ТЕКСТ",
|
||||||
|
"visaMasterSettings.actions.create": "Создать настройку Visa/Master, Sber",
|
||||||
|
"visaMasterSettings.actions.update": "Сохранить",
|
||||||
|
"visaMasterSettings.detail.editTitle": "Редактировать настройку",
|
||||||
|
"visaMasterSettings.notFound": "Настройка не найдена",
|
||||||
|
"visaMasterSettings.toast.created": "Настройка создана",
|
||||||
|
"visaMasterSettings.toast.updated": "Настройка изменена",
|
||||||
|
"visaMasterSettings.toast.deleted": "Настройка удалена",
|
||||||
|
"visaMasterSettings.deleteDialog.title": "Вы уверены, что хотите удалить?",
|
||||||
|
"visaMasterSettings.deleteDialog.description": "Это действие необратимо. Настройка будет удалена навсегда.",
|
||||||
|
"sberPayments.title": "Sber платежи (для студентов)",
|
||||||
|
"sberPayments.formTitle.create": "Создать Sber платеж",
|
||||||
|
"sberPayments.formTitle.edit": "Редактировать Sber платеж",
|
||||||
|
"sberPayments.viewTitle": "Sberbank платеж",
|
||||||
|
"sberPayments.notFound": "Платеж не найден",
|
||||||
|
"sberPayments.loading": "Загрузка...",
|
||||||
|
"sberPayments.toast.created": "Платеж успешно создан",
|
||||||
|
"sberPayments.toast.updated": "Платеж успешно обновлен",
|
||||||
|
"sberPayments.toast.deleted": "Платеж удален",
|
||||||
|
"sberPayments.steps.general.title": "Основное",
|
||||||
|
"sberPayments.steps.general.subtitle": "Статус, клиент",
|
||||||
|
"sberPayments.steps.location.title": "Локация",
|
||||||
|
"sberPayments.steps.location.subtitle": "Велаят, филиал",
|
||||||
|
"sberPayments.steps.personal.title": "Личные",
|
||||||
|
"sberPayments.steps.personal.subtitle": "Паспорт, контакт",
|
||||||
|
"sberPayments.steps.payment.title": "Платеж",
|
||||||
|
"sberPayments.steps.payment.subtitle": "Счет, отправитель",
|
||||||
|
"sberPayments.steps.docs.title": "Документы",
|
||||||
|
"sberPayments.steps.docs.subtitle": "14 документов",
|
||||||
|
"sberPayments.cards.musteri": "Клиент",
|
||||||
|
"sberPayments.cards.status": "Статус",
|
||||||
|
"sberPayments.cards.bellik": "Примечание",
|
||||||
|
"sberPayments.cards.welayat": "Велаят",
|
||||||
|
"sberPayments.cards.sahamca": "Филиал",
|
||||||
|
"sberPayments.cards.atFamilia": "Имя-Фамилия",
|
||||||
|
"sberPayments.cards.kontakt": "Контакт",
|
||||||
|
"sberPayments.cards.yasysYeri": "Текущее место жительства",
|
||||||
|
"sberPayments.cards.pasportMaglumatlary": "Паспортные данные",
|
||||||
|
"sberPayments.cards.ugradyjy": "Отправитель",
|
||||||
|
"sberPayments.cards.documentsAccepted": "Студент-получатель — 8 док.",
|
||||||
|
"sberPayments.cards.documentsSent": "Отправитель — 6 док.",
|
||||||
|
"sberPayments.fields.client_id": "Пользователь",
|
||||||
|
"sberPayments.fields.status": "Статус",
|
||||||
|
"sberPayments.fields.bellik": "Примечание",
|
||||||
|
"sberPayments.fields.welayat": "Велаят",
|
||||||
|
"sberPayments.fields.sahamca": "Филиал",
|
||||||
|
"sberPayments.fields.lastName": "Фамилия (как в паспорте)",
|
||||||
|
"sberPayments.fields.firstName": "Имя (как в паспорте)",
|
||||||
|
"sberPayments.fields.phone": "Телефон",
|
||||||
|
"sberPayments.fields.email": "Email",
|
||||||
|
"sberPayments.fields.address": "Адрес",
|
||||||
|
"sberPayments.fields.passportSeries": "Серия паспорта",
|
||||||
|
"sberPayments.fields.passportNumber": "Номер паспорта",
|
||||||
|
"sberPayments.fields.fullName": "Полное имя",
|
||||||
|
"sberPayments.fields.accountNumber": "Номер счета",
|
||||||
|
"sberPayments.placeholders.select": "Нажмите для выбора",
|
||||||
|
"sberPayments.placeholders.bellik": "Примечание...",
|
||||||
|
"sberPayments.placeholders.welayat": "Ашхабад",
|
||||||
|
"sberPayments.placeholders.lastName": "ФАМИЛИЯ",
|
||||||
|
"sberPayments.placeholders.firstName": "ИМЯ",
|
||||||
|
"sberPayments.placeholders.email": "email@example.com",
|
||||||
|
"sberPayments.placeholders.address": "Улица, номер дома...",
|
||||||
|
"sberPayments.placeholders.passportNumber": "A123456",
|
||||||
|
"sberPayments.placeholders.fullName": "Полное имя...",
|
||||||
|
"sberPayments.placeholders.accountNumber": "1234 5678 ...",
|
||||||
|
"sberPayments.hints.selectRegion": "Филиалы обновятся после выбора велаята.",
|
||||||
|
"sberPayments.documents.sberbankCard": "Реквизиты карты SBERBANK студента",
|
||||||
|
"sberPayments.documents.enrollment": "Справка об обучении в зарубежном вузе",
|
||||||
|
"sberPayments.documents.summons": "Копия письма-вызова",
|
||||||
|
"sberPayments.documents.passportTm": "Оригинал и копия TM внутреннего паспорта",
|
||||||
|
"sberPayments.documents.zagranPassport": "Копия заграничного паспорта",
|
||||||
|
"sberPayments.documents.visaPage": "Копия страницы с визой",
|
||||||
|
"sberPayments.documents.entryStamp": "Копия страницы со штампом въезда",
|
||||||
|
"sberPayments.documents.schoolLetter": "Письмо из вуза (на иностранном языке)",
|
||||||
|
"sberPayments.documents.sentPassportTm": "Оригинал и копия TM внутр. паспорта отправителя",
|
||||||
|
"sberPayments.documents.sentZagranPassport": "Копия загран. паспорта отправителя",
|
||||||
|
"sberPayments.documents.sentEntryStamp": "Копия страницы со штампом въезда отправителя",
|
||||||
|
"sberPayments.documents.sentRelationDoc": "Копия док-та о родстве между отправителем и получателем",
|
||||||
|
"sberPayments.documents.sentNewPassportSeries": "Инфо о новой (2015+) серии паспорта отпр./получ.",
|
||||||
|
"sberPayments.documents.sentOldPassportSeries": "Справка о старой серии паспорта отпр./получ.",
|
||||||
|
"sberPayments.buttons.create": "Создать Sber платеж (для студентов)",
|
||||||
|
"sberPayments.buttons.update": "Сохранить",
|
||||||
|
"sberPayments.buttons.loading": "Загрузка...",
|
||||||
|
"sberPayments.columns.id": "ID",
|
||||||
|
"sberPayments.columns.createdAt": "Дата создания",
|
||||||
|
"sberPayments.columns.welayat": "Велаят",
|
||||||
|
"sberPayments.columns.sahamca": "Филиал",
|
||||||
|
"sberPayments.columns.firstName": "Имя",
|
||||||
|
"sberPayments.columns.lastName": "Фамилия",
|
||||||
|
"sberPayments.columns.phone": "Телефон",
|
||||||
|
"sberPayments.columns.status": "Статус",
|
||||||
|
"sberPayments.columns.paidStatus": "Оплачено (за месяц)",
|
||||||
|
"sberPayments.filters.welayat": "Велаят",
|
||||||
|
"sberPayments.filters.status": "Статус",
|
||||||
|
"sberPayments.list.actionLabel": "Создать Sber платеж (для студентов)",
|
||||||
|
"sberPayments.list.title": "Sber платежи (для студентов)",
|
||||||
|
"sberPayments.list.monthLabel": "Оплата за месяц",
|
||||||
|
"sberPayments.deleteDialog.title": "Вы уверены, что хотите удалить этот платеж?",
|
||||||
|
"sberPayments.deleteDialog.description": "Это действие необратимо.",
|
||||||
|
"sberPayments.deleteDialog.confirm": "Удалить",
|
||||||
|
"sberPayments.status.pending": "Ожидание",
|
||||||
|
"sberPayments.status.approved": "Подтвержден",
|
||||||
|
"sberPayments.status.rejected": "Отклонен",
|
||||||
|
"sberPayments.paidStatus.paid": "Оплачено",
|
||||||
|
"sberPayments.paidStatus.unpaid": "Не оплачено",
|
||||||
|
"sberPayments.view.sections.main": "Основная информация",
|
||||||
|
"sberPayments.view.sections.location": "Локация",
|
||||||
|
"sberPayments.view.sections.personal": "Личная информация",
|
||||||
|
"sberPayments.view.sections.payment": "Платеж",
|
||||||
|
"sberPayments.view.sections.acceptedDocs": "Документы студента-получателя",
|
||||||
|
"sberPayments.view.sections.sentDocs": "Документы отправителя",
|
||||||
|
"sberPayments.view.sections.paymentHistory": "История платежей",
|
||||||
|
"sberPayments.view.noDocuments": "Нет документов",
|
||||||
|
"sberPayments.view.noPaymentHistory": "Платежей по заданным критериям не найдено.",
|
||||||
|
"sberPayments.view.edit": "Редактировать",
|
||||||
|
"sberPayments.view.delete": "Удалить",
|
||||||
|
"operators.title": "Операторы",
|
||||||
|
"operators.detailTitle": "Детали оператора",
|
||||||
|
"operators.createTitle": "Создать оператора",
|
||||||
|
"operators.editTitle": "Редактировать оператора",
|
||||||
|
"operators.createBtn": "Создать оператора",
|
||||||
|
"operators.updateBtn": "Сохранить изменения",
|
||||||
|
"operators.createSuccess": "Оператор успешно создан",
|
||||||
|
"operators.updateSuccess": "Оператор успешно обновлен",
|
||||||
|
"operators.deleteSuccess": "Оператор успешно удален",
|
||||||
|
"operators.deleteTitle": "Удалить оператора",
|
||||||
|
"operators.deleteDescription": "Вы уверены, что хотите удалить \"{name}\"?",
|
||||||
|
"operators.deleteConfirm": "Вы уверены, что хотите удалить оператора {{name}}?",
|
||||||
|
"operators.fields.username": "Имя пользователя",
|
||||||
|
"operators.fields.name": "Имя",
|
||||||
|
"operators.fields.phone": "Телефон",
|
||||||
|
"operators.fields.email": "Email",
|
||||||
|
"operators.fields.password": "Пароль",
|
||||||
|
"operators.fields.passwordEditHint": "Введите новый пароль для изменения",
|
||||||
|
"operators.fields.passwordEditNote": "Оставьте пустым, чтобы сохранить текущий пароль",
|
||||||
|
"operators.fields.isActive": "Активный",
|
||||||
|
"operators.sections.basic": "Основная информация",
|
||||||
|
"operators.sections.contact": "Контакт",
|
||||||
|
"operators.sections.roles": "Роли",
|
||||||
|
"operators.sections.permissions": "Разрешения",
|
||||||
|
"operators.sections.branches": "Филиалы",
|
||||||
|
"operators.sections.loanLimits": "Лимиты заявок на кредит",
|
||||||
|
"operators.sections.cardLimits": "Лимиты заявок на карту",
|
||||||
|
"operators.addRole": "Добавить роль",
|
||||||
|
"operators.addPermission": "Добавить разрешение",
|
||||||
|
"operators.addBranch": "Добавить филиал",
|
||||||
|
"operators.addLoanLimit": "Создать лимит заявок на кредит",
|
||||||
|
"operators.addCardLimit": "Создать лимит заявок на карту",
|
||||||
|
"operators.noPermissions": "Разрешений по заданным критериям не найдено.",
|
||||||
|
"operators.noLoanLimits": "Лимитов заявок на кредит по заданным критериям не найдено.",
|
||||||
|
"operators.noCardLimits": "Лимитов заявок на карту по заданным критериям не найдено.",
|
||||||
|
"operators.roleAssigned": "Роль назначена",
|
||||||
|
"operators.roleRemoved": "Роль удалена"
|
||||||
}
|
}
|
||||||
@@ -582,5 +582,164 @@
|
|||||||
"intlPaymentForm.placeholders.payerAccount": "1234 5678 ...",
|
"intlPaymentForm.placeholders.payerAccount": "1234 5678 ...",
|
||||||
"intlPaymentForm.placeholders.receiverInfo": "Kabul ediji bank, hasap, Swift...",
|
"intlPaymentForm.placeholders.receiverInfo": "Kabul ediji bank, hasap, Swift...",
|
||||||
"intlPaymentForm.placeholders.address": "Köçe, jaý belgisi...",
|
"intlPaymentForm.placeholders.address": "Köçe, jaý belgisi...",
|
||||||
"intlPaymentForm.hints.selectRegion": "Welaýaty saýlasaňyz şahamçalar güncellenar."
|
"intlPaymentForm.hints.selectRegion": "Welaýaty saýlasaňyz şahamçalar güncellenar.",
|
||||||
|
"visaMasterSettings.title": "Visa/Master, Sber sazlamalar",
|
||||||
|
"visaMasterSettings.fields.kod": "Kod",
|
||||||
|
"visaMasterSettings.fields.ady": "Ady",
|
||||||
|
"visaMasterSettings.fields.yazgy": "Ýazgy",
|
||||||
|
"visaMasterSettings.columns.kod": "KOD",
|
||||||
|
"visaMasterSettings.columns.ady": "ADY",
|
||||||
|
"visaMasterSettings.columns.yazgy": "ÝAZGY",
|
||||||
|
"visaMasterSettings.actions.create": "Visa/Master, Sber sazlamalar dörediň",
|
||||||
|
"visaMasterSettings.actions.update": "Ýatda sakla",
|
||||||
|
"visaMasterSettings.detail.editTitle": "Sazlamany üýtgetmek",
|
||||||
|
"visaMasterSettings.notFound": "Sazlama tapylmady",
|
||||||
|
"visaMasterSettings.toast.created": "Sazlama döredildi",
|
||||||
|
"visaMasterSettings.toast.updated": "Sazlama üýtgedildi",
|
||||||
|
"visaMasterSettings.toast.deleted": "Sazlama pozuldy",
|
||||||
|
"visaMasterSettings.deleteDialog.title": "Pozmak isleýärsiňizmi?",
|
||||||
|
"visaMasterSettings.deleteDialog.description": "Bu amal yzyna gaýtarylyp bilinmez. Sazlama hemişelik pozular.",
|
||||||
|
"sberPayments.title": "Sber tölegler (talyplar üçin)",
|
||||||
|
"sberPayments.formTitle.create": "Sber töleg dörediň",
|
||||||
|
"sberPayments.formTitle.edit": "Sber töleg redaktirläň",
|
||||||
|
"sberPayments.viewTitle": "Sberbank töleg",
|
||||||
|
"sberPayments.notFound": "Töleg tapylmady",
|
||||||
|
"sberPayments.loading": "Ýüklenýär...",
|
||||||
|
"sberPayments.toast.created": "Töleg üstünlikli döredildi",
|
||||||
|
"sberPayments.toast.updated": "Töleg üstünlikli täzelendi",
|
||||||
|
"sberPayments.toast.deleted": "Töleg pozuldy",
|
||||||
|
"sberPayments.steps.general.title": "Esasy",
|
||||||
|
"sberPayments.steps.general.subtitle": "Status, müşderi",
|
||||||
|
"sberPayments.steps.location.title": "Lokasiýa",
|
||||||
|
"sberPayments.steps.location.subtitle": "Welaýat, şahamça",
|
||||||
|
"sberPayments.steps.personal.title": "Şahsy",
|
||||||
|
"sberPayments.steps.personal.subtitle": "Pasport, kontakt",
|
||||||
|
"sberPayments.steps.payment.title": "Töleg",
|
||||||
|
"sberPayments.steps.payment.subtitle": "Hasap, ugradyjy",
|
||||||
|
"sberPayments.steps.docs.title": "Resminamalar",
|
||||||
|
"sberPayments.steps.docs.subtitle": "14 resminama",
|
||||||
|
"sberPayments.cards.musteri": "Müşderi",
|
||||||
|
"sberPayments.cards.status": "Status",
|
||||||
|
"sberPayments.cards.bellik": "Bellik",
|
||||||
|
"sberPayments.cards.welayat": "Welaýat",
|
||||||
|
"sberPayments.cards.sahamca": "Şahamça",
|
||||||
|
"sberPayments.cards.atFamilia": "At-familýa",
|
||||||
|
"sberPayments.cards.kontakt": "Kontakt",
|
||||||
|
"sberPayments.cards.yasysYeri": "Häzirki ýaşyş ýeri",
|
||||||
|
"sberPayments.cards.pasportMaglumatlary": "Pasport maglumatlary",
|
||||||
|
"sberPayments.cards.ugradyjy": "Ugradyjy",
|
||||||
|
"sberPayments.cards.documentsAccepted": "Kabul ediji talyp — 8 resminama",
|
||||||
|
"sberPayments.cards.documentsSent": "Ugradyjy — 6 resminama",
|
||||||
|
"sberPayments.fields.client_id": "Ulanyjy",
|
||||||
|
"sberPayments.fields.status": "Status",
|
||||||
|
"sberPayments.fields.bellik": "Bellik",
|
||||||
|
"sberPayments.fields.welayat": "Welaýat",
|
||||||
|
"sberPayments.fields.sahamca": "Şahamça",
|
||||||
|
"sberPayments.fields.lastName": "Pasportdaky familiýa",
|
||||||
|
"sberPayments.fields.firstName": "Pasportdaky ady",
|
||||||
|
"sberPayments.fields.phone": "Telefon",
|
||||||
|
"sberPayments.fields.email": "E-poçta",
|
||||||
|
"sberPayments.fields.address": "Salgy",
|
||||||
|
"sberPayments.fields.passportSeries": "Pasport seriýasy",
|
||||||
|
"sberPayments.fields.passportNumber": "Pasport nomeri",
|
||||||
|
"sberPayments.fields.fullName": "Ady Familiýasy Atasynyň ady",
|
||||||
|
"sberPayments.fields.accountNumber": "Goýum hasaby",
|
||||||
|
"sberPayments.placeholders.select": "Saýlamak üçin basyň",
|
||||||
|
"sberPayments.placeholders.bellik": "Bellik...",
|
||||||
|
"sberPayments.placeholders.welayat": "Aşgabat",
|
||||||
|
"sberPayments.placeholders.lastName": "NURYYEW",
|
||||||
|
"sberPayments.placeholders.firstName": "HAÝDAR",
|
||||||
|
"sberPayments.placeholders.email": "email@example.com",
|
||||||
|
"sberPayments.placeholders.address": "Köçe, jaý belgisi...",
|
||||||
|
"sberPayments.placeholders.passportNumber": "A123456",
|
||||||
|
"sberPayments.placeholders.fullName": "Doly ady...",
|
||||||
|
"sberPayments.placeholders.accountNumber": "1234 5678 ...",
|
||||||
|
"sberPayments.hints.selectRegion": "Welaýaty saýlasaňyz şahamçalar güncellenar.",
|
||||||
|
"sberPayments.documents.sberbankCard": "Talýba degişli SBERBANK kartynyň rekwizitleri",
|
||||||
|
"sberPayments.documents.enrollment": "Daşary ýurt ÝOM-da okaýandygy baradaky güwänamasy",
|
||||||
|
"sberPayments.documents.summons": "Çagyrylma hatynyn göçürmesi",
|
||||||
|
"sberPayments.documents.passportTm": "TM içki pasportynyň asyl görnüşi we göçürmesi",
|
||||||
|
"sberPayments.documents.zagranPassport": "Daşary ýurt (zagran) pasportynyň göçürmesi",
|
||||||
|
"sberPayments.documents.visaPage": "Daşary ýurda rugsat (wizasy) bellenen sahypasynyň göçürmesi",
|
||||||
|
"sberPayments.documents.entryStamp": "Daşary ýurt döwletine girenliği baradaky ştamply sahypasynyň göçürmesi",
|
||||||
|
"sberPayments.documents.schoolLetter": "ÝOM-dan hat (daşary ýurt dilinde maglumatly)",
|
||||||
|
"sberPayments.documents.sentPassportTm": "Ugradyjynyň TM içki pasportynyň asyl görnüşi we göçürmesi",
|
||||||
|
"sberPayments.documents.sentZagranPassport": "Ugradyjynyň daşary ýurt pasportynyň asyl görnüşi we göçürmesi",
|
||||||
|
"sberPayments.documents.sentEntryStamp": "Ugradyjynyň daşary döwletine girenliği ştamply sahypasynyň göçürmesi",
|
||||||
|
"sberPayments.documents.sentRelationDoc": "Ugradyjy we kabul edijiniň garyndaşlyk tassyklaýjy resminamasynyn göçürmesi",
|
||||||
|
"sberPayments.documents.sentNewPassportSeries": "Ugradyjy/kabul ediji täze (2015+) pasport seriýasy maglumaty",
|
||||||
|
"sberPayments.documents.sentOldPassportSeries": "Ugradyjy/kabul ediji köne pasport seriýasy baradaky güwänamasy",
|
||||||
|
"sberPayments.buttons.create": "Sber töleg (talyplar üçin) dörediň",
|
||||||
|
"sberPayments.buttons.update": "Ýatda sakla",
|
||||||
|
"sberPayments.buttons.loading": "Ýüklenýär...",
|
||||||
|
"sberPayments.columns.id": "ID",
|
||||||
|
"sberPayments.columns.createdAt": "Döredilen wagty",
|
||||||
|
"sberPayments.columns.welayat": "Welaýat",
|
||||||
|
"sberPayments.columns.sahamca": "Şahamça",
|
||||||
|
"sberPayments.columns.firstName": "Ady",
|
||||||
|
"sberPayments.columns.lastName": "Familiýasy",
|
||||||
|
"sberPayments.columns.phone": "Telefon",
|
||||||
|
"sberPayments.columns.status": "Status",
|
||||||
|
"sberPayments.columns.paidStatus": "Tölenen (şul aý)",
|
||||||
|
"sberPayments.filters.welayat": "Welaýat",
|
||||||
|
"sberPayments.filters.status": "Status",
|
||||||
|
"sberPayments.list.actionLabel": "Sber töleg (talyplar üçin) dörediň",
|
||||||
|
"sberPayments.list.title": "Sber tölegler (talyplar üçin)",
|
||||||
|
"sberPayments.list.monthLabel": "Aý tölegi",
|
||||||
|
"sberPayments.deleteDialog.title": "Bu tölegi pozmak isleýärsiňizmi?",
|
||||||
|
"sberPayments.deleteDialog.description": "Bu amal yzyna gaýtarylyp bilinmez.",
|
||||||
|
"sberPayments.deleteDialog.confirm": "Poz",
|
||||||
|
"sberPayments.status.pending": "Garaşylýar",
|
||||||
|
"sberPayments.status.approved": "Tassyklandy",
|
||||||
|
"sberPayments.status.rejected": "Ýatyryldy",
|
||||||
|
"sberPayments.paidStatus.paid": "Tölendi",
|
||||||
|
"sberPayments.paidStatus.unpaid": "Tölmedi",
|
||||||
|
"sberPayments.view.sections.main": "Esasy maglumatlar",
|
||||||
|
"sberPayments.view.sections.location": "Lokasiýa",
|
||||||
|
"sberPayments.view.sections.personal": "Şahsy maglumatlar",
|
||||||
|
"sberPayments.view.sections.payment": "Töleg",
|
||||||
|
"sberPayments.view.sections.acceptedDocs": "Kabul ediji talyp boýunça resminamalary",
|
||||||
|
"sberPayments.view.sections.sentDocs": "Ugradyjy boýunça resminamalary",
|
||||||
|
"sberPayments.view.sections.paymentHistory": "Töleg taryhy",
|
||||||
|
"sberPayments.view.noDocuments": "Resminamalar ýok",
|
||||||
|
"sberPayments.view.noPaymentHistory": "Berlen kriteriýalara Töleg gabat gelmedi.",
|
||||||
|
"sberPayments.view.edit": "Redaktirle",
|
||||||
|
"sberPayments.view.delete": "Poz",
|
||||||
|
"operators.title": "Operatorlar",
|
||||||
|
"operators.detailTitle": "Operator giňişleýin",
|
||||||
|
"operators.createTitle": "Operator dörediň",
|
||||||
|
"operators.editTitle": "Operator üýtget",
|
||||||
|
"operators.createBtn": "Operator dörediň",
|
||||||
|
"operators.updateBtn": "Üýtgetmeleri sakla",
|
||||||
|
"operators.createSuccess": "Operator üstünlikli döredildi",
|
||||||
|
"operators.updateSuccess": "Operator üstünlikli täzelendi",
|
||||||
|
"operators.deleteSuccess": "Operator üstünlikli pozuldy",
|
||||||
|
"operators.deleteTitle": "Operatory pozmak",
|
||||||
|
"operators.deleteDescription": "Siz \"{name}\" operatoryny pozjakmy?",
|
||||||
|
"operators.deleteConfirm": "{{name}} operatoryny pozmak isleýärsiňizmi?",
|
||||||
|
"operators.fields.username": "Ulanyjy ady",
|
||||||
|
"operators.fields.name": "Ady",
|
||||||
|
"operators.fields.phone": "Telefon",
|
||||||
|
"operators.fields.email": "E-poçta",
|
||||||
|
"operators.fields.password": "Açar sözi",
|
||||||
|
"operators.fields.passwordEditHint": "Üýtgetmek üçin täze açar söz giriziň",
|
||||||
|
"operators.fields.passwordEditNote": "Boş goýsaňyz, açar sözi üýtgemez",
|
||||||
|
"operators.fields.isActive": "Işjeň",
|
||||||
|
"operators.sections.basic": "Esasy maglumatlar",
|
||||||
|
"operators.sections.contact": "Kontakt",
|
||||||
|
"operators.sections.roles": "Rollar",
|
||||||
|
"operators.sections.permissions": "Rugsatlar",
|
||||||
|
"operators.sections.branches": "Şahamçalar",
|
||||||
|
"operators.sections.loanLimits": "Karz sargyt",
|
||||||
|
"operators.sections.cardLimits": "Kart sargyt",
|
||||||
|
"operators.addRole": "Rol birikdiriň",
|
||||||
|
"operators.addPermission": "Rugsat birikdiriň",
|
||||||
|
"operators.addBranch": "Şahamça birikdiriň",
|
||||||
|
"operators.addLoanLimit": "Karz sargyt döredin",
|
||||||
|
"operators.addCardLimit": "Kart sargyt döredin",
|
||||||
|
"operators.noPermissions": "Berlen kriterýalara Rugsat gabat gelmedi.",
|
||||||
|
"operators.noLoanLimits": "Berlen kriterýalara Karz sargyt gabat gelmedi.",
|
||||||
|
"operators.noCardLimits": "Berlen kriterýalara Kart sargyt gabat gelmedi.",
|
||||||
|
"operators.roleAssigned": "Rol birikdirildi",
|
||||||
|
"operators.roleRemoved": "Rol aýryldy"
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
|
|
||||||
import { useState, useMemo } from 'react'
|
import { useState, useMemo, useCallback } from 'react'
|
||||||
import { format } from 'date-fns'
|
import { format } from 'date-fns'
|
||||||
import { Eye, Edit, ArrowUpDown, Trash2 } from 'lucide-react'
|
import { Eye, Edit, ArrowUpDown, Trash2 } from 'lucide-react'
|
||||||
import type { ColumnDef, VisibilityState } from '@tanstack/react-table'
|
import type { ColumnDef, VisibilityState } from '@tanstack/react-table'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { DataTable } from '@/components/dataTable'
|
import { DataTable } from '@/components/dataTable'
|
||||||
import { DataTableToolbar, type ColumnMeta, type FilterField, type ActiveFilter } from '@/components/dataTableToolbar'
|
import { DataTableToolbar, type ColumnMeta, type FilterField, type ActiveFilter } from '@/components/dataTableToolbar'
|
||||||
import { useSberPaymentOrders, useDeleteSberPayment } from '@/features/sberPayments/hooks/useSberPayments'
|
import { useSberPaymentOrders, useDeleteSberPayment } from '@/features/sberPayments/hooks/useSberPayments'
|
||||||
@@ -22,46 +23,49 @@ import {
|
|||||||
|
|
||||||
// ─── Status badge ─────────────────────────────────────────────────────────────
|
// ─── Status badge ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const STATUS_CONFIG = {
|
function getStatusConfig(t: (key: string, fallback?: string) => string) {
|
||||||
GARASYLYYAR: {
|
return {
|
||||||
label: 'Garaşylýar',
|
GARASYLYYAR: {
|
||||||
variant: 'warning' as StatusBadgeVariant,
|
label: t('sberPayments.status.pending', 'Garaşylýar'),
|
||||||
icon: AlertCircle,
|
variant: 'warning' as StatusBadgeVariant,
|
||||||
},
|
icon: AlertCircle,
|
||||||
KANAGATLANDYRYLAN: {
|
},
|
||||||
label: 'Tassyklandy',
|
KANAGATLANDYRYLAN: {
|
||||||
variant: 'success' as StatusBadgeVariant,
|
label: t('sberPayments.status.approved', 'Tassyklandy'),
|
||||||
icon: CheckCircle2,
|
variant: 'success' as StatusBadgeVariant,
|
||||||
},
|
icon: CheckCircle2,
|
||||||
RET_EDILEN: {
|
},
|
||||||
label: 'Ýatyryldy',
|
RET_EDILEN: {
|
||||||
variant: 'error' as StatusBadgeVariant,
|
label: t('sberPayments.status.rejected', 'Ýatyryldy'),
|
||||||
icon: XCircle,
|
variant: 'error' as StatusBadgeVariant,
|
||||||
},
|
icon: XCircle,
|
||||||
|
},
|
||||||
|
} satisfies Record<PaymentStatus, { label: string; variant: StatusBadgeVariant; icon: React.ElementType }>
|
||||||
|
}
|
||||||
|
|
||||||
} satisfies Record<PaymentStatus, { label: string; variant: StatusBadgeVariant; icon: React.ElementType }>
|
function getPaidStatusConfig(t: (key: string, fallback?: string) => string) {
|
||||||
|
return {
|
||||||
|
Tolenmedik: {
|
||||||
|
label: t('sberPayments.paidStatus.unpaid', 'Tölmedi'),
|
||||||
|
variant: 'error' as StatusBadgeVariant,
|
||||||
|
icon: XCircle,
|
||||||
|
},
|
||||||
|
Tolendi: {
|
||||||
|
label: t('sberPayments.paidStatus.paid', 'Tölendi'),
|
||||||
|
variant: 'success' as StatusBadgeVariant,
|
||||||
|
icon: CheckCircle2,
|
||||||
|
},
|
||||||
|
} satisfies Record<PaymentPaidStatus, { label: string; variant: StatusBadgeVariant; icon: React.ElementType }>
|
||||||
|
}
|
||||||
|
|
||||||
const PAID_STATUS_CONFIG = {
|
function PaymentPaidStatusBadge({ status, t }: { status: PaymentPaidStatus; t: (key: string, fallback?: string) => string }) {
|
||||||
Tolenmedik: {
|
const cfg = getPaidStatusConfig(t)[status]
|
||||||
label: 'Tölmedi',
|
|
||||||
variant: 'error' as StatusBadgeVariant,
|
|
||||||
icon: XCircle,
|
|
||||||
},
|
|
||||||
Tolendi: {
|
|
||||||
label: 'Tölendi',
|
|
||||||
variant: 'success' as StatusBadgeVariant,
|
|
||||||
icon: CheckCircle2,
|
|
||||||
},
|
|
||||||
} satisfies Record<PaymentPaidStatus, { label: string; variant: StatusBadgeVariant; icon: React.ElementType }>
|
|
||||||
|
|
||||||
function PaymentPaidStatusBadge({ status }: { status: PaymentPaidStatus }) {
|
|
||||||
const cfg = PAID_STATUS_CONFIG[status]
|
|
||||||
if (!cfg) return <span className="text-xs text-muted-foreground">{String(status)}</span>
|
if (!cfg) return <span className="text-xs text-muted-foreground">{String(status)}</span>
|
||||||
return <StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} />
|
return <StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} />
|
||||||
}
|
}
|
||||||
|
|
||||||
function PaymentStatusBadge({ status }: { status: PaymentStatus }) {
|
function PaymentStatusBadge({ status, t }: { status: PaymentStatus; t: (key: string, fallback?: string) => string }) {
|
||||||
const cfg = STATUS_CONFIG[status]
|
const cfg = getStatusConfig(t)[status]
|
||||||
if (!cfg) return <span className="text-xs text-muted-foreground">{String(status)}</span>
|
if (!cfg) return <span className="text-xs text-muted-foreground">{String(status)}</span>
|
||||||
return <StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} />
|
return <StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} />
|
||||||
}
|
}
|
||||||
@@ -72,158 +76,183 @@ function PaymentStatusBadge({ status }: { status: PaymentStatus }) {
|
|||||||
|
|
||||||
// ─── Column Meta for Toolbar ──────────────────────────────────────────────────
|
// ─── Column Meta for Toolbar ──────────────────────────────────────────────────
|
||||||
|
|
||||||
const columnMeta: ColumnMeta[] = [
|
function getColumnMeta(t: (key: string, fallback?: string) => string): ColumnMeta[] {
|
||||||
{ id: 'id', label: 'ID' },
|
return [
|
||||||
{ id: 'createdAt', label: 'Doredilen wagty' },
|
{ id: 'id', label: t('sberPayments.columns.id', 'ID') },
|
||||||
{ id: 'welayat', label: 'Welayat' },
|
{ id: 'createdAt', label: t('sberPayments.columns.createdAt', 'Döredilen wagty') },
|
||||||
{ id: 'sahamca', label: 'Sahamca' },
|
{ id: 'welayat', label: t('sberPayments.columns.welayat', 'Welaýat') },
|
||||||
{ id: 'firstName', label: 'Ady' },
|
{ id: 'sahamca', label: t('sberPayments.columns.sahamca', 'Şahamça') },
|
||||||
{ id: 'lastName', label: 'Familiyasy' },
|
{ id: 'firstName', label: t('sberPayments.columns.firstName', 'Ady') },
|
||||||
{ id: 'phone', label: 'Telefon' },
|
{ id: 'lastName', label: t('sberPayments.columns.lastName', 'Familiýasy') },
|
||||||
{ id: 'status', label: 'Status' },
|
{ id: 'phone', label: t('sberPayments.columns.phone', 'Telefon') },
|
||||||
{ id: 'paidStatus', label: 'Tolenen (sul ay)' },
|
{ id: 'status', label: t('sberPayments.columns.status', 'Status') },
|
||||||
]
|
{ id: 'paidStatus', label: t('sberPayments.columns.paidStatus', 'Tölenen (şul aý)') },
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
// ─── Filter Fields ────────────────────────────────────────────────────────────
|
// ─── Filter Fields ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const filterFields: FilterField[] = [
|
function getFilterFields(t: (key: string, fallback?: string) => string): FilterField[] {
|
||||||
{
|
return [
|
||||||
id: 'welayat',
|
{
|
||||||
label: 'Welayat',
|
id: 'welayat',
|
||||||
options: WELAYATLAR.map((w) => ({ value: w, label: w })),
|
label: t('sberPayments.filters.welayat', 'Welaýat'),
|
||||||
},
|
options: WELAYATLAR.map((w) => ({ value: w, label: w })),
|
||||||
{
|
},
|
||||||
id: 'status',
|
{
|
||||||
label: 'Status',
|
id: 'status',
|
||||||
options: STATUSES,
|
label: t('sberPayments.filters.status', 'Status'),
|
||||||
},
|
options: STATUSES,
|
||||||
]
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
// ─── List Page Component ──────────────────────────────────────────────────────
|
// ─── List Page Component ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
export default function SberPaymentsListPage() {
|
export default function SberPaymentsListPage() {
|
||||||
|
const { t: _t, i18n } = useTranslation()
|
||||||
|
const t: (key: string, fallback?: string) => string = useCallback(
|
||||||
|
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||||
|
[_t],
|
||||||
|
)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const deleteMutation = useDeleteSberPayment()
|
const deleteMutation = useDeleteSberPayment()
|
||||||
|
|
||||||
const columns = useMemo<ColumnDef<SberPaymentOrder>[]>(() => [
|
const colMeta = useMemo(() => getColumnMeta(t), [i18n.language])
|
||||||
{
|
const filterFlds = useMemo(() => getFilterFields(t), [i18n.language])
|
||||||
accessorKey: 'id',
|
|
||||||
header: ({ column }) => (
|
|
||||||
<button
|
|
||||||
className="flex items-center gap-1 hover:text-foreground transition-colors"
|
|
||||||
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
|
|
||||||
>
|
|
||||||
ID
|
|
||||||
<ArrowUpDown size={12} />
|
|
||||||
</button>
|
|
||||||
),
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<span className="font-medium text-foreground">{row.getValue('id')}</span>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'createdAt',
|
|
||||||
header: 'Doredilen wagty',
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const date = new Date(row.getValue('createdAt'))
|
|
||||||
return (
|
|
||||||
<div className="text-sm">
|
|
||||||
<div>{format(date, 'HH:mm, dd.MM.yyyy')}</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'welayat',
|
|
||||||
header: 'Welayat',
|
|
||||||
cell: ({ row }) => <span>{row.getValue('welayat')}</span>,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'sahamca',
|
|
||||||
header: ({ column }) => (
|
|
||||||
<button
|
|
||||||
className="flex items-center gap-1 hover:text-foreground transition-colors"
|
|
||||||
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
|
|
||||||
>
|
|
||||||
Sahamca
|
|
||||||
<ArrowUpDown size={12} />
|
|
||||||
</button>
|
|
||||||
),
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<span className="text-primary font-medium">{row.getValue('sahamca')}</span>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'firstName',
|
|
||||||
header: 'Ady',
|
|
||||||
cell: ({ row }) => <span>{row.getValue('firstName')}</span>,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'lastName',
|
|
||||||
header: 'Familiyasy',
|
|
||||||
cell: ({ row }) => <span>{row.getValue('lastName')}</span>,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'phone',
|
|
||||||
header: 'Telefon',
|
|
||||||
cell: ({ row }) => <span className="text-muted-foreground">{row.getValue('phone')}</span>,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'status',
|
|
||||||
header: ({ column }) => (
|
|
||||||
<button
|
|
||||||
className="flex items-center gap-1 hover:text-foreground transition-colors"
|
|
||||||
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
|
|
||||||
>
|
|
||||||
Status
|
|
||||||
<ArrowUpDown size={12} />
|
|
||||||
</button>
|
|
||||||
),
|
|
||||||
cell: ({ row }) => <PaymentStatusBadge status={row.getValue('status')} />,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'paidStatus',
|
|
||||||
header: 'Tolenen (sul ay)',
|
|
||||||
cell: ({ row }) => <PaymentPaidStatusBadge status={row.getValue('paidStatus')} />,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 'actions',
|
|
||||||
header: '',
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const order = row.original
|
|
||||||
|
|
||||||
return (
|
const columns = useMemo<ColumnDef<SberPaymentOrder>[]>(() => {
|
||||||
<div className="flex items-center gap-1">
|
const colMetaLabels = getColumnMeta(t)
|
||||||
<button
|
const idLabel = colMetaLabels.find(c => c.id === 'id')?.label ?? 'ID'
|
||||||
onClick={() => navigate(`/sber-payments/${order.id}`)}
|
const createdAtLabel = colMetaLabels.find(c => c.id === 'createdAt')?.label ?? 'Döredilen wagty'
|
||||||
className="p-1.5 rounded hover:bg-accent text-muted-foreground hover:text-foreground transition-colors"
|
const welayatLabel = colMetaLabels.find(c => c.id === 'welayat')?.label ?? 'Welaýat'
|
||||||
title="View"
|
const sahamcaLabel = colMetaLabels.find(c => c.id === 'sahamca')?.label ?? 'Şahamça'
|
||||||
>
|
const firstNameLabel = colMetaLabels.find(c => c.id === 'firstName')?.label ?? 'Ady'
|
||||||
<Eye size={16} />
|
const lastNameLabel = colMetaLabels.find(c => c.id === 'lastName')?.label ?? 'Familiýasy'
|
||||||
</button>
|
const phoneLabel = colMetaLabels.find(c => c.id === 'phone')?.label ?? 'Telefon'
|
||||||
<button
|
const statusLabel = colMetaLabels.find(c => c.id === 'status')?.label ?? 'Status'
|
||||||
onClick={() => navigate(`/sber-payments/${order.id}/edit`)}
|
const paidStatusLabel = colMetaLabels.find(c => c.id === 'paidStatus')?.label ?? 'Tölenen (şul aý)'
|
||||||
className="p-1.5 rounded hover:bg-accent text-muted-foreground hover:text-foreground transition-colors"
|
|
||||||
title="Edit"
|
return [
|
||||||
>
|
{
|
||||||
<Edit size={16} />
|
accessorKey: 'id',
|
||||||
</button>
|
header: ({ column }) => (
|
||||||
<button
|
<button
|
||||||
onClick={async () => {
|
className="flex items-center gap-1 hover:text-foreground transition-colors"
|
||||||
if (confirm('Bu tolegi pozmak isleyanizmi?')) {
|
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
|
||||||
await deleteMutation.mutateAsync(order.id)
|
>
|
||||||
}
|
{idLabel}
|
||||||
}}
|
<ArrowUpDown size={12} />
|
||||||
className="p-1.5 rounded hover:bg-accent text-destructive hover:bg-destructive/10 transition-colors"
|
</button>
|
||||||
title="Delete"
|
),
|
||||||
>
|
cell: ({ row }) => (
|
||||||
<Trash2 size={16} />
|
<span className="font-medium text-foreground">{row.getValue('id')}</span>
|
||||||
</button>
|
),
|
||||||
</div>
|
|
||||||
)
|
|
||||||
},
|
},
|
||||||
},
|
{
|
||||||
], [navigate, deleteMutation])
|
accessorKey: 'createdAt',
|
||||||
|
header: createdAtLabel,
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const date = new Date(row.getValue('createdAt'))
|
||||||
|
return (
|
||||||
|
<div className="text-sm">
|
||||||
|
<div>{format(date, 'HH:mm, dd.MM.yyyy')}</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'welayat',
|
||||||
|
header: welayatLabel,
|
||||||
|
cell: ({ row }) => <span>{row.getValue('welayat')}</span>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'sahamca',
|
||||||
|
header: ({ column }) => (
|
||||||
|
<button
|
||||||
|
className="flex items-center gap-1 hover:text-foreground transition-colors"
|
||||||
|
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
|
||||||
|
>
|
||||||
|
{sahamcaLabel}
|
||||||
|
<ArrowUpDown size={12} />
|
||||||
|
</button>
|
||||||
|
),
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<span className="text-primary font-medium">{row.getValue('sahamca')}</span>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'firstName',
|
||||||
|
header: firstNameLabel,
|
||||||
|
cell: ({ row }) => <span>{row.getValue('firstName')}</span>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'lastName',
|
||||||
|
header: lastNameLabel,
|
||||||
|
cell: ({ row }) => <span>{row.getValue('lastName')}</span>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'phone',
|
||||||
|
header: phoneLabel,
|
||||||
|
cell: ({ row }) => <span className="text-muted-foreground">{row.getValue('phone')}</span>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'status',
|
||||||
|
header: ({ column }) => (
|
||||||
|
<button
|
||||||
|
className="flex items-center gap-1 hover:text-foreground transition-colors"
|
||||||
|
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
|
||||||
|
>
|
||||||
|
{statusLabel}
|
||||||
|
<ArrowUpDown size={12} />
|
||||||
|
</button>
|
||||||
|
),
|
||||||
|
cell: ({ row }) => <PaymentStatusBadge status={row.getValue('status')} t={t} />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'paidStatus',
|
||||||
|
header: paidStatusLabel,
|
||||||
|
cell: ({ row }) => <PaymentPaidStatusBadge status={row.getValue('paidStatus')} t={t} />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'actions',
|
||||||
|
header: '',
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const order = row.original
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<button
|
||||||
|
onClick={() => navigate(`/sber-payments/${order.id}`)}
|
||||||
|
className="p-1.5 rounded hover:bg-accent text-muted-foreground hover:text-foreground transition-colors"
|
||||||
|
title={t('common.view', 'View')}
|
||||||
|
>
|
||||||
|
<Eye size={16} />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => navigate(`/sber-payments/${order.id}/edit`)}
|
||||||
|
className="p-1.5 rounded hover:bg-accent text-muted-foreground hover:text-foreground transition-colors"
|
||||||
|
title={t('common.edit', 'Edit')}
|
||||||
|
>
|
||||||
|
<Edit size={16} />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
if (confirm(t('sberPayments.deleteDialog.title', 'Bu tölegi pozmak isleýärsiňizmi?'))) {
|
||||||
|
await deleteMutation.mutateAsync(order.id)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="p-1.5 rounded hover:bg-accent text-destructive hover:bg-destructive/10 transition-colors"
|
||||||
|
title={t('common.delete', 'Delete')}
|
||||||
|
>
|
||||||
|
<Trash2 size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}, [navigate, deleteMutation, t, i18n.language])
|
||||||
|
|
||||||
// Pagination state
|
// Pagination state
|
||||||
const [page, setPage] = useState(1)
|
const [page, setPage] = useState(1)
|
||||||
@@ -237,7 +266,7 @@ export default function SberPaymentsListPage() {
|
|||||||
|
|
||||||
// Column visibility & order
|
// Column visibility & order
|
||||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({})
|
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({})
|
||||||
const [columnOrder, setColumnOrder] = useState<string[]>(columnMeta.map((c) => c.id))
|
const [columnOrder, setColumnOrder] = useState<string[]>(colMeta.map((c) => c.id))
|
||||||
|
|
||||||
// Month filter
|
// Month filter
|
||||||
const [selectedMonth, setSelectedMonth] = useState<string>('')
|
const [selectedMonth, setSelectedMonth] = useState<string>('')
|
||||||
@@ -276,32 +305,32 @@ export default function SberPaymentsListPage() {
|
|||||||
{/* Month Filter Card */}
|
{/* Month Filter Card */}
|
||||||
<div className="bg-card border border-border rounded-lg p-4 max-w-xs">
|
<div className="bg-card border border-border rounded-lg p-4 max-w-xs">
|
||||||
<label className="block text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2">
|
<label className="block text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2">
|
||||||
Ay Tolegi
|
{t('sberPayments.list.monthLabel', 'Aý tölegi')}
|
||||||
</label>
|
</label>
|
||||||
<Select value={selectedMonth} onValueChange={setSelectedMonth}>
|
<Select value={selectedMonth} onValueChange={setSelectedMonth}>
|
||||||
<SelectTrigger className="w-full">
|
<SelectTrigger className="w-full">
|
||||||
<SelectValue placeholder="--" />
|
<SelectValue placeholder="--" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="01">Yanwar</SelectItem>
|
<SelectItem value="01">{t('months.january', 'Ýanwar')}</SelectItem>
|
||||||
<SelectItem value="02">Fewral</SelectItem>
|
<SelectItem value="02">{t('months.february', 'Fewral')}</SelectItem>
|
||||||
<SelectItem value="03">Mart</SelectItem>
|
<SelectItem value="03">{t('months.march', 'Mart')}</SelectItem>
|
||||||
<SelectItem value="04">Aprel</SelectItem>
|
<SelectItem value="04">{t('months.april', 'Aprel')}</SelectItem>
|
||||||
<SelectItem value="05">May</SelectItem>
|
<SelectItem value="05">{t('months.may', 'Maý')}</SelectItem>
|
||||||
<SelectItem value="06">Iýun</SelectItem>
|
<SelectItem value="06">{t('months.june', 'Iýun')}</SelectItem>
|
||||||
<SelectItem value="07">Iýul</SelectItem>
|
<SelectItem value="07">{t('months.july', 'Iýul')}</SelectItem>
|
||||||
<SelectItem value="08">Awgust</SelectItem>
|
<SelectItem value="08">{t('months.august', 'Awgust')}</SelectItem>
|
||||||
<SelectItem value="09">Sentýabr</SelectItem>
|
<SelectItem value="09">{t('months.september', 'Sentýabr')}</SelectItem>
|
||||||
<SelectItem value="10">Oktýabr</SelectItem>
|
<SelectItem value="10">{t('months.october', 'Oktýabr')}</SelectItem>
|
||||||
<SelectItem value="11">Noýabr</SelectItem>
|
<SelectItem value="11">{t('months.november', 'Noýabr')}</SelectItem>
|
||||||
<SelectItem value="12">Dekabr</SelectItem>
|
<SelectItem value="12">{t('months.december', 'Dekabr')}</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Page Title */}
|
{/* Page Title */}
|
||||||
<h1 className="text-xl font-semibold text-foreground">
|
<h1 className="text-xl font-semibold text-foreground">
|
||||||
Sber tolegier (talyplar ucin)
|
{t('sberPayments.list.title', 'Sber tölegler (talyplar üçin)')}
|
||||||
</h1>
|
</h1>
|
||||||
<div className="bg-card border border-border rounded-xl p-4">
|
<div className="bg-card border border-border rounded-xl p-4">
|
||||||
|
|
||||||
@@ -312,13 +341,13 @@ export default function SberPaymentsListPage() {
|
|||||||
setSearch(val)
|
setSearch(val)
|
||||||
setPage(1)
|
setPage(1)
|
||||||
}}
|
}}
|
||||||
searchPlaceholder="Gozlemek"
|
searchPlaceholder={t('common.search', 'Gözlemek')}
|
||||||
columns={columnMeta}
|
columns={colMeta}
|
||||||
columnVisibility={columnVisibility}
|
columnVisibility={columnVisibility}
|
||||||
onColumnVisibilityChange={setColumnVisibility}
|
onColumnVisibilityChange={setColumnVisibility}
|
||||||
columnOrder={columnOrder}
|
columnOrder={columnOrder}
|
||||||
onColumnOrderChange={setColumnOrder}
|
onColumnOrderChange={setColumnOrder}
|
||||||
filterFields={filterFields}
|
filterFields={filterFlds}
|
||||||
activeFilters={activeFilters}
|
activeFilters={activeFilters}
|
||||||
onFilterChange={handleFilterChange}
|
onFilterChange={handleFilterChange}
|
||||||
onFilterReset={handleFilterReset}
|
onFilterReset={handleFilterReset}
|
||||||
@@ -327,7 +356,7 @@ export default function SberPaymentsListPage() {
|
|||||||
setPerPage(val)
|
setPerPage(val)
|
||||||
setPage(1)
|
setPage(1)
|
||||||
}}
|
}}
|
||||||
actionLabel="Sber toleg (talyplar ucin) doredih"
|
actionLabel={t('sberPayments.list.actionLabel', 'Sber töleg (talyplar üçin) dörediň')}
|
||||||
onAction={() => navigate('/sber-payments/create')}
|
onAction={() => navigate('/sber-payments/create')}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -4,9 +4,6 @@ import { SberPaymentForm } from '@/features/sberPayments/components/sberPayments
|
|||||||
export default function SberPaymentCreatePage() {
|
export default function SberPaymentCreatePage() {
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-xl font-semibold text-foreground mb-6">
|
|
||||||
Sber toleg (talyplar ucin) doredih
|
|
||||||
</h1>
|
|
||||||
<SberPaymentForm mode="create" />
|
<SberPaymentForm mode="create" />
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useParams } from 'react-router-dom'
|
import { useParams } from 'react-router-dom'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { SberPaymentForm } from '@/features/sberPayments/components/sberPaymentsForm'
|
import { SberPaymentForm } from '@/features/sberPayments/components/sberPaymentsForm'
|
||||||
import { useSberPaymentOrder } from '@/features/sberPayments/hooks/useSberPayments'
|
import { useSberPaymentOrder } from '@/features/sberPayments/hooks/useSberPayments'
|
||||||
import { Spinner } from '@/components/ui/spinner'
|
import { Spinner } from '@/components/ui/spinner'
|
||||||
@@ -6,6 +7,7 @@ import { Spinner } from '@/components/ui/spinner'
|
|||||||
export default function SberPaymentEditPage() {
|
export default function SberPaymentEditPage() {
|
||||||
const params = useParams()
|
const params = useParams()
|
||||||
const id = params.id as string
|
const id = params.id as string
|
||||||
|
const { t } = useTranslation()
|
||||||
|
|
||||||
const { data: order, isLoading } = useSberPaymentOrder(id)
|
const { data: order, isLoading } = useSberPaymentOrder(id)
|
||||||
|
|
||||||
@@ -20,7 +22,7 @@ export default function SberPaymentEditPage() {
|
|||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-xl font-semibold text-foreground mb-6">
|
<h1 className="text-xl font-semibold text-foreground mb-6">
|
||||||
Sber toleg (talyplar ucin) uytgetmek: {id}
|
{t('sberPayments.formTitle.edit', 'Sber töleg redaktirläň')}: {id}
|
||||||
</h1>
|
</h1>
|
||||||
<SberPaymentForm mode="edit" initialData={order} orderId={id} />
|
<SberPaymentForm mode="edit" initialData={order} orderId={id} />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in new issue
Block a user