added users pages, stepper

This commit is contained in:
Jelaletdin12
2026-05-10 23:31:01 +05:00
parent 2424093a4f
commit ab7fdf46b3
30 changed files with 4665 additions and 446 deletions

View File

@@ -0,0 +1,267 @@
// ─── Types ────────────────────────────────────────────────────────────────────
export interface Client {
id: number
username: string
name: string
phone: string | null
email: string | null
isActive: boolean
}
export interface ClientDetail extends Client {
roles: ClientRole[]
permissions: ClientPermission[]
branches: ClientBranch[]
loanOrders: ClientLoanOrder[]
cardOrders: ClientCardOrder[]
auditLogs: ClientAuditLog[]
}
export interface ClientRole {
id: number
code: string
name: string
guardName: string
}
export interface ClientPermission {
id: number
name: string
guardName: string
}
export interface ClientBranch {
id: number
name: string
region: string
district: string
uniqueCode: string
isActive: boolean
billingUsernameIbr: string
billingUsernameSber: string
billingUsernameVisa: string
}
export interface ClientLoanOrder {
id: number
name: string
amount: number
status: string
createdAt: string
}
export interface ClientCardOrder {
id: number
name: string
amount: number
status: string
createdAt: string
}
export interface ClientAuditLog {
id: number
actionName: string
performedBy: string
target: string
status: string
createdAt: string
}
export interface ClientsListResponse {
data: Client[]
meta: {
currentPage: number
totalPages: number
totalCount: number
perPage: number
}
}
export interface CreateClientPayload {
username: string
name: string
phone: string
email?: string
password: string
isActive: boolean
}
export interface UpdateClientPayload {
username?: string
name?: string
phone?: string
email?: string
password?: string
isActive?: boolean
}
export interface ClientsListParams {
page?: number
perPage?: number
search?: string
isActive?: string
}
// ─── Mock Data & API ────────────────────────────────────────────────────────────
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
let mockClients: ClientDetail[] = [
{
id: 1,
username: 'client_01',
name: 'Merdan Merdanow',
phone: '+99361234567',
email: 'merdan@example.com',
isActive: true,
roles: [{ id: 1, code: 'CLIENT_STANDARD', name: 'Standard Client', guardName: 'web' }],
permissions: [],
branches: [
{
id: 1,
name: 'Aşgabat Baş Şahamça',
region: 'Aşgabat',
district: 'Kopetdag',
uniqueCode: '01',
isActive: true,
billingUsernameIbr: 'ibr_c1',
billingUsernameSber: 'sber_c1',
billingUsernameVisa: 'visa_c1',
},
],
loanOrders: [
{ id: 101, name: 'Sarp ediş karzy', amount: 20000, status: 'Active', createdAt: '2023-11-01T10:00:00Z' }
],
cardOrders: [
{ id: 201, name: 'Visa Gold', amount: 500, status: 'Pending', createdAt: '2023-11-05T14:30:00Z' }
],
auditLogs: [
{
id: 1,
actionName: 'Profile Update',
performedBy: 'System',
target: 'client_01',
status: 'Success',
createdAt: '2023-10-27T10:00:00Z',
},
],
},
{
id: 2,
username: 'client_02',
name: 'Aýnabat Aýmyradowa',
phone: '+99365765432',
email: 'aynabat@example.com',
isActive: false,
roles: [{ id: 2, code: 'CLIENT_PREMIUM', name: 'Premium Client', guardName: 'web' }],
permissions: [],
branches: [],
loanOrders: [],
cardOrders: [],
auditLogs: [],
},
]
export const clientsApi = {
getAll: async (params: ClientsListParams): Promise<ClientsListResponse> => {
await delay(500)
let filtered = [...mockClients]
if (params.search) {
const q = params.search.toLowerCase()
filtered = filtered.filter(
(c) =>
c.name.toLowerCase().includes(q) ||
c.username.toLowerCase().includes(q) ||
(c.phone && c.phone.includes(q))
)
}
if (params.isActive !== undefined && params.isActive !== '') {
const isActive = params.isActive === 'true'
filtered = filtered.filter((c) => c.isActive === isActive)
}
return {
data: filtered,
meta: {
currentPage: params.page || 1,
totalPages: Math.ceil(filtered.length / (params.perPage || 25)) || 1,
totalCount: filtered.length,
perPage: params.perPage || 25,
},
}
},
getById: async (id: number): Promise<ClientDetail> => {
await delay(500)
const client = mockClients.find((c) => c.id === Number(id))
if (!client) throw new Error('Not found')
return client
},
create: async (payload: CreateClientPayload): Promise<Client> => {
await delay(500)
const newClient: ClientDetail = {
id: mockClients.length > 0 ? Math.max(...mockClients.map((c) => c.id)) + 1 : 1,
username: payload.username,
name: payload.name,
phone: payload.phone,
email: payload.email || null,
isActive: payload.isActive,
roles: [],
permissions: [],
branches: [],
loanOrders: [],
cardOrders: [],
auditLogs: [],
}
mockClients.unshift(newClient)
return newClient
},
update: async (id: number, payload: UpdateClientPayload): Promise<Client> => {
await delay(500)
const index = mockClients.findIndex((c) => c.id === Number(id))
if (index === -1) throw new Error('Not found')
mockClients[index] = {
...mockClients[index],
...payload,
username: payload.username ?? mockClients[index].username,
name: payload.name ?? mockClients[index].name,
phone: payload.phone ?? mockClients[index].phone,
email: payload.email !== undefined ? payload.email : mockClients[index].email,
isActive: payload.isActive ?? mockClients[index].isActive,
}
return mockClients[index]
},
delete: async (id: number): Promise<void> => {
await delay(500)
mockClients = mockClients.filter((c) => c.id !== Number(id))
},
assignRole: async (_clientId: number, _roleId: number): Promise<void> => {
await delay(500)
},
removeRole: async (_clientId: number, _roleId: number): Promise<void> => {
await delay(500)
},
assignPermission: async (_clientId: number, _permissionId: number): Promise<void> => {
await delay(500)
},
removePermission: async (_clientId: number, _permissionId: number): Promise<void> => {
await delay(500)
},
assignBranch: async (_clientId: number, _branchId: number): Promise<void> => {
await delay(500)
},
removeBranch: async (_clientId: number, _branchId: number): Promise<void> => {
await delay(500)
},
}

