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