From ab7fdf46b3a3a77235aec4510317029ea27b55d8 Mon Sep 17 00:00:00 2001 From: Jelaletdin12 Date: Sun, 10 May 2026 23:31:01 +0500 Subject: [PATCH] added users pages, stepper --- PROJECT_STANDARDS.md | 1 + package-lock.json | 45 +- src/app/router/index.tsx | 114 ++++ src/components/formInput.tsx | 2 +- src/components/stepBar.tsx | 215 ++++++ src/components/stepBarV2.tsx | 109 +++ src/components/ui/label.tsx | 22 + src/features/allUsers/api/allUsersApi.ts | 198 ++++++ .../allUsers/components/allUsersForm.tsx | 326 +++++++++ src/features/allUsers/hooks/useAllUsers.ts | 94 +++ src/features/clients/api/clientsApi.ts | 267 ++++++++ .../clients/components/clientForm.tsx | 255 +++++++ src/features/clients/hooks/useClients.ts | 148 ++++ .../loanOrders/components/loanOrderForm.tsx | 645 ++++++------------ src/features/operators/api/operatorsApi.ts | 234 +++++++ .../operators/components/operatorForms.tsx | 253 +++++++ src/features/operators/hooks/useOperators.ts | 130 ++++ src/layouts/DashboardLayout.tsx | 6 +- src/pages/users/allUsers/index.tsx | 281 ++++++++ src/pages/users/allUsersCreate/index.tsx | 44 ++ src/pages/users/allUsersEdit/index.tsx | 45 ++ src/pages/users/allUsersView/index.tsx | 284 ++++++++ src/pages/users/clients/index.tsx | 227 ++++++ src/pages/users/clientsCreate/index.tsx | 34 + src/pages/users/clientsEdit/index.tsx | 37 + src/pages/users/clientsView/index.tsx | 294 ++++++++ src/pages/users/operators/index.tsx | 271 ++++++++ src/pages/users/operatorsCreate/index.tsx | 36 + src/pages/users/operatorsEdit/index.tsx | 37 + src/pages/users/operatorsView/index.tsx | 457 +++++++++++++ 30 files changed, 4665 insertions(+), 446 deletions(-) create mode 100644 src/components/stepBar.tsx create mode 100644 src/components/stepBarV2.tsx create mode 100644 src/components/ui/label.tsx create mode 100644 src/features/allUsers/api/allUsersApi.ts create mode 100644 src/features/allUsers/components/allUsersForm.tsx create mode 100644 src/features/allUsers/hooks/useAllUsers.ts create mode 100644 src/features/clients/api/clientsApi.ts create mode 100644 src/features/clients/components/clientForm.tsx create mode 100644 src/features/clients/hooks/useClients.ts create mode 100644 src/features/operators/api/operatorsApi.ts create mode 100644 src/features/operators/components/operatorForms.tsx create mode 100644 src/features/operators/hooks/useOperators.ts create mode 100644 src/pages/users/allUsers/index.tsx create mode 100644 src/pages/users/allUsersCreate/index.tsx create mode 100644 src/pages/users/allUsersEdit/index.tsx create mode 100644 src/pages/users/allUsersView/index.tsx create mode 100644 src/pages/users/clients/index.tsx create mode 100644 src/pages/users/clientsCreate/index.tsx create mode 100644 src/pages/users/clientsEdit/index.tsx create mode 100644 src/pages/users/clientsView/index.tsx create mode 100644 src/pages/users/operators/index.tsx create mode 100644 src/pages/users/operatorsCreate/index.tsx create mode 100644 src/pages/users/operatorsEdit/index.tsx create mode 100644 src/pages/users/operatorsView/index.tsx diff --git a/PROJECT_STANDARDS.md b/PROJECT_STANDARDS.md index 5006130..6dae3ed 100644 --- a/PROJECT_STANDARDS.md +++ b/PROJECT_STANDARDS.md @@ -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]/ diff --git a/package-lock.json b/package-lock.json index 764c914..b5489ce 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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" } diff --git a/src/app/router/index.tsx b/src/app/router/index.tsx index 4e5d1e8..f6e05f9 100644 --- a/src/app/router/index.tsx +++ b/src/app/router/index.tsx @@ -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 ; @@ -481,6 +499,102 @@ export const router = createBrowserRouter([ ), }, + { // Sidebar: /operators + path: "/operators", + element: ( + }> + + + ), + }, + { + path: "/operators/create", + element: ( + }> + + + ), + }, + { + path: "/operators/:id", + element: ( + }> + + + ), + }, + { + path: "/operators/:id/edit", + element: ( + }> + + + ), + }, + { // Sidebar: /all-users + path: "/all-users", + element: ( + }> + + + ), + }, + { + path: "/all-users/create", + element: ( + }> + + + ), + }, + { + path: "/all-users/:id", + element: ( + }> + + + ), + }, + { + path: "/all-users/:id/edit", + element: ( + }> + + + ), + }, + { // Sidebar: /clients + path: "/clients", + element: ( + }> + + + ), + }, + { + path: "/clients/create", + element: ( + }> + + + ), + }, + { + path: "/clients/:id", + element: ( + }> + + + ), + }, + { + path: "/clients/:id/edit", + element: ( + }> + + + ), + }, ], }, ], diff --git a/src/components/formInput.tsx b/src/components/formInput.tsx index 1877f9c..9b6d16b 100644 --- a/src/components/formInput.tsx +++ b/src/components/formInput.tsx @@ -182,7 +182,7 @@ function TextInput({ function PhoneInput({ value = '', onChange, - placeholder = '61 097 651', + placeholder = '61 111213', error, disabled, required, diff --git a/src/components/stepBar.tsx b/src/components/stepBar.tsx new file mode 100644 index 0000000..94c2c67 --- /dev/null +++ b/src/components/stepBar.tsx @@ -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 + if (status === 'error') + return + return ( + + {index + 1} + + ) +} + +// ─── Component ─────────────────────────────────────────────────────────────── + +export function StepBar({ steps, onGoTo, showLabels }: StepBarProps) { + const btnRefs = useRef>([]) + 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, 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 ( + + ) +} \ No newline at end of file diff --git a/src/components/stepBarV2.tsx b/src/components/stepBarV2.tsx new file mode 100644 index 0000000..35b8878 --- /dev/null +++ b/src/components/stepBarV2.tsx @@ -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 ( + + ) +} diff --git a/src/components/ui/label.tsx b/src/components/ui/label.tsx new file mode 100644 index 0000000..f752f82 --- /dev/null +++ b/src/components/ui/label.tsx @@ -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) { + return ( + + ) +} + +export { Label } diff --git a/src/features/allUsers/api/allUsersApi.ts b/src/features/allUsers/api/allUsersApi.ts new file mode 100644 index 0000000..9581a78 --- /dev/null +++ b/src/features/allUsers/api/allUsersApi.ts @@ -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 => { + await delay() + // Uncomment for real API: + // const res = await apiClient.get('/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 => { + await delay() + // const res = await apiClient.get(`/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 => { + await delay(800) + // const res = await apiClient.post('/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 => { + await delay(800) + // const res = await apiClient.put(`/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 => { + 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) + }, +} \ No newline at end of file diff --git a/src/features/allUsers/components/allUsersForm.tsx b/src/features/allUsers/components/allUsersForm.tsx new file mode 100644 index 0000000..3ca16c5 --- /dev/null +++ b/src/features/allUsers/components/allUsersForm.tsx @@ -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({ + username: '', + name: '', + phone: '', + email: '', + password: '', + phoneVerified: false, + isActive: true, + }) + + const [errors, setErrors] = useState({}) + + // 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 = (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 ( +
+ {/* Form card */} +
+ + {/* Username */} +
+
+