View File

@@ -0,0 +1,255 @@
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { FormInput } from '@/components/formInput'
import { useCreateClient, useUpdateClient } from '../hooks/useClients'
import type { Client, CreateClientPayload, UpdateClientPayload } from '../api/clientsApi'
// ─── Types ────────────────────────────────────────────────────────────────────
interface ClientFormProps {
mode: 'create' | 'edit'
initialData?: Client
clientId?: number
}
interface FormState {
username: string
name: string
phone: string
email: string
password: string
isActive: boolean
}
interface FormErrors {
username?: string
name?: string
phone?: string
password?: string
}
// ─── ClientForm ───────────────────────────────────────────────────────────────
export function ClientForm({ mode, initialData, clientId }: ClientFormProps) {
const { t } = useTranslation()
const navigate = useNavigate()
const createMutation = useCreateClient()
const updateMutation = useUpdateClient(clientId ?? 0)
const isPending = createMutation.isPending || updateMutation.isPending
// ── Form state ──────────────────────────────────────────────────────────────
const [form, setForm] = useState<FormState>({
username: '',
name: '',
phone: '',
email: '',
password: '',
isActive: true,
})
const [errors, setErrors] = useState<FormErrors>({})
// Populate form in edit mode
useEffect(() => {
if (mode === 'edit' && initialData) {
setForm({
username: initialData.username ?? '',
name: initialData.name ?? '',
phone: initialData.phone ?? '',
email: initialData.email ?? '',
password: '',
isActive: initialData.isActive ?? true,
})
}
}, [mode, initialData])
// ── Helpers ─────────────────────────────────────────────────────────────────
const set = (field: keyof FormState) => (value: string) =>
setForm((prev) => ({ ...prev, [field]: value }))
const validate = (): boolean => {
const next: FormErrors = {}
if (!form.username.trim())
next.username = t('clients.errors.usernameRequired', 'Ulanyjy ady hökmany')
if (!form.name.trim())
next.name = t('clients.errors.nameRequired', 'Ady hökmany')
if (!form.phone.trim())
next.phone = t('clients.errors.phoneRequired', 'Telefon hökmany')
if (mode === 'create' && !form.password.trim())
next.password = t('clients.errors.passwordRequired', 'Açar sözi hökmany')
setErrors(next)
return Object.keys(next).length === 0
}
// ── Submit ──────────────────────────────────────────────────────────────────
const handleSubmit = () => {
if (!validate()) return
if (mode === 'create') {
const payload: CreateClientPayload = {
username: form.username.trim(),
name: form.name.trim(),
phone: form.phone.trim(),
email: form.email.trim() || undefined,
password: form.password,
isActive: form.isActive,
}
createMutation.mutate(payload, {
onSuccess: () => navigate('/clients'),
})
} else {
const payload: UpdateClientPayload = {
username: form.username.trim(),
name: form.name.trim(),
phone: form.phone.trim(),
email: form.email.trim() || undefined,
isActive: form.isActive,
}
if (form.password.trim()) {
payload.password = form.password
}
updateMutation.mutate(payload, {
onSuccess: () => navigate(`/clients/${clientId}`),
})
}
}
// ── Render ──────────────────────────────────────────────────────────────────
return (
<div className="bg-card border border-border rounded-xl overflow-hidden">
{/* Username */}
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
<span className="text-sm text-muted-foreground pt-2">
{t('clients.fields.username', 'Ulanyjy ady')}
<span className="text-destructive ml-0.5">*</span>
</span>
<FormInput
type="text"
value={form.username}
onChange={set('username')}
placeholder={t('clients.fields.username', 'Ulanyjy ady')}
error={errors.username}
disabled={isPending}
className="max-w-lg"
/>
</div>
{/* Name */}
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
<span className="text-sm text-muted-foreground pt-2">
{t('clients.fields.name', 'Ady')}
<span className="text-destructive ml-0.5">*</span>
</span>
<FormInput
type="text"
value={form.name}
onChange={set('name')}
placeholder={t('clients.fields.name', 'Ady')}
error={errors.name}
disabled={isPending}
className="max-w-lg"
/>
</div>
{/* Phone */}
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
<span className="text-sm text-muted-foreground pt-2">
{t('clients.fields.phone', 'Telefon')}
<span className="text-destructive ml-0.5">*</span>
</span>
<FormInput
type="phone"
value={form.phone}
onChange={set('phone')}
error={errors.phone}
disabled={isPending}
className="max-w-lg"
/>
</div>
{/* Email */}
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
<span className="text-sm text-muted-foreground pt-2">
{t('clients.fields.email', 'E-poçta')}
</span>
<FormInput
type="email"
value={form.email}
onChange={set('email')}
placeholder={t('clients.fields.email', 'E-poçta')}
disabled={isPending}
className="max-w-lg"
/>
</div>
{/* Password */}
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
<span className="text-sm text-muted-foreground pt-2">
{t('clients.fields.password', 'Açar sözi')}
{mode === 'create' && <span className="text-destructive ml-0.5">*</span>}
</span>
<div className="max-w-lg space-y-1">
<FormInput
type="password"
value={form.password}
onChange={set('password')}
placeholder={
mode === 'edit'
? t('clients.fields.passwordEditHint', 'Üýtgetmek üçin täze açar söz giriziň')
: t('clients.fields.password', 'Açar sözi')
}
error={errors.password}
disabled={isPending}
/>
{mode === 'edit' && (
<p className="text-xs text-muted-foreground">
{t('clients.fields.passwordEditNote', 'Boş goýsaňyz, açar sözi üýtgemez')}
</p>
)}
</div>
</div>
{/* isActive */}
<div className="grid grid-cols-[220px_1fr] items-center py-4 px-6">
<span className="text-sm text-muted-foreground">
{t('clients.fields.isActive', 'Işjeň')}
</span>
<Checkbox
checked={form.isActive}
onCheckedChange={(v) => setForm((prev) => ({ ...prev, isActive: !!v }))}
disabled={isPending}
className="data-[state=checked]:bg-primary data-[state=checked]:border-primary"
/>
</div>
{/* Actions */}
<div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-border bg-muted/20">
<Button
type="button"
variant="ghost"
onClick={() => navigate(-1)}
disabled={isPending}
>
{t('common.cancel', 'Ýatyr')}
</Button>
<Button
type="button"
onClick={handleSubmit}
disabled={isPending}
className="bg-primary hover:bg-primary/90 text-primary-foreground min-w-[160px]"
>
{isPending
? t('common.saving', 'Saklanýar...')
: mode === 'create'
? t('clients.createBtn', 'Müşderi döredin')
: t('clients.updateBtn', 'Üýtgetmeleri sakla')}
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,148 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { useTranslation } from 'react-i18next'
import {
clientsApi,
type ClientsListParams,
type CreateClientPayload,
type UpdateClientPayload,
} from '../api/clientsApi'
// ─── Query Keys ───────────────────────────────────────────────────────────────
export const clientKeys = {
all: ['clients'] as const,
lists: () => [...clientKeys.all, 'list'] as const,
list: (params: ClientsListParams) => [...clientKeys.lists(), params] as const,
details: () => [...clientKeys.all, 'detail'] as const,
detail: (id: number) => [...clientKeys.details(), id] as const,
}
// ─── useClients ───────────────────────────────────────────────────────────────
export function useClients(params: ClientsListParams) {
return useQuery({
queryKey: clientKeys.list(params),
queryFn: () => clientsApi.getAll(params),
placeholderData: (prev) => prev,
})
}
// ─── useClient ────────────────────────────────────────────────────────────────
export function useClient(id: number) {
return useQuery({
queryKey: clientKeys.detail(id),
queryFn: () => clientsApi.getById(id),
enabled: !!id,
})
}
// ─── useCreateClient ──────────────────────────────────────────────────────────
export function useCreateClient() {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: CreateClientPayload) => clientsApi.create(payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: clientKeys.lists() })
toast.success(t('clients.createSuccess', 'Müşderi üstünlikli döredildi'))
},
onError: () => {
toast.error(t('clients.createError', 'Müşderi döretmekde ýalňyşlyk'))
},
})
}
// ─── useUpdateClient ──────────────────────────────────────────────────────────
export function useUpdateClient(id: number) {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: UpdateClientPayload) => clientsApi.update(id, payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: clientKeys.lists() })
queryClient.invalidateQueries({ queryKey: clientKeys.detail(id) })
toast.success(t('clients.updateSuccess', 'Müşderi üstünlikli täzelendi'))
},
onError: () => {
toast.error(t('clients.updateError', 'Müşderi täzelemekde ýalňyşlyk'))
},
})
}
// ─── useDeleteClient ──────────────────────────────────────────────────────────
export function useDeleteClient() {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (id: number) => clientsApi.delete(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: clientKeys.lists() })
toast.success(t('clients.deleteSuccess', 'Müşderi üstünlikli pozuldy'))
},
onError: () => {
toast.error(t('clients.deleteError', 'Müşderi pozmakda ýalňyşlyk'))
},
})
}
// ─── useAssignClientRole ──────────────────────────────────────────────────────
export function useAssignClientRole(clientId: number) {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (roleId: number) => clientsApi.assignRole(clientId, roleId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: clientKeys.detail(clientId) })
toast.success(t('clients.roleAssigned', 'Rol birikdirildi'))
},
onError: () => {
toast.error(t('clients.roleAssignError', 'Rol birikdirmekde ýalňyşlyk'))
},
})
}
// ─── useRemoveClientRole ──────────────────────────────────────────────────────
export function useRemoveClientRole(clientId: number) {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (roleId: number) => clientsApi.removeRole(clientId, roleId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: clientKeys.detail(clientId) })
toast.success(t('clients.roleRemoved', 'Rol aýryldy'))
},
onError: () => {
toast.error(t('clients.roleRemoveError', 'Rol aýyrmakda ýalňyşlyk'))
},
})
}
// ─── useAssignClientBranch ────────────────────────────────────────────────────
export function useAssignClientBranch(clientId: number) {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (branchId: number) => clientsApi.assignBranch(clientId, branchId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: clientKeys.detail(clientId) })
toast.success(t('clients.branchAssigned', 'Şahamça birikdirildi'))
},
onError: () => {
toast.error(t('clients.branchAssignError', 'Şahamça birikdirmekde ýalňyşlyk'))
},
})
}