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

@@ -81,6 +81,7 @@ src/
- Create ve Edit sayfaları (`pages/`) sadece bu component'i çağıran birer **wrapper** olmalıdır.
- Edit sayfası `useParams()` ile URL'den `id` alır, ilgili hook ile veriyi fetch eder ve `initialData` prop'u olarak form'a geçer.
- Validation, form state, submit logic — hepsi shared component içinde tek yerde yönetilir.
- Create ve Edit form lar multiple form ise yani bir cok adimdan olusuyorsa o zaman `src/components/stepBarV2.tsx` componentini kullan. Çünkü orada Progressive Disclosure var. Ama eger sadece bir form ise o zaman `src/components/form.tsx` componentini kullan.
- Örnek yapı:
```
features/[feature]/

45
package-lock.json generated
View File

@@ -94,6 +94,7 @@
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz",
"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/code-frame": "^7.29.0",
"@babel/generator": "^7.29.0",
@@ -655,29 +656,6 @@
"@noble/ciphers": "^1.0.0"
}
},
"node_modules/@emnapi/core": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
"integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/wasi-threads": "1.2.1",
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/runtime": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz",
"integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/wasi-threads": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz",
@@ -1187,6 +1165,7 @@
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",
"integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",
"license": "MIT",
"peer": true,
"engines": {
"node": "^14.21.3 || >=16"
},
@@ -3566,6 +3545,7 @@
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.2.tgz",
"integrity": "sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g==",
"license": "MIT",
"peer": true,
"dependencies": {
"undici-types": "~7.16.0"
}
@@ -3576,6 +3556,7 @@
"integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"csstype": "^3.2.2"
}
@@ -3586,6 +3567,7 @@
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
"devOptional": true,
"license": "MIT",
"peer": true,
"peerDependencies": {
"@types/react": "^19.2.0"
}
@@ -3662,6 +3644,7 @@
"integrity": "sha512-HDQH9O/47Dxi1ceDhBXdaldtf/WV9yRYMjbjCuNk3qnaTD564qwv61Y7+gTxwxRKzSrgO5uhtw584igXVuuZkA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.59.1",
"@typescript-eslint/types": "8.59.1",
@@ -3905,6 +3888,7 @@
"integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -4186,6 +4170,7 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.10.12",
"caniuse-lite": "^1.0.30001782",
@@ -5046,6 +5031,7 @@
"integrity": "sha512-XbEXaRva5cF0ZQB8w6MluHA0kZZfV2DuCMJ3ozyEOHLwDpZX2Lmm/7Pp0xdJmI0GL1W05VH5VwIFHEm1Vcw2gw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.2",
@@ -5302,6 +5288,7 @@
"resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",
"integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
"license": "MIT",
"peer": true,
"dependencies": {
"accepts": "^2.0.0",
"body-parser": "^2.2.1",
@@ -5967,6 +5954,7 @@
"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.16.tgz",
"integrity": "sha512-jN0ZewiNAWSe5khM3EyCmBb250+b40wWbwNILNfEvq84VREWwOIkuUsFONk/3i3nqkz7Oe1PcpM2mwQEK2L9Kg==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=16.9.0"
}
@@ -6041,6 +6029,7 @@
}
],
"license": "MIT",
"peer": true,
"peerDependencies": {
"typescript": "^5 || ^6"
},
@@ -7438,6 +7427,7 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"nanoid": "^3.3.11",
"picocolors": "^1.1.1",
@@ -7699,6 +7689,7 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.2.5.tgz",
"integrity": "sha512-llUJLzz1zTUBrskt2pwZgLq59AemifIftw4aB7JxOqf1HY2FDaGDxgwpAPVzHU1kdWabH7FauP4i1oEeer2WCA==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -7730,6 +7721,7 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.5.tgz",
"integrity": "sha512-J5bAZz+DXMMwW/wV3xzKke59Af6CHY7G4uYLN1OvBcKEsWOs4pQExj86BBKamxl/Ik5bx9whOrvBlSDfWzgSag==",
"license": "MIT",
"peer": true,
"dependencies": {
"scheduler": "^0.27.0"
},
@@ -7776,6 +7768,7 @@
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz",
"integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/use-sync-external-store": "^0.0.6",
"use-sync-external-store": "^1.4.0"
@@ -7970,7 +7963,8 @@
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/redux-thunk": {
"version": "3.1.0",
@@ -8736,6 +8730,7 @@
"integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -8970,6 +8965,7 @@
"integrity": "sha512-rZuUu9j6J5uotLDs+cAA4O5H4K1SfPliUlQwqa6YEwSrWDZzP4rhm00oJR5snMewjxF5V/K3D4kctsUTsIU9Mw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"lightningcss": "^1.32.0",
"picomatch": "^4.0.4",
@@ -9293,6 +9289,7 @@
"resolved": "https://registry.npmjs.org/zod/-/zod-4.4.2.tgz",
"integrity": "sha512-IynmDyxsEsb9RKzO3J9+4SxXnl2FTFSzNBaKKaMV6tsSk0rw9gYw9gs+JFCq/qk2LCZ78KDwyj+Z289TijSkUw==",
"license": "MIT",
"peer": true,
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}

View File

@@ -97,6 +97,24 @@ const SberPaymentPage = lazy(() => import("@/pages/internationalPayments/sberPay
const SberPaymentCreatePage = lazy(() => import("@/pages/internationalPayments/sberPaymentsCreate"));
const SberPaymentViewPage = lazy(() => import("@/pages/internationalPayments/sberPaymentsView"));
const SberPaymentEditPage = lazy(() => import("@/pages/internationalPayments/sberPaymentsEdit"));
const OperatorsPage = lazy(() => import("@/pages/users/operators"));
const OperatorCreatePage = lazy(() => import("@/pages/users/operatorsCreate"));
const OperatorsViewPage = lazy(() => import("@/pages/users/operatorsView"));
const OperatorEditPage = lazy(() => import("@/pages/users/operatorsEdit"));
const AllUsersPage = lazy(() => import("@/pages/users/allUsers"));
const AllUserCreatePage = lazy(() => import("@/pages/users/allUsersCreate"));
const AllUsersViewPage = lazy(() => import("@/pages/users/allUsersView"));
const AllUserEditPage = lazy(() => import("@/pages/users/allUsersEdit"));
const ClientsPage = lazy(() => import("@/pages/users/clients"));
const ClientCreatePage = lazy(() => import("@/pages/users/clientsCreate"));
const ClientViewPage = lazy(() => import("@/pages/users/clientsView"));
const ClientEditPage = lazy(() => import("@/pages/users/clientsEdit"));
function AuthGuard() {
const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
if (!isAuthenticated) return <Navigate to="/login" replace />;
@@ -481,6 +499,102 @@ export const router = createBrowserRouter([
</Suspense>
),
},
{ // Sidebar: /operators
path: "/operators",
element: (
<Suspense fallback={<PageLoader />}>
<OperatorsPage />
</Suspense>
),
},
{
path: "/operators/create",
element: (
<Suspense fallback={<PageLoader />}>
<OperatorCreatePage />
</Suspense>
),
},
{
path: "/operators/:id",
element: (
<Suspense fallback={<PageLoader />}>
<OperatorsViewPage />
</Suspense>
),
},
{
path: "/operators/:id/edit",
element: (
<Suspense fallback={<PageLoader />}>
<OperatorEditPage />
</Suspense>
),
},
{ // Sidebar: /all-users
path: "/all-users",
element: (
<Suspense fallback={<PageLoader />}>
<AllUsersPage />
</Suspense>
),
},
{
path: "/all-users/create",
element: (
<Suspense fallback={<PageLoader />}>
<AllUserCreatePage />
</Suspense>
),
},
{
path: "/all-users/:id",
element: (
<Suspense fallback={<PageLoader />}>
<AllUsersViewPage />
</Suspense>
),
},
{
path: "/all-users/:id/edit",
element: (
<Suspense fallback={<PageLoader />}>
<AllUserEditPage />
</Suspense>
),
},
{ // Sidebar: /clients
path: "/clients",
element: (
<Suspense fallback={<PageLoader />}>
<ClientsPage />
</Suspense>
),
},
{
path: "/clients/create",
element: (
<Suspense fallback={<PageLoader />}>
<ClientCreatePage />
</Suspense>
),
},
{
path: "/clients/:id",
element: (
<Suspense fallback={<PageLoader />}>
<ClientViewPage />
</Suspense>
),
},
{
path: "/clients/:id/edit",
element: (
<Suspense fallback={<PageLoader />}>
<ClientEditPage />
</Suspense>
),
},
],
},
],

View File

@@ -182,7 +182,7 @@ function TextInput({
function PhoneInput({
value = '',
onChange,
placeholder = '61 097 651',
placeholder = '61 111213',
error,
disabled,
required,

215
src/components/stepBar.tsx Normal file
View File

@@ -0,0 +1,215 @@
'use client'
import { useEffect, useRef, type KeyboardEvent } from 'react'
import { Check, AlertTriangle } from 'lucide-react'
import { cn } from '@/lib/utils'
// ─── Types ──────────────────────────────────────────────────────────────────
export type StepStatus = 'idle' | 'active' | 'done' | 'error'
export interface StepBarItem {
id: string
label: string
status: StepStatus
}
interface StepBarProps {
steps: StepBarItem[]
onGoTo: (index: number) => void
showLabels?: boolean
}
// ─── Helper ──────────────────────────────────────────────────────────────────
function DotIcon({ status, index }: { status: StepStatus; index: number }) {
if (status === 'done')
return <Check className="w-3.5 h-3.5" strokeWidth={3} aria-hidden />
if (status === 'error')
return <AlertTriangle className="w-3 h-3" aria-hidden />
return (
<span className="text-[11px] font-bold tabular-nums leading-none">
{index + 1}
</span>
)
}
// ─── Component ───────────────────────────────────────────────────────────────
export function StepBar({ steps, onGoTo, showLabels }: StepBarProps) {
const btnRefs = useRef<Array<HTMLButtonElement | null>>([])
const total = steps.length
const activeIdx = steps.findIndex((s) => s.status === 'active')
const fillPct = total > 1 ? (Math.max(0, activeIdx) / (total - 1)) * 100 : 0
useEffect(() => {
btnRefs.current[activeIdx]?.scrollIntoView({
behavior: 'smooth',
inline: 'center',
block: 'nearest',
})
}, [activeIdx])
const isReachable = (i: number) => {
const s = steps[i].status
if (s === 'done' || s === 'active' || s === 'error') return true
return i > 0 && steps[i - 1].status === 'done'
}
const handleKey = (e: KeyboardEvent<HTMLButtonElement>, i: number) => {
let next = i
if (e.key === 'ArrowRight') next = Math.min(total - 1, i + 1)
else if (e.key === 'ArrowLeft') next = Math.max(0, i - 1)
else if (e.key === 'Home') next = 0
else if (e.key === 'End') next = total - 1
else return
e.preventDefault()
const dir = next > i ? 1 : -1
while (next !== i && !isReachable(next)) {
next += dir
if (next < 0 || next >= total) return
}
btnRefs.current[next]?.focus()
}
return (
<nav
role="tablist"
aria-label="Form steps"
className="relative w-full"
>
{/*
* Track layer — z-index: 1 so it sits BELOW the dots (z-index: 2).
* top: 32px = paddingTop(16px) + dotSize(32px)/2
*/}
<div
aria-hidden
className="pointer-events-none absolute"
style={{
top: 32,
left: `calc(${(0.5 / total) * 100}%)`,
right: `calc(${(0.5 / total) * 100}%)`,
transform: 'translateY(-50%)',
zIndex: 1,
}}
>
<div className="relative h-[2px] w-full overflow-hidden rounded-full bg-border">
<div
className="absolute inset-y-0 left-0 rounded-full bg-primary"
style={{
width: `${fillPct}%`,
transition: 'width 500ms cubic-bezier(0.4, 0, 0.2, 1)',
willChange: 'width',
}}
/>
</div>
</div>
{/* Steps row — z-index: 2, establishes stacking context above track */}
<div className="relative flex w-full" style={{ zIndex: 2 }}>
{steps.map((step, i) => {
const isActive = step.status === 'active'
const isDone = step.status === 'done'
const isError = step.status === 'error'
const isIdle = step.status === 'idle'
const reachable = isReachable(i)
const displayLabel = showLabels ?? true
return (
<button
key={step.id}
ref={(el) => { btnRefs.current[i] = el }}
type="button"
role="tab"
aria-selected={isActive}
aria-current={isActive ? 'step' : undefined}
aria-label={`${step.label}${isError ? ' — hata' : ''} (${i + 1} / ${total})`}
onClick={() => reachable && onGoTo(i)}
onKeyDown={(e) => handleKey(e, i)}
disabled={!reachable}
tabIndex={isActive ? 0 : -1}
className={cn(
'group flex flex-1 flex-col items-center',
'pt-4 pb-3 gap-2',
'select-none outline-none rounded-xl',
'focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
reachable ? 'cursor-pointer' : 'cursor-not-allowed opacity-40',
)}
>
{/*
* Dot wrapper — position: relative + z-index: 2
* This creates a stacking context that sits above the track (z:1).
* Fixed 32×32 for ALL states so track top:32px never shifts.
*/}
<span
className="relative flex h-8 w-8 items-center justify-center"
style={{ zIndex: 2 }}
>
{/* Active pulse ring */}
{isActive && (
<span
className="absolute inset-0 rounded-full bg-primary/20 animate-ping"
aria-hidden
style={{ animationDuration: '2s' }}
/>
)}
<span
className={cn(
'relative flex h-7 w-7 items-center justify-center rounded-full border',
'transition-[transform,box-shadow,background-color,border-color] duration-300',
// Active — opaque bg
isActive && [
'scale-[1.14]',
'bg-primary border-transparent text-primary-foreground',
'shadow-[0_0_0_4px_hsl(var(--primary)/0.18)]',
],
// Done — opaque bg (track cannot bleed through)
isDone && !isActive && [
'bg-emerald-50 border-emerald-400 text-emerald-700',
'dark:bg-emerald-950 dark:border-emerald-500 dark:text-emerald-300',
],
// Error — opaque bg, was /50 (semi-transparent) which caused bleed
isError && !isActive && [
'bg-background border-destructive/60 text-destructive',
],
// Idle — bg-background is always opaque
isIdle && [
'bg-background border-border text-muted-foreground',
],
!isActive && reachable && 'group-hover:scale-110 group-hover:shadow-sm',
)}
>
<DotIcon status={step.status} index={i} />
</span>
</span>
{/* Label */}
{displayLabel && (
<span
className={cn(
'max-w-full truncate px-0.5 text-center text-[11px] leading-snug tracking-tight',
'transition-colors duration-200',
total > 4 && 'hidden sm:block',
isActive && 'font-semibold text-foreground',
isDone && !isActive && 'text-muted-foreground',
isError && !isActive && 'font-medium text-destructive',
isIdle && 'text-muted-foreground',
)}
>
{step.label}
</span>
)}
</button>
)
})}
</div>
</nav>
)
}

View File

@@ -0,0 +1,109 @@
import { type LucideIcon, ChevronRight, Check, AlertTriangle } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { StepStatus } from './stepBar'
export interface StepCardItem {
id: string
title: string
subtitle: string
icon: LucideIcon
status: StepStatus
}
interface StepBarCardsProps {
steps: StepCardItem[]
onGoTo: (index: number) => void
}
/**
* Card-style horizontal step bar (icon + title + subtitle, chevron separators).
* Inspired by the reference mockup. Uses semantic tokens only.
*/
export function StepBarCards({ steps, onGoTo }: StepBarCardsProps) {
return (
<nav
role="tablist"
aria-label="Form adımları"
className={cn(
'flex items-center gap-2 overflow-x-auto',
'[&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]',
)}
>
{steps.map((step, i) => {
const Icon = step.icon
const isActive = step.status === 'active'
const isDone = step.status === 'done'
const isError = step.status === 'error'
const isIdle = step.status === 'idle'
const reachable = !isIdle || (i > 0 && steps[i - 1].status === 'done')
return (
<div key={step.id} className="flex items-center gap-2 shrink-0">
<button
type="button"
role="tab"
aria-selected={isActive}
aria-current={isActive ? 'step' : undefined}
disabled={!reachable}
onClick={() => reachable && onGoTo(i)}
className={cn(
'group flex items-center gap-3 rounded-2xl px-3 py-2.5 transition-all duration-200',
'outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
'disabled:cursor-not-allowed disabled:opacity-40',
reachable && !isActive && 'hover:bg-muted/40 cursor-pointer',
isActive && 'bg-muted/60',
)}
>
{/* Icon disc */}
<span
className={cn(
'relative flex items-center justify-center rounded-full w-11 h-11 shrink-0 transition-all duration-300',
isActive &&
'bg-primary text-primary-foreground ring-4 ring-primary/15',
isDone &&
'bg-muted text-foreground',
isError &&
'bg-destructive/10 text-destructive ring-2 ring-destructive/30',
isIdle && 'bg-muted text-muted-foreground',
reachable && !isActive && 'group-hover:scale-105',
)}
>
{isDone ? (
<Check className="w-5 h-5 animate-scale-in" strokeWidth={2.5} />
) : isError ? (
<AlertTriangle className="w-5 h-5 animate-scale-in" />
) : (
<Icon className="w-5 h-5" strokeWidth={2} />
)}
</span>
{/* Texts */}
<span className="flex flex-col items-start text-left leading-tight">
<span
className={cn(
'text-sm font-semibold tracking-tight',
isActive || isDone ? 'text-foreground' : 'text-foreground/90',
isError && 'text-destructive',
)}
>
{step.title}
</span>
<span className="text-xs text-muted-foreground mt-0.5">
{step.subtitle}
</span>
</span>
</button>
{/* Chevron separator */}
{i < steps.length - 1 && (
<ChevronRight
className="w-4 h-4 text-muted-foreground/60 shrink-0 mx-1"
aria-hidden
/>
)}
</div>
)
})}
</nav>
)
}

View File

@@ -0,0 +1,22 @@
import * as React from "react"
import { Label as LabelPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }

View File

@@ -0,0 +1,198 @@
// ─── Types ────────────────────────────────────────────────────────────────────
export interface User {
id: number
username: string
name: string
phone: string
email: string | null
isActive: boolean
phoneVerified: boolean
createdAt: string
updatedAt: string
}
export interface UserListItem {
id: number
username: string
name: string
phone: string
email: string | null
isActive: boolean
}
export interface UsersListResponse {
data: UserListItem[]
total: number
page: number
perPage: number
totalPages: number
}
export interface UsersListParams {
page?: number
perPage?: number
search?: string
isActive?: string
}
export interface CreateUserPayload {
username: string
name: string
phone: string
email?: string
password: string
phoneVerified: boolean
isActive: boolean
}
export interface UpdateUserPayload {
username?: string
name?: string
phone?: string
email?: string
phoneVerified?: boolean
isActive?: boolean
}
// ─── Mock Data ────────────────────────────────────────────────────────────────
const MOCK_USERS: User[] = Array.from({ length: 50 }, (_, i) => {
const id = 5970 - i
const names = [
'Orazowa Nurtuwak Täşliyewna',
'Hallyýewa Aýna Gurbanmyradowna',
'Sopýýewa Maral Agamyradowna',
'Babamurat Baýnazarow Şanazarowič',
'Narmet Narmet',
'Sheker Durdyyewa',
'kamalowyusup',
'Mahmudowberdimet',
'allanazarowasayyara',
'dadayewjepbar',
]
const usernames = [
'Nurtuwak_1970', 'Ayna_1989', 'Maral_1974', 'Babamurat_0002', 'Narmet',
'8319_ShekerDurdyyewa', 'kamalowyusup', 'Mahmudowberdimet',
'allanazarowasayyara', 'dadayewjepbar',
]
const idx = i % names.length
return {
id,
username: i < usernames.length ? usernames[idx] : `user_${id}`,
name: names[idx],
phone: `+(993)-6${Math.floor(Math.random() * 9 + 1)}-${String(Math.floor(Math.random() * 90 + 10))}-${String(Math.floor(Math.random() * 90 + 10))}-${String(Math.floor(Math.random() * 90 + 10))}`,
email: i % 4 === 0 ? `user${id}@tbbank.gov.tm` : null,
isActive: Math.random() > 0.1,
phoneVerified: Math.random() > 0.3,
createdAt: new Date(Date.now() - Math.random() * 1e10).toISOString(),
updatedAt: new Date(Date.now() - Math.random() * 1e9).toISOString(),
}
})
// ─── Mock delay helper ────────────────────────────────────────────────────────
const delay = (ms = 500) => new Promise((res) => setTimeout(res, ms))
// ─── API Functions ────────────────────────────────────────────────────────────
export const usersApi = {
/**
* GET /users
*/
getUsers: async (params: UsersListParams = {}): Promise<UsersListResponse> => {
await delay()
// Uncomment for real API:
// const res = await apiClient.get<UsersListResponse>('/users', { params })
// return res.data
const { page = 1, perPage = 25, search = '', isActive } = params
let filtered = [...MOCK_USERS]
if (search.trim()) {
const q = search.toLowerCase()
filtered = filtered.filter(
(u) =>
u.username.toLowerCase().includes(q) ||
u.name.toLowerCase().includes(q) ||
u.phone.includes(q),
)
}
if (isActive !== undefined && isActive !== '') {
const active = isActive === 'true'
filtered = filtered.filter((u) => u.isActive === active)
}
const total = filtered.length
const totalPages = Math.ceil(total / perPage)
const start = (page - 1) * perPage
const data = filtered.slice(start, start + perPage).map(({ id, username, name, phone, email, isActive }) => ({
id, username, name, phone, email, isActive,
}))
return { data, total, page, perPage, totalPages }
},
/**
* GET /users/:id
*/
getUserById: async (id: number): Promise<User> => {
await delay()
// const res = await apiClient.get<User>(`/users/${id}`)
// return res.data
const user = MOCK_USERS.find((u) => u.id === id)
if (!user) throw new Error(`User ${id} not found`)
return user
},
/**
* POST /users
*/
createUser: async (payload: CreateUserPayload): Promise<User> => {
await delay(800)
// const res = await apiClient.post<User>('/users', payload)
// return res.data
const newUser: User = {
id: Math.max(...MOCK_USERS.map((u) => u.id)) + 1,
username: payload.username,
name: payload.name,
phone: payload.phone,
email: payload.email ?? null,
isActive: payload.isActive,
phoneVerified: payload.phoneVerified,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
}
MOCK_USERS.unshift(newUser)
return newUser
},
/**
* PUT /users/:id
*/
updateUser: async (id: number, payload: UpdateUserPayload): Promise<User> => {
await delay(800)
// const res = await apiClient.put<User>(`/users/${id}`, payload)
// return res.data
const idx = MOCK_USERS.findIndex((u) => u.id === id)
if (idx === -1) throw new Error(`User ${id} not found`)
MOCK_USERS[idx] = { ...MOCK_USERS[idx], ...payload, updatedAt: new Date().toISOString() }
return MOCK_USERS[idx]
},
/**
* DELETE /users/:id
*/
deleteUser: async (id: number): Promise<void> => {
await delay(600)
// await apiClient.delete(`/users/${id}`)
const idx = MOCK_USERS.findIndex((u) => u.id === id)
if (idx !== -1) MOCK_USERS.splice(idx, 1)
},
}

View File

@@ -0,0 +1,326 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { FormInput } from '@/components/formInput'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Label } from '@/components/ui/label'
import { Loader2 } from 'lucide-react'
import { useCreateUser, useUpdateUser } from '../hooks/useAllUsers'
import type { User, CreateUserPayload, UpdateUserPayload } from '../api/allUsersApi'
// ─── Types ────────────────────────────────────────────────────────────────────
interface UserFormProps {
mode: 'create' | 'edit'
initialData?: User
userId?: number
}
interface FormState {
username: string
name: string
phone: string
email: string
password: string
phoneVerified: boolean
isActive: boolean
}
interface FormErrors {
username?: string
name?: string
phone?: string
email?: string
password?: string
}
// ─── Validation ───────────────────────────────────────────────────────────────
function validateForm(state: FormState, mode: 'create' | 'edit'): FormErrors {
const errors: FormErrors = {}
if (!state.username.trim()) errors.username = 'Ulanyjy ady hökmany'
else if (state.username.length < 3) errors.username = 'Ulanyjy ady iň az 3 harp bolmaly'
if (!state.name.trim()) errors.name = 'Ady hökmany'
if (!state.phone.trim()) errors.phone = 'Telefon hökmany'
else if (!/^\d[\d\s-]{6,}$/.test(state.phone)) errors.phone = 'Nädogry telefon formaty'
if (state.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(state.email)) {
errors.email = 'Nädogry e-poçta formaty'
}
if (mode === 'create') {
if (!state.password) errors.password = 'Açar sözi hökmany'
else if (state.password.length < 6) errors.password = 'Açar sözi iň az 6 harp bolmaly'
}
return errors
}
// ─── UserForm ─────────────────────────────────────────────────────────────────
export function UserForm({ mode, initialData, userId }: UserFormProps) {
const { t } = useTranslation()
const navigate = useNavigate()
const createUser = useCreateUser()
const updateUser = useUpdateUser(userId ?? 0)
const isPending = createUser.isPending || updateUser.isPending
const [form, setForm] = useState<FormState>({
username: '',
name: '',
phone: '',
email: '',
password: '',
phoneVerified: false,
isActive: true,
})
const [errors, setErrors] = useState<FormErrors>({})
// Populate form when initialData is available (edit mode)
useEffect(() => {
if (initialData) {
setForm({
username: initialData.username,
name: initialData.name,
phone: initialData.phone.replace(/^\+993[-\s]?/, ''),
email: initialData.email ?? '',
password: '',
phoneVerified: initialData.phoneVerified,
isActive: initialData.isActive,
})
}
}, [initialData])
const setField = <K extends keyof FormState>(key: K, value: FormState[K]) => {
setForm((prev) => ({ ...prev, [key]: value }))
if (errors[key as keyof FormErrors]) {
setErrors((prev) => ({ ...prev, [key]: undefined }))
}
}
const handleSubmit = async () => {
const validationErrors = validateForm(form, mode)
if (Object.keys(validationErrors).length > 0) {
setErrors(validationErrors)
return
}
if (mode === 'create') {
const payload: CreateUserPayload = {
username: form.username.trim(),
name: form.name.trim(),
phone: form.phone.trim(),
email: form.email.trim() || undefined,
password: form.password,
phoneVerified: form.phoneVerified,
isActive: form.isActive,
}
await createUser.mutateAsync(payload)
navigate('/users')
} else {
const payload: UpdateUserPayload = {
username: form.username.trim(),
name: form.name.trim(),
phone: form.phone.trim(),
email: form.email.trim() || undefined,
phoneVerified: form.phoneVerified,
isActive: form.isActive,
}
await updateUser.mutateAsync(payload)
navigate(`/users/${userId}`)
}
}
return (
<div className="space-y-6">
{/* Form card */}
<div className="bg-card border border-border rounded-xl divide-y divide-border">
{/* Username */}
<div className="grid grid-cols-[280px_1fr] items-start px-6 py-4">
<div className="pt-0.5">
<p className="text-sm font-medium text-foreground">
{t('users.fields.username', 'Ulanyjy ady')}
<span className="text-destructive ml-0.5">*</span>
</p>
<p className="text-xs text-muted-foreground mt-0.5">
{t('users.fields.usernameHint', 'Unikal login ady')}
</p>
</div>
<FormInput
type="text"
value={form.username}
onChange={(v) => setField('username', v)}
placeholder={t('users.fields.username', 'Ulanyjy ady')}
error={errors.username}
disabled={isPending}
/>
</div>
{/* Full name */}
<div className="grid grid-cols-[280px_1fr] items-start px-6 py-4">
<div className="pt-0.5">
<p className="text-sm font-medium text-foreground">
{t('users.fields.name', 'Ady')}
<span className="text-destructive ml-0.5">*</span>
</p>
<p className="text-xs text-muted-foreground mt-0.5">
{t('users.fields.nameHint', 'Doly ady we familiýasy')}
</p>
</div>
<FormInput
type="text"
value={form.name}
onChange={(v) => setField('name', v)}
placeholder={t('users.fields.name', 'Ady')}
error={errors.name}
disabled={isPending}
/>
</div>
{/* Phone */}
<div className="grid grid-cols-[280px_1fr] items-start px-6 py-4">
<div className="pt-0.5">
<p className="text-sm font-medium text-foreground">
{t('users.fields.phone', 'Telefon')}
<span className="text-destructive ml-0.5">*</span>
</p>
<p className="text-xs text-muted-foreground mt-0.5">
{t('users.fields.phoneHint', '+993 bilen başlanýar')}
</p>
</div>
<FormInput
type="phone"
value={form.phone}
onChange={(v) => setField('phone', v)}
placeholder="62-38-49-56"
error={errors.phone}
disabled={isPending}
/>
</div>
{/* Email */}
<div className="grid grid-cols-[280px_1fr] items-start px-6 py-4">
<div className="pt-0.5">
<p className="text-sm font-medium text-foreground">
{t('users.fields.email', 'E-poçta')}
</p>
<p className="text-xs text-muted-foreground mt-0.5">
{t('users.fields.emailHint', 'Islege görä')}
</p>
</div>
<FormInput
type="email"
value={form.email}
onChange={(v) => setField('email', v)}
placeholder={t('users.fields.email', 'E-poçta')}
error={errors.email}
disabled={isPending}
/>
</div>
{/* Password — only in create mode */}
{mode === 'create' && (
<div className="grid grid-cols-[280px_1fr] items-start px-6 py-4">
<div className="pt-0.5">
<p className="text-sm font-medium text-foreground">
{t('users.fields.password', 'Açar sözi')}
<span className="text-destructive ml-0.5">*</span>
</p>
<p className="text-xs text-muted-foreground mt-0.5">
{t('users.fields.passwordHint', 'Iň az 6 harp')}
</p>
</div>
<FormInput
type="password"
value={form.password}
onChange={(v) => setField('password', v)}
placeholder={t('users.fields.password', 'Açar sözi')}
error={errors.password}
disabled={isPending}
/>
</div>
)}
{/* Phone verified */}
<div className="grid grid-cols-[280px_1fr] items-center px-6 py-4">
<div>
<p className="text-sm font-medium text-foreground">
{t('users.fields.phoneVerified', 'Telefon tassyklanan')}
</p>
<p className="text-xs text-muted-foreground mt-0.5">
{t('users.fields.phoneVerifiedHint', 'SMS arkaly tassyklandy')}
</p>
</div>
<div className="flex items-center gap-2">
<Checkbox
id="phoneVerified"
checked={form.phoneVerified}
onCheckedChange={(v) => setField('phoneVerified', !!v)}
disabled={isPending}
/>
<Label htmlFor="phoneVerified" className="text-sm text-muted-foreground cursor-pointer">
{form.phoneVerified
? t('common.yes', 'Hawa')
: t('common.no', 'Ýok')}
</Label>
</div>
</div>
{/* Active */}
<div className="grid grid-cols-[280px_1fr] items-center px-6 py-4">
<div>
<p className="text-sm font-medium text-foreground">
{t('users.fields.isActive', 'Işjeň')}
</p>
<p className="text-xs text-muted-foreground mt-0.5">
{t('users.fields.isActiveHint', 'Ulanyjynyň ulgama girip-bilmezligi')}
</p>
</div>
<div className="flex items-center gap-2">
<Checkbox
id="isActive"
checked={form.isActive}
onCheckedChange={(v) => setField('isActive', !!v)}
disabled={isPending}
/>
<Label htmlFor="isActive" className="text-sm text-muted-foreground cursor-pointer">
{form.isActive
? t('common.active', 'Işjeň')
: t('common.inactive', 'Işjeň däl')}
</Label>
</div>
</div>
</div>
{/* Footer actions */}
<div className="flex items-center justify-end gap-3">
<Button
type="button"
variant="outline"
onClick={() => navigate(-1)}
disabled={isPending}
>
{t('common.cancel', 'Ýatyr')}
</Button>
<Button
type="button"
onClick={handleSubmit}
disabled={isPending}
>
{isPending && <Loader2 size={14} className="mr-2 animate-spin" />}
{mode === 'create'
? t('users.actions.create', 'Ulanyjy dörediň')
: t('users.actions.save', 'Ýatda sakla')}
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,94 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { useTranslation } from 'react-i18next'
import {
usersApi,
type CreateUserPayload,
type UpdateUserPayload,
type UsersListParams,
} from '../api/allUsersApi'
// ─── Query Keys ───────────────────────────────────────────────────────────────
export const userKeys = {
all: ['users'] as const,
lists: () => [...userKeys.all, 'list'] as const,
list: (params: UsersListParams) => [...userKeys.lists(), params] as const,
details: () => [...userKeys.all, 'detail'] as const,
detail: (id: number) => [...userKeys.details(), id] as const,
}
// ─── useUsers ─────────────────────────────────────────────────────────────────
export function useUsers(params: UsersListParams = {}) {
return useQuery({
queryKey: userKeys.list(params),
queryFn: () => usersApi.getUsers(params),
placeholderData: (prev) => prev,
})
}
// ─── useUser ──────────────────────────────────────────────────────────────────
export function useUser(id: number) {
return useQuery({
queryKey: userKeys.detail(id),
queryFn: () => usersApi.getUserById(id),
enabled: !!id,
})
}
// ─── useCreateUser ────────────────────────────────────────────────────────────
export function useCreateUser() {
const { t } = useTranslation()
const queryClient = useQueryClient()
return useMutation({
mutationFn: (payload: CreateUserPayload) => usersApi.createUser(payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: userKeys.lists() })
toast.success(t('users.toast.createSuccess', 'Ulanyjy üstünlikli döredildi'))
},
onError: () => {
toast.error(t('users.toast.createError', 'Ulanyjy döretmek başartmady'))
},
})
}
// ─── useUpdateUser ────────────────────────────────────────────────────────────
export function useUpdateUser(id: number) {
const { t } = useTranslation()
const queryClient = useQueryClient()
return useMutation({
mutationFn: (payload: UpdateUserPayload) => usersApi.updateUser(id, payload),
onSuccess: (updatedUser) => {
queryClient.invalidateQueries({ queryKey: userKeys.lists() })
queryClient.setQueryData(userKeys.detail(id), updatedUser)
toast.success(t('users.toast.updateSuccess', 'Ulanyjy üstünlikli täzelendi'))
},
onError: () => {
toast.error(t('users.toast.updateError', 'Ulanyjy täzelemek başartmady'))
},
})
}
// ─── useDeleteUser ────────────────────────────────────────────────────────────
export function useDeleteUser() {
const { t } = useTranslation()
const queryClient = useQueryClient()
return useMutation({
mutationFn: (id: number) => usersApi.deleteUser(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: userKeys.lists() })
toast.success(t('users.toast.deleteSuccess', 'Ulanyjy üstünlikli öçürildi'))
},
onError: () => {
toast.error(t('users.toast.deleteError', 'Ulanyjy öçürmek başartmady'))
},
})
}

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'))
},
})
}

View File

@@ -2,13 +2,17 @@ import { useState, useCallback, useMemo } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { CheckCircle2, ChevronLeft, ChevronRight, Loader2 } from 'lucide-react'
import { ChevronLeft, ChevronRight, Loader2 } from 'lucide-react'
import { FormInput } from '@/components/formInput'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { useCreateLoanOrder, useUpdateLoanOrder } from '@/features/loanOrders/hooks/useLoanOrders'
import type { LoanOrder, LoanOrderPayload } from '@/features/loanOrders/api/loanOrdersApi'
import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
import {
CircleDot, CreditCard, MapPin, User, Wallet,
FileText, Phone, Briefcase, FolderOpen, ShieldCheck
} from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
// ─── Static options ───────────────────────────────────────────────────────────
const REGION_OPTIONS = [
@@ -237,24 +241,32 @@ interface StepDef {
id: string
titleKey: string
titleFallback: string
/** Returns error keys relevant to this step */
shortLabel: string
icon: LucideIcon
subtitle: string
validate: (form: FormState, mode: 'create' | 'edit') => FormErrors
}
// 3. STEPS dizisini güncelle
const STEPS: StepDef[] = [
{
id: 'status',
titleKey: 'Status',
titleFallback: 'Status',
shortLabel: 'Status',
icon: CircleDot,
subtitle: 'Ýagdaý we bellik',
validate: () => ({}),
},
{
id: 'loan',
titleKey: 'Loan',
titleFallback: 'Karz',
shortLabel: 'Karz',
icon: Wallet,
subtitle: 'Görnüş we möçber',
validate: (form) => {
const e: FormErrors = {}
if (!form.loanType) e.loanType = 'Karz görnüşi — hökmany'
if (!form.loanType) e.loanType = 'Karz görnüşi — hökmany'
if (!form.loanAmount) e.loanAmount = 'Karz möçberi — hökmany'
return e
},
@@ -263,6 +275,9 @@ const STEPS: StepDef[] = [
id: 'location',
titleKey: 'Location',
titleFallback: 'Lokasiýa',
shortLabel: 'Lokasiýa',
icon: MapPin,
subtitle: 'Welaýat we şahamça',
validate: (form) => {
const e: FormErrors = {}
if (!form.region) e.region = 'Welaýat — hökmany'
@@ -274,6 +289,9 @@ const STEPS: StepDef[] = [
id: 'personal',
titleKey: 'Personal data',
titleFallback: 'Şahsy maglumatlar',
shortLabel: 'Şahsy',
icon: User,
subtitle: 'At, bilim, maşgala',
validate: (form) => {
const e: FormErrors = {}
if (!form.firstName) e.firstName = 'Ady — hökmany'
@@ -289,6 +307,9 @@ const STEPS: StepDef[] = [
id: 'card',
titleKey: 'Card (Salary)',
titleFallback: 'Kart (Zähmet haky)',
shortLabel: 'Kart',
icon: CreditCard,
subtitle: 'Zähmet haky karty',
validate: (form) => {
const e: FormErrors = {}
if (!form.cardNumber) e.cardNumber = 'Kart belgisi — hökmany'
@@ -302,6 +323,9 @@ const STEPS: StepDef[] = [
id: 'passport',
titleKey: 'Passport',
titleFallback: 'Pasport',
shortLabel: 'Pasport',
icon: FileText,
subtitle: 'Seriýa, belgisi, senesi',
validate: (form) => {
const e: FormErrors = {}
if (!form.passportSerie) e.passportSerie = 'Pasport seriýasy — hökmany'
@@ -315,6 +339,9 @@ const STEPS: StepDef[] = [
id: 'contact',
titleKey: 'Contact data',
titleFallback: 'Habarlaşmak',
shortLabel: 'Habarlaşmak',
icon: Phone,
subtitle: 'Telefon we e-poçta',
validate: (form) => {
const e: FormErrors = {}
if (!form.phone) {
@@ -329,6 +356,9 @@ const STEPS: StepDef[] = [
id: 'job',
titleKey: 'Job',
titleFallback: 'Iş',
shortLabel: 'Iş',
icon: Briefcase,
subtitle: 'Kärhana we wezipe',
validate: (form) => {
const e: FormErrors = {}
if (!form.workCompany) e.workCompany = 'Kärhananyň ady — hökmany'
@@ -342,6 +372,9 @@ const STEPS: StepDef[] = [
id: 'files',
titleKey: 'Passport files',
titleFallback: 'Pasport faýllar',
shortLabel: 'Faýllar',
icon: FolderOpen,
subtitle: 'Pasport suratlary',
validate: (form, mode) => {
const e: FormErrors = {}
if (mode === 'create') {
@@ -355,6 +388,9 @@ const STEPS: StepDef[] = [
id: 'guarantor',
titleKey: '1. Guarantor',
titleFallback: '1. Zamun',
shortLabel: 'Zamun',
icon: ShieldCheck,
subtitle: 'Zamun maglumatlary',
validate: (form) => {
const e: FormErrors = {}
if (!form.guarantor1Name) e.guarantor1Name = 'Zamunyň ady — hökmany'
@@ -371,243 +407,79 @@ const STEPS: StepDef[] = [
},
]
// ─── Step Sidebar ─────────────────────────────────────────────────────────────
function StepSidebar({
steps,
current,
completed,
onGoTo,
}: {
steps: StepDef[]
current: number
completed: Set<number>
onGoTo: (i: number) => void
}) {
return (
<nav className="bg-card border border-border rounded-xl py-2 sticky top-4 overflow-hidden">
{steps.map((step, i) => {
const isDone = completed.has(i)
const isActive = i === current
const isReachable = i === 0 || completed.has(i - 1) || isDone
return (
<button
key={step.id}
type="button"
onClick={() => isReachable && onGoTo(i)}
disabled={!isReachable}
className={cn(
'relative w-full flex items-center gap-2.5 px-3.5 py-2 text-left transition-colors duration-150',
'disabled:cursor-not-allowed',
isActive && 'bg-muted',
!isActive && isReachable && 'hover:bg-muted/50',
)}
>
{/* Active indicator bar */}
{isActive && (
<span className="absolute left-0 top-1.5 bottom-1.5 w-[3px] rounded-r-full bg-primary" />
)}
{/* Dot */}
<span
className={cn(
'flex items-center justify-center w-[22px] h-[22px] rounded-full shrink-0 text-[11px] font-semibold border transition-all duration-200',
isActive && 'bg-primary border-primary text-primary-foreground',
isDone && !isActive && 'bg-primary/10 border-primary/30 text-primary',
!isDone && !isActive && 'bg-background border-border text-muted-foreground',
)}
>
{isDone && !isActive
? <CheckCircle2 className="w-3 h-3" />
: i + 1
}
</span>
{/* Label */}
<span
className={cn(
'text-[13px] leading-snug transition-colors duration-150',
isActive && 'text-foreground font-medium',
isDone && !isActive && 'text-muted-foreground',
!isDone && !isActive && 'text-muted-foreground',
)}
>
{step.titleFallback}
</span>
</button>
)
})}
</nav>
)
}
// ─── Step content renderers ───────────────────────────────────────────────────
function StepStatus({
form, errors, set,
}: {
form: FormState
errors: FormErrors
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
}) {
function StepStatus({ form, errors, set }: StepContentProps) {
return (
<div className="flex flex-col gap-6">
<div className="max-w-md">
<FormInput
type="select"
label="Status"
required
value={form.status}
onChange={(v) => set('status', v)}
options={STATUS_OPTIONS}
error={errors.status}
placeholder="Saýlaň"
/>
<FormInput type="select" label="Status" required value={form.status} onChange={(v) => set('status', v)} options={STATUS_OPTIONS} error={errors.status} placeholder="Saýlaň" />
</div>
<FormInput
type="text"
label="Bellik"
value={form.note}
onChange={(v) => set('note', v)}
placeholder="Bellik"
/>
<FormInput type="text" label="Bellik" value={form.note} onChange={(v) => set('note', v)} placeholder="Bellik" />
</div>
)
}
function StepLoan({
form, errors, set,
}: {
form: FormState
errors: FormErrors
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
}) {
function StepLoan({ form, errors, set }: StepContentProps) {
return (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<FormInput
type="searchable-select"
label="Karz görnüşi"
required
value={form.loanType}
onChange={(v) => set('loanType', v)}
options={LOAN_TYPE_OPTIONS}
placeholder="Saýlamak üçin basyň"
error={errors.loanType}
/>
<FormInput
type="number"
label="Karz möçberi"
required
value={form.loanAmount}
onChange={(v) => set('loanAmount', v)}
placeholder="Karz möçberi"
error={errors.loanAmount}
/>
<FormInput type="searchable-select" label="Karz görnüşi" required value={form.loanType} onChange={(v) => set('loanType', v)} options={LOAN_TYPE_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.loanType} />
<FormInput type="number" label="Karz möçberi" required value={form.loanAmount} onChange={(v) => set('loanAmount', v)} placeholder="Karz möçberi" error={errors.loanAmount} />
</div>
)
}
function StepLocation({
form, errors, set,
}: {
form: FormState
errors: FormErrors
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
}) {
function StepLocation({ form, errors, set }: StepContentProps) {
return (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<FormInput
type="searchable-select"
label="Welaýat"
required
value={form.region}
onChange={(v) => set('region', v)}
options={REGION_OPTIONS}
placeholder="Saýlamak üçin basyň"
error={errors.region}
/>
<FormInput
type="searchable-select"
label="Şahamça"
required
value={form.branch}
onChange={(v) => set('branch', v)}
options={[]}
placeholder="Saýlamak üçin basyň"
error={errors.branch}
/>
<FormInput type="searchable-select" label="Welaýat" required value={form.region} onChange={(v) => set('region', v)} options={REGION_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.region} />
<FormInput type="searchable-select" label="Şahamça" required value={form.branch} onChange={(v) => set('branch', v)} options={[]} placeholder="Saýlamak üçin basyň" error={errors.branch} />
</div>
)
}
function StepPersonal({
form, errors, set,
}: {
form: FormState
errors: FormErrors
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
}) {
function StepPersonal({ form, errors, set }: StepContentProps) {
return (
<div className="flex flex-col gap-6">
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
<FormInput type="text" label="Ady" required value={form.firstName} onChange={(v) => set('firstName', v)} placeholder="Ady" error={errors.firstName} />
<FormInput type="text" label="Familiýasy" required value={form.lastName} onChange={(v) => set('lastName', v)} placeholder="Familiýasy" error={errors.lastName} />
<FormInput type="text" label="Atasynyň ady" value={form.patronicName} onChange={(v) => set('patronicName', v)} placeholder="Atasynyň ady" />
<FormInput type="text" label="Ady" required value={form.firstName} onChange={(v) => set('firstName', v)} placeholder="Ady" error={errors.firstName} />
<FormInput type="text" label="Familiýasy" required value={form.lastName} onChange={(v) => set('lastName', v)} placeholder="Familiýasy" error={errors.lastName} />
<FormInput type="text" label="Atasynyň ady" value={form.patronicName} onChange={(v) => set('patronicName', v)} placeholder="Atasynyň ady" />
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
<FormInput type="select" label="Bilimi" required value={form.education} onChange={(v) => set('education', v)} options={EDUCATION_OPTIONS} placeholder="Saýlaň" error={errors.education} />
<FormInput type="select" label="Maşgala ýagdaýy" required value={form.marriageStatus} onChange={(v) => set('marriageStatus', v)} options={MARRIAGE_OPTIONS} placeholder="Saýlaň" error={errors.marriageStatus} />
<FormInput type="date" label="Doglan güni" required value={form.dateOfBirth} onChange={(v) => set('dateOfBirth', v)} error={errors.dateOfBirth} />
<FormInput type="select" label="Bilimi" required value={form.education} onChange={(v) => set('education', v)} options={EDUCATION_OPTIONS} placeholder="Saýlaň" error={errors.education} />
<FormInput type="select" label="Maşgala ýagdaýy" required value={form.marriageStatus} onChange={(v) => set('marriageStatus', v)} options={MARRIAGE_OPTIONS} placeholder="Saýlaň" error={errors.marriageStatus} />
<FormInput type="date" label="Doglan güni" required value={form.dateOfBirth} onChange={(v) => set('dateOfBirth', v)} error={errors.dateOfBirth} />
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<FormInput type="text" label="Ýazgy edilen salgyňyz" required value={form.residence} onChange={(v) => set('residence', v)} placeholder="Ýazgy edilen salgy" error={errors.residence} />
<FormInput type="text" label="Häzirki ýaşaýyş ýeri" value={form.currentResidence} onChange={(v) => set('currentResidence', v)} placeholder="Häzirki ýaşaýyş ýeri" />
<FormInput type="text" label="Ýazgy edilen salgyňyz" required value={form.residence} onChange={(v) => set('residence', v)} placeholder="Ýazgy edilen salgy" error={errors.residence} />
<FormInput type="text" label="Häzirki ýaşaýyş ýeri" value={form.currentResidence} onChange={(v) => set('currentResidence', v)} placeholder="Häzirki ýaşaýyş ýeri" />
</div>
<div className="max-w-md">
<FormInput
type="searchable-select"
label="Karz taryhy"
value={form.loanHistory}
onChange={(v) => set('loanHistory', v)}
options={[]}
placeholder="Saýlamak üçin basyň"
/>
<FormInput type="searchable-select" label="Karz taryhy" value={form.loanHistory} onChange={(v) => set('loanHistory', v)} options={[]} placeholder="Saýlamak üçin basyň" />
</div>
</div>
)
}
function StepCard({
form, errors, set,
}: {
form: FormState
errors: FormErrors
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
}) {
function StepCard({ form, errors, set }: StepContentProps) {
return (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
<FormInput type="text" label="Kart belgisi" required value={form.cardNumber} onChange={(v) => set('cardNumber', v)} placeholder="Kart belgisi" error={errors.cardNumber} />
<FormInput type="text" label="Kartdaky ady" required value={form.cardName} onChange={(v) => set('cardName', v)} placeholder="Kartdaky ady" error={errors.cardName} />
<FormInput type="searchable-select" label="Kart Möhleti (aý)" required value={form.cardExpMonth} onChange={(v) => set('cardExpMonth', v)} options={MONTH_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.cardExpMonth} />
<FormInput type="searchable-select" label="Kart Möhleti (ýyl)" required value={form.cardExpYear} onChange={(v) => set('cardExpYear', v)} options={YEAR_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.cardExpYear} />
<FormInput type="text" label="Kart belgisi" required value={form.cardNumber} onChange={(v) => set('cardNumber', v)} placeholder="Kart belgisi" error={errors.cardNumber} />
<FormInput type="text" label="Kartdaky ady" required value={form.cardName} onChange={(v) => set('cardName', v)} placeholder="Kartdaky ady" error={errors.cardName} />
<FormInput type="searchable-select" label="Kart Möhleti (aý)" required value={form.cardExpMonth} onChange={(v) => set('cardExpMonth', v)} options={MONTH_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.cardExpMonth} />
<FormInput type="searchable-select" label="Kart Möhleti (ýyl)" required value={form.cardExpYear} onChange={(v) => set('cardExpYear', v)} options={YEAR_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.cardExpYear} />
</div>
)
}
function StepPassport({
form, errors, set,
}: {
form: FormState
errors: FormErrors
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
}) {
function StepPassport({ form, errors, set }: StepContentProps) {
return (
<div className="flex flex-col gap-6">
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
<FormInput type="searchable-select" label="Pasport seriýasy" required value={form.passportSerie} onChange={(v) => set('passportSerie', v)} options={PASSPORT_SERIES_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.passportSerie} />
<FormInput type="text" label="Pasport belgisi" required value={form.passportNumber} onChange={(v) => set('passportNumber', v)} placeholder="Pasport belgisi" error={errors.passportNumber} />
<FormInput type="date" label="Pasport berlen senesi" required value={form.passportDateOfIssue} onChange={(v) => set('passportDateOfIssue', v)} error={errors.passportDateOfIssue} />
<FormInput type="searchable-select" label="Pasport seriýasy" required value={form.passportSerie} onChange={(v) => set('passportSerie', v)} options={PASSPORT_SERIES_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.passportSerie} />
<FormInput type="text" label="Pasport belgisi" required value={form.passportNumber} onChange={(v) => set('passportNumber', v)} placeholder="Pasport belgisi" error={errors.passportNumber} />
<FormInput type="date" label="Pasport berlen senesi" required value={form.passportDateOfIssue} onChange={(v) => set('passportDateOfIssue', v)} error={errors.passportDateOfIssue} />
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<FormInput type="text" label="Kim tarapyndan berildi" required value={form.passportGivenBy} onChange={(v) => set('passportGivenBy', v)} placeholder="Kim tarapyndan berildi" error={errors.passportGivenBy} />
@@ -617,30 +489,18 @@ function StepPassport({
)
}
function StepContact({
form, errors, set,
}: {
form: FormState
errors: FormErrors
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
}) {
function StepContact({ form, errors, set }: StepContentProps) {
return (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
<FormInput type="email" label="E-poçta" value={form.email} onChange={(v) => set('email', v)} placeholder="E-poçta" />
<FormInput type="phone" label="Telefon" required value={form.phone} onChange={(v) => set('phone', v)} placeholder="61 097 651" error={errors.phone} />
<FormInput type="phone" label="Telefon goşmaça" value={form.phoneAdditional} onChange={(v) => set('phoneAdditional', v)} placeholder="61 097 651" />
<FormInput type="phone" label="Öý telefony" value={form.homePhone} onChange={(v) => set('homePhone', v)} placeholder="61 097 651" />
<FormInput type="phone" label="Telefon" required value={form.phone} onChange={(v) => set('phone', v)} placeholder="61 097 651" error={errors.phone} />
<FormInput type="phone" label="Telefon goşmaça" value={form.phoneAdditional} onChange={(v) => set('phoneAdditional', v)} placeholder="61 097 651" />
<FormInput type="phone" label="Öý telefony" value={form.homePhone} onChange={(v) => set('homePhone', v)} placeholder="61 097 651" />
</div>
)
}
function StepJob({
form, errors, set,
}: {
form: FormState
errors: FormErrors
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
}) {
function StepJob({ form, errors, set }: StepContentProps) {
return (
<div className="flex flex-col gap-6">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
@@ -652,23 +512,15 @@ function StepJob({
<FormInput type="searchable-select" label="Işleýän etrabyňyz" value={form.workProvince} onChange={(v) => set('workProvince', v)} options={[]} placeholder="Saýlamak üçin basyň" />
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
<FormInput type="text" label="Wezipe" required value={form.position} onChange={(v) => set('position', v)} placeholder="Wezipe" error={errors.position} />
<FormInput type="number" label="Zähmet haky" required value={form.salary} onChange={(v) => set('salary', v)} placeholder="Zähmet haky" error={errors.salary} />
<FormInput type="text" label="Wezipe" required value={form.position} onChange={(v) => set('position', v)} placeholder="Wezipe" error={errors.position} />
<FormInput type="number" label="Zähmet haky" required value={form.salary} onChange={(v) => set('salary', v)} placeholder="Zähmet haky" error={errors.salary} />
<FormInput type="date" label="Işe başlan wagtyňyz" required value={form.workStartedAt} onChange={(v) => set('workStartedAt', v)} error={errors.workStartedAt} />
</div>
</div>
)
}
function StepFiles({
form, errors, set, mode, initialData,
}: {
form: FormState
errors: FormErrors
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
mode: 'create' | 'edit'
initialData?: LoanOrder
}) {
function StepFiles({ form, errors, set, mode, initialData }: StepContentProps & { mode: 'create' | 'edit'; initialData?: LoanOrder }) {
return (
<div className="flex flex-col gap-6">
{mode === 'edit' && initialData && (
@@ -684,79 +536,39 @@ function StepFiles({
url ? (
<div key={label} className="flex flex-col gap-1">
<span className="text-xs text-muted-foreground">{label} — häzirki</span>
<a href={url} target="_blank" rel="noopener noreferrer" className="text-xs text-primary underline truncate">
Faýly gör
</a>
<a href={url} target="_blank" rel="noopener noreferrer" className="text-xs text-primary underline truncate">Faýly gör</a>
</div>
) : null
)}
</div>
)}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<FormInput
type="file"
label={mode === 'edit' ? 'Pasport (sahypa 1) (çalyşmak)' : 'Pasport (sahypa 1)'}
required={mode === 'create'}
accept="image/*"
fileValue={form.passportPage1}
onFileChange={(f) => set('passportPage1', f)}
placeholder="Faýl saýlaň ýa-da salmak üçin basyň"
error={errors.passportPage1}
/>
<FormInput
type="file"
label={mode === 'edit' ? 'Pasport (2-3-nji sahypa) (çalyşmak)' : 'Pasport (2-3-nji sahypa)'}
required={mode === 'create'}
accept="image/*"
fileValue={form.passportPage23}
onFileChange={(f) => set('passportPage23', f)}
placeholder="Faýl saýlaň ýa-da salmak üçin basyň"
error={errors.passportPage23}
/>
<FormInput
type="file"
label="Pasport (8-9 sahypa)"
accept="image/*"
fileValue={form.passportPage89}
onFileChange={(f) => set('passportPage89', f)}
placeholder="Faýl saýlaň ýa-da salmak üçin basyň"
/>
<FormInput
type="file"
label="Pasport (32-nji sahypa)"
accept="image/*"
fileValue={form.passportPage32}
onFileChange={(f) => set('passportPage32', f)}
placeholder="Faýl saýlaň ýa-da salmak üçin basyň"
/>
<FormInput type="file" label={mode === 'edit' ? 'Pasport (sahypa 1) (çalyşmak)' : 'Pasport (sahypa 1)'} required={mode === 'create'} accept="image/*" fileValue={form.passportPage1} onFileChange={(f) => set('passportPage1', f)} placeholder="Faýl saýlaň ýa-da salmak üçin basyň" error={errors.passportPage1} />
<FormInput type="file" label={mode === 'edit' ? 'Pasport (2-3-nji sahypa) (çalyşmak)' : 'Pasport (2-3-nji sahypa)'} required={mode === 'create'} accept="image/*" fileValue={form.passportPage23} onFileChange={(f) => set('passportPage23', f)} placeholder="Faýl saýlaň ýa-da salmak üçin basyň" error={errors.passportPage23} />
<FormInput type="file" label="Pasport (8-9 sahypa)" accept="image/*" fileValue={form.passportPage89} onFileChange={(f) => set('passportPage89', f)} placeholder="Faýl saýlaň ýa-da salmak üçin basyň" />
<FormInput type="file" label="Pasport (32-nji sahypa)" accept="image/*" fileValue={form.passportPage32} onFileChange={(f) => set('passportPage32', f)} placeholder="Faýl saýlaň ýa-da salmak üçin basyň" />
</div>
</div>
)
}
function StepGuarantor({
form, errors, set,
}: {
form: FormState
errors: FormErrors
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
}) {
function StepGuarantor({ form, errors, set }: StepContentProps) {
return (
<div className="flex flex-col gap-6">
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
<FormInput type="text" label="Zamunyň ady" required value={form.guarantor1Name} onChange={(v) => set('guarantor1Name', v)} placeholder="Zamunyň ady" error={errors.guarantor1Name} />
<FormInput type="text" label="Zamunyň familiýasy" required value={form.guarantor1Surname} onChange={(v) => set('guarantor1Surname', v)} placeholder="Zamunyň familiýasy" error={errors.guarantor1Surname} />
<FormInput type="text" label="Zamunyň atasynyň ady" value={form.guarantor1Patronic} onChange={(v) => set('guarantor1Patronic', v)} placeholder="Zamunyň atasynyň ady" />
<FormInput type="text" label="Zamunyň ady" required value={form.guarantor1Name} onChange={(v) => set('guarantor1Name', v)} placeholder="Zamunyň ady" error={errors.guarantor1Name} />
<FormInput type="text" label="Zamunyň familiýasy" required value={form.guarantor1Surname} onChange={(v) => set('guarantor1Surname', v)} placeholder="Zamunyň familiýasy" error={errors.guarantor1Surname} />
<FormInput type="text" label="Zamunyň atasynyň ady" value={form.guarantor1Patronic} onChange={(v) => set('guarantor1Patronic', v)} placeholder="Zamunyň atasynyň ady" />
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<FormInput type="searchable-select" label="Pasport seriýasy" required value={form.guarantor1PassportSerie} onChange={(v) => set('guarantor1PassportSerie', v)} options={PASSPORT_SERIES_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1PassportSerie} />
<FormInput type="text" label="Pasport belgisi" required value={form.guarantor1PassportNumber} onChange={(v) => set('guarantor1PassportNumber', v)} placeholder="Pasport belgisi" error={errors.guarantor1PassportNumber} />
<FormInput type="text" label="Pasport belgisi" required value={form.guarantor1PassportNumber} onChange={(v) => set('guarantor1PassportNumber', v)} placeholder="Pasport belgisi" error={errors.guarantor1PassportNumber} />
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
<FormInput type="text" label="Kart belgisi" required value={form.guarantor1CardNumber} onChange={(v) => set('guarantor1CardNumber', v)} placeholder="Kart belgisi" error={errors.guarantor1CardNumber} />
<FormInput type="text" label="Kartdaky ady" required value={form.guarantor1CardName} onChange={(v) => set('guarantor1CardName', v)} placeholder="Kartdaky ady" error={errors.guarantor1CardName} />
<FormInput type="searchable-select" label="Möhleti (aý)" required value={form.guarantor1CardExpMonth} onChange={(v) => set('guarantor1CardExpMonth', v)} options={MONTH_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpMonth} />
<FormInput type="searchable-select" label="Möhleti (ýyl)" required value={form.guarantor1CardExpYear} onChange={(v) => set('guarantor1CardExpYear', v)} options={YEAR_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpYear} />
<FormInput type="text" label="Kart belgisi" required value={form.guarantor1CardNumber} onChange={(v) => set('guarantor1CardNumber', v)} placeholder="Kart belgisi" error={errors.guarantor1CardNumber} />
<FormInput type="text" label="Kartdaky ady" required value={form.guarantor1CardName} onChange={(v) => set('guarantor1CardName', v)} placeholder="Kartdaky ady" error={errors.guarantor1CardName} />
<FormInput type="searchable-select" label="Möhleti (aý)" required value={form.guarantor1CardExpMonth} onChange={(v) => set('guarantor1CardExpMonth', v)} options={MONTH_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpMonth} />
<FormInput type="searchable-select" label="Möhleti (ýyl)" required value={form.guarantor1CardExpYear} onChange={(v) => set('guarantor1CardExpYear', v)} options={YEAR_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpYear} />
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<FormInput type="number" label="Ortaca zähmet haky" required value={form.guarantor1Salary} onChange={(v) => set('guarantor1Salary', v)} placeholder="Ortaca zähmet haky" error={errors.guarantor1Salary} />
@@ -765,6 +577,14 @@ function StepGuarantor({
)
}
// ─── Shared step content prop type ───────────────────────────────────────────
interface StepContentProps {
form: FormState
errors: FormErrors
set: <K extends keyof FormState>(k: K, v: FormState[K]) => void
}
// ─── Props ────────────────────────────────────────────────────────────────────
interface LoanOrderFormProps {
@@ -776,45 +596,56 @@ interface LoanOrderFormProps {
// ─── Main Component ───────────────────────────────────────────────────────────
export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormProps) {
const { t } = useTranslation()
const navigate = useNavigate()
const { t } = useTranslation()
const navigate = useNavigate()
const createMutation = useCreateLoanOrder()
const updateMutation = useUpdateLoanOrder()
const isPending = createMutation.isPending || updateMutation.isPending
const [form, setForm] = useState<FormState>(() => initialData ? mapToFormState(initialData) : INITIAL_STATE)
const [errors, setErrors] = useState<FormErrors>({})
const [form, setForm] = useState<FormState>(() => initialData ? mapToFormState(initialData) : INITIAL_STATE)
const [errors, setErrors] = useState<FormErrors>({})
const [currentStep, setCurrentStep] = useState(0)
const [completed, setCompleted] = useState<Set<number>>(
// In edit mode, mark all steps as reachable from the start
/**
* `visited`: steps the user has explicitly moved away from (via Next or direct nav).
* Used to mark steps as "done" or "error" in the step bar.
* In edit mode all steps start visited so errors show immediately on submit.
*/
const [visited, setVisited] = useState<Set<number>>(
() => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set<number>()
)
const set = useCallback(
<K extends keyof FormState>(key: K, value: FormState[K]) => {
setForm((prev) => ({ ...prev, [key]: value }))
setErrors((prev) => ({ ...prev, [key]: undefined }))
},
[]
)
/** Steps with at least one error (evaluated lazily — only after being visited). */
const stepsWithErrors = useMemo(() => {
const out = new Set<number>()
visited.forEach((i) => {
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) out.add(i)
})
return out
}, [form, mode, visited])
const set = useCallback(<K extends keyof FormState>(key: K, value: FormState[K]) => {
setForm((prev) => ({ ...prev, [key]: value }))
setErrors((prev) => ({ ...prev, [key]: undefined }))
}, [])
const stepProps = useMemo(() => ({ form, errors, set }), [form, errors, set])
// Validate current step and advance
const handleNext = () => {
const stepDef = STEPS[currentStep]
const errs = stepDef.validate(form, mode)
// ── Navigation ──────────────────────────────────────────────────────────────
const markVisited = (i: number) =>
setVisited((prev) => new Set([...prev, i]))
const handleNext = () => {
markVisited(currentStep)
const errs = STEPS[currentStep].validate(form, mode)
if (Object.keys(errs).length > 0) {
setErrors(errs)
toast.error('Dogry maglumat girizmegiňizi haýyş edýäris.')
return
}
setErrors({})
setCompleted((prev) => new Set([...prev, currentStep]))
if (currentStep < STEPS.length - 1) {
setCurrentStep(currentStep + 1)
window.scrollTo({ top: 0, behavior: 'smooth' })
@@ -823,6 +654,7 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP
const handleBack = () => {
if (currentStep > 0) {
markVisited(currentStep)
setErrors({})
setCurrentStep(currentStep - 1)
window.scrollTo({ top: 0, behavior: 'smooth' })
@@ -830,25 +662,26 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP
}
const handleGoTo = (i: number) => {
markVisited(currentStep)
setErrors({})
setCurrentStep(i)
window.scrollTo({ top: 0, behavior: 'smooth' })
}
// Final submit — validate all steps at once
// ── Submit ──────────────────────────────────────────────────────────────────
const handleSubmit = () => {
// Mark all steps visited so error states show in the bar
setVisited(new Set(STEPS.map((_, i) => i)))
const allErrors: FormErrors = {}
for (const step of STEPS) {
Object.assign(allErrors, step.validate(form, mode))
}
for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode))
if (Object.keys(allErrors).length > 0) {
setErrors(allErrors)
toast.error('Käbir hökmany meýdanlar doldurylan däldir.')
// Find which step has the first error and jump there
for (let i = 0; i < STEPS.length; i++) {
const stepErrs = STEPS[i].validate(form, mode)
if (Object.keys(stepErrs).length > 0) {
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) {
setCurrentStep(i)
break
}
@@ -905,138 +738,114 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP
}
if (mode === 'create') {
createMutation.mutate(payload, {
onSuccess: () => navigate('/loan-orders'),
})
createMutation.mutate(payload, { onSuccess: () => navigate('/loan-orders') })
} else {
updateMutation.mutate(
{ id: loanOrderId!, payload },
{ onSuccess: () => navigate('/loan-orders') }
)
updateMutation.mutate({ id: loanOrderId!, payload }, { onSuccess: () => navigate('/loan-orders') })
}
}
const isLastStep = currentStep === STEPS.length - 1
// ── StepBar items ───────────────────────────────────────────────────────────
// Completed step count for progress bar
const completedCount = completed.size
// 4. stepBarItems'i StepCardItem[] olarak oluştur
const stepBarItems: StepCardItem[] = STEPS.map((s, i) => {
const isActive = i === currentStep
const hasErrors = stepsWithErrors.has(i)
const isDone = visited.has(i) && !hasErrors
return {
id: s.id,
title: t(s.titleKey) || s.titleFallback,
subtitle: s.subtitle,
icon: s.icon,
status: isActive ? 'active'
: hasErrors ? 'error'
: isDone ? 'done'
: 'idle',
}
})
const isLastStep = currentStep === STEPS.length - 1
// ── Render ──────────────────────────────────────────────────────────────────
return (
<div className="flex flex-col gap-5">
{/* ── Page header ── */}
{/* Page header */}
<div className="flex flex-col gap-1">
<h1 className="text-xl font-semibold text-foreground">
{mode === 'create'
? (t('Loan order create') || 'Karz sargyt döredüň')
: (t('Loan order edit') || 'Karz sargydy üýtget')}
{mode === 'create' ? (t('Loan order create') || 'Karz sargyt döredüň') : (t('Loan order edit') || 'Karz sargydy üýtget')}
</h1>
<p className="text-sm text-muted-foreground">
{t('Fill in all sections step by step') || 'Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.'}
</p>
</div>
{/* ── Thin progress bar ── */}
<div className="flex items-center gap-3">
<div className="flex-1 h-[3px] rounded-full bg-border overflow-hidden">
<div
className="h-full bg-primary rounded-full transition-all duration-500"
style={{ width: `${(completedCount / STEPS.length) * 100}%` }}
/>
{/* Horizontal step bar — sits above the form card */}
<StepBarCards steps={stepBarItems} onGoTo={handleGoTo} />
{/* Form card */}
<div className="flex flex-col bg-card border border-border rounded-xl overflow-hidden">
{/* Card header */}
<div className="flex items-center gap-2.5 px-5 py-3.5 border-b border-border">
<span className="inline-flex items-center px-2 py-0.5 rounded-full bg-primary/10 text-primary text-[11px] font-semibold tabular-nums">
{currentStep + 1} / {STEPS.length}
</span>
<h2 className="text-sm font-semibold text-foreground">
{t(STEPS[currentStep].titleKey) || STEPS[currentStep].titleFallback}
</h2>
</div>
<span className="text-xs text-muted-foreground tabular-nums shrink-0">
{completedCount} / {STEPS.length}
</span>
</div>
{/* ── Sidebar + content layout ── */}
<div className="grid grid-cols-[200px_1fr] gap-5 items-start">
{/* Sidebar */}
<StepSidebar
steps={STEPS}
current={currentStep}
completed={completed}
onGoTo={handleGoTo}
/>
{/* Card body */}
<div className="p-5">
{currentStep === 0 && <StepStatus {...stepProps} />}
{currentStep === 1 && <StepLoan {...stepProps} />}
{currentStep === 2 && <StepLocation {...stepProps} />}
{currentStep === 3 && <StepPersonal {...stepProps} />}
{currentStep === 4 && <StepCard {...stepProps} />}
{currentStep === 5 && <StepPassport {...stepProps} />}
{currentStep === 6 && <StepContact {...stepProps} />}
{currentStep === 7 && <StepJob {...stepProps} />}
{currentStep === 8 && <StepFiles {...stepProps} mode={mode} initialData={initialData} />}
{currentStep === 9 && <StepGuarantor {...stepProps} />}
</div>
{/* Step card */}
<div className="flex flex-col gap-0 bg-card border border-border rounded-xl overflow-hidden">
{/* Card header */}
<div className="flex items-center gap-2.5 px-5 py-3.5 border-b border-border">
<span className="inline-flex items-center px-2 py-0.5 rounded-full bg-primary/10 text-primary text-[11px] font-semibold tabular-nums">
{currentStep + 1} / {STEPS.length}
</span>
<h2 className="text-sm font-semibold text-foreground">
{t(STEPS[currentStep].titleKey) || STEPS[currentStep].titleFallback}
</h2>
</div>
{/* Card body */}
<div className="p-5">
{currentStep === 0 && <StepStatus {...stepProps} />}
{currentStep === 1 && <StepLoan {...stepProps} />}
{currentStep === 2 && <StepLocation {...stepProps} />}
{currentStep === 3 && <StepPersonal {...stepProps} />}
{currentStep === 4 && <StepCard {...stepProps} />}
{currentStep === 5 && <StepPassport {...stepProps} />}
{currentStep === 6 && <StepContact {...stepProps} />}
{currentStep === 7 && <StepJob {...stepProps} />}
{currentStep === 8 && <StepFiles {...stepProps} mode={mode} initialData={initialData} />}
{currentStep === 9 && <StepGuarantor {...stepProps} />}
</div>
{/* Card footer with navigation */}
<div className="flex items-center justify-between px-5 py-3.5 border-t border-border bg-muted/30">
<Button
type="button"
variant="outline"
size="sm"
onClick={currentStep === 0 ? () => navigate(-1) : handleBack}
disabled={isPending}
>
{currentStep === 0 ? (
t('Cancel') || 'Ýatyr'
) : (
<span className="flex items-center gap-1.5">
<ChevronLeft className="w-3.5 h-3.5" />
{t('Back') || 'Yza'}
</span>
)}
</Button>
{isLastStep ? (
<Button
type="button"
size="sm"
onClick={handleSubmit}
disabled={isPending}
className="min-w-[150px]"
>
{isPending ? (
<span className="flex items-center gap-2">
<Loader2 className="w-3.5 h-3.5 animate-spin" />
{t('Loading') || 'Ýüklenilýär...'}
</span>
) : mode === 'create'
? (t('loanOrderMobiles.createButton') || 'Karz sargyt döredüň')
: (t('loanOrders.saveButton') || 'Ýatda sakla')
}
</Button>
) : (
<Button
type="button"
size="sm"
onClick={handleNext}
disabled={isPending}
className="min-w-[120px]"
>
<span className="flex items-center gap-1.5">
{t('Next') || 'Indiki'}
<ChevronRight className="w-3.5 h-3.5" />
</span>
</Button>
{/* Card footer */}
<div className="flex items-center justify-between px-5 py-3.5 border-t border-border bg-muted/30">
<Button
type="button"
variant="outline"
size="sm"
onClick={currentStep === 0 ? () => navigate(-1) : handleBack}
disabled={isPending}
>
{currentStep === 0 ? (t('Cancel') || 'Ýatyr') : (
<span className="flex items-center gap-1.5">
<ChevronLeft className="w-3.5 h-3.5" />
{t('Back') || 'Yza'}
</span>
)}
</div>
</Button>
{isLastStep ? (
<Button type="button" size="sm" onClick={handleSubmit} disabled={isPending} className="min-w-[150px]">
{isPending ? (
<span className="flex items-center gap-2">
<Loader2 className="w-3.5 h-3.5 animate-spin" />
{t('Loading') || 'Ýüklenilýär...'}
</span>
) : mode === 'create'
? (t('loanOrderMobiles.createButton') || 'Karz sargyt döredüň')
: (t('loanOrders.saveButton') || 'Ýatda sakla')
}
</Button>
) : (
<Button type="button" size="sm" onClick={handleNext} disabled={isPending} className="min-w-[120px]">
<span className="flex items-center gap-1.5">
{t('Next') || 'Indiki'}
<ChevronRight className="w-3.5 h-3.5" />
</span>
</Button>
)}
</div>
</div>
</div>

View 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)
},
}

View 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>
)
}

View 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'))
},
})
}

View File

@@ -327,9 +327,9 @@ function AppSidebar() {
title: t("Users", "Ulanyjylar"),
icon: Users,
items: [
{ title: t("Operators", "Operatorlar"), url: "/users/operators" },
{ title: t("Clients", "Müşderiler"), url: "/users/clients" },
{ title: t("All users", "Ähli ulanyjylar"), url: "/users/all" },
{ title: t("Operators", "Operatorlar"), url: "/operators" },
{ title: t("Clients", "Müşderiler"), url: "/clients" },
{ title: t("All users", "Ähli ulanyjylar"), url: "/all-users" },
],
},
{

View File

@@ -0,0 +1,281 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Eye, Pencil, Trash2, CheckCircle2, XCircle } from 'lucide-react'
import { DataTable, type ColumnDef } from '@/components/dataTable'
import { DataTableToolbar, type ActiveFilter } from '@/components/dataTableToolbar'
import { Button } from '@/components/ui/button'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import type { VisibilityState } from '@tanstack/react-table'
import { useUsers, useDeleteUser } from '@/features/allUsers/hooks/useAllUsers'
import type { UserListItem } from '@/features/allUsers/api/allUsersApi'
// ─── Constants ────────────────────────────────────────────────────────────────
const DEFAULT_PER_PAGE = 25
// ─── UsersListPage ────────────────────────────────────────────────────────────
export default function UsersListPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const deleteUser = useDeleteUser()
// Table state
const [page, setPage] = useState(1)
const [perPage, setPerPage] = useState(DEFAULT_PER_PAGE)
const [search, setSearch] = useState('')
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([])
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({})
const [columnOrder, setColumnOrder] = useState<string[]>([
'id', 'username', 'name', 'phone', 'email', 'isActive', 'actions',
])
// Delete confirm dialog
const [deleteTarget, setDeleteTarget] = useState<UserListItem | null>(null)
// ── Derived filter values ───────────────────────────────────────────────────
const isActiveFilter = activeFilters.find((f) => f.fieldId === 'isActive')?.value ?? ''
// ── Data fetch ─────────────────────────────────────────────────────────────
const { data, isLoading } = useUsers({
page,
perPage,
search,
isActive: isActiveFilter || undefined,
})
// ── Handlers ───────────────────────────────────────────────────────────────
const handleSearchChange = (value: string) => {
setSearch(value)
setPage(1)
}
const handleFilterChange = (fieldId: string, value: string) => {
setActiveFilters((prev) => {
const rest = prev.filter((f) => f.fieldId !== fieldId)
return value ? [...rest, { fieldId, value }] : rest
})
setPage(1)
}
const handleFilterReset = () => {
setActiveFilters([])
setPage(1)
}
const handleDeleteConfirm = async () => {
if (!deleteTarget) return
await deleteUser.mutateAsync(deleteTarget.id)
setDeleteTarget(null)
}
// ── Columns ────────────────────────────────────────────────────────────────
const columns: ColumnDef<UserListItem>[] = [
{
accessorKey: 'id',
header: 'ID',
size: 80,
cell: ({ row }) => (
<span className="text-xs font-mono text-primary font-semibold">
{row.original.id}
</span>
),
},
{
accessorKey: 'username',
header: t('users.fields.username', 'ULANYJY ADY'),
enableSorting: true,
cell: ({ row }) => (
<span className="text-sm font-medium text-foreground">
{row.original.username}
</span>
),
},
{
accessorKey: 'name',
header: t('users.fields.name', 'ADY'),
enableSorting: true,
cell: ({ row }) => (
<span className="text-sm text-foreground">{row.original.name}</span>
),
},
{
accessorKey: 'phone',
header: t('users.fields.phone', 'TELEFON'),
cell: ({ row }) => (
<span className="text-sm text-foreground font-mono">{row.original.phone}</span>
),
},
{
accessorKey: 'email',
header: t('users.fields.email', 'E-POÇTA'),
enableSorting: true,
cell: ({ row }) => (
<span className="text-sm text-muted-foreground">
{row.original.email ?? '—'}
</span>
),
},
{
accessorKey: 'isActive',
header: t('users.fields.isActive', 'IŞJEŇ'),
size: 80,
cell: ({ row }) =>
row.original.isActive ? (
<CheckCircle2 size={18} className="text-emerald-500" />
) : (
<XCircle size={18} className="text-muted-foreground/40" />
),
},
{
id: 'actions',
header: '',
size: 100,
enableHiding: false,
cell: ({ row }) => (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() => navigate(`/all-users/${row.original.id}`)}
>
<Eye size={14} />
</Button>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() => navigate(`/all-users/${row.original.id}/edit`)}
>
<Pencil size={14} />
</Button>
<Button
variant="ghost"
size="icon"
className="h-7 w-7 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => setDeleteTarget(row.original)}
>
<Trash2 size={14} />
</Button>
</div>
),
},
]
const columnMetas = columns
.filter((c) => 'accessorKey' in c || (c.id && c.id !== 'actions' && c.id !== 'select'))
.map((c) => ({
id: 'accessorKey' in c ? (c.accessorKey as string) : (c.id as string),
label:
typeof c.header === 'string'
? c.header
: 'accessorKey' in c
? (c.accessorKey as string)
: (c.id as string),
}))
// ── Render ─────────────────────────────────────────────────────────────────
return (
<div className="p-6 space-y-4">
{/* Page header */}
<div>
<nav className="flex items-center gap-1.5 text-xs text-muted-foreground mb-3">
<span>{t('nav.resources', 'Resurslar')}</span>
<span>›</span>
<span className="text-foreground font-medium">
{t('nav.users', 'Ulanyjylar')}
</span>
</nav>
<h1 className="text-2xl font-bold text-foreground">
{t('users.title', 'Ulanyjylar')}
</h1>
</div>
{/* Toolbar */}
<DataTableToolbar
searchValue={search}
onSearchChange={handleSearchChange}
searchPlaceholder={t('users.searchPlaceholder', 'Gözlemek')}
columns={columnMetas}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
filterFields={[
{
id: 'isActive',
label: t('users.fields.isActive', 'Işjeň'),
options: [
{ value: 'true', label: t('common.active', 'Işjeň') },
{ value: 'false', label: t('common.inactive', 'Işjeň däl') },
],
},
]}
activeFilters={activeFilters}
onFilterChange={handleFilterChange}
onFilterReset={handleFilterReset}
perPageOptions={[10, 25, 50, 100]}
perPage={perPage}
onPerPageChange={(v) => { setPerPage(v); setPage(1) }}
actionLabel={t('users.actions.create', 'Ulanyjy dörediň')}
onAction={() => navigate('/all-users/create')}
/>
{/* Table */}
<DataTable
columns={columns}
data={data?.data ?? []}
isLoading={isLoading}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
enableRowSelection
getRowId={(row) => String(row.id)}
currentPage={page}
totalPages={data?.totalPages ?? 1}
totalCount={data?.total}
onPageChange={setPage}
/>
{/* Delete confirm dialog */}
<AlertDialog open={!!deleteTarget} onOpenChange={(o) => !o && setDeleteTarget(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t('users.deleteDialog.title', 'Ulanyjyny öçürmek')}
</AlertDialogTitle>
<AlertDialogDescription>
{t(
'users.deleteDialog.description',
'Siz "{name}" ulanyjysyny öçürjekmi? Bu amal yzyna gaýtarylyp bilinmez.',
).replace('{name}', deleteTarget?.username ?? '')}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('common.cancel', 'Ýok')}</AlertDialogCancel>
<AlertDialogAction
onClick={handleDeleteConfirm}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{t('common.delete', 'Öçür')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}

View File

@@ -0,0 +1,44 @@
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router-dom'
import { ChevronRight } from 'lucide-react'
import { UserForm } from '@/features/allUsers/components/allUsersForm'
// ─── UserCreatePage ───────────────────────────────────────────────────────────
export default function UserCreatePage() {
const { t } = useTranslation()
const navigate = useNavigate()
return (
<div className="p-6 space-y-4 max-w-4xl">
{/* Breadcrumb */}
<nav className="flex items-center gap-1.5 text-xs text-muted-foreground">
<button
onClick={() => navigate('/users')}
className="hover:text-foreground transition-colors"
>
{t('nav.resources', 'Resurslar')}
</button>
<ChevronRight size={12} />
<button
onClick={() => navigate('/users')}
className="hover:text-foreground transition-colors"
>
{t('nav.users', 'Ulanyjylar')}
</button>
<ChevronRight size={12} />
<span className="text-foreground font-medium">
{t('users.actions.create', 'Ulanyjy dörediň')}
</span>
</nav>
{/* Title */}
<h1 className="text-2xl font-bold text-foreground">
{t('users.actions.create', 'Ulanyjy dörediň')}
</h1>
{/* Shared form — create mode */}
<UserForm mode="create" />
</div>
)
}

View File

@@ -0,0 +1,45 @@
import { useParams } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Loader2 } from 'lucide-react'
import { UserForm } from '@/features/allUsers/components/allUsersForm'
import { useUser } from '@/features/allUsers/hooks/useAllUsers'
// ─── UserEditPage ─────────────────────────────────────────────────────────────
export default function UserEditPage() {
const { t } = useTranslation()
const { id } = useParams<{ id: string }>()
const userId = Number(id)
const { data: user, isLoading, isError } = useUser(userId)
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-[300px]">
<Loader2 size={24} className="animate-spin text-muted-foreground" />
</div>
)
}
if (isError || !user) {
return (
<div className="p-6 text-center text-muted-foreground">
{t('common.notFound', 'Maglumat tapylmady')}
</div>
)
}
return (
<div className="p-6 space-y-4 max-w-4xl">
{/* Title */}
<h1 className="text-2xl font-bold text-foreground">
{t('users.editTitle', 'Ulanyjy giňişleýin')}: {user.name} ({user.username})
</h1>
{/* Shared form — edit mode, passes fetched data */}
<UserForm mode="edit" initialData={user} userId={userId} />
</div>
)
}

View File

@@ -0,0 +1,284 @@
import { useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import {
ChevronRight,
Loader2,
Pencil,
Trash2,
CheckCircle2,
XCircle,
ChevronDown,
Plus,
Search,
SlidersHorizontal,
ChevronUp,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Section, InfoRow } from '@/components/viewPageComponents'
import { useUser, useDeleteUser } from '@/features/allUsers/hooks/useAllUsers'
// ─── Collapsible Section ──────────────────────────────────────────────────────
interface CollapsibleBlockProps {
title: string
actionLabel: string
onAction: () => void
emptyMessage: string
searchPlaceholder?: string
showFilter?: boolean
}
function CollapsibleBlock({
title,
actionLabel,
onAction,
emptyMessage,
searchPlaceholder = 'Gözlemek',
showFilter = false,
}: CollapsibleBlockProps) {
const [open, setOpen] = useState(true)
const [search, setSearch] = useState('')
return (
<div className="mb-6">
<button
onClick={() => setOpen((v) => !v)}
className="flex items-center gap-1.5 text-base font-semibold text-foreground mb-2 hover:opacity-80 transition-opacity select-none"
>
{title}
{open ? <ChevronDown size={15} /> : <ChevronUp size={15} />}
</button>
{open && (
<div className="bg-card border border-border rounded-xl overflow-hidden">
{/* Sub-toolbar */}
<div className="flex items-center justify-between px-4 py-3 border-b border-border">
<div className="relative">
<Search
size={13}
className="absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none"
/>
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder={searchPlaceholder}
className="h-8 pl-8 pr-3 rounded-md border border-border bg-background text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-1 focus:ring-ring w-48"
/>
</div>
<div className="flex items-center gap-2">
{showFilter && (
<Button variant="outline" size="icon" className="h-8 w-8">
<SlidersHorizontal size={13} />
</Button>
)}
<Button size="sm" className="h-8 gap-1.5" onClick={onAction}>
<Plus size={13} />
{actionLabel}
</Button>
</div>
</div>
{/* Empty state */}
<div className="flex flex-col items-center justify-center py-16 gap-3">
<div className="w-16 h-16 rounded-lg border border-border bg-muted/30 flex items-center justify-center">
<svg
width="32"
height="32"
viewBox="0 0 32 32"
fill="none"
className="text-muted-foreground/40"
>
<rect x="4" y="8" width="24" height="18" rx="2" stroke="currentColor" strokeWidth="1.5" />
<path d="M4 13h24" stroke="currentColor" strokeWidth="1.5" />
<path d="M9 8V6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
<path d="M23 8V6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
<circle cx="22" cy="22" r="5" fill="currentColor" fillOpacity="0.1" stroke="currentColor" strokeWidth="1.5" />
<path d="M22 20v4M20 22h4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
</div>
<p className="text-sm text-muted-foreground">{emptyMessage}</p>
<Button variant="outline" size="sm" onClick={onAction}>
{actionLabel}
</Button>
</div>
</div>
)}
</div>
)
}
// ─── UserViewPage ─────────────────────────────────────────────────────────────
export default function UserViewPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const { id } = useParams<{ id: string }>()
const userId = Number(id)
const { data: user, isLoading, isError } = useUser(userId)
const deleteUser = useDeleteUser()
const [showDeleteDialog, setShowDeleteDialog] = useState(false)
const handleDeleteConfirm = async () => {
await deleteUser.mutateAsync(userId)
navigate('/users')
}
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-[400px]">
<Loader2 size={24} className="animate-spin text-muted-foreground" />
</div>
)
}
if (isError || !user) {
return (
<div className="p-6 text-center text-muted-foreground">
{t('common.notFound', 'Maglumat tapylmady')}
</div>
)
}
return (
<div className="p-6 max-w-4xl space-y-0">
{/* Breadcrumb */}
<nav className="flex items-center gap-1.5 text-xs text-muted-foreground mb-3">
<button
onClick={() => navigate('/users')}
className="hover:text-foreground transition-colors"
>
{t('nav.resources', 'Resurslar')}
</button>
<ChevronRight size={12} />
<button
onClick={() => navigate('/users')}
className="hover:text-foreground transition-colors"
>
{t('nav.users', 'Ulanyjylar')}
</button>
<ChevronRight size={12} />
<span className="text-foreground font-medium">
{t('users.viewTitle', 'Ulanyjy giňişleýin')}: {user.name} ({user.username})
</span>
</nav>
{/* Title + actions */}
<div className="flex items-start justify-between mb-6">
<h1 className="text-xl font-bold text-foreground leading-tight">
{t('users.viewTitle', 'Ulanyjy giňişleýin')}: {user.name} ({user.username})
</h1>
<div className="flex items-center gap-2 shrink-0 ml-4">
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => setShowDeleteDialog(true)}
>
<Trash2 size={15} />
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => navigate(`/users/${userId}/edit`)}
>
<Pencil size={15} />
</Button>
</div>
</div>
{/* Main info */}
<Section>
<InfoRow label="ID" value={user.id} />
<InfoRow label={t('users.fields.username', 'Ulanyjy ady')} value={user.username} />
<InfoRow label={t('users.fields.name', 'Ady')} value={user.name} />
<InfoRow label={t('users.fields.phone', 'Telefon')} value={user.phone} />
<InfoRow label={t('users.fields.email', 'E-poçta')} value={user.email} />
<InfoRow label={t('users.fields.isActive', 'Işjeň')}>
{user.isActive ? (
<CheckCircle2 size={18} className="text-emerald-500" />
) : (
<XCircle size={18} className="text-muted-foreground/40" />
)}
</InfoRow>
</Section>
{/* Rollar */}
<CollapsibleBlock
title={t('users.sections.roles', 'Rollar')}
actionLabel={t('users.actions.addRole', 'Rol birikdiriň')}
onAction={() => {}}
emptyMessage={t('users.empty.roles', 'Berlen kriteriýalara Rol gabat gelmedi.')}
searchPlaceholder={t('common.search', 'Gözlemek')}
/>
{/* Rugsatlar */}
<CollapsibleBlock
title={t('users.sections.permissions', 'Rugsatlar')}
actionLabel={t('users.actions.addPermission', 'Rugsat birikdiriň')}
onAction={() => {}}
emptyMessage={t('users.empty.permissions', 'Berlen kriteriýalara Rugsat gabat gelmedi.')}
searchPlaceholder={t('common.search', 'Gözlemek')}
/>
{/* Şahamçalar */}
<CollapsibleBlock
title={t('users.sections.branches', 'Şahamçalar')}
actionLabel={t('users.actions.addBranch', 'Şahamça birikdiriň')}
onAction={() => {}}
emptyMessage={t('users.empty.branches', 'Berlen kriteriýalara Şahamça gabat gelmedi.')}
searchPlaceholder={t('common.search', 'Gözlemek')}
showFilter
/>
{/* Ammallar */}
<CollapsibleBlock
title={t('users.sections.audit', 'Ammallar')}
actionLabel={t('users.actions.addAction', 'Hereket')}
onAction={() => {}}
emptyMessage={t('users.empty.audit', 'Berlen kriteriýalara Hereket gabat gelmedi.')}
searchPlaceholder={t('common.search', 'Gözlemek')}
/>
{/* Delete dialog */}
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t('users.deleteDialog.title', 'Ulanyjyny öçürmek')}
</AlertDialogTitle>
<AlertDialogDescription>
{t(
'users.deleteDialog.description',
'Siz "{name}" ulanyjysyny öçürjekmi? Bu amal yzyna gaýtarylyp bilinmez.',
).replace('{name}', user.username)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('common.cancel', 'Ýok')}</AlertDialogCancel>
<AlertDialogAction
onClick={handleDeleteConfirm}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{t('common.delete', 'Öçür')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}

View File

@@ -0,0 +1,227 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Trash2, Eye, Pencil } from 'lucide-react'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Button } from '@/components/ui/button'
import { DataTable, type ColumnDef } from '@/components/dataTable'
import { DataTableToolbar } from '@/components/dataTableToolbar'
import { useClients, useDeleteClient } from '@/features/clients/hooks/useClients'
import type { Client } from '@/features/clients/api/clientsApi'
export default function ClientsPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const deleteMutation = useDeleteClient()
const [page, setPage] = useState(1)
const [perPage, setPerPage] = useState(25)
const [search, setSearch] = useState('')
const [isActiveFilter, setIsActiveFilter] = useState('')
const [columnVisibility, setColumnVisibility] = useState({})
const [columnOrder, setColumnOrder] = useState<string[]>([])
const [deleteTarget, setDeleteTarget] = useState<Client | null>(null)
const { data, isLoading } = useClients({
page,
perPage,
search: search || undefined,
isActive: isActiveFilter || undefined,
})
const clients = data?.data ?? []
const totalPages = data?.meta.totalPages ?? 1
const totalCount = data?.meta.totalCount ?? 0
const columns: ColumnDef<Client>[] = [
{
accessorKey: 'id',
header: 'ID',
cell: ({ row }) => (
<span
className="text-primary font-semibold cursor-pointer hover:underline text-sm"
onClick={() => navigate(`/clients/${row.original.id}`)}
>
{row.original.id}
</span>
),
size: 80,
},
{
accessorKey: 'username',
header: t('clients.fields.username', 'ULANYJY ADY'),
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.username}</span>,
},
{
accessorKey: 'name',
header: t('clients.fields.name', 'ADY'),
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.name}</span>,
},
{
accessorKey: 'phone',
header: t('clients.fields.phone', 'TELEFON'),
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.phone ?? '—'}</span>,
},
{
accessorKey: 'email',
header: t('clients.fields.email', 'E-POÇTA'),
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.email ?? '—'}</span>,
},
{
accessorKey: 'isActive',
header: t('clients.fields.isActive', 'IŞJEŇ'),
cell: ({ row }) =>
row.original.isActive ? (
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-primary text-primary">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M2 6l3 3 5-5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</span>
) : (
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-destructive text-destructive">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M3 3l6 6M9 3l-6 6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
</svg>
</span>
),
size: 80,
},
{
id: 'actions',
header: '',
cell: ({ row }) => (
<div className="flex items-center gap-1 justify-end">
<Button
size="icon"
variant="ghost"
className="h-7 w-7 text-muted-foreground hover:text-foreground"
onClick={() => navigate(`/clients/${row.original.id}`)}
>
<Eye size={14} />
</Button>
<Button
size="icon"
variant="ghost"
className="h-7 w-7 text-muted-foreground hover:text-foreground"
onClick={() => navigate(`/clients/${row.original.id}/edit`)}
>
<Pencil size={14} />
</Button>
<Button
size="icon"
variant="ghost"
className="h-7 w-7 text-muted-foreground hover:text-destructive"
onClick={() => setDeleteTarget(row.original)}
>
<Trash2 size={14} />
</Button>
</div>
),
size: 120,
enableSorting: false,
},
]
const columnMetas = columns
.filter((c) => 'accessorKey' in c && c.accessorKey)
.map((c) => ({
id: ('accessorKey' in c ? String(c.accessorKey) : c.id) as string,
label: typeof c.header === 'string' ? c.header : ('accessorKey' in c ? String(c.accessorKey) : '') ?? '',
}))
return (
<div className="p-6">
<div className="mb-6">
<h1 className="text-2xl font-semibold text-foreground">
{t('clients.title', 'Müşderiler')}
</h1>
</div>
<DataTableToolbar
searchValue={search}
onSearchChange={(v) => { setSearch(v); setPage(1) }}
searchPlaceholder={t('common.search', 'Gözlemek')}
columns={columnMetas}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
filterFields={[
{
id: 'isActive',
label: t('clients.fields.isActive', 'Işjeň'),
options: [
{ value: 'true', label: t('common.active', 'Işjeň') },
{ value: 'false', label: t('common.inactive', 'Işjeň däl') },
],
},
]}
activeFilters={[{ fieldId: 'isActive', value: isActiveFilter }]}
onFilterChange={(fieldId, value) => {
if (fieldId === 'isActive') setIsActiveFilter(value)
setPage(1)
}}
onFilterReset={() => { setIsActiveFilter(''); setPage(1) }}
perPageOptions={[10, 25, 50, 100]}
perPage={perPage}
onPerPageChange={(v) => { setPerPage(v); setPage(1) }}
actionLabel={t('clients.createBtn', 'Müşderi dörediň')}
onAction={() => navigate('/clients/create')}
/>
<DataTable
columns={columns}
data={clients}
isLoading={isLoading}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
getRowId={(row) => String(row.id)}
currentPage={page}
totalPages={totalPages}
totalCount={totalCount}
onPageChange={setPage}
enableRowSelection
/>
<AlertDialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('clients.deleteTitle', 'Müşderini pozmak')}</AlertDialogTitle>
<AlertDialogDescription>
{t('clients.deleteConfirm', '{{name}} müşderisini pozmak isleýärsiňizmi? Bu amaly yzyna gaýtaryp bolmaz.', {
name: deleteTarget?.name ?? '',
})}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive hover:bg-destructive/90 text-destructive-foreground"
onClick={() => {
if (deleteTarget) {
deleteMutation.mutate(deleteTarget.id, {
onSuccess: () => setDeleteTarget(null),
})
}
}}
>
{t('common.delete', 'Poz')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}

View File

@@ -0,0 +1,34 @@
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router-dom'
import { ChevronRight } from 'lucide-react'
import { ClientForm } from '@/features/clients/components/clientForm'
export default function ClientCreatePage() {
const { t } = useTranslation()
const navigate = useNavigate()
return (
<div className="p-6">
{/* Breadcrumb */}
<nav className="flex items-center gap-1.5 text-sm text-muted-foreground mb-4">
<span
className="cursor-pointer hover:text-foreground transition-colors"
onClick={() => navigate('/clients')}
>
{t('clients.title', 'Müşderiler')}
</span>
<ChevronRight size={14} />
<span className="text-foreground font-medium">
{t('clients.createTitle', 'Müşderi dörediň')}
</span>
</nav>
{/* Page heading */}
<h1 className="text-2xl font-semibold text-foreground mb-6">
{t('clients.createTitle', 'Müşderi dörediň')}
</h1>
<ClientForm mode="create" />
</div>
)
}

View File

@@ -0,0 +1,37 @@
import { useParams } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { ClientForm } from '@/features/clients/components/clientForm'
import { useClient } from '@/features/clients/hooks/useClients'
export default function ClientEditPage() {
const { id } = useParams<{ id: string }>()
const clientId = Number(id)
const { t } = useTranslation()
const { data: client, isLoading } = useClient(clientId)
return (
<div className="p-6">
{/* Page heading */}
<h1 className="text-2xl font-semibold text-foreground mb-6">
{t('clients.editTitle', 'Müşderi üýtget')}: {client?.name ?? ''}
</h1>
{isLoading ? (
<div className="space-y-3">
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="h-14 bg-muted rounded-xl animate-pulse" />
))}
</div>
) : (
<ClientForm
mode="edit"
initialData={client}
clientId={clientId}
/>
)}
</div>
)
}

View File

@@ -0,0 +1,294 @@
import { useParams, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Pencil, Trash2, ChevronDown, ChevronRight } from 'lucide-react'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Section, InfoRow, AuditLog } from '@/components/viewPageComponents'
import { DataTable, type ColumnDef } from '@/components/dataTable'
import { DataTableToolbar } from '@/components/dataTableToolbar'
import { useClient, useDeleteClient } from '@/features/clients/hooks/useClients'
import type { ClientRole, ClientBranch, ClientAuditLog } from '@/features/clients/api/clientsApi'
export default function ClientDetailPage() {
const { id } = useParams<{ id: string }>()
const clientId = Number(id)
const { t } = useTranslation()
const navigate = useNavigate()
const deleteMutation = useDeleteClient()
const { data: client, isLoading } = useClient(clientId)
const [deleteOpen, setDeleteOpen] = useState(false)
const [roleSearch, setRoleSearch] = useState('')
const [permSearch, setPermSearch] = useState('')
const [branchSearch, setBranchSearch] = useState('')
const [loanSearch, setLoanSearch] = useState('')
const [cardSearch, setCardSearch] = useState('')
const roleColumns: ColumnDef<ClientRole>[] = [
{
accessorKey: 'id',
header: 'ID',
cell: ({ row }) => <span className="text-primary font-semibold text-sm">{row.original.id}</span>,
size: 80,
},
{
accessorKey: 'code',
header: t('roles.fields.code', 'KOD'),
cell: ({ row }) => <span className="text-sm">{row.original.code}</span>,
},
{
accessorKey: 'name',
header: t('roles.fields.name', 'ADY'),
cell: ({ row }) => <span className="text-sm">{row.original.name}</span>,
},
{
accessorKey: 'guardName',
header: t('roles.fields.guardName', 'GUARD NAME'),
cell: ({ row }) => <span className="text-sm">{row.original.guardName}</span>,
},
{
id: 'actions',
header: '',
cell: () => (
<div className="flex items-center gap-1 justify-end">
<Button size="icon" variant="ghost" className="h-7 w-7 text-muted-foreground hover:text-destructive">
<Trash2 size={13} />
</Button>
</div>
),
size: 60,
},
]
const branchColumns: ColumnDef<ClientBranch>[] = [
{
accessorKey: 'id',
header: 'ID',
cell: ({ row }) => <span className="text-primary font-semibold text-sm">{row.original.id}</span>,
size: 60,
},
{
accessorKey: 'name',
header: t('branches.fields.name', 'ADY'),
cell: ({ row }) => <span className="text-sm">{row.original.name}</span>,
},
{
accessorKey: 'region',
header: t('branches.fields.region', 'WELAÝAT'),
cell: ({ row }) => <span className="text-sm">{row.original.region}</span>,
},
{
accessorKey: 'district',
header: t('branches.fields.district', 'ETRAP'),
cell: ({ row }) => <span className="text-sm">{row.original.district}</span>,
},
{
accessorKey: 'uniqueCode',
header: t('branches.fields.uniqueCode', 'UNIKAL BELGI'),
cell: ({ row }) => <span className="text-sm">{row.original.uniqueCode}</span>,
},
{
id: 'actions',
header: '',
cell: () => (
<div className="flex items-center gap-1 justify-end">
<Button size="icon" variant="ghost" className="h-7 w-7 text-muted-foreground hover:text-destructive">
<Trash2 size={13} />
</Button>
</div>
),
size: 60,
},
]
if (isLoading) {
return (
<div className="p-6 space-y-4">
{Array.from({ length: 3 }).map((_, i) => (
<div key={i} className="h-16 bg-muted rounded-xl animate-pulse" />
))}
</div>
)
}
if (!client) return null
const auditLogs = (client.auditLogs ?? []).map((log: ClientAuditLog) => ({
id: String(log.id),
action: log.actionName,
by: log.performedBy,
target: log.target,
status: log.status,
date: log.createdAt,
}))
const filteredRoles = (client.roles ?? []).filter((r) =>
r.name.toLowerCase().includes(roleSearch.toLowerCase()) || r.code.toLowerCase().includes(roleSearch.toLowerCase()),
)
const filteredBranches = (client.branches ?? []).filter((b) =>
b.name.toLowerCase().includes(branchSearch.toLowerCase()),
)
return (
<div className="p-6">
<nav className="flex items-center gap-1.5 text-sm text-muted-foreground mb-4">
<span className="cursor-pointer hover:text-foreground transition-colors" onClick={() => navigate('/clients')}>
{t('clients.title', 'Müşderiler')}
</span>
<ChevronRight size={14} />
<span className="text-foreground font-medium">
{t('clients.detailTitle', 'Müşderi giňişleýin')}
</span>
</nav>
<div className="flex items-center justify-between mb-6">
<h1 className="text-2xl font-semibold text-foreground">
{t('clients.detailTitle', 'Müşderi giňişleýin')}: {client.name}
</h1>
<div className="flex items-center gap-2">
<Button size="icon" variant="ghost" className="h-8 w-8 text-muted-foreground hover:text-destructive" onClick={() => setDeleteOpen(true)}>
<Trash2 size={15} />
</Button>
<Button size="icon" variant="ghost" className="h-8 w-8 text-muted-foreground hover:text-foreground" onClick={() => navigate(`/clients/${clientId}/edit`)}>
<Pencil size={15} />
</Button>
</div>
</div>
<Section>
<InfoRow label="ID" value={client.id} />
<InfoRow label={t('clients.fields.username', 'Ulanyjy ady')} value={client.username} />
<InfoRow label={t('clients.fields.name', 'Ady')} value={client.name} />
<InfoRow label={t('clients.fields.phone', 'Telefon')} value={client.phone ?? '—'} />
<InfoRow label={t('clients.fields.email', 'E-poçta')} value={client.email ?? '—'} />
<InfoRow label={t('clients.fields.isActive', 'Işjeň')}>
{client.isActive ? (
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-primary text-primary">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M2 6l3 3 5-5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</span>
) : (
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-destructive text-destructive">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M3 3l6 6M9 3l-6 6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
</svg>
</span>
)}
</InfoRow>
</Section>
<CollapsibleSection title={t('clients.sections.roles', 'Rollar')} actionLabel={t('clients.addRole', 'Rol birikdiriň')} onAction={() => {}}>
<DataTableToolbar searchValue={roleSearch} onSearchChange={setRoleSearch} searchPlaceholder={t('common.search', 'Gözlemek')} columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}} columnOrder={[]} onColumnOrderChange={() => {}} hideAction />
{(filteredRoles.length > 0) ? (
<DataTable columns={roleColumns} data={filteredRoles} getRowId={(r) => String(r.id)} enableRowSelection />
) : (
<EmptyState label={t('clients.noRoles', 'Berlen kriterýalara Rol gabat gelmedi.')} actionLabel={t('clients.addRole', 'Rol birikdiriň')} onAction={() => {}} />
)}
</CollapsibleSection>
<CollapsibleSection title={t('clients.sections.permissions', 'Rugsatlar')} actionLabel={t('clients.addPermission', 'Rugsat birikdiriň')} onAction={() => {}}>
<DataTableToolbar searchValue={permSearch} onSearchChange={setPermSearch} searchPlaceholder={t('common.search', 'Gözlemek')} columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}} columnOrder={[]} onColumnOrderChange={() => {}} hideAction />
{(client.permissions ?? []).length === 0 ? (
<EmptyState label={t('clients.noPermissions', 'Berlen kriterýalara Rugsat gabat gelmedi.')} actionLabel={t('clients.addPermission', 'Rugsat birikdiriň')} onAction={() => {}} />
) : null}
</CollapsibleSection>
<CollapsibleSection title={t('clients.sections.branches', 'Şahamçalar')} actionLabel={t('clients.addBranch', 'Şahamça birikdiriň')} onAction={() => {}}>
<DataTableToolbar searchValue={branchSearch} onSearchChange={setBranchSearch} searchPlaceholder={t('common.search', 'Gözlemek')} columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}} columnOrder={[]} onColumnOrderChange={() => {}} hideAction />
{(filteredBranches.length > 0) ? (
<DataTable columns={branchColumns} data={filteredBranches} getRowId={(r) => String(r.id)} enableRowSelection />
) : (
<EmptyState label={t('clients.noBranches', 'Berlen kriterýalara Şahamça gabat gelmedi.')} actionLabel={t('clients.addBranch', 'Şahamça birikdiriň')} onAction={() => {}} />
)}
</CollapsibleSection>
<CollapsibleSection title={t('clients.sections.loanOrders', 'Karz sargyt')} actionLabel={t('clients.addLoanOrder', 'Karz sargyt dörediň')} onAction={() => {}}>
<DataTableToolbar searchValue={loanSearch} onSearchChange={setLoanSearch} searchPlaceholder={t('common.search', 'Gözlemek')} columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}} columnOrder={[]} onColumnOrderChange={() => {}} hideAction />
{(client.loanOrders ?? []).length === 0 ? (
<EmptyState label={t('clients.noLoanOrders', 'Berlen kriterýalara Karz sargyt gabat gelmedi.')} actionLabel={t('clients.addLoanOrder', 'Karz sargyt dörediň')} onAction={() => {}} />
) : null}
</CollapsibleSection>
<CollapsibleSection title={t('clients.sections.cardOrders', 'Kart sargyt')} actionLabel={t('clients.addCardOrder', 'Kart sargyt dörediň')} onAction={() => {}}>
<DataTableToolbar searchValue={cardSearch} onSearchChange={setCardSearch} searchPlaceholder={t('common.search', 'Gözlemek')} columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}} columnOrder={[]} onColumnOrderChange={() => {}} hideAction />
{(client.cardOrders ?? []).length === 0 ? (
<EmptyState label={t('clients.noCardOrders', 'Berlen kriterýalara Kart sargyt gabat gelmedi.')} actionLabel={t('clients.addCardOrder', 'Kart sargyt dörediň')} onAction={() => {}} />
) : null}
</CollapsibleSection>
<AuditLog logs={auditLogs} />
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('clients.deleteTitle', 'Müşderini pozmak')}</AlertDialogTitle>
<AlertDialogDescription>
{t('clients.deleteConfirm', '{{name}} müşderisini pozmak isleýärsiňizmi?', { name: client.name })}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogAction className="bg-destructive hover:bg-destructive/90 text-destructive-foreground" onClick={() => deleteMutation.mutate(clientId, { onSuccess: () => navigate('/clients') })}>
{t('common.delete', 'Poz')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}
interface CollapsibleSectionProps { title: string; actionLabel: string; onAction: () => void; children: React.ReactNode }
function CollapsibleSection({ title, actionLabel, onAction, children }: CollapsibleSectionProps) {
const [open, setOpen] = useState(true)
return (
<div className="mb-6">
<div className="flex items-center justify-between mb-2 cursor-pointer select-none w-fit gap-2" onClick={() => setOpen((v) => !v)}>
<h2 className="text-base font-semibold text-foreground">{title}</h2>
<ChevronDown size={15} className={`text-muted-foreground transition-transform duration-200 ${open ? '' : '-rotate-90'}`} />
</div>
{open && (
<div className="bg-card border border-border rounded-xl overflow-hidden p-4 space-y-3">
<div className="flex justify-end">
<Button size="sm" className="bg-primary hover:bg-primary/90 text-primary-foreground h-8 text-xs" onClick={onAction}>
{actionLabel}
</Button>
</div>
{children}
</div>
)}
</div>
)
}
interface EmptyStateProps { label: string; actionLabel: string; onAction: () => void }
function EmptyState({ label, actionLabel, onAction }: EmptyStateProps) {
return (
<div className="flex flex-col items-center justify-center py-12 gap-4">
<div className="w-16 h-16 rounded-full bg-muted flex items-center justify-center">
<svg width="32" height="32" viewBox="0 0 32 32" fill="none" className="text-muted-foreground">
<rect x="4" y="8" width="24" height="18" rx="2" stroke="currentColor" strokeWidth="1.5" />
<path d="M4 13h24" stroke="currentColor" strokeWidth="1.5" />
<path d="M10 8V6M22 8V6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
<circle cx="16" cy="20" r="3" stroke="currentColor" strokeWidth="1.5" />
<path d="M19 23l2 2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
</div>
<p className="text-sm text-muted-foreground text-center">{label}</p>
<Button size="sm" variant="outline" className="h-8 text-xs" onClick={onAction}>{actionLabel}</Button>
</div>
)
}

View File

@@ -0,0 +1,271 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Trash2, Eye, Pencil } from 'lucide-react'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Button } from '@/components/ui/button'
import { DataTable, type ColumnDef } from '@/components/dataTable'
import { DataTableToolbar } from '@/components/dataTableToolbar'
import { useOperators, useDeleteOperator } from '@/features/operators/hooks/useOperators'
import type { Operator } from '@/features/operators/api/operatorsApi'
// ─── OperatorsPage ────────────────────────────────────────────────────────────
export default function OperatorsPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const deleteMutation = useDeleteOperator()
// ── Table state ─────────────────────────────────────────────────────────────
const [page, setPage] = useState(1)
const [perPage, setPerPage] = useState(25)
const [search, setSearch] = useState('')
const [isActiveFilter, setIsActiveFilter] = useState('')
const [columnVisibility, setColumnVisibility] = useState({})
const [columnOrder, setColumnOrder] = useState<string[]>([])
// ── Delete dialog ────────────────────────────────────────────────────────────
const [deleteTarget, setDeleteTarget] = useState<Operator | null>(null)
// ── Query ────────────────────────────────────────────────────────────────────
const { data, isLoading } = useOperators({
page,
perPage,
search: search || undefined,
isActive: isActiveFilter || undefined,
})
const operators = data?.data ?? []
const totalPages = data?.meta.totalPages ?? 1
const totalCount = data?.meta.totalCount ?? 0
// ── Columns ──────────────────────────────────────────────────────────────────
const columns: ColumnDef<Operator>[] = [
{
accessorKey: 'id',
header: 'ID',
cell: ({ row }) => (
<span
className="text-primary font-semibold cursor-pointer hover:underline text-sm"
onClick={() => navigate(`/operators/${row.original.id}`)}
>
{row.original.id}
</span>
),
size: 80,
},
{
accessorKey: 'username',
header: t('operators.fields.username', 'ULANYJY ADY'),
cell: ({ row }) => (
<span className="text-sm text-foreground">{row.original.username}</span>
),
},
{
accessorKey: 'name',
header: t('operators.fields.name', 'ADY'),
cell: ({ row }) => (
<span className="text-sm text-foreground">{row.original.name}</span>
),
},
{
accessorKey: 'phone',
header: t('operators.fields.phone', 'TELEFON'),
cell: ({ row }) => (
<span className="text-sm text-foreground">
{row.original.phone ?? '—'}
</span>
),
},
{
accessorKey: 'email',
header: t('operators.fields.email', 'E-POÇTA'),
cell: ({ row }) => (
<span className="text-sm text-foreground">
{row.original.email ?? '—'}
</span>
),
},
{
accessorKey: 'isActive',
header: t('operators.fields.isActive', 'IŞJEŇ'),
cell: ({ row }) =>
row.original.isActive ? (
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-primary text-primary">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path
d="M2 6l3 3 5-5"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</span>
) : (
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-destructive text-destructive">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path
d="M3 3l6 6M9 3l-6 6"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
/>
</svg>
</span>
),
size: 80,
},
{
id: 'actions',
header: '',
cell: ({ row }) => (
<div className="flex items-center gap-1 justify-end">
<Button
size="icon"
variant="ghost"
className="h-7 w-7 text-muted-foreground hover:text-foreground"
onClick={() => navigate(`/operators/${row.original.id}`)}
>
<Eye size={14} />
</Button>
<Button
size="icon"
variant="ghost"
className="h-7 w-7 text-muted-foreground hover:text-foreground"
onClick={() => navigate(`/operators/${row.original.id}/edit`)}
>
<Pencil size={14} />
</Button>
<Button
size="icon"
variant="ghost"
className="h-7 w-7 text-muted-foreground hover:text-destructive"
onClick={() => setDeleteTarget(row.original)}
>
<Trash2 size={14} />
</Button>
</div>
),
size: 120,
enableSorting: false,
},
]
const columnMetas = columns
.filter((c) => 'accessorKey' in c && c.accessorKey)
.map((c) => ({
id: ('accessorKey' in c ? String(c.accessorKey) : c.id) as string,
label:
typeof c.header === 'string'
? c.header
: ('accessorKey' in c ? String(c.accessorKey) : '') ?? '',
}))
// ── Render ───────────────────────────────────────────────────────────────────
return (
<div className="p-6">
{/* Page header */}
<div className="mb-6">
<h1 className="text-2xl font-semibold text-foreground">
{t('operators.title', 'Operatorlar')}
</h1>
</div>
{/* Toolbar */}
<DataTableToolbar
searchValue={search}
onSearchChange={(v) => { setSearch(v); setPage(1) }}
searchPlaceholder={t('common.search', 'Gözlemek')}
columns={columnMetas}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
filterFields={[
{
id: 'isActive',
label: t('operators.fields.isActive', 'Işjeň'),
options: [
{ value: 'true', label: t('common.active', 'Işjeň') },
{ value: 'false', label: t('common.inactive', 'Işjeň däl') },
],
},
]}
activeFilters={[{ fieldId: 'isActive', value: isActiveFilter }]}
onFilterChange={(fieldId, value) => {
if (fieldId === 'isActive') setIsActiveFilter(value)
setPage(1)
}}
onFilterReset={() => { setIsActiveFilter(''); setPage(1) }}
perPageOptions={[10, 25, 50, 100]}
perPage={perPage}
onPerPageChange={(v) => { setPerPage(v); setPage(1) }}
actionLabel={t('operators.createBtn', 'Operator döredin')}
onAction={() => navigate('/operators/create')}
/>
{/* Table */}
<DataTable
columns={columns}
data={operators}
isLoading={isLoading}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
getRowId={(row) => String(row.id)}
currentPage={page}
totalPages={totalPages}
totalCount={totalCount}
onPageChange={setPage}
enableRowSelection
/>
{/* Delete dialog */}
<AlertDialog
open={!!deleteTarget}
onOpenChange={(open) => !open && setDeleteTarget(null)}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t('operators.deleteTitle', 'Operatory pozmak')}
</AlertDialogTitle>
<AlertDialogDescription>
{t(
'operators.deleteConfirm',
'{{name}} operatoryny pozmak isleýärsiňizmi? Bu amaly yzyna gaýtaryp bolmaz.',
{ name: deleteTarget?.name ?? '' },
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive hover:bg-destructive/90 text-destructive-foreground"
onClick={() => {
if (deleteTarget) {
deleteMutation.mutate(deleteTarget.id, {
onSuccess: () => setDeleteTarget(null),
})
}
}}
>
{t('common.delete', 'Poz')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}

View File

@@ -0,0 +1,36 @@
// ─── OperatorCreatePage.tsx ───────────────────────────────────────────────────
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router-dom'
import { ChevronRight } from 'lucide-react'
import { OperatorForm } from '@/features/operators/components/operatorForms'
export default function OperatorCreatePage() {
const { t } = useTranslation()
const navigate = useNavigate()
return (
<div className="p-6">
{/* Breadcrumb */}
<nav className="flex items-center gap-1.5 text-sm text-muted-foreground mb-4">
<span
className="cursor-pointer hover:text-foreground transition-colors"
onClick={() => navigate('/operators')}
>
{t('operators.title', 'Operatorlar')}
</span>
<ChevronRight size={14} />
<span className="text-foreground font-medium">
{t('operators.createTitle', 'Operator döredin')}
</span>
</nav>
{/* Page heading */}
<h1 className="text-2xl font-semibold text-foreground mb-6">
{t('operators.createTitle', 'Operator döredin')}
</h1>
<OperatorForm mode="create" />
</div>
)
}

View File

@@ -0,0 +1,37 @@
// ─── OperatorEditPage.tsx ─────────────────────────────────────────────────────
import { useParams, } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { OperatorForm } from '@/features/operators/components/operatorForms'
import { useOperator } from '@/features/operators/hooks/useOperators'
export default function OperatorEditPage() {
const { id } = useParams<{ id: string }>()
const operatorId = Number(id)
const { t } = useTranslation()
const { data: operator, isLoading } = useOperator(operatorId)
return (
<div className="p-6">
{/* Page heading */}
<h1 className="text-2xl font-semibold text-foreground mb-6">
{t('operators.editTitle', 'Operator üýtget')}: {operator?.name ?? ''}
</h1>
{isLoading ? (
<div className="space-y-3">
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="h-14 bg-muted rounded-xl animate-pulse" />
))}
</div>
) : (
<OperatorForm
mode="edit"
initialData={operator}
operatorId={operatorId}
/>
)}
</div>
)
}

View File

@@ -0,0 +1,457 @@
import { useParams, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Pencil, Trash2, ChevronDown } from 'lucide-react'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Section, InfoRow, AuditLog } from '@/components/viewPageComponents'
import { DataTable, type ColumnDef } from '@/components/dataTable'
import { DataTableToolbar } from '@/components/dataTableToolbar'
import { useOperator, useDeleteOperator } from '@/features/operators/hooks/useOperators'
import type { OperatorRole, OperatorBranch, OperatorAuditLog } from '@/features/operators/api/operatorsApi'
// ─── OperatorDetailPage ───────────────────────────────────────────────────────
export default function OperatorDetailPage() {
const { id } = useParams<{ id: string }>()
const operatorId = Number(id)
const { t } = useTranslation()
const navigate = useNavigate()
const deleteMutation = useDeleteOperator()
const { data: operator, isLoading } = useOperator(operatorId)
const [deleteOpen, setDeleteOpen] = useState(false)
const [roleSearch, setRoleSearch] = useState('')
const [permSearch, setPermSearch] = useState('')
const [branchSearch, setBranchSearch] = useState('')
// ── Role columns ──────────────────────────────────────────────────────────
const roleColumns: ColumnDef<OperatorRole>[] = [
{
accessorKey: 'id',
header: 'ID',
cell: ({ row }) => (
<span className="text-primary font-semibold text-sm">{row.original.id}</span>
),
size: 80,
},
{
accessorKey: 'code',
header: t('roles.fields.code', 'KOD'),
cell: ({ row }) => <span className="text-sm">{row.original.code}</span>,
},
{
accessorKey: 'name',
header: t('roles.fields.name', 'ADY'),
cell: ({ row }) => <span className="text-sm">{row.original.name}</span>,
},
{
accessorKey: 'guardName',
header: t('roles.fields.guardName', 'GUARD NAME'),
cell: ({ row }) => <span className="text-sm">{row.original.guardName}</span>,
},
{
id: 'actions',
header: '',
cell: ({ row }) => (
<div className="flex items-center gap-1 justify-end">
<Button
size="icon"
variant="ghost"
className="h-7 w-7 text-muted-foreground hover:text-foreground"
onClick={() => navigate(`/roles/${row.original.id}`)}
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
</Button>
<Button
size="icon"
variant="ghost"
className="h-7 w-7 text-muted-foreground hover:text-foreground"
>
<Pencil size={13} />
</Button>
<Button
size="icon"
variant="ghost"
className="h-7 w-7 text-muted-foreground hover:text-destructive"
>
<Trash2 size={13} />
</Button>
</div>
),
size: 120,
},
]
// ── Branch columns ────────────────────────────────────────────────────────
const branchColumns: ColumnDef<OperatorBranch>[] = [
{
accessorKey: 'id',
header: 'ID',
cell: ({ row }) => (
<span className="text-primary font-semibold text-sm">{row.original.id}</span>
),
size: 60,
},
{
accessorKey: 'name',
header: t('branches.fields.name', 'ADY'),
cell: ({ row }) => <span className="text-sm">{row.original.name}</span>,
},
{
accessorKey: 'region',
header: t('branches.fields.region', 'WELAÝAT'),
cell: ({ row }) => <span className="text-sm">{row.original.region}</span>,
},
{
accessorKey: 'district',
header: t('branches.fields.district', 'ETRAP'),
cell: ({ row }) => <span className="text-sm">{row.original.district}</span>,
},
{
accessorKey: 'uniqueCode',
header: t('branches.fields.uniqueCode', 'UNIKAL BELGI'),
cell: ({ row }) => <span className="text-sm">{row.original.uniqueCode}</span>,
},
{
accessorKey: 'isActive',
header: t('branches.fields.isActive', 'IŞJEŇ'),
cell: ({ row }) =>
row.original.isActive ? (
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-primary text-primary">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M2 6l3 3 5-5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</span>
) : (
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-destructive text-destructive">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M3 3l6 6M9 3l-6 6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
</svg>
</span>
),
size: 80,
},
{
accessorKey: 'billingUsernameIbr',
header: t('branches.fields.billingIbr', 'BILLING ULANYJY ADY'),
cell: ({ row }) => <span className="text-sm font-mono text-xs">{row.original.billingUsernameIbr}</span>,
},
{
accessorKey: 'billingUsernameSber',
header: t('branches.fields.billingSber', 'BILLING USERNAME (SBER)'),
cell: ({ row }) => <span className="text-sm font-mono text-xs">{row.original.billingUsernameSber}</span>,
},
{
accessorKey: 'billingUsernameVisa',
header: t('branches.fields.billingVisa', 'BILLING USERNAME (VISA)'),
cell: ({ row }) => <span className="text-sm font-mono text-xs">{row.original.billingUsernameVisa}</span>,
},
{
id: 'actions',
header: '',
cell: () => (
<div className="flex items-center gap-1 justify-end">
<Button size="icon" variant="ghost" className="h-7 w-7 text-muted-foreground hover:text-foreground">
<Trash2 size={13} />
</Button>
</div>
),
size: 60,
},
]
if (isLoading) {
return (
<div className="p-6 space-y-4">
{Array.from({ length: 3 }).map((_, i) => (
<div key={i} className="h-16 bg-muted rounded-xl animate-pulse" />
))}
</div>
)
}
if (!operator) return null
// Map audit logs to AuditLog component format
const auditLogs = (operator.auditLogs ?? []).map((log: OperatorAuditLog) => ({
id: String(log.id),
action: log.actionName,
by: log.performedBy,
target: log.target,
status: log.status,
date: log.createdAt,
}))
const filteredRoles = (operator.roles ?? []).filter(
(r) =>
r.name.toLowerCase().includes(roleSearch.toLowerCase()) ||
r.code.toLowerCase().includes(roleSearch.toLowerCase()),
)
const filteredBranches = (operator.branches ?? []).filter((b) =>
b.name.toLowerCase().includes(branchSearch.toLowerCase()),
)
return (
<div className="p-6">
{/* Page header */}
<div className="flex items-center justify-between mb-6">
<h1 className="text-2xl font-semibold text-foreground">
{t('operators.detailTitle', 'Operator giňişleýin')}: {operator.name}
</h1>
<div className="flex items-center gap-2">
<Button
size="icon"
variant="ghost"
className="h-8 w-8 text-muted-foreground hover:text-destructive"
onClick={() => setDeleteOpen(true)}
>
<Trash2 size={15} />
</Button>
<Button
size="icon"
variant="ghost"
className="h-8 w-8 text-muted-foreground hover:text-foreground"
onClick={() => navigate(`/operators/${operatorId}/edit`)}
>
<Pencil size={15} />
</Button>
</div>
</div>
{/* Basic info */}
<Section>
<InfoRow label="ID" value={operator.id} />
<InfoRow label={t('operators.fields.username', 'Ulanyjy ady')} value={operator.username} />
<InfoRow label={t('operators.fields.name', 'Ady')} value={operator.name} />
<InfoRow label={t('operators.fields.phone', 'Telefon')} value={operator.phone ?? '—'} />
<InfoRow label={t('operators.fields.email', 'E-poçta')} value={operator.email ?? '—'} />
<InfoRow label={t('operators.fields.isActive', 'Işjeň')}>
{operator.isActive ? (
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-primary text-primary">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M2 6l3 3 5-5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</span>
) : (
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-destructive text-destructive">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M3 3l6 6M9 3l-6 6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
</svg>
</span>
)}
</InfoRow>
</Section>
{/* Roles */}
<CollapsibleSection
title={t('operators.sections.roles', 'Rollar')}
actionLabel={t('operators.addRole', 'Rol birikdiriň')}
onAction={() => {/* open role assign modal */}}
>
<DataTableToolbar
searchValue={roleSearch}
onSearchChange={setRoleSearch}
searchPlaceholder={t('common.search', 'Gözlemek')}
columns={[]}
columnVisibility={{}}
onColumnVisibilityChange={() => {}}
columnOrder={[]}
onColumnOrderChange={() => {}}
hideAction
/>
<DataTable
columns={roleColumns}
data={filteredRoles}
getRowId={(r) => String(r.id)}
enableRowSelection
/>
</CollapsibleSection>
{/* Permissions */}
<CollapsibleSection
title={t('operators.sections.permissions', 'Rugsatlar')}
actionLabel={t('operators.addPermission', 'Rugsat birikdiriň')}
onAction={() => {/* open permission modal */}}
>
<DataTableToolbar
searchValue={permSearch}
onSearchChange={setPermSearch}
searchPlaceholder={t('common.search', 'Gözlemek')}
columns={[]}
columnVisibility={{}}
onColumnVisibilityChange={() => {}}
columnOrder={[]}
onColumnOrderChange={() => {}}
hideAction
/>
{(operator.permissions ?? []).length === 0 ? (
<EmptyState label={t('operators.noPermissions', 'Berlen kriterýalara Rugsat gabat gelmedi.')} actionLabel={t('operators.addPermission', 'Rugsat birikdiriň')} onAction={() => {}} />
) : null}
</CollapsibleSection>
{/* Branches */}
<CollapsibleSection
title={t('operators.sections.branches', 'Şahamçalar')}
actionLabel={t('operators.addBranch', 'Şahamça birikdiriň')}
onAction={() => {}}
>
<DataTableToolbar
searchValue={branchSearch}
onSearchChange={setBranchSearch}
searchPlaceholder={t('common.search', 'Gözlemek')}
columns={[]}
columnVisibility={{}}
onColumnVisibilityChange={() => {}}
columnOrder={[]}
onColumnOrderChange={() => {}}
hideAction
/>
<DataTable
columns={branchColumns}
data={filteredBranches}
getRowId={(r) => String(r.id)}
enableRowSelection
/>
</CollapsibleSection>
{/* Karz sargyt */}
<CollapsibleSection
title={t('operators.sections.loanLimits', 'Karz sargyt')}
actionLabel={t('operators.addLoanLimit', 'Karz sargyt döredin')}
onAction={() => {}}
>
{(operator.loanLimits ?? []).length === 0 ? (
<EmptyState label={t('operators.noLoanLimits', 'Berlen kriterýalara Karz sargyt gabat gelmedi.')} actionLabel={t('operators.addLoanLimit', 'Karz sargyt döredin')} onAction={() => {}} />
) : null}
</CollapsibleSection>
{/* Kart sargyt */}
<CollapsibleSection
title={t('operators.sections.cardLimits', 'Kart sargyt')}
actionLabel={t('operators.addCardLimit', 'Kart sargyt döredin')}
onAction={() => {}}
>
{(operator.cardLimits ?? []).length === 0 ? (
<EmptyState label={t('operators.noCardLimits', 'Berlen kriterýalara Kart sargyt gabat gelmedi.')} actionLabel={t('operators.addCardLimit', 'Kart sargyt döredin')} onAction={() => {}} />
) : null}
</CollapsibleSection>
{/* Audit log */}
<AuditLog logs={auditLogs} />
{/* Delete dialog */}
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('operators.deleteTitle', 'Operatory pozmak')}</AlertDialogTitle>
<AlertDialogDescription>
{t('operators.deleteConfirm', '{{name}} operatoryny pozmak isleýärsiňizmi?', {
name: operator.name,
})}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive hover:bg-destructive/90 text-destructive-foreground"
onClick={() =>
deleteMutation.mutate(operatorId, {
onSuccess: () => navigate('/operators'),
})
}
>
{t('common.delete', 'Poz')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}
// ─── CollapsibleSection ───────────────────────────────────────────────────────
interface CollapsibleSectionProps {
title: string
actionLabel: string
onAction: () => void
children: React.ReactNode
}
function CollapsibleSection({ title, actionLabel, onAction, children }: CollapsibleSectionProps) {
const [open, setOpen] = useState(true)
return (
<div className="mb-6">
<div
className="flex items-center justify-between mb-2 cursor-pointer select-none w-fit gap-2"
onClick={() => setOpen((v) => !v)}
>
<h2 className="text-base font-semibold text-foreground">{title}</h2>
<ChevronDown
size={15}
className={`text-muted-foreground transition-transform duration-200 ${open ? '' : '-rotate-90'}`}
/>
</div>
{open && (
<div className="bg-card border border-border rounded-xl overflow-hidden p-4 space-y-3">
<div className="flex justify-end">
<Button
size="sm"
className="bg-primary hover:bg-primary/90 text-primary-foreground h-8 text-xs"
onClick={onAction}
>
{actionLabel}
</Button>
</div>
{children}
</div>
)}
</div>
)
}
// ─── EmptyState ───────────────────────────────────────────────────────────────
interface EmptyStateProps {
label: string
actionLabel: string
onAction: () => void
}
function EmptyState({ label, actionLabel, onAction }: EmptyStateProps) {
return (
<div className="flex flex-col items-center justify-center py-12 gap-4">
<div className="w-16 h-16 rounded-full bg-muted flex items-center justify-center">
<svg width="32" height="32" viewBox="0 0 32 32" fill="none" className="text-muted-foreground">
<rect x="4" y="8" width="24" height="18" rx="2" stroke="currentColor" strokeWidth="1.5" />
<path d="M4 13h24" stroke="currentColor" strokeWidth="1.5" />
<path d="M10 8V6M22 8V6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
<circle cx="16" cy="20" r="3" stroke="currentColor" strokeWidth="1.5" />
<path d="M19 23l2 2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
</div>
<p className="text-sm text-muted-foreground text-center">{label}</p>
<Button
size="sm"
variant="outline"
className="h-8 text-xs"
onClick={onAction}
>
{actionLabel}
</Button>
</div>
)
}