+ {t('users.fields.username', 'Ulanyjy ady')} + * +

+

+ {t('users.fields.usernameHint', 'Unikal login ady')} +

+
+ setField('username', v)} + placeholder={t('users.fields.username', 'Ulanyjy ady')} + error={errors.username} + disabled={isPending} + /> +
+ + {/* Full name */} +
+
+

+ {t('users.fields.name', 'Ady')} + * +

+

+ {t('users.fields.nameHint', 'Doly ady we familiýasy')} +

+
+ setField('name', v)} + placeholder={t('users.fields.name', 'Ady')} + error={errors.name} + disabled={isPending} + /> +
+ + {/* Phone */} +
+
+

+ {t('users.fields.phone', 'Telefon')} + * +

+

+ {t('users.fields.phoneHint', '+993 bilen başlanýar')} +

+
+ setField('phone', v)} + placeholder="62-38-49-56" + error={errors.phone} + disabled={isPending} + /> +
+ + {/* Email */} +
+
+

+ {t('users.fields.email', 'E-poçta')} +

+

+ {t('users.fields.emailHint', 'Islege görä')} +

+
+ setField('email', v)} + placeholder={t('users.fields.email', 'E-poçta')} + error={errors.email} + disabled={isPending} + /> +
+ + {/* Password — only in create mode */} + {mode === 'create' && ( +
+
+

+ {t('users.fields.password', 'Açar sözi')} + * +

+

+ {t('users.fields.passwordHint', 'Iň az 6 harp')} +

+
+ setField('password', v)} + placeholder={t('users.fields.password', 'Açar sözi')} + error={errors.password} + disabled={isPending} + /> +
+ )} + + {/* Phone verified */} +
+
+

+ {t('users.fields.phoneVerified', 'Telefon tassyklanan')} +

+

+ {t('users.fields.phoneVerifiedHint', 'SMS arkaly tassyklandy')} +

+
+
+ setField('phoneVerified', !!v)} + disabled={isPending} + /> + +
+
+ + {/* Active */} +
+
+

+ {t('users.fields.isActive', 'Işjeň')} +

+

+ {t('users.fields.isActiveHint', 'Ulanyjynyň ulgama girip-bilmezligi')} +

