added users pages, stepper
This commit is contained in:
234
src/features/operators/api/operatorsApi.ts
Normal file
234
src/features/operators/api/operatorsApi.ts
Normal file
@@ -0,0 +1,234 @@
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface Operator {
|
||||
id: number
|
||||
username: string
|
||||
name: string
|
||||
phone: string | null
|
||||
email: string | null
|
||||
isActive: boolean
|
||||
}
|
||||
|
||||
export interface OperatorDetail extends Operator {
|
||||
roles: OperatorRole[]
|
||||
permissions: OperatorPermission[]
|
||||
branches: OperatorBranch[]
|
||||
loanLimits: OperatorLoanLimit[]
|
||||
cardLimits: OperatorCardLimit[]
|
||||
auditLogs: OperatorAuditLog[]
|
||||
}
|
||||
|
||||
export interface OperatorRole {
|
||||
id: number
|
||||
code: string
|
||||
name: string
|
||||
guardName: string
|
||||
}
|
||||
|
||||
export interface OperatorPermission {
|
||||
id: number
|
||||
name: string
|
||||
guardName: string
|
||||
}
|
||||
|
||||
export interface OperatorBranch {
|
||||
id: number
|
||||
name: string
|
||||
region: string
|
||||
district: string
|
||||
uniqueCode: string
|
||||
isActive: boolean
|
||||
billingUsernameIbr: string
|
||||
billingUsernameSber: string
|
||||
billingUsernameVisa: string
|
||||
}
|
||||
|
||||
export interface OperatorLoanLimit {
|
||||
id: number
|
||||
name: string
|
||||
amount: number
|
||||
}
|
||||
|
||||
export interface OperatorCardLimit {
|
||||
id: number
|
||||
name: string
|
||||
amount: number
|
||||
}
|
||||
|
||||
export interface OperatorAuditLog {
|
||||
id: number
|
||||
actionName: string
|
||||
performedBy: string
|
||||
target: string
|
||||
status: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface OperatorsListResponse {
|
||||
data: Operator[]
|
||||
meta: {
|
||||
currentPage: number
|
||||
totalPages: number
|
||||
totalCount: number
|
||||
perPage: number
|
||||
}
|
||||
}
|
||||
|
||||
export interface CreateOperatorPayload {
|
||||
username: string
|
||||
name: string
|
||||
phone?: string
|
||||
email?: string
|
||||
password: string
|
||||
isActive: boolean
|
||||
}
|
||||
|
||||
export interface UpdateOperatorPayload {
|
||||
username?: string
|
||||
name?: string
|
||||
phone?: string
|
||||
email?: string
|
||||
password?: string
|
||||
isActive?: boolean
|
||||
}
|
||||
|
||||
export interface OperatorsListParams {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
isActive?: string
|
||||
}
|
||||
|
||||
// ─── Mock Data & API ────────────────────────────────────────────────────────────
|
||||
|
||||
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
|
||||
|
||||
let mockOperators: OperatorDetail[] = [
|
||||
{
|
||||
id: 1,
|
||||
username: 'johndoe',
|
||||
name: 'John Doe',
|
||||
phone: '+99365123456',
|
||||
email: 'johndoe@example.com',
|
||||
isActive: true,
|
||||
roles: [{ id: 1, code: 'ADMIN', name: 'Administrator', guardName: 'web' }],
|
||||
permissions: [{ id: 1, name: 'create_user', guardName: 'web' }],
|
||||
branches: [
|
||||
{
|
||||
id: 1,
|
||||
name: 'Main Branch',
|
||||
region: 'Aşgabat',
|
||||
district: 'Kopetdag',
|
||||
uniqueCode: '01',
|
||||
isActive: true,
|
||||
billingUsernameIbr: 'ibr_1',
|
||||
billingUsernameSber: 'sber_1',
|
||||
billingUsernameVisa: 'visa_1',
|
||||
},
|
||||
],
|
||||
loanLimits: [{ id: 1, name: 'Consumer Loan', amount: 50000 }],
|
||||
cardLimits: [{ id: 1, name: 'Credit Card', amount: 10000 }],
|
||||
auditLogs: [
|
||||
{
|
||||
id: 1,
|
||||
actionName: 'Login',
|
||||
performedBy: 'System',
|
||||
target: 'johndoe',
|
||||
status: 'Success',
|
||||
createdAt: '2023-10-27T10:00:00Z',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
username: 'janedoe',
|
||||
name: 'Jane Doe',
|
||||
phone: '+99365654321',
|
||||
email: 'janedoe@example.com',
|
||||
isActive: false,
|
||||
roles: [{ id: 2, code: 'OPERATOR', name: 'Operator', guardName: 'web' }],
|
||||
permissions: [],
|
||||
branches: [],
|
||||
loanLimits: [],
|
||||
cardLimits: [],
|
||||
auditLogs: [],
|
||||
},
|
||||
]
|
||||
|
||||
export const operatorsApi = {
|
||||
getAll: async (params: OperatorsListParams): Promise<OperatorsListResponse> => {
|
||||
await delay(500)
|
||||
let filtered = [...mockOperators]
|
||||
if (params.search) {
|
||||
const q = params.search.toLowerCase()
|
||||
filtered = filtered.filter(
|
||||
(o) =>
|
||||
o.name.toLowerCase().includes(q) ||
|
||||
o.username.toLowerCase().includes(q)
|
||||
)
|
||||
}
|
||||
return {
|
||||
data: filtered,
|
||||
meta: {
|
||||
currentPage: params.page || 1,
|
||||
totalPages: 1,
|
||||
totalCount: filtered.length,
|
||||
perPage: params.perPage || 10,
|
||||
},
|
||||
}
|
||||
},
|
||||
|
||||
getById: async (id: number): Promise<OperatorDetail> => {
|
||||
await delay(500)
|
||||
const op = mockOperators.find((o) => o.id === Number(id))
|
||||
if (!op) throw new Error('Not found')
|
||||
return op
|
||||
},
|
||||
|
||||
create: async (payload: CreateOperatorPayload): Promise<Operator> => {
|
||||
await delay(500)
|
||||
const newOp: OperatorDetail = {
|
||||
id: mockOperators.length > 0 ? Math.max(...mockOperators.map((o) => o.id)) + 1 : 1,
|
||||
...payload,
|
||||
phone: payload.phone || null,
|
||||
email: payload.email || null,
|
||||
roles: [],
|
||||
permissions: [],
|
||||
branches: [],
|
||||
loanLimits: [],
|
||||
cardLimits: [],
|
||||
auditLogs: [],
|
||||
}
|
||||
mockOperators.push(newOp)
|
||||
return newOp
|
||||
},
|
||||
|
||||
update: async (id: number, payload: UpdateOperatorPayload): Promise<Operator> => {
|
||||
await delay(500)
|
||||
const index = mockOperators.findIndex((o) => o.id === Number(id))
|
||||
if (index === -1) throw new Error('Not found')
|
||||
mockOperators[index] = { ...mockOperators[index], ...payload }
|
||||
return mockOperators[index]
|
||||
},
|
||||
|
||||
delete: async (id: number): Promise<void> => {
|
||||
await delay(500)
|
||||
mockOperators = mockOperators.filter((o) => o.id !== Number(id))
|
||||
},
|
||||
|
||||
assignRole: async (_operatorId: number, _roleId: number): Promise<void> => {
|
||||
await delay(500)
|
||||
},
|
||||
|
||||
removeRole: async (_operatorId: number, _roleId: number): Promise<void> => {
|
||||
await delay(500)
|
||||
},
|
||||
|
||||
assignPermission: async (_operatorId: number, _permissionId: number): Promise<void> => {
|
||||
await delay(500)
|
||||
},
|
||||
|
||||
removePermission: async (_operatorId: number, _permissionId: number): Promise<void> => {
|
||||
await delay(500)
|
||||
},
|
||||
}
|
||||
253
src/features/operators/components/operatorForms.tsx
Normal file
253
src/features/operators/components/operatorForms.tsx
Normal file
@@ -0,0 +1,253 @@
|
||||
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 { useCreateOperator, useUpdateOperator } from '../hooks/useOperators'
|
||||
import type { Operator, CreateOperatorPayload, UpdateOperatorPayload } from '../api/operatorsApi'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface OperatorFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: Operator
|
||||
operatorId?: number
|
||||
}
|
||||
|
||||
interface FormState {
|
||||
username: string
|
||||
name: string
|
||||
phone: string
|
||||
email: string
|
||||
password: string
|
||||
isActive: boolean
|
||||
}
|
||||
|
||||
interface FormErrors {
|
||||
username?: string
|
||||
name?: string
|
||||
password?: string
|
||||
}
|
||||
|
||||
// ─── OperatorForm ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function OperatorForm({ mode, initialData, operatorId }: OperatorFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const createMutation = useCreateOperator()
|
||||
const updateMutation = useUpdateOperator(operatorId ?? 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('operators.errors.usernameRequired', 'Ulanyjy ady hökmany')
|
||||
if (!form.name.trim())
|
||||
next.name = t('operators.errors.nameRequired', 'Ady hökmany')
|
||||
if (mode === 'create' && !form.password.trim())
|
||||
next.password = t('operators.errors.passwordRequired', 'Açar sözi hökmany')
|
||||
setErrors(next)
|
||||
return Object.keys(next).length === 0
|
||||
}
|
||||
|
||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
||||
const handleSubmit = () => {
|
||||
if (!validate()) return
|
||||
|
||||
if (mode === 'create') {
|
||||
const payload: CreateOperatorPayload = {
|
||||
username: form.username.trim(),
|
||||
name: form.name.trim(),
|
||||
phone: form.phone.trim() || undefined,
|
||||
email: form.email.trim() || undefined,
|
||||
password: form.password,
|
||||
isActive: form.isActive,
|
||||
}
|
||||
createMutation.mutate(payload, {
|
||||
onSuccess: () => navigate('/operators'),
|
||||
})
|
||||
} else {
|
||||
const payload: UpdateOperatorPayload = {
|
||||
username: form.username.trim(),
|
||||
name: form.name.trim(),
|
||||
phone: form.phone.trim() || undefined,
|
||||
email: form.email.trim() || undefined,
|
||||
isActive: form.isActive,
|
||||
}
|
||||
if (form.password.trim()) {
|
||||
payload.password = form.password
|
||||
}
|
||||
updateMutation.mutate(payload, {
|
||||
onSuccess: () => navigate(`/operators/${operatorId}`),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── 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('operators.fields.username', 'Ulanyjy ady')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.username}
|
||||
onChange={set('username')}
|
||||
placeholder={t('operators.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('operators.fields.name', 'Ady')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.name}
|
||||
onChange={set('name')}
|
||||
placeholder={t('operators.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('operators.fields.phone', 'Telefon')}
|
||||
</span>
|
||||
<FormInput
|
||||
type="phone"
|
||||
value={form.phone}
|
||||
onChange={set('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('operators.fields.email', 'E-poçta')}
|
||||
</span>
|
||||
<FormInput
|
||||
type="email"
|
||||
value={form.email}
|
||||
onChange={set('email')}
|
||||
placeholder={t('operators.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('operators.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('operators.fields.passwordEditHint', 'Üýtgetmek üçin täze açar söz giriziň')
|
||||
: t('operators.fields.password', 'Açar sözi')
|
||||
}
|
||||
error={errors.password}
|
||||
disabled={isPending}
|
||||
/>
|
||||
{mode === 'edit' && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
'operators.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('operators.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('operators.createBtn', 'Operator döredin')
|
||||
: t('operators.updateBtn', 'Üýtgetmeleri sakla')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
130
src/features/operators/hooks/useOperators.ts
Normal file
130
src/features/operators/hooks/useOperators.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
operatorsApi,
|
||||
type OperatorsListParams,
|
||||
type CreateOperatorPayload,
|
||||
type UpdateOperatorPayload,
|
||||
} from '../api/operatorsApi'
|
||||
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const operatorKeys = {
|
||||
all: ['operators'] as const,
|
||||
lists: () => [...operatorKeys.all, 'list'] as const,
|
||||
list: (params: OperatorsListParams) => [...operatorKeys.lists(), params] as const,
|
||||
details: () => [...operatorKeys.all, 'detail'] as const,
|
||||
detail: (id: number) => [...operatorKeys.details(), id] as const,
|
||||
}
|
||||
|
||||
// ─── useOperators ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function useOperators(params: OperatorsListParams) {
|
||||
return useQuery({
|
||||
queryKey: operatorKeys.list(params),
|
||||
queryFn: () => operatorsApi.getAll(params),
|
||||
placeholderData: (prev) => prev,
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useOperator ──────────────────────────────────────────────────────────────
|
||||
|
||||
export function useOperator(id: number) {
|
||||
return useQuery({
|
||||
queryKey: operatorKeys.detail(id),
|
||||
queryFn: () => operatorsApi.getById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useCreateOperator ────────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateOperator() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CreateOperatorPayload) => operatorsApi.create(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: operatorKeys.lists() })
|
||||
toast.success(t('operators.createSuccess', 'Operator üstünlikli döredildi'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('operators.createError', 'Operator döretmekde ýalňyşlyk'))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useUpdateOperator ────────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateOperator(id: number) {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: UpdateOperatorPayload) => operatorsApi.update(id, payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: operatorKeys.lists() })
|
||||
queryClient.invalidateQueries({ queryKey: operatorKeys.detail(id) })
|
||||
toast.success(t('operators.updateSuccess', 'Operator üstünlikli täzelendi'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('operators.updateError', 'Operator täzelemekde ýalňyşlyk'))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useDeleteOperator ────────────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteOperator() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => operatorsApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: operatorKeys.lists() })
|
||||
toast.success(t('operators.deleteSuccess', 'Operator üstünlikli pozuldy'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('operators.deleteError', 'Operator pozmakda ýalňyşlyk'))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useAssignRole ────────────────────────────────────────────────────────────
|
||||
|
||||
export function useAssignRole(operatorId: number) {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (roleId: number) => operatorsApi.assignRole(operatorId, roleId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: operatorKeys.detail(operatorId) })
|
||||
toast.success(t('operators.roleAssigned', 'Rol birikdirildi'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('operators.roleAssignError', 'Rol birikdirmekde ýalňyşlyk'))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useRemoveRole ────────────────────────────────────────────────────────────
|
||||
|
||||
export function useRemoveRole(operatorId: number) {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (roleId: number) => operatorsApi.removeRole(operatorId, roleId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: operatorKeys.detail(operatorId) })
|
||||
toast.success(t('operators.roleRemoved', 'Rol aýryldy'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('operators.roleRemoveError', 'Rol aýyrmakda ýalňyşlyk'))
|
||||
},
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user