diff --git a/src/app/store/authStore.ts b/src/app/store/authStore.ts index c77273d..2227dd1 100644 --- a/src/app/store/authStore.ts +++ b/src/app/store/authStore.ts @@ -12,6 +12,7 @@ export interface AuthUser { phone?: string; role?: string; avatar?: string; + createdAt?: string; } interface AuthState { diff --git a/src/components/avatarUpload.tsx b/src/components/avatarUpload.tsx new file mode 100644 index 0000000..7ef341c --- /dev/null +++ b/src/components/avatarUpload.tsx @@ -0,0 +1,157 @@ +import { useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Upload, X, Loader2 } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { postFile, buildFileUrl } from "@/features/shared/api/sharedApi"; + +// ─── Types ──────────────────────────────────────────────────────────────────── + +interface AvatarUploadProps { + label?: string; + value?: string; + onChange?: (url: string) => void; + error?: string; + required?: boolean; + disabled?: boolean; +} + +// ─── FieldLabel ─────────────────────────────────────────────────────────────── + +function FieldLabel({ label, required }: { label?: string; required?: boolean }) { + if (!label) return null; + return ( + + ); +} + +// ─── ErrorMsg ───────────────────────────────────────────────────────────────── + +function ErrorMsg({ error }: { error?: string }) { + if (!error) return null; + return ( +

+ + {error} +

+ ); +} + +// ─── AvatarUpload ───────────────────────────────────────────────────────────── + +export function AvatarUpload({ label, value, onChange, error, required, disabled }: AvatarUploadProps) { + const { t } = useTranslation(); + const inputRef = useRef(null); + const [dragOver, setDragOver] = useState(false); + const [uploading, setUploading] = useState(false); + const [uploadError, setUploadError] = useState(""); + + const handleFile = async (file: File | null) => { + if (!file || disabled) return; + + if (!file.type.startsWith("image/")) { + setUploadError(t("users.fields.avatarInvalid", "Diňe surat faýllary kabul edilýär")); + return; + } + + setUploading(true); + setUploadError(""); + try { + const filename = await postFile(file); + onChange?.(buildFileUrl(filename)); + } catch { + setUploadError(t("users.fields.avatarUploadError", "Surat ýüklenip bilinmedi")); + } finally { + setUploading(false); + if (inputRef.current) inputRef.current.value = ""; + } + }; + + const handleDrop = (e: React.DragEvent) => { + e.preventDefault(); + setDragOver(false); + handleFile(e.dataTransfer.files[0] ?? null); + }; + + const effectiveError = error || uploadError; + + return ( +
+ + +
+ {/* Preview — rounded, on top */} +
+ {value ? ( + avatar + ) : ( + + )} +
+ + {/* Upload zone — full width, below */} +
+
!disabled && !uploading && inputRef.current?.click()} + onKeyDown={(e) => e.key === "Enter" && !disabled && !uploading && inputRef.current?.click()} + onDragOver={(e) => { + if (disabled) return; + e.preventDefault(); + setDragOver(true); + }} + onDragLeave={() => setDragOver(false)} + onDrop={handleDrop} + className={cn( + "flex items-center justify-center gap-2", + "min-h-20 rounded-md border-2 border-dashed cursor-pointer select-none px-4", + "transition-all duration-200 text-sm", + "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2", + dragOver && "border-primary bg-primary/5 scale-[1.01]", + effectiveError ? "border-destructive/60" : "border-border", + !dragOver && !effectiveError && "hover:border-primary/50 hover:bg-muted/20", + (disabled || uploading) && "opacity-60 cursor-not-allowed pointer-events-none", + )} + > + {uploading ? ( + <> + + {t("users.fields.avatarUploading", "Ýüklenýär...")} + + ) : ( + <> + + {t("users.fields.avatarUpload", "Surat saýlaň")} + + )} +
+ + {value && !disabled && ( + + )} +
+
+ + handleFile(e.target.files?.[0] ?? null)} + className="hidden" + /> + + +
+ ); +} diff --git a/src/components/formInput.tsx b/src/components/formInput.tsx index 49a1a17..b8d6264 100644 --- a/src/components/formInput.tsx +++ b/src/components/formInput.tsx @@ -333,7 +333,7 @@ function SelectInput({ -
+
{options.map((opt) => { const isSelected = opt.value === value; return ( @@ -488,7 +488,7 @@ function SearchableSelect({
{/* Options */} -
+
{filtered.length === 0 ? (

Netije tapylmady

) : ( diff --git a/src/components/infiniteSelect.tsx b/src/components/infiniteSelect.tsx index 9d69003..60a9893 100644 --- a/src/components/infiniteSelect.tsx +++ b/src/components/infiniteSelect.tsx @@ -170,7 +170,7 @@ export function InfiniteSelect({
)} -
+
{loading && options.length === 0 ? (

Loading... diff --git a/src/components/ui/calendar.tsx b/src/components/ui/calendar.tsx index 9b2b838..9569f65 100644 --- a/src/components/ui/calendar.tsx +++ b/src/components/ui/calendar.tsx @@ -1,14 +1,9 @@ -import * as React from "react" -import { - DayPicker, - getDefaultClassNames, - type DayButton, - type Locale, -} from "react-day-picker" +import * as React from "react"; +import { DayPicker, getDefaultClassNames, type DayButton, type Locale } from "react-day-picker"; -import { cn } from "@/lib/utils" -import { Button, buttonVariants } from "@/components/ui/button" -import { ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon } from "lucide-react" +import { cn } from "@/lib/utils"; +import { Button, buttonVariants } from "@/components/ui/button"; +import { ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon } from "lucide-react"; function Calendar({ className, @@ -21,9 +16,9 @@ function Calendar({ components, ...props }: React.ComponentProps & { - buttonVariant?: React.ComponentProps["variant"] + buttonVariant?: React.ComponentProps["variant"]; }) { - const defaultClassNames = getDefaultClassNames() + const defaultClassNames = getDefaultClassNames(); return ( svg]:rotate-180`, String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`, - className + className, )} captionLayout={captionLayout} locale={locale} formatters={{ - formatMonthDropdown: (date) => - date.toLocaleString(locale?.code, { month: "short" }), + formatMonthDropdown: (date) => date.toLocaleString(locale?.code, { month: "short" }), ...formatters, }} classNames={{ root: cn("w-fit", defaultClassNames.root), - months: cn( - "relative flex flex-col gap-4 md:flex-row", - defaultClassNames.months - ), + months: cn("relative flex flex-col gap-4 md:flex-row", defaultClassNames.months), month: cn("flex w-full flex-col gap-4", defaultClassNames.month), - nav: cn( - "absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1", - defaultClassNames.nav - ), + nav: cn("absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1", defaultClassNames.nav), button_previous: cn( buttonVariants({ variant: buttonVariant }), "size-(--cell-size) p-0 select-none aria-disabled:opacity-50", - defaultClassNames.button_previous + defaultClassNames.button_previous, ), button_next: cn( buttonVariants({ variant: buttonVariant }), "size-(--cell-size) p-0 select-none aria-disabled:opacity-50", - defaultClassNames.button_next - ), - month_caption: cn( - "flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)", - defaultClassNames.month_caption - ), - dropdowns: cn( - "flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium", - defaultClassNames.dropdowns - ), - dropdown_root: cn( - "relative rounded-(--cell-radius)", - defaultClassNames.dropdown_root - ), - dropdown: cn( - "absolute inset-0 bg-popover opacity-0", - defaultClassNames.dropdown + defaultClassNames.button_next, ), + month_caption: cn("flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)", defaultClassNames.month_caption), + dropdowns: cn("flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium", defaultClassNames.dropdowns), + dropdown_root: cn("relative rounded-(--cell-radius)", defaultClassNames.dropdown_root), + dropdown: cn("absolute inset-0 bg-popover opacity-0 scrollbar-thin", defaultClassNames.dropdown), caption_label: cn( "font-medium select-none", captionLayout === "label" ? "text-sm" : "flex items-center gap-1 rounded-(--cell-radius) text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground", - defaultClassNames.caption_label + defaultClassNames.caption_label, ), table: "w-full border-collapse", weekdays: cn("flex", defaultClassNames.weekdays), weekday: cn( "flex-1 rounded-(--cell-radius) text-[0.8rem] font-normal text-muted-foreground select-none", - defaultClassNames.weekday + defaultClassNames.weekday, ), week: cn("mt-2 flex w-full", defaultClassNames.week), - week_number_header: cn( - "w-(--cell-size) select-none", - defaultClassNames.week_number_header - ), - week_number: cn( - "text-[0.8rem] text-muted-foreground select-none", - defaultClassNames.week_number - ), + week_number_header: cn("w-(--cell-size) select-none", defaultClassNames.week_number_header), + week_number: cn("text-[0.8rem] text-muted-foreground select-none", defaultClassNames.week_number), day: cn( "group/day relative aspect-square h-full w-full rounded-(--cell-radius) p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius)", props.showWeekNumber ? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)" : "[&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)", - defaultClassNames.day + defaultClassNames.day, ), range_start: cn( "relative isolate z-0 rounded-l-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:right-0 after:w-4 after:bg-muted", - defaultClassNames.range_start + defaultClassNames.range_start, ), range_middle: cn("rounded-none", defaultClassNames.range_middle), range_end: cn( "relative isolate z-0 rounded-r-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:left-0 after:w-4 after:bg-muted", - defaultClassNames.range_end - ), - today: cn( - "rounded-(--cell-radius) bg-muted text-foreground data-[selected=true]:rounded-none", - defaultClassNames.today - ), - outside: cn( - "text-muted-foreground aria-selected:text-muted-foreground", - defaultClassNames.outside - ), - disabled: cn( - "text-muted-foreground opacity-50", - defaultClassNames.disabled + defaultClassNames.range_end, ), + today: cn("rounded-(--cell-radius) bg-muted text-foreground data-[selected=true]:rounded-none", defaultClassNames.today), + outside: cn("text-muted-foreground aria-selected:text-muted-foreground", defaultClassNames.outside), + disabled: cn("text-muted-foreground opacity-50", defaultClassNames.disabled), hidden: cn("invisible", defaultClassNames.hidden), ...classNames, }} components={{ Root: ({ className, rootRef, ...props }) => { - return ( -

- ) + return
; }, Chevron: ({ className, orientation, ...props }) => { if (orientation === "left") { - return ( - - ) + return ; } if (orientation === "right") { - return ( - - ) + return ; } - return ( - - ) + return ; }, - DayButton: ({ ...props }) => ( - - ), + DayButton: ({ ...props }) => , WeekNumber: ({ children, ...props }) => { return ( -
- {children} -
+
{children}
- ) + ); }, ...components, }} {...props} /> - ) + ); } function CalendarDayButton({ @@ -185,12 +129,12 @@ function CalendarDayButton({ locale, ...props }: React.ComponentProps & { locale?: Partial }) { - const defaultClassNames = getDefaultClassNames() + const defaultClassNames = getDefaultClassNames(); - const ref = React.useRef(null) + const ref = React.useRef(null); React.useEffect(() => { - if (modifiers.focused) ref.current?.focus() - }, [modifiers.focused]) + if (modifiers.focused) ref.current?.focus(); + }, [modifiers.focused]); return ( - - -
- ), - }, - ], - [t], - ); + const [errors, setErrors] = useState>({}); - // ── ColumnMeta for DataTableToolbar ─────────────────────────────────────── + useEffect(() => { + if (user) { + setFormData({ + name: user.name ?? "", + firstName: user.firstName ?? "", + lastName: user.lastName ?? "", + phone: user.phone ?? "", + avatar: user.avatar ?? "", + }); + } + }, [user, isEditing]); - const roleColumnMeta: ColumnMeta[] = useMemo( - () => [ - { id: "id", label: t("common.id", "ID") }, - { id: "code", label: t("roles.fields.code", "KOD") }, - { id: "name", label: t("roles.fields.name", "ADY") }, - { id: "guardName", label: t("roles.fields.guardName", "GUARD NAME") }, - ], - [t], - ); + const handleFieldChange = (field: keyof typeof formData, value: string) => { + setFormData((prev) => ({ ...prev, [field]: value })); + if (errors[field]) { + setErrors((prev) => { + const next = { ...prev }; + delete next[field]; + return next; + }); + } + }; - // ── Filtered roles ──────────────────────────────────────────────────────── + const handleSave = async () => { + if (!formData.name.trim()) { + setErrors({ name: t("common.errors.required", "Meýdança hökmany doldurylmaly") }); + return; + } - const filteredRoles = useMemo(() => { - const q = roleSearch.toLowerCase().trim(); - if (!q) return MOCK_ROLES; - return MOCK_ROLES.filter( - (r) => r.code.toLowerCase().includes(q) || r.name.toLowerCase().includes(q) || r.guardName.toLowerCase().includes(q), - ); - }, [roleSearch]); + try { + await updateProfileMutation.mutateAsync({ + name: formData.name.trim(), + firstName: formData.firstName.trim() || undefined, + lastName: formData.lastName.trim() || undefined, + phone: formData.phone.trim() || undefined, + avatar: formData.avatar || undefined, + }); + setIsEditing(false); + } catch { + // Error is handled in useUpdateProfile onError toast + } + }; - // ── Loading skeleton ────────────────────────────────────────────────────── - - if (!user) { + // ── Loading state ── + if (isLoading && !user) { return (
-
+
{Array.from({ length: 5 }).map((_, i) => (
@@ -142,100 +96,198 @@ export default function ProfilePage() { ); } + if (!user) { + return null; + } + return (
{/* ── Title + actions ──────────────────────────────────────────────── */} -
+

- {t("users.viewTitle", "Ulanyjy giňişleýin")}: {user.name} + {isEditing ? t("profile.editTitle", "Profili üýtgetmek") : `${t("profile.title", "Meniň profilim")}: ${user.name}`}

-
- +
+ {!isEditing ? ( + + ) : ( + + )}
- {/* ── Main info ────────────────────────────────────────────────────── */} -
- - - - - - - - -
+ {/* ── Main content ─────────────────────────────────────────────────── */} + {!isEditing ? ( + <> + + +
+ {user.avatar ? ( + avatar + ) : ( +
+ +
+ )} +
+

+ {[user.firstName, user.lastName].filter(Boolean).join(" ") || user.name} +

+ {user.phone &&

{user.phone}

} +
+
- {/* ── Rollar ───────────────────────────────────────────────────────── */} - - {}} - /> - String(row.id)} - currentPage={1} - totalPages={1} - totalCount={filteredRoles.length} - /> - + + + + + + {user.role && } + {user.email && } + + +
+ + {t("common.active", "Işjeň")} +
+
+
+
- {/* ── Rugsatlar ────────────────────────────────────────────────────── */} - - {}} - columnOrder={[]} - onColumnOrderChange={() => {}} - actionLabel={t("users.actions.addPermission", "Rugsat birikdiriň")} - onAction={() => {}} - /> - - + {/* ── Rollar ───────────────────────────────────────────────────────── */} + + {}} + columnOrder={[]} + onColumnOrderChange={() => {}} + actionLabel={t("users.actions.addRole", "Rol birikdiriň")} + onAction={() => {}} + /> + + - {/* ── Şahamçalar ───────────────────────────────────────────────────── */} - - {}} - columnOrder={[]} - onColumnOrderChange={() => {}} - actionLabel={t("users.actions.addBranch", "Şahamça birikdiriň")} - onAction={() => {}} - /> - - + {/* ── Rugsatlar ────────────────────────────────────────────────────── */} + + {}} + columnOrder={[]} + onColumnOrderChange={() => {}} + actionLabel={t("users.actions.addPermission", "Rugsat birikdiriň")} + onAction={() => {}} + /> + + - {/* ── Ammallar ─────────────────────────────────────────────────────── */} - - - + {/* ── Şahamçalar ───────────────────────────────────────────────────── */} + + {}} + columnOrder={[]} + onColumnOrderChange={() => {}} + actionLabel={t("users.actions.addBranch", "Şahamça birikdiriň")} + onAction={() => {}} + /> + + + + {/* ── Ammallar ─────────────────────────────────────────────────────── */} + + + + + ) : ( +
+ +
+ handleFieldChange("avatar", url)} + disabled={updateProfileMutation.isPending} + /> + + handleFieldChange("name", v)} + error={errors.name} + required + disabled={updateProfileMutation.isPending} + /> + +
+ handleFieldChange("firstName", v)} + disabled={updateProfileMutation.isPending} + /> + + handleFieldChange("lastName", v)} + disabled={updateProfileMutation.isPending} + /> +
+ + handleFieldChange("phone", v)} + disabled={updateProfileMutation.isPending} + /> + +
+ setIsEditing(false)} + isPending={updateProfileMutation.isPending} + submitLabel={t("common.save", "Ýatda sakla")} + /> +
+
+
+
+ )}
); } diff --git a/src/pages/users/allUsers/index.tsx b/src/pages/users/allUsers/index.tsx index 0b8436a..c5737c4 100644 --- a/src/pages/users/allUsers/index.tsx +++ b/src/pages/users/allUsers/index.tsx @@ -31,7 +31,7 @@ export default function UsersListPage() { const [search, setSearch] = useState(""); const [activeFilters, setActiveFilters] = useState([]); const [columnVisibility, setColumnVisibility] = useState({}); - const [columnOrder, setColumnOrder] = useState(["id", "username", "name", "phone", "email", "isActive", "actions"]); + const [columnOrder, setColumnOrder] = useState(["id", "username", "name", "phone", "email", "active", "actions"]); // Delete confirm dialog const [deleteTarget, setDeleteTarget] = useState(null); diff --git a/src/pages/users/allUsersView/index.tsx b/src/pages/users/allUsersView/index.tsx index caa7727..965bb39 100644 --- a/src/pages/users/allUsersView/index.tsx +++ b/src/pages/users/allUsersView/index.tsx @@ -1,49 +1,45 @@ import { useState } from "react"; -import { useNavigate, useParams } from "react-router-dom"; +import { useParams, useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Pencil, Trash2, CheckCircle2, XCircle, Link2 } from "lucide-react"; +import { Pencil, Trash2, XCircle, CheckCircle2, UserRound, Link2 } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Skeleton } from "@/components/ui/skeleton"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/components/ui/alert-dialog"; -import { Section, InfoRow } from "@/components/viewPageComponents"; +import { ConfirmDialog } from "@/components/confirmDialog"; +import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents"; import { useUser, useDeleteUser } from "@/features/allUsers/hooks/useAllUsers"; -// ─── UserViewPage ───────────────────────────────────────────────────────────── +// ─── ActiveIndicator ────────────────────────────────────────────────────────── + +function ActiveIndicator({ active }: { active: boolean }) { + return active ? : ; +} + +// ─── Page ───────────────────────────────────────────────────────────────────── 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 { t } = useTranslation(); + const navigate = useNavigate(); const deleteUser = useDeleteUser(); - const [showDeleteDialog, setShowDeleteDialog] = useState(false); + const { data: user, isLoading, isError } = useUser(userId); - const handleDeleteConfirm = async () => { - await deleteUser.mutateAsync(userId); - navigate("/all-users"); - }; + const [deleteOpen, setDeleteOpen] = useState(false); + + // ── Loading ─────────────────────────────────────────────────────────────── if (isLoading) { return ( -
+
-
- {Array.from({ length: 5 }).map((_, i) => ( -
- - +
+ {Array.from({ length: 4 }).map((_, i) => ( +
+ + {Array.from({ length: 3 }).map((_, j) => ( + + ))}
))}
@@ -51,9 +47,7 @@ export default function UserViewPage() { ); } - if (isError || !user) { - return
{t("common.notFound", "Maglumat tapylmady")}
; - } + if (isError || !user) return null; const socialLinks = [ { key: "facebook", url: user.socialMedia?.facebook, label: t("users.fields.facebook", "Facebook") }, @@ -62,107 +56,106 @@ export default function UserViewPage() { ].filter((s) => !!s.url); return ( -
- {/* Title + actions */} -
-

- {t("users.viewTitle", "Ulanyjy giňişleýin")}: {user.name} ({user.username}) +
+ {/* ── Page header ──────────────────────────────────────────────────── */} +
+

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

-
+
-
- {/* Main info */} -
- - - - - - - - - - {user.lightMode ? ( - {t("common.yes", "Hawa")} - ) : ( - {t("common.no", "Ýok")} - )} - - - {user.active ? ( - - ) : ( - - )} - - {user.avatar && ( - - - {user.avatar} - + {/* ── Esasy maglumatlar + Kontakt ──────────────────────────────────── */} + + +
+ {user.avatar ? ( + avatar + ) : ( +
+ +
+ )} +
+

{user.name}

+
+
+ + + + + + + + + +
+ + + + + {socialLinks.length > 0 && ( + <> + {socialLinks.map((s) => ( + + + + {s.url} + + + ))} + + )} + +
+ + - -
- - {/* Sosial media */} - {socialLinks.length > 0 && ( -
- {socialLinks.map((s) => ( - - - - {s.url} - - - ))} -
- )} - - {/* 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")} - - - - + confirmLabel={t("common.delete", "Öçür")} + onConfirm={async () => { + await deleteUser.mutateAsync(userId); + navigate("/all-users"); + }} + isLoading={deleteUser.isPending} + />
); } diff --git a/src/pages/users/clientsView/index.tsx b/src/pages/users/clientsView/index.tsx index 0801885..176d645 100644 --- a/src/pages/users/clientsView/index.tsx +++ b/src/pages/users/clientsView/index.tsx @@ -1,15 +1,13 @@ import { useState } from "react"; -import { useParams, useNavigate } from "react-router-dom"; +import { useParams, useNavigate, Link } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Pencil, Trash2, XCircle, CheckCircle2 } from "lucide-react"; +import { Pencil, Trash2, XCircle, CheckCircle2, UserRound } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Skeleton } from "@/components/ui/skeleton"; import { ConfirmDialog } from "@/components/confirmDialog"; -import { BentoGrid, BentoCard, InfoRow, AuditLog, CollapsibleSection, EmptyState } from "@/components/viewPageComponents"; -import { DataTable, type ColumnDef } from "@/components/dataTable"; -import { DataTableToolbar } from "@/components/dataTableToolbar"; +import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents"; +import { Badge } from "@/components/ui/badge"; import { useClient, useDeleteClient } from "@/features/clients/hooks/useClients"; -import type { ClientRole, ClientBranch, ClientAuditLog } from "@/features/clients/api/clientsApi"; // ─── ActiveIndicator ────────────────────────────────────────────────────────── @@ -29,92 +27,6 @@ export default function ClientDetailPage() { 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(""); - - // ── Role columns ────────────────────────────────────────────────────────── - - const roleColumns: ColumnDef[] = [ - { - accessorKey: "id", - header: t("common.id", "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, - }, - ]; - - // ── Branch columns ──────────────────────────────────────────────────────── - - const branchColumns: ColumnDef[] = [ - { - accessorKey: "id", - header: t("common.id", "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, - }, - ]; // ── Loading ─────────────────────────────────────────────────────────────── @@ -138,19 +50,9 @@ export default function ClientDetailPage() { 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())); + const roles = client.roles ?? []; + const permissions = client.permissions ?? []; + const branches = client.branches ?? []; return (
@@ -182,12 +84,77 @@ export default function ClientDetailPage() { {/* ── Row 1: Esasy maglumatlar + Kontakt ──────────────────────────── */} +
+ {client.avatar ? ( + avatar + ) : ( +
+ +
+ )} +
+

{client.name}

+
+
+ + {roles.length > 0 && ( + +
+ {roles.map((r) => ( + + {r.name} + + ))} +
+
+ )} + {permissions.length > 0 && ( + +
+ {permissions.map((p) => ( + + {p.name} + + ))} +
+
+ )} + {branches.length > 0 && ( + +
+ {branches.map((b) => ( + + + {b.name} + + {b.region ? ( + <> + {" — "} + + {b.region} + + + ) : null} + + ))} +
+
+ )}
@@ -196,108 +163,6 @@ export default function ClientDetailPage() {
- {/* ── Rollar ───────────────────────────────────────────────────────── */} - - {}} - columnOrder={[]} - onColumnOrderChange={() => {}} - actionLabel={t("clients.addRole", "Rol birikdiriň")} - onAction={() => {}} - /> - {filteredRoles.length > 0 ? ( - String(r.id)} enableRowSelection /> - ) : ( - - )} - - - {/* ── Rugsatlar ────────────────────────────────────────────────────── */} - - {}} - columnOrder={[]} - onColumnOrderChange={() => {}} - actionLabel={t("clients.addPermission", "Rugsat birikdiriň")} - onAction={() => {}} - /> - {(client.permissions ?? []).length === 0 && ( - - )} - - - {/* ── Şahamçalar ───────────────────────────────────────────────────── */} - - {}} - columnOrder={[]} - onColumnOrderChange={() => {}} - actionLabel={t("clients.addBranch", "Şahamça birikdiriň")} - onAction={() => {}} - /> - {filteredBranches.length > 0 ? ( - String(r.id)} enableRowSelection /> - ) : ( - - )} - - - {/* ── Karz sargyt ──────────────────────────────────────────────────── */} - - {}} - columnOrder={[]} - onColumnOrderChange={() => {}} - actionLabel={t("clients.addLoanOrder", "Karz sargyt dörediň")} - onAction={() => {}} - /> - {(client.loanOrders ?? []).length === 0 && ( - - )} - - - {/* ── Kart sargyt ──────────────────────────────────────────────────── */} - - {}} - columnOrder={[]} - onColumnOrderChange={() => {}} - actionLabel={t("clients.addCardOrder", "Kart sargyt dörediň")} - onAction={() => {}} - /> - {(client.cardOrders ?? []).length === 0 && ( - - )} - - - {/* ── Audit log ────────────────────────────────────────────────────── */} - - {row.original.name}, }, + { + accessorKey: "role", + header: t("operators.fields.role", "ROLY"), + cell: ({ row }) => {row.original.role ?? "—"}, + }, { accessorKey: "phone", header: t("operators.fields.phone", "TELEFON"), diff --git a/src/pages/users/operatorsView/index.tsx b/src/pages/users/operatorsView/index.tsx index ba4cf5f..f6a6c68 100644 --- a/src/pages/users/operatorsView/index.tsx +++ b/src/pages/users/operatorsView/index.tsx @@ -1,16 +1,21 @@ -import { useParams, useNavigate } from "react-router-dom"; +import { useParams, useNavigate, Link } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { TableActions } from "@/components/tableActions"; -import { Pencil, Trash2, CheckCircle2, XCircle } from "lucide-react"; +import { Pencil, Trash2, CheckCircle2, XCircle, UserRound } from "lucide-react"; import { useState } from "react"; import { Button } from "@/components/ui/button"; import { Skeleton } from "@/components/ui/skeleton"; import { ConfirmDialog } from "@/components/confirmDialog"; -import { BentoGrid, BentoCard, InfoRow, AuditLog, CollapsibleSection, EmptyState } from "@/components/viewPageComponents"; -import { DataTable, type ColumnDef } from "@/components/dataTable"; -import { DataTableToolbar } from "@/components/dataTableToolbar"; +import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents"; +import { Badge } from "@/components/ui/badge"; import { useOperator, useDeleteOperator } from "@/features/operators/hooks/useOperators"; -import type { OperatorRole, OperatorBranch, OperatorAuditLog, OperatorPermission } from "@/features/operators/api/operatorsApi"; +import type { LocalizedText } from "@/features/branches/api/branchesApi"; + +// ─── Helper: resolve LocalizedText | string ─────────────────────────────────── + +function resolveLocalizedName(name: LocalizedText | string, lang = "en"): string { + if (typeof name === "string") return name; + return name[lang as keyof LocalizedText] ?? name.en ?? ""; +} // ─── ActiveIndicator ────────────────────────────────────────────────────────── @@ -23,145 +28,14 @@ function ActiveIndicator({ active }: { active: boolean }) { export default function OperatorDetailPage() { const { id } = useParams<{ id: string }>(); const operatorId = Number(id); - const { t } = useTranslation(); + const { t, i18n } = useTranslation(); + const lang = i18n.language ?? "en"; 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: t("common.id", "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: "", - size: 120, - cell: ({ row }) => navigate(`/roles/${row.original.id}`)} />, - }, - ]; - - // ── Permission columns ──────────────────────────────────────────────────── - - const permissionColumns: ColumnDef[] = [ - { - accessorKey: "id", - header: t("common.id", "ID"), - cell: ({ row }) => {row.original.id}, - size: 80, - }, - { - accessorKey: "name", - header: t("permissions.fields.name", "ADY"), - cell: ({ row }) => {row.original.name}, - }, - { - accessorKey: "guardName", - header: t("permissions.fields.guardName", "GUARD NAME"), - cell: ({ row }) => {row.original.guardName}, - }, - { - id: "actions", - header: "", - size: 60, - cell: () => ( -
- -
- ), - }, - ]; - - // ── Branch columns ──────────────────────────────────────────────────────── - - const branchColumns: ColumnDef[] = [ - { - accessorKey: "id", - header: t("common.id", "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 }) => , - 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: "", - size: 60, - cell: () => ( -
- -
- ), - }, - ]; // ── Loading ─────────────────────────────────────────────────────────────── @@ -185,22 +59,9 @@ export default function OperatorDetailPage() { if (!operator) return null; - 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 filteredPermissions = (operator.permissions ?? []).filter((p) => p.name.toLowerCase().includes(permSearch.toLowerCase())); - - const filteredBranches = (operator.branches ?? []).filter((b) => b.name.toLowerCase().includes(branchSearch.toLowerCase())); + const roles = operator.roles ?? []; + const permissions = operator.permissions ?? []; + const branches = operator.branches ?? []; return (
@@ -232,12 +93,77 @@ export default function OperatorDetailPage() { {/* ── Esasy maglumatlar + Kontakt ──────────────────────────────────── */} +
+ {operator.avatar ? ( + avatar + ) : ( +
+ +
+ )} +
+

{operator.name}

+
+
+ + {roles.length > 0 && ( + +
+ {roles.map((r) => ( + + {r.name} + + ))} +
+
+ )} + {permissions.length > 0 && ( + +
+ {permissions.map((p) => ( + + {p.name} + + ))} +
+
+ )} + {branches.length > 0 && ( + +
+ {branches.map((b) => ( + + + {resolveLocalizedName(b.name, lang)} + + {b.region ? ( + <> + {" — "} + + {b.region} + + + ) : null} + + ))} +
+
+ )}
@@ -246,102 +172,6 @@ export default function OperatorDetailPage() {
- {/* ── Rollar ───────────────────────────────────────────────────────── */} - - {}} - columnOrder={[]} - onColumnOrderChange={() => {}} - actionLabel={t("operators.addRole", "Rol birikdiriň")} - onAction={() => {}} - /> - String(r.id)} enableRowSelection /> - - - {/* ── Rugsatlar ────────────────────────────────────────────────────── */} - - {}} - columnOrder={[]} - onColumnOrderChange={() => {}} - actionLabel={t("operators.addPermission", "Rugsat birikdiriň")} - onAction={() => {}} - /> - {filteredPermissions.length === 0 ? ( - - ) : ( - String(p.id)} enableRowSelection /> - )} - - - {/* ── Şahamçalar ───────────────────────────────────────────────────── */} - - {}} - columnOrder={[]} - onColumnOrderChange={() => {}} - actionLabel={t("operators.addBranch", "Şahamça birikdiriň")} - onAction={() => {}} - /> - String(r.id)} enableRowSelection /> - - - {/* ── Karz sargyt ──────────────────────────────────────────────────── */} - - {}} - columns={[]} - columnVisibility={{}} - onColumnVisibilityChange={() => {}} - columnOrder={[]} - onColumnOrderChange={() => {}} - actionLabel={t("operators.addLoanLimit", "Karz sargyt döredin")} - onAction={() => {}} - hideSearch - /> - {(operator.loanLimits ?? []).length === 0 && ( - - )} - - - {/* ── Kart sargyt ──────────────────────────────────────────────────── */} - - {}} - columns={[]} - columnVisibility={{}} - onColumnVisibilityChange={() => {}} - columnOrder={[]} - onColumnOrderChange={() => {}} - actionLabel={t("operators.addCardLimit", "Kart sargyt döredin")} - onAction={() => {}} - hideSearch - /> - {(operator.cardLimits ?? []).length === 0 && ( - - )} - - - {/* ── Audit log ────────────────────────────────────────────────────── */} - -