+
+
+ setField('isActive', !!v)} + disabled={isPending} + /> + +
+
+
+ + {/* Footer actions */} +
+ + +
+
+ ) +} \ No newline at end of file diff --git a/src/features/allUsers/hooks/useAllUsers.ts b/src/features/allUsers/hooks/useAllUsers.ts new file mode 100644 index 0000000..649750e --- /dev/null +++ b/src/features/allUsers/hooks/useAllUsers.ts @@ -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')) + }, + }) +} \ No newline at end of file diff --git a/src/features/clients/api/clientsApi.ts b/src/features/clients/api/clientsApi.ts new file mode 100644 index 0000000..334ea53 --- /dev/null +++ b/src/features/clients/api/clientsApi.ts @@ -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 => { + 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 => { + 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 => { + 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 => { + 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 => { + await delay(500) + mockClients = mockClients.filter((c) => c.id !== Number(id)) + }, + + assignRole: async (_clientId: number, _roleId: number): Promise => { + await delay(500) + }, + + removeRole: async (_clientId: number, _roleId: number): Promise => { + await delay(500) + }, + + assignPermission: async (_clientId: number, _permissionId: number): Promise => { + await delay(500) + }, + + removePermission: async (_clientId: number, _permissionId: number): Promise => { + await delay(500) + }, + + assignBranch: async (_clientId: number, _branchId: number): Promise => { + await delay(500) + }, + + removeBranch: async (_clientId: number, _branchId: number): Promise => { + await delay(500) + }, +} \ No newline at end of file diff --git a/src/features/clients/components/clientForm.tsx b/src/features/clients/components/clientForm.tsx new file mode 100644 index 0000000..25c1979 --- /dev/null +++ b/src/features/clients/components/clientForm.tsx @@ -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({ + username: '', + name: '', + phone: '', + email: '', + password: '', + isActive: true, + }) + + const [errors, setErrors] = useState({}) + + // 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 ( +
+ {/* Username */} +
+ + {t('clients.fields.username', 'Ulanyjy ady')} + * + + +
+ + {/* Name */} +
+ + {t('clients.fields.name', 'Ady')} + * + + +
+ + {/* Phone */} +
+ + {t('clients.fields.phone', 'Telefon')} + * + + +
+ + {/* Email */} +
+ + {t('clients.fields.email', 'E-poçta')} + + +
+ + {/* Password */} +
+ + {t('clients.fields.password', 'Açar sözi')} + {mode === 'create' && *} + +
+ + {mode === 'edit' && ( +

+ {t('clients.fields.passwordEditNote', 'Boş goýsaňyz, açar sözi üýtgemez')} +

+ )} +
+
+ + {/* isActive */} +
+ + {t('clients.fields.isActive', 'Işjeň')} + + setForm((prev) => ({ ...prev, isActive: !!v }))} + disabled={isPending} + className="data-[state=checked]:bg-primary data-[state=checked]:border-primary" + /> +
+ + {/* Actions */} +
+ + +
+
+ ) +} \ No newline at end of file diff --git a/src/features/clients/hooks/useClients.ts b/src/features/clients/hooks/useClients.ts new file mode 100644 index 0000000..e9a16ee --- /dev/null +++ b/src/features/clients/hooks/useClients.ts @@ -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')) + }, + }) +} \ No newline at end of file diff --git a/src/features/loanOrders/components/loanOrderForm.tsx b/src/features/loanOrders/components/loanOrderForm.tsx index c8245ab..19e302b 100644 --- a/src/features/loanOrders/components/loanOrderForm.tsx +++ b/src/features/loanOrders/components/loanOrderForm.tsx @@ -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 - onGoTo: (i: number) => void -}) { - return ( - - ) -} - // ─── Step content renderers ─────────────────────────────────────────────────── -function StepStatus({ - form, errors, set, -}: { - form: FormState - errors: FormErrors - set: (k: K, v: FormState[K]) => void -}) { +function StepStatus({ form, errors, set }: StepContentProps) { return (
- set('status', v)} - options={STATUS_OPTIONS} - error={errors.status} - placeholder="Saýlaň" - /> + set('status', v)} options={STATUS_OPTIONS} error={errors.status} placeholder="Saýlaň" />
- set('note', v)} - placeholder="Bellik" - /> + set('note', v)} placeholder="Bellik" />
) } -function StepLoan({ - form, errors, set, -}: { - form: FormState - errors: FormErrors - set: (k: K, v: FormState[K]) => void -}) { +function StepLoan({ form, errors, set }: StepContentProps) { return (
- set('loanType', v)} - options={LOAN_TYPE_OPTIONS} - placeholder="Saýlamak üçin basyň" - error={errors.loanType} - /> - set('loanAmount', v)} - placeholder="Karz möçberi" - error={errors.loanAmount} - /> + set('loanType', v)} options={LOAN_TYPE_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.loanType} /> + set('loanAmount', v)} placeholder="Karz möçberi" error={errors.loanAmount} />
) } -function StepLocation({ - form, errors, set, -}: { - form: FormState - errors: FormErrors - set: (k: K, v: FormState[K]) => void -}) { +function StepLocation({ form, errors, set }: StepContentProps) { return (
- set('region', v)} - options={REGION_OPTIONS} - placeholder="Saýlamak üçin basyň" - error={errors.region} - /> - set('branch', v)} - options={[]} - placeholder="Saýlamak üçin basyň" - error={errors.branch} - /> + set('region', v)} options={REGION_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.region} /> + set('branch', v)} options={[]} placeholder="Saýlamak üçin basyň" error={errors.branch} />
) } -function StepPersonal({ - form, errors, set, -}: { - form: FormState - errors: FormErrors - set: (k: K, v: FormState[K]) => void -}) { +function StepPersonal({ form, errors, set }: StepContentProps) { return (
- set('firstName', v)} placeholder="Ady" error={errors.firstName} /> - set('lastName', v)} placeholder="Familiýasy" error={errors.lastName} /> - set('patronicName', v)} placeholder="Atasynyň ady" /> + set('firstName', v)} placeholder="Ady" error={errors.firstName} /> + set('lastName', v)} placeholder="Familiýasy" error={errors.lastName} /> + set('patronicName', v)} placeholder="Atasynyň ady" />
- set('education', v)} options={EDUCATION_OPTIONS} placeholder="Saýlaň" error={errors.education} /> - set('marriageStatus', v)} options={MARRIAGE_OPTIONS} placeholder="Saýlaň" error={errors.marriageStatus} /> - set('dateOfBirth', v)} error={errors.dateOfBirth} /> + set('education', v)} options={EDUCATION_OPTIONS} placeholder="Saýlaň" error={errors.education} /> + set('marriageStatus', v)} options={MARRIAGE_OPTIONS} placeholder="Saýlaň" error={errors.marriageStatus} /> + set('dateOfBirth', v)} error={errors.dateOfBirth} />
- set('residence', v)} placeholder="Ýazgy edilen salgy" error={errors.residence} /> - set('currentResidence', v)} placeholder="Häzirki ýaşaýyş ýeri" /> + set('residence', v)} placeholder="Ýazgy edilen salgy" error={errors.residence} /> + set('currentResidence', v)} placeholder="Häzirki ýaşaýyş ýeri" />
- set('loanHistory', v)} - options={[]} - placeholder="Saýlamak üçin basyň" - /> + set('loanHistory', v)} options={[]} placeholder="Saýlamak üçin basyň" />
) } -function StepCard({ - form, errors, set, -}: { - form: FormState - errors: FormErrors - set: (k: K, v: FormState[K]) => void -}) { +function StepCard({ form, errors, set }: StepContentProps) { return (
- set('cardNumber', v)} placeholder="Kart belgisi" error={errors.cardNumber} /> - set('cardName', v)} placeholder="Kartdaky ady" error={errors.cardName} /> - set('cardExpMonth', v)} options={MONTH_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.cardExpMonth} /> - set('cardExpYear', v)} options={YEAR_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.cardExpYear} /> + set('cardNumber', v)} placeholder="Kart belgisi" error={errors.cardNumber} /> + set('cardName', v)} placeholder="Kartdaky ady" error={errors.cardName} /> + set('cardExpMonth', v)} options={MONTH_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.cardExpMonth} /> + set('cardExpYear', v)} options={YEAR_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.cardExpYear} />
) } -function StepPassport({ - form, errors, set, -}: { - form: FormState - errors: FormErrors - set: (k: K, v: FormState[K]) => void -}) { +function StepPassport({ form, errors, set }: StepContentProps) { return (
- set('passportSerie', v)} options={PASSPORT_SERIES_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.passportSerie} /> - set('passportNumber', v)} placeholder="Pasport belgisi" error={errors.passportNumber} /> - set('passportDateOfIssue', v)} error={errors.passportDateOfIssue} /> + set('passportSerie', v)} options={PASSPORT_SERIES_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.passportSerie} /> + set('passportNumber', v)} placeholder="Pasport belgisi" error={errors.passportNumber} /> + set('passportDateOfIssue', v)} error={errors.passportDateOfIssue} />
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: K, v: FormState[K]) => void -}) { +function StepContact({ form, errors, set }: StepContentProps) { return (
set('email', v)} placeholder="E-poçta" /> - set('phone', v)} placeholder="61 097 651" error={errors.phone} /> - set('phoneAdditional', v)} placeholder="61 097 651" /> - set('homePhone', v)} placeholder="61 097 651" /> + set('phone', v)} placeholder="61 097 651" error={errors.phone} /> + set('phoneAdditional', v)} placeholder="61 097 651" /> + set('homePhone', v)} placeholder="61 097 651" />
) } -function StepJob({ - form, errors, set, -}: { - form: FormState - errors: FormErrors - set: (k: K, v: FormState[K]) => void -}) { +function StepJob({ form, errors, set }: StepContentProps) { return (
@@ -652,23 +512,15 @@ function StepJob({ set('workProvince', v)} options={[]} placeholder="Saýlamak üçin basyň" />
- set('position', v)} placeholder="Wezipe" error={errors.position} /> - set('salary', v)} placeholder="Zähmet haky" error={errors.salary} /> + set('position', v)} placeholder="Wezipe" error={errors.position} /> + set('salary', v)} placeholder="Zähmet haky" error={errors.salary} /> set('workStartedAt', v)} error={errors.workStartedAt} />
) } -function StepFiles({ - form, errors, set, mode, initialData, -}: { - form: FormState - errors: FormErrors - set: (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 (
{mode === 'edit' && initialData && ( @@ -684,79 +536,39 @@ function StepFiles({ url ? (
{label} — häzirki - - Faýly gör - + Faýly gör
) : null )}
)}
- set('passportPage1', f)} - placeholder="Faýl saýlaň ýa-da salmak üçin basyň" - error={errors.passportPage1} - /> - set('passportPage23', f)} - placeholder="Faýl saýlaň ýa-da salmak üçin basyň" - error={errors.passportPage23} - /> - set('passportPage89', f)} - placeholder="Faýl saýlaň ýa-da salmak üçin basyň" - /> - set('passportPage32', f)} - placeholder="Faýl saýlaň ýa-da salmak üçin basyň" - /> + set('passportPage1', f)} placeholder="Faýl saýlaň ýa-da salmak üçin basyň" error={errors.passportPage1} /> + set('passportPage23', f)} placeholder="Faýl saýlaň ýa-da salmak üçin basyň" error={errors.passportPage23} /> + set('passportPage89', f)} placeholder="Faýl saýlaň ýa-da salmak üçin basyň" /> + set('passportPage32', f)} placeholder="Faýl saýlaň ýa-da salmak üçin basyň" />
) } -function StepGuarantor({ - form, errors, set, -}: { - form: FormState - errors: FormErrors - set: (k: K, v: FormState[K]) => void -}) { +function StepGuarantor({ form, errors, set }: StepContentProps) { return (
- set('guarantor1Name', v)} placeholder="Zamunyň ady" error={errors.guarantor1Name} /> - set('guarantor1Surname', v)} placeholder="Zamunyň familiýasy" error={errors.guarantor1Surname} /> - set('guarantor1Patronic', v)} placeholder="Zamunyň atasynyň ady" /> + set('guarantor1Name', v)} placeholder="Zamunyň ady" error={errors.guarantor1Name} /> + set('guarantor1Surname', v)} placeholder="Zamunyň familiýasy" error={errors.guarantor1Surname} /> + set('guarantor1Patronic', v)} placeholder="Zamunyň atasynyň ady" />
set('guarantor1PassportSerie', v)} options={PASSPORT_SERIES_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1PassportSerie} /> - set('guarantor1PassportNumber', v)} placeholder="Pasport belgisi" error={errors.guarantor1PassportNumber} /> + set('guarantor1PassportNumber', v)} placeholder="Pasport belgisi" error={errors.guarantor1PassportNumber} />
- set('guarantor1CardNumber', v)} placeholder="Kart belgisi" error={errors.guarantor1CardNumber} /> - set('guarantor1CardName', v)} placeholder="Kartdaky ady" error={errors.guarantor1CardName} /> - set('guarantor1CardExpMonth', v)} options={MONTH_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpMonth} /> - set('guarantor1CardExpYear', v)} options={YEAR_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpYear} /> + set('guarantor1CardNumber', v)} placeholder="Kart belgisi" error={errors.guarantor1CardNumber} /> + set('guarantor1CardName', v)} placeholder="Kartdaky ady" error={errors.guarantor1CardName} /> + set('guarantor1CardExpMonth', v)} options={MONTH_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpMonth} /> + set('guarantor1CardExpYear', v)} options={YEAR_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpYear} />
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: 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(() => initialData ? mapToFormState(initialData) : INITIAL_STATE) - const [errors, setErrors] = useState({}) + const [form, setForm] = useState(() => initialData ? mapToFormState(initialData) : INITIAL_STATE) + const [errors, setErrors] = useState({}) const [currentStep, setCurrentStep] = useState(0) - const [completed, setCompleted] = useState>( - // 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>( () => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set() ) - const set = useCallback( - (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() + visited.forEach((i) => { + if (Object.keys(STEPS[i].validate(form, mode)).length > 0) out.add(i) + }) + return out + }, [form, mode, visited]) + + const set = useCallback((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 (
- {/* ── Page header ── */} + {/* Page header */}

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

{t('Fill in all sections step by step') || 'Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.'}

- {/* ── Thin progress bar ── */} -
-
-
+ {/* Horizontal step bar — sits above the form card */} + + + {/* Form card */} +
+ {/* Card header */} +
+ + {currentStep + 1} / {STEPS.length} + +

+ {t(STEPS[currentStep].titleKey) || STEPS[currentStep].titleFallback} +

- - {completedCount} / {STEPS.length} - -
- {/* ── Sidebar + content layout ── */} -
- {/* Sidebar */} - + {/* Card body */} +
+ {currentStep === 0 && } + {currentStep === 1 && } + {currentStep === 2 && } + {currentStep === 3 && } + {currentStep === 4 && } + {currentStep === 5 && } + {currentStep === 6 && } + {currentStep === 7 && } + {currentStep === 8 && } + {currentStep === 9 && } +
- {/* Step card */} -
- {/* Card header */} -
- - {currentStep + 1} / {STEPS.length} - -

- {t(STEPS[currentStep].titleKey) || STEPS[currentStep].titleFallback} -

-
- - {/* Card body */} -
- {currentStep === 0 && } - {currentStep === 1 && } - {currentStep === 2 && } - {currentStep === 3 && } - {currentStep === 4 && } - {currentStep === 5 && } - {currentStep === 6 && } - {currentStep === 7 && } - {currentStep === 8 && } - {currentStep === 9 && } -
- - {/* Card footer with navigation */} -
- - - {isLastStep ? ( - - ) : ( - + {/* Card footer */} +
+
+ + + {isLastStep ? ( + + ) : ( + + )}
diff --git a/src/features/operators/api/operatorsApi.ts b/src/features/operators/api/operatorsApi.ts new file mode 100644 index 0000000..bdd7d4f --- /dev/null +++ b/src/features/operators/api/operatorsApi.ts @@ -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 => { + 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 => { + 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 => { + 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 => { + 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 => { + await delay(500) + mockOperators = mockOperators.filter((o) => o.id !== Number(id)) + }, + + assignRole: async (_operatorId: number, _roleId: number): Promise => { + await delay(500) + }, + + removeRole: async (_operatorId: number, _roleId: number): Promise => { + await delay(500) + }, + + assignPermission: async (_operatorId: number, _permissionId: number): Promise => { + await delay(500) + }, + + removePermission: async (_operatorId: number, _permissionId: number): Promise => { + await delay(500) + }, +} \ No newline at end of file diff --git a/src/features/operators/components/operatorForms.tsx b/src/features/operators/components/operatorForms.tsx new file mode 100644 index 0000000..835e886 --- /dev/null +++ b/src/features/operators/components/operatorForms.tsx @@ -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({ + username: '', + name: '', + phone: '', + email: '', + password: '', + isActive: true, + }) + + const [errors, setErrors] = useState({}) + + // 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 ( +
+ {/* Username */} +
+ + {t('operators.fields.username', 'Ulanyjy ady')} + * + + +
+ + {/* Name */} +
+ + {t('operators.fields.name', 'Ady')} + * + + +
+ + {/* Phone */} +
+ + {t('operators.fields.phone', 'Telefon')} + + +
+ + {/* Email */} +
+ + {t('operators.fields.email', 'E-poçta')} + + +
+ + {/* Password */} +
+ + {t('operators.fields.password', 'Açar sözi')} + {mode === 'create' && *} + +
+ + {mode === 'edit' && ( +

+ {t( + 'operators.fields.passwordEditNote', + 'Boş goýsaňyz, açar sözi üýtgemez', + )} +

+ )} +
+
+ + {/* isActive */} +
+ + {t('operators.fields.isActive', 'Işjeň')} + + setForm((prev) => ({ ...prev, isActive: !!v }))} + disabled={isPending} + className="data-[state=checked]:bg-primary data-[state=checked]:border-primary" + /> +
+ + {/* Actions */} +
+ + +
+
+ ) +} \ No newline at end of file diff --git a/src/features/operators/hooks/useOperators.ts b/src/features/operators/hooks/useOperators.ts new file mode 100644 index 0000000..92067c8 --- /dev/null +++ b/src/features/operators/hooks/useOperators.ts @@ -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')) + }, + }) +} \ No newline at end of file diff --git a/src/layouts/DashboardLayout.tsx b/src/layouts/DashboardLayout.tsx index 2a5e570..221de7b 100644 --- a/src/layouts/DashboardLayout.tsx +++ b/src/layouts/DashboardLayout.tsx @@ -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" }, ], }, { diff --git a/src/pages/users/allUsers/index.tsx b/src/pages/users/allUsers/index.tsx new file mode 100644 index 0000000..7848e10 --- /dev/null +++ b/src/pages/users/allUsers/index.tsx @@ -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([]) + const [columnVisibility, setColumnVisibility] = useState({}) + const [columnOrder, setColumnOrder] = useState([ + 'id', 'username', 'name', 'phone', 'email', 'isActive', 'actions', + ]) + + // Delete confirm dialog + const [deleteTarget, setDeleteTarget] = useState(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[] = [ + { + accessorKey: 'id', + header: 'ID', + size: 80, + cell: ({ row }) => ( + + {row.original.id} + + ), + }, + { + accessorKey: 'username', + header: t('users.fields.username', 'ULANYJY ADY'), + enableSorting: true, + cell: ({ row }) => ( + + {row.original.username} + + ), + }, + { + accessorKey: 'name', + header: t('users.fields.name', 'ADY'), + enableSorting: true, + cell: ({ row }) => ( + {row.original.name} + ), + }, + { + accessorKey: 'phone', + header: t('users.fields.phone', 'TELEFON'), + cell: ({ row }) => ( + {row.original.phone} + ), + }, + { + accessorKey: 'email', + header: t('users.fields.email', 'E-POÇTA'), + enableSorting: true, + cell: ({ row }) => ( + + {row.original.email ?? '—'} + + ), + }, + { + accessorKey: 'isActive', + header: t('users.fields.isActive', 'IŞJEŇ'), + size: 80, + cell: ({ row }) => + row.original.isActive ? ( + + ) : ( + + ), + }, + { + id: 'actions', + header: '', + size: 100, + enableHiding: false, + cell: ({ row }) => ( +
+ + + +
+ ), + }, + ] + + 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 ( +
+ {/* Page header */} +
+ +

+ {t('users.title', 'Ulanyjylar')} +

+
+ + {/* Toolbar */} + { setPerPage(v); setPage(1) }} + actionLabel={t('users.actions.create', 'Ulanyjy dörediň')} + onAction={() => navigate('/all-users/create')} + /> + + {/* Table */} + String(row.id)} + currentPage={page} + totalPages={data?.totalPages ?? 1} + totalCount={data?.total} + onPageChange={setPage} + /> + + {/* Delete confirm dialog */} + !o && setDeleteTarget(null)}> + + + + {t('users.deleteDialog.title', 'Ulanyjyny öçürmek')} + + + {t( + 'users.deleteDialog.description', + 'Siz "{name}" ulanyjysyny öçürjekmi? Bu amal yzyna gaýtarylyp bilinmez.', + ).replace('{name}', deleteTarget?.username ?? '')} + + + + {t('common.cancel', 'Ýok')} + + {t('common.delete', 'Öçür')} + + + + +
+ ) +} \ No newline at end of file diff --git a/src/pages/users/allUsersCreate/index.tsx b/src/pages/users/allUsersCreate/index.tsx new file mode 100644 index 0000000..72144a6 --- /dev/null +++ b/src/pages/users/allUsersCreate/index.tsx @@ -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 ( +
+ {/* Breadcrumb */} + + + {/* Title */} +

+ {t('users.actions.create', 'Ulanyjy dörediň')} +

+ + {/* Shared form — create mode */} + +
+ ) +} \ No newline at end of file diff --git a/src/pages/users/allUsersEdit/index.tsx b/src/pages/users/allUsersEdit/index.tsx new file mode 100644 index 0000000..1839f35 --- /dev/null +++ b/src/pages/users/allUsersEdit/index.tsx @@ -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 ( +
+ +
+ ) + } + + if (isError || !user) { + return ( +
+ {t('common.notFound', 'Maglumat tapylmady')} +
+ ) + } + + return ( +
+ + + {/* Title */} +

+ {t('users.editTitle', 'Ulanyjy giňişleýin')}: {user.name} ({user.username}) +

+ + {/* Shared form — edit mode, passes fetched data */} + +
+ ) +} \ No newline at end of file diff --git a/src/pages/users/allUsersView/index.tsx b/src/pages/users/allUsersView/index.tsx new file mode 100644 index 0000000..3c46c6a --- /dev/null +++ b/src/pages/users/allUsersView/index.tsx @@ -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 ( +
+ + + {open && ( +
+ {/* Sub-toolbar */} +
+
+ + 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" + /> +
+
+ {showFilter && ( + + )} + +
+
+ + {/* Empty state */} +
+
+ + + + + + + + +
+

{emptyMessage}

+ +
+
+ )} +
+ ) +} + +// ─── 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 ( +
+ +
+ ) + } + + if (isError || !user) { + return ( +
+ {t('common.notFound', 'Maglumat tapylmady')} +
+ ) + } + + return ( +
+ {/* Breadcrumb */} + + + {/* Title + actions */} +
+

+ {t('users.viewTitle', 'Ulanyjy giňişleýin')}: {user.name} ({user.username}) +

+
+ + +
+
+ + {/* Main info */} +
+ + + + + + + {user.isActive ? ( + + ) : ( + + )} + +
+ + {/* Rollar */} + {}} + emptyMessage={t('users.empty.roles', 'Berlen kriteriýalara Rol gabat gelmedi.')} + searchPlaceholder={t('common.search', 'Gözlemek')} + /> + + {/* Rugsatlar */} + {}} + emptyMessage={t('users.empty.permissions', 'Berlen kriteriýalara Rugsat gabat gelmedi.')} + searchPlaceholder={t('common.search', 'Gözlemek')} + /> + + {/* Şahamçalar */} + {}} + emptyMessage={t('users.empty.branches', 'Berlen kriteriýalara Şahamça gabat gelmedi.')} + searchPlaceholder={t('common.search', 'Gözlemek')} + showFilter + /> + + {/* Ammallar */} + {}} + emptyMessage={t('users.empty.audit', 'Berlen kriteriýalara Hereket gabat gelmedi.')} + searchPlaceholder={t('common.search', 'Gözlemek')} + /> + + {/* Delete dialog */} + + + + + {t('users.deleteDialog.title', 'Ulanyjyny öçürmek')} + + + {t( + 'users.deleteDialog.description', + 'Siz "{name}" ulanyjysyny öçürjekmi? Bu amal yzyna gaýtarylyp bilinmez.', + ).replace('{name}', user.username)} + + + + {t('common.cancel', 'Ýok')} + + {t('common.delete', 'Öçür')} + + + + +
+ ) +} \ No newline at end of file diff --git a/src/pages/users/clients/index.tsx b/src/pages/users/clients/index.tsx new file mode 100644 index 0000000..004feb6 --- /dev/null +++ b/src/pages/users/clients/index.tsx @@ -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([]) + + const [deleteTarget, setDeleteTarget] = useState(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[] = [ + { + accessorKey: 'id', + header: 'ID', + cell: ({ row }) => ( + navigate(`/clients/${row.original.id}`)} + > + {row.original.id} + + ), + size: 80, + }, + { + accessorKey: 'username', + header: t('clients.fields.username', 'ULANYJY ADY'), + cell: ({ row }) => {row.original.username}, + }, + { + accessorKey: 'name', + header: t('clients.fields.name', 'ADY'), + cell: ({ row }) => {row.original.name}, + }, + { + accessorKey: 'phone', + header: t('clients.fields.phone', 'TELEFON'), + cell: ({ row }) => {row.original.phone ?? '—'}, + }, + { + accessorKey: 'email', + header: t('clients.fields.email', 'E-POÇTA'), + cell: ({ row }) => {row.original.email ?? '—'}, + }, + { + accessorKey: 'isActive', + header: t('clients.fields.isActive', 'IŞJEŇ'), + cell: ({ row }) => + row.original.isActive ? ( + + + + + + ) : ( + + + + + + ), + size: 80, + }, + { + id: 'actions', + header: '', + cell: ({ row }) => ( +
+ + + +
+ ), + 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 ( +
+
+

+ {t('clients.title', 'Müşderiler')} +

+
+ + { 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')} + /> + + String(row.id)} + currentPage={page} + totalPages={totalPages} + totalCount={totalCount} + onPageChange={setPage} + enableRowSelection + /> + + !open && setDeleteTarget(null)}> + + + {t('clients.deleteTitle', 'Müşderini pozmak')} + + {t('clients.deleteConfirm', '{{name}} müşderisini pozmak isleýärsiňizmi? Bu amaly yzyna gaýtaryp bolmaz.', { + name: deleteTarget?.name ?? '', + })} + + + + {t('common.cancel', 'Ýatyr')} + { + if (deleteTarget) { + deleteMutation.mutate(deleteTarget.id, { + onSuccess: () => setDeleteTarget(null), + }) + } + }} + > + {t('common.delete', 'Poz')} + + + + +
+ ) +} diff --git a/src/pages/users/clientsCreate/index.tsx b/src/pages/users/clientsCreate/index.tsx new file mode 100644 index 0000000..f03fa2d --- /dev/null +++ b/src/pages/users/clientsCreate/index.tsx @@ -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 ( +
+ {/* Breadcrumb */} + + + {/* Page heading */} +

+ {t('clients.createTitle', 'Müşderi dörediň')} +

+ + +
+ ) +} diff --git a/src/pages/users/clientsEdit/index.tsx b/src/pages/users/clientsEdit/index.tsx new file mode 100644 index 0000000..a8aca47 --- /dev/null +++ b/src/pages/users/clientsEdit/index.tsx @@ -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 ( +
+ + + {/* Page heading */} +

+ {t('clients.editTitle', 'Müşderi üýtget')}: {client?.name ?? ''} +

+ + {isLoading ? ( +
+ {Array.from({ length: 6 }).map((_, i) => ( +
+ ))} +
+ ) : ( + + )} +
+ ) +} diff --git a/src/pages/users/clientsView/index.tsx b/src/pages/users/clientsView/index.tsx new file mode 100644 index 0000000..7752443 --- /dev/null +++ b/src/pages/users/clientsView/index.tsx @@ -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[] = [ + { + accessorKey: 'id', + header: 'ID', + cell: ({ row }) => {row.original.id}, + size: 80, + }, + { + accessorKey: 'code', + header: t('roles.fields.code', 'KOD'), + cell: ({ row }) => {row.original.code}, + }, + { + accessorKey: 'name', + header: t('roles.fields.name', 'ADY'), + cell: ({ row }) => {row.original.name}, + }, + { + accessorKey: 'guardName', + header: t('roles.fields.guardName', 'GUARD NAME'), + cell: ({ row }) => {row.original.guardName}, + }, + { + id: 'actions', + header: '', + cell: () => ( +
+ +
+ ), + size: 60, + }, + ] + + const branchColumns: ColumnDef[] = [ + { + accessorKey: 'id', + header: 'ID', + cell: ({ row }) => {row.original.id}, + size: 60, + }, + { + accessorKey: 'name', + header: t('branches.fields.name', 'ADY'), + cell: ({ row }) => {row.original.name}, + }, + { + accessorKey: 'region', + header: t('branches.fields.region', 'WELAÝAT'), + cell: ({ row }) => {row.original.region}, + }, + { + accessorKey: 'district', + header: t('branches.fields.district', 'ETRAP'), + cell: ({ row }) => {row.original.district}, + }, + { + accessorKey: 'uniqueCode', + header: t('branches.fields.uniqueCode', 'UNIKAL BELGI'), + cell: ({ row }) => {row.original.uniqueCode}, + }, + { + id: 'actions', + header: '', + cell: () => ( +
+ +
+ ), + size: 60, + }, + ] + + if (isLoading) { + return ( +
+ {Array.from({ length: 3 }).map((_, i) => ( +
+ ))} +
+ ) + } + + 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 ( +
+ + +
+

+ {t('clients.detailTitle', 'Müşderi giňişleýin')}: {client.name} +

+
+ + +
+
+ +
+ + + + + + + {client.isActive ? ( + + + + + + ) : ( + + + + + + )} + +
+ + {}}> + {}} columnOrder={[]} onColumnOrderChange={() => {}} hideAction /> + {(filteredRoles.length > 0) ? ( + String(r.id)} enableRowSelection /> + ) : ( + {}} /> + )} + + + {}}> + {}} columnOrder={[]} onColumnOrderChange={() => {}} hideAction /> + {(client.permissions ?? []).length === 0 ? ( + {}} /> + ) : null} + + + {}}> + {}} columnOrder={[]} onColumnOrderChange={() => {}} hideAction /> + {(filteredBranches.length > 0) ? ( + String(r.id)} enableRowSelection /> + ) : ( + {}} /> + )} + + + {}}> + {}} columnOrder={[]} onColumnOrderChange={() => {}} hideAction /> + {(client.loanOrders ?? []).length === 0 ? ( + {}} /> + ) : null} + + + {}}> + {}} columnOrder={[]} onColumnOrderChange={() => {}} hideAction /> + {(client.cardOrders ?? []).length === 0 ? ( + {}} /> + ) : null} + + + + + + + + {t('clients.deleteTitle', 'Müşderini pozmak')} + + {t('clients.deleteConfirm', '{{name}} müşderisini pozmak isleýärsiňizmi?', { name: client.name })} + + + + {t('common.cancel', 'Ýatyr')} + deleteMutation.mutate(clientId, { onSuccess: () => navigate('/clients') })}> + {t('common.delete', 'Poz')} + + + + +
+ ) +} + +interface CollapsibleSectionProps { title: string; actionLabel: string; onAction: () => void; children: React.ReactNode } +function CollapsibleSection({ title, actionLabel, onAction, children }: CollapsibleSectionProps) { + const [open, setOpen] = useState(true) + return ( +
+
setOpen((v) => !v)}> +

{title}

+ +
+ {open && ( +
+
+ +
+ {children} +
+ )} +
+ ) +} + +interface EmptyStateProps { label: string; actionLabel: string; onAction: () => void } +function EmptyState({ label, actionLabel, onAction }: EmptyStateProps) { + return ( +
+
+ + + + + + + +
+

{label}

+ +
+ ) +} diff --git a/src/pages/users/operators/index.tsx b/src/pages/users/operators/index.tsx new file mode 100644 index 0000000..c02fd2d --- /dev/null +++ b/src/pages/users/operators/index.tsx @@ -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([]) + + // ── Delete dialog ──────────────────────────────────────────────────────────── + const [deleteTarget, setDeleteTarget] = useState(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[] = [ + { + accessorKey: 'id', + header: 'ID', + cell: ({ row }) => ( + navigate(`/operators/${row.original.id}`)} + > + {row.original.id} + + ), + size: 80, + }, + { + accessorKey: 'username', + header: t('operators.fields.username', 'ULANYJY ADY'), + cell: ({ row }) => ( + {row.original.username} + ), + }, + { + accessorKey: 'name', + header: t('operators.fields.name', 'ADY'), + cell: ({ row }) => ( + {row.original.name} + ), + }, + { + accessorKey: 'phone', + header: t('operators.fields.phone', 'TELEFON'), + cell: ({ row }) => ( + + {row.original.phone ?? '—'} + + ), + }, + { + accessorKey: 'email', + header: t('operators.fields.email', 'E-POÇTA'), + cell: ({ row }) => ( + + {row.original.email ?? '—'} + + ), + }, + { + accessorKey: 'isActive', + header: t('operators.fields.isActive', 'IŞJEŇ'), + cell: ({ row }) => + row.original.isActive ? ( + + + + + + ) : ( + + + + + + ), + size: 80, + }, + { + id: 'actions', + header: '', + cell: ({ row }) => ( +
+ + + +
+ ), + 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 ( +
+ {/* Page header */} +
+

+ {t('operators.title', 'Operatorlar')} +

+
+ + {/* Toolbar */} + { 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 */} + String(row.id)} + currentPage={page} + totalPages={totalPages} + totalCount={totalCount} + onPageChange={setPage} + enableRowSelection + /> + + {/* Delete dialog */} + !open && setDeleteTarget(null)} + > + + + + {t('operators.deleteTitle', 'Operatory pozmak')} + + + {t( + 'operators.deleteConfirm', + '{{name}} operatoryny pozmak isleýärsiňizmi? Bu amaly yzyna gaýtaryp bolmaz.', + { name: deleteTarget?.name ?? '' }, + )} + + + + {t('common.cancel', 'Ýatyr')} + { + if (deleteTarget) { + deleteMutation.mutate(deleteTarget.id, { + onSuccess: () => setDeleteTarget(null), + }) + } + }} + > + {t('common.delete', 'Poz')} + + + + +
+ ) +} \ No newline at end of file diff --git a/src/pages/users/operatorsCreate/index.tsx b/src/pages/users/operatorsCreate/index.tsx new file mode 100644 index 0000000..15d17b4 --- /dev/null +++ b/src/pages/users/operatorsCreate/index.tsx @@ -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 ( +
+ {/* Breadcrumb */} + + + {/* Page heading */} +

+ {t('operators.createTitle', 'Operator döredin')} +

+ + +
+ ) +} \ No newline at end of file diff --git a/src/pages/users/operatorsEdit/index.tsx b/src/pages/users/operatorsEdit/index.tsx new file mode 100644 index 0000000..1c543e2 --- /dev/null +++ b/src/pages/users/operatorsEdit/index.tsx @@ -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 ( +
+ {/* Page heading */} +

+ {t('operators.editTitle', 'Operator üýtget')}: {operator?.name ?? ''} +

+ + {isLoading ? ( +
+ {Array.from({ length: 6 }).map((_, i) => ( +
+ ))} +
+ ) : ( + + )} +
+ ) +} \ No newline at end of file diff --git a/src/pages/users/operatorsView/index.tsx b/src/pages/users/operatorsView/index.tsx new file mode 100644 index 0000000..175540e --- /dev/null +++ b/src/pages/users/operatorsView/index.tsx @@ -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[] = [ + { + accessorKey: 'id', + header: 'ID', + cell: ({ row }) => ( + {row.original.id} + ), + size: 80, + }, + { + accessorKey: 'code', + header: t('roles.fields.code', 'KOD'), + cell: ({ row }) => {row.original.code}, + }, + { + accessorKey: 'name', + header: t('roles.fields.name', 'ADY'), + cell: ({ row }) => {row.original.name}, + }, + { + accessorKey: 'guardName', + header: t('roles.fields.guardName', 'GUARD NAME'), + cell: ({ row }) => {row.original.guardName}, + }, + { + id: 'actions', + header: '', + cell: ({ row }) => ( +
+ + + +
+ ), + size: 120, + }, + ] + + // ── Branch columns ──────────────────────────────────────────────────────── + const branchColumns: ColumnDef[] = [ + { + accessorKey: 'id', + header: 'ID', + cell: ({ row }) => ( + {row.original.id} + ), + size: 60, + }, + { + accessorKey: 'name', + header: t('branches.fields.name', 'ADY'), + cell: ({ row }) => {row.original.name}, + }, + { + accessorKey: 'region', + header: t('branches.fields.region', 'WELAÝAT'), + cell: ({ row }) => {row.original.region}, + }, + { + accessorKey: 'district', + header: t('branches.fields.district', 'ETRAP'), + cell: ({ row }) => {row.original.district}, + }, + { + accessorKey: 'uniqueCode', + header: t('branches.fields.uniqueCode', 'UNIKAL BELGI'), + cell: ({ row }) => {row.original.uniqueCode}, + }, + { + accessorKey: 'isActive', + header: t('branches.fields.isActive', 'IŞJEŇ'), + cell: ({ row }) => + row.original.isActive ? ( + + + + + + ) : ( + + + + + + ), + size: 80, + }, + { + accessorKey: 'billingUsernameIbr', + header: t('branches.fields.billingIbr', 'BILLING ULANYJY ADY'), + cell: ({ row }) => {row.original.billingUsernameIbr}, + }, + { + accessorKey: 'billingUsernameSber', + header: t('branches.fields.billingSber', 'BILLING USERNAME (SBER)'), + cell: ({ row }) => {row.original.billingUsernameSber}, + }, + { + accessorKey: 'billingUsernameVisa', + header: t('branches.fields.billingVisa', 'BILLING USERNAME (VISA)'), + cell: ({ row }) => {row.original.billingUsernameVisa}, + }, + { + id: 'actions', + header: '', + cell: () => ( +
+ +
+ ), + size: 60, + }, + ] + + if (isLoading) { + return ( +
+ {Array.from({ length: 3 }).map((_, i) => ( +
+ ))} +
+ ) + } + + 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 ( +
+ {/* Page header */} +
+

+ {t('operators.detailTitle', 'Operator giňişleýin')}: {operator.name} +

+
+ + +
+
+ + {/* Basic info */} +
+ + + + + + + {operator.isActive ? ( + + + + + + ) : ( + + + + + + )} + +
+ + {/* Roles */} + {/* open role assign modal */}} + > + {}} + columnOrder={[]} + onColumnOrderChange={() => {}} + hideAction + /> + String(r.id)} + enableRowSelection + /> + + + {/* Permissions */} + {/* open permission modal */}} + > + {}} + columnOrder={[]} + onColumnOrderChange={() => {}} + hideAction + /> + {(operator.permissions ?? []).length === 0 ? ( + {}} /> + ) : null} + + + {/* Branches */} + {}} + > + {}} + columnOrder={[]} + onColumnOrderChange={() => {}} + hideAction + /> + String(r.id)} + enableRowSelection + /> + + + {/* Karz sargyt */} + {}} + > + {(operator.loanLimits ?? []).length === 0 ? ( + {}} /> + ) : null} + + + {/* Kart sargyt */} + {}} + > + {(operator.cardLimits ?? []).length === 0 ? ( + {}} /> + ) : null} + + + {/* Audit log */} + + + {/* Delete dialog */} + + + + {t('operators.deleteTitle', 'Operatory pozmak')} + + {t('operators.deleteConfirm', '{{name}} operatoryny pozmak isleýärsiňizmi?', { + name: operator.name, + })} + + + + {t('common.cancel', 'Ýatyr')} + + deleteMutation.mutate(operatorId, { + onSuccess: () => navigate('/operators'), + }) + } + > + {t('common.delete', 'Poz')} + + + + +
+ ) +} + +// ─── 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 ( +
+
setOpen((v) => !v)} + > +

{title}

+ +
+ {open && ( +
+
+ +
+ {children} +
+ )} +
+ ) +} + +// ─── EmptyState ─────────────────────────────────────────────────────────────── + +interface EmptyStateProps { + label: string + actionLabel: string + onAction: () => void +} + +function EmptyState({ label, actionLabel, onAction }: EmptyStateProps) { + return ( +
+
+ + + + + + + +
+

{label}

+ +
+ ) +} \ No newline at end of file