diff options
Diffstat (limited to 'lib/vendor-users/table')
| -rw-r--r-- | lib/vendor-users/table/add-ausers-dialog.tsx | 291 | ||||
| -rw-r--r-- | lib/vendor-users/table/ausers-table-columns.tsx | 228 | ||||
| -rw-r--r-- | lib/vendor-users/table/ausers-table-floating-bar.tsx | 302 | ||||
| -rw-r--r-- | lib/vendor-users/table/ausers-table-toolbar-actions.tsx | 118 | ||||
| -rw-r--r-- | lib/vendor-users/table/ausers-table.tsx | 163 | ||||
| -rw-r--r-- | lib/vendor-users/table/delete-ausers-dialog.tsx | 149 | ||||
| -rw-r--r-- | lib/vendor-users/table/update-auser-sheet.tsx | 273 |
7 files changed, 1524 insertions, 0 deletions
diff --git a/lib/vendor-users/table/add-ausers-dialog.tsx b/lib/vendor-users/table/add-ausers-dialog.tsx new file mode 100644 index 00000000..632adb7f --- /dev/null +++ b/lib/vendor-users/table/add-ausers-dialog.tsx @@ -0,0 +1,291 @@ +"use client" + +import * as React from "react" +import { useForm } from "react-hook-form" +import { zodResolver } from "@hookform/resolvers/zod" +import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog" +import { Button } from "@/components/ui/button" +import { Input } from "@/components/ui/input" + +// react-hook-form + shadcn/ui Form +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, + FormDescription, +} from "@/components/ui/form" +import { + Select, + SelectContent, + SelectGroup, + SelectItem, + SelectLabel, + SelectTrigger, + SelectValue, +} from "@/components/ui/select" +import { Role, userRoles } from "@/db/schema/users" +import { type Company } from "@/db/schema/companies" +import { MultiSelect } from "@/components/ui/multi-select" +import { + Popover, + PopoverTrigger, + PopoverContent, +} from "@/components/ui/popover" +import { + Command, + CommandInput, + CommandList, + CommandGroup, + CommandItem, + CommandEmpty, +} from "@/components/ui/command" +import { Check, ChevronsUpDown, Loader } from "lucide-react" +import { cn } from "@/lib/utils" +import { toast } from "sonner" +import { Vendor } from "@/db/schema/vendors" +import { CreateVendorUserSchema, createVendorUserSchema } from "../validations" +import { createVendorUser, getAllRolesbyVendor } from "../service" + +const languageOptions = [ + { value: "ko", label: "한국어" }, + { value: "en", label: "English" }, +] + + +// Phone validation helper +const validatePhoneNumber = (phone: string): boolean => { + if (!phone) return false; + // Basic international phone number validation + const cleanPhone = phone.replace(/[\s\-\(\)]/g, ''); + return /^\+\d{10,15}$/.test(cleanPhone); +}; + +// Get phone placeholder based on common patterns +const getPhonePlaceholder = (): string => { + return "+82 010-1234-5678"; // Default to Korean format +}; + +// Get phone description +const getPhoneDescription = (): string => { + return "국제 전화번호를 입력하세요. (예: +82 010-1234-5678)"; +}; + +export function AddUserDialog() { + const [open, setOpen] = React.useState(false) + const [roles, setRoles] = React.useState<Role[]>([]) + const [isAddPending, startAddTransition] = React.useTransition() + + React.useEffect(() => { + getAllRolesbyVendor().then((res) => { + setRoles(res) + }) + }, []) + + // react-hook-form 세팅 + const form = useForm<CreateVendorUserSchema & { language?: string; phone?: string }>({ + resolver: zodResolver(createVendorUserSchema), + defaultValues: { + name: "", + email: "", + phone: "", // Add phone field + companyId: null, + language: 'en', + roles: ["Vendor Admin"], + domain: 'partners' + }, + }) + + async function onSubmit(data: CreateVendorUserSchema & { language?: string; phone?: string }) { + data.domain = "partners" + + // Validate phone number if provided + if (data.phone && !validatePhoneNumber(data.phone)) { + toast.error("올바른 국제 전화번호 형식이 아닙니다.") + return + } + + startAddTransition(async () => { + const result = await createVendorUser(data) + if (result.error) { + toast.error(`에러: ${result.error}`) + return + } + form.reset() + setOpen(false) + toast.success("User added") + }) + } + + function handleDialogOpenChange(nextOpen: boolean) { + if (!nextOpen) { + form.reset() + } + setOpen(nextOpen) + } + + return ( + <Dialog open={open} onOpenChange={handleDialogOpenChange}> + {/* 모달을 열기 위한 버튼 */} + <DialogTrigger asChild> + <Button variant="default" size="sm"> + Add User + </Button> + </DialogTrigger> + + <DialogContent className="max-w-md"> + <DialogHeader> + <DialogTitle>Create New User</DialogTitle> + <DialogDescription> + 새 User 정보를 입력하고 <b>Create</b> 버튼을 누르세요. + </DialogDescription> + </DialogHeader> + + {/* shadcn/ui Form을 이용해 react-hook-form과 연결 */} + <Form {...form}> + <form onSubmit={form.handleSubmit(onSubmit)}> + <div className="space-y-4 py-4"> + {/* 사용자 이름 */} + <FormField + control={form.control} + name="name" + render={({ field }) => ( + <FormItem> + <FormLabel>User Name</FormLabel> + <FormControl> + <Input + placeholder="e.g. dujin" + {...field} + /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + {/* 이메일 */} + <FormField + control={form.control} + name="email" + render={({ field }) => ( + <FormItem> + <FormLabel>Email</FormLabel> + <FormControl> + <Input + placeholder="e.g. user@example.com" + type="email" + {...field} + /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + {/* 전화번호 - 새로 추가 */} + <FormField + control={form.control} + name="phone" + render={({ field }) => ( + <FormItem> + <FormLabel>Phone Number</FormLabel> + <FormControl> + <Input + placeholder={getPhonePlaceholder()} + {...field} + className={cn( + field.value && !validatePhoneNumber(field.value) && "border-red-500" + )} + /> + </FormControl> + <FormDescription className="text-xs text-muted-foreground"> + {getPhoneDescription()} + </FormDescription> + <FormMessage /> + </FormItem> + )} + /> + + {/* Role (Vendor Admin) - 읽기 전용 */} + <FormField + control={form.control} + name="roles" + render={({ field }) => ( + <FormItem> + <FormLabel>Role</FormLabel> + <FormControl> + <Input + readOnly + disabled + value="Vendor Admin" + className="bg-gray-50 text-gray-500" + /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + {/* language Select */} + <FormField + control={form.control} + name="language" + render={({ field }) => ( + <FormItem> + <FormLabel>Language</FormLabel> + <FormControl> + <Select + onValueChange={field.onChange} + value={field.value} + > + <SelectTrigger> + <SelectValue placeholder="Select language" /> + </SelectTrigger> + <SelectContent> + {languageOptions.map((v, index) => ( + <SelectItem key={index} value={v.value}> + {v.label} + </SelectItem> + ))} + </SelectContent> + </Select> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + </div> + + <DialogFooter> + <Button + type="button" + variant="outline" + onClick={() => setOpen(false)} + disabled={isAddPending} + > + {isAddPending && ( + <Loader + className="mr-2 size-4 animate-spin" + aria-hidden="true" + /> + )} + Cancel + </Button> + <Button type="submit" disabled={form.formState.isSubmitting || isAddPending}> + {isAddPending && ( + <Loader + className="mr-2 size-4 animate-spin" + aria-hidden="true" + /> + )} + Create + </Button> + </DialogFooter> + </form> + </Form> + </DialogContent> + </Dialog> + ) +}
\ No newline at end of file diff --git a/lib/vendor-users/table/ausers-table-columns.tsx b/lib/vendor-users/table/ausers-table-columns.tsx new file mode 100644 index 00000000..38281c7e --- /dev/null +++ b/lib/vendor-users/table/ausers-table-columns.tsx @@ -0,0 +1,228 @@ +"use client" + +import * as React from "react" +import { type DataTableRowAction } from "@/types/table" +import { type ColumnDef } from "@tanstack/react-table" +import { Ellipsis } from "lucide-react" +import { userRoles, type UserView } from "@/db/schema/users" + +import { formatDate } from "@/lib/utils" +import { Badge } from "@/components/ui/badge" +import { Button } from "@/components/ui/button" +import { Checkbox } from "@/components/ui/checkbox" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuRadioGroup, + DropdownMenuRadioItem, + DropdownMenuSeparator, + DropdownMenuShortcut, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu" +import { DataTableColumnHeader } from "@/components/data-table/data-table-column-header" +import { UserWithCompanyAndRoles } from "@/types/user" +import { getErrorMessage } from "@/lib/handle-error" + +import { modifiUser } from "@/lib/admin-users/service" +import { toast } from "sonner" + +import { userColumnsConfig } from "@/config/userColumnsConfig" +import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header" +import { MultiSelect } from "@/components/ui/multi-select" + +interface GetColumnsProps { + setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<UserView> | null>> +} + +/** + * tanstack table 컬럼 정의 (중첩 헤더 버전) + */ +export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<UserView>[] { + // ---------------------------------------------------------------- + // 1) select 컬럼 (체크박스) + // ---------------------------------------------------------------- + const selectColumn: ColumnDef<UserView> = { + id: "select", + header: ({ table }) => ( + <Checkbox + checked={ + table.getIsAllPageRowsSelected() || + (table.getIsSomePageRowsSelected() && "indeterminate") + } + onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)} + aria-label="Select all" + className="translate-y-0.5" + /> + ), + cell: ({ row }) => ( + <Checkbox + checked={row.getIsSelected()} + onCheckedChange={(value) => row.toggleSelected(!!value)} + aria-label="Select row" + className="translate-y-0.5" + /> + ), + size:40, + enableSorting: false, + enableHiding: false, + } + + // ---------------------------------------------------------------- + // 2) actions 컬럼 (Dropdown 메뉴) + // ---------------------------------------------------------------- + const actionsColumn: ColumnDef<UserView> = { + id: "actions", + enableHiding: false, + cell: function Cell({ row }) { + const [isUpdatePending, startUpdateTransition] = React.useTransition() + + return ( + <DropdownMenu> + <DropdownMenuTrigger asChild> + <Button + aria-label="Open menu" + variant="ghost" + className="flex size-8 p-0 data-[state=open]:bg-muted" + > + <Ellipsis className="size-4" aria-hidden="true" /> + </Button> + </DropdownMenuTrigger> + <DropdownMenuContent align="end" className="w-40"> + <DropdownMenuItem + onSelect={() => setRowAction({ row, type: "update" })} + > + Edit + </DropdownMenuItem> + + {/* <DropdownMenuSub> + <DropdownMenuSubTrigger>Roles</DropdownMenuSubTrigger> + <DropdownMenuSubContent> + <MultiSelect + defaultValue={row.original.roles} + options={userRoles.role.enumValues.map((role) => ({ + value: role, + label: role, + }))} + value={row.original.roles} + onValueChange={(value) => { + startUpdateTransition(() => { + + toast.promise( + modifiUser({ + id: row.original.user_id, + roles: value as ("admin"|"normal")[], + }), + { + loading: "Updating...", + success: "Roles updated", + error: (err) => getErrorMessage(err), + } + ); + }); + }} + + /> + </DropdownMenuSubContent> + </DropdownMenuSub> */} + + <DropdownMenuSeparator /> + <DropdownMenuItem + onSelect={() => setRowAction({ row, type: "delete" })} + > + Delete + <DropdownMenuShortcut>⌘⌫</DropdownMenuShortcut> + </DropdownMenuItem> + </DropdownMenuContent> + </DropdownMenu> + ) + }, + size: 40, + } + + // ---------------------------------------------------------------- + // 3) 일반 컬럼들을 "그룹"별로 묶어 중첩 columns 생성 + // ---------------------------------------------------------------- + // 3-1) groupMap: { [groupName]: ColumnDef<User>[] } + const groupMap: Record<string, ColumnDef<UserView>[]> = {} + + userColumnsConfig.forEach((cfg) => { + // 만약 group가 없으면 "_noGroup" 처리 + const groupName = cfg.group || "_noGroup" + + if (!groupMap[groupName]) { + groupMap[groupName] = [] + } + + // child column 정의 + const childCol: ColumnDef<UserView> = { + accessorKey: cfg.id, + enableResizing: true, + header: ({ column }) => ( + <DataTableColumnHeaderSimple column={column} title={cfg.label} /> + ), + meta: { + excelHeader: cfg.excelHeader, + group: cfg.group, + type: cfg.type, + }, + cell: ({ row, cell }) => { + + if (cfg.id === "created_at") { + const dateVal = cell.getValue() as Date + return formatDate(dateVal) + } + + if (cfg.id === "roles") { + const roleValues = row.original.roles; + return ( + <div className="flex flex-wrap gap-1"> + {roleValues.map((v) => ( + <Badge key={v} variant="outline"> + {v} + </Badge> + ))} + </div> + ); + } + + return row.getValue(cfg.id) ?? "" + }, + } + + groupMap[groupName].push(childCol) + }) + + // ---------------------------------------------------------------- + // 3-2) groupMap에서 실제 상위 컬럼(그룹)을 만들기 + // ---------------------------------------------------------------- + const nestedColumns: ColumnDef<UserView>[] = [] + + // 순서를 고정하고 싶다면 group 순서를 미리 정의하거나 sort해야 함 + // 여기서는 그냥 Object.entries 순서 + Object.entries(groupMap).forEach(([groupName, colDefs]) => { + if (groupName === "_noGroup") { + // 그룹 없음 → 그냥 최상위 레벨 컬럼 + nestedColumns.push(...colDefs) + } else { + // 상위 컬럼 + nestedColumns.push({ + id: groupName, + header: groupName, // "Basic Info", "Metadata" 등 + columns: colDefs, + }) + } + }) + + // ---------------------------------------------------------------- + // 4) 최종 컬럼 배열: select, nestedColumns, actions + // ---------------------------------------------------------------- + return [ + selectColumn, + ...nestedColumns, + actionsColumn, + ] +}
\ No newline at end of file diff --git a/lib/vendor-users/table/ausers-table-floating-bar.tsx b/lib/vendor-users/table/ausers-table-floating-bar.tsx new file mode 100644 index 00000000..8778da45 --- /dev/null +++ b/lib/vendor-users/table/ausers-table-floating-bar.tsx @@ -0,0 +1,302 @@ +"use client" + +import * as React from "react" +import { userRoles, users, UserView, type User } from "@/db/schema/users" +import { SelectTrigger } from "@radix-ui/react-select" +import { type Table } from "@tanstack/react-table" +import { + ArrowUp, + CheckCircle2, + Download, + Loader, + Trash2, + X, Check +} from "lucide-react" +import { toast } from "sonner" + +import { exportTableToExcel } from "@/lib/export" +import { Button } from "@/components/ui/button" +import { Portal } from "@/components/ui/portal" +import { + Select, + SelectContent, + SelectGroup, + SelectItem, +} from "@/components/ui/select" +import { Separator } from "@/components/ui/separator" +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@/components/ui/tooltip" +import { Kbd } from "@/components/kbd" + +import { + Popover, + PopoverTrigger, + PopoverContent, +} from "@/components/ui/popover" +import { + Command, + CommandInput, + CommandList, + CommandGroup, + CommandItem, + CommandEmpty, +} from "@/components/ui/command" +import { cn } from "@/lib/utils" +import { MultiSelect } from "@/components/ui/multi-select" +import { ActionConfirmDialog } from "@/components/ui/action-dialog" +import { modifiVendorUsers, removeVendorUsers } from "../service" + +interface AusersTableFloatingBarProps { + table: Table<UserView> +} + + +export function AusersTableFloatingBar({ table }: AusersTableFloatingBarProps) { + const rows = table.getFilteredSelectedRowModel().rows + + const [isPending, startTransition] = React.useTransition() + const [action, setAction] = React.useState< + "update-roles" | "export" | "delete" + >() + + // Clear selection on Escape key press + React.useEffect(() => { + function handleKeyDown(event: KeyboardEvent) { + if (event.key === "Escape") { + table.toggleAllRowsSelected(false) + } + } + + window.addEventListener("keydown", handleKeyDown) + return () => window.removeEventListener("keydown", handleKeyDown) + }, [table]) + + + const [popoverOpen, setPopoverOpen] = React.useState(false) + const [rolesPopoverOpen, setRolesPopoverOpen] = React.useState(false) + + + // 공용 confirm dialog state + const [confirmDialogOpen, setConfirmDialogOpen] = React.useState(false) + const [confirmProps, setConfirmProps] = React.useState<{ + title: string + description?: string + onConfirm: () => Promise<void> | void + }>({ + title: "", + description: "", + onConfirm: () => { }, + }) + + // 1) "삭제" Confirm 열기 + function handleDeleteConfirm() { + setAction("delete") + setConfirmProps({ + title: `Delete ${rows.length} user${rows.length > 1 ? "s" : ""}?`, + description: "This action cannot be undone.", + onConfirm: async () => { + startTransition(async () => { + const { error } = await removeVendorUsers({ + ids: rows.map((row) => row.original.user_id), + }) + if (error) { + toast.error(error) + return + } + toast.success("Users deleted") + table.toggleAllRowsSelected(false) + setConfirmDialogOpen(false) + }) + }, + }) + setConfirmDialogOpen(true) + } + + + // 3) "역할 업데이트" MultiSelect 후 → Confirm Dialog + function handleSelectRoles(newRoles: string[]) { + setAction("update-roles") + setRolesPopoverOpen(false) + + setConfirmProps({ + title: `Update ${rows.length} user${rows.length > 1 ? "s" : ""} with roles: ${newRoles.join(", ")}?`, + description: "This action will override their current roles.", + onConfirm: async () => { + startTransition(async () => { + const { error } = await modifiVendorUsers({ + ids: rows.map((row) => row.original.user_id), + roles: newRoles as ("admin" | "normal")[], + }) + if (error) { + toast.error(error) + return + } + toast.success("Users updated") + setConfirmDialogOpen(false) + }) + }, + }) + setConfirmDialogOpen(true) + } + + return ( + <Portal > + <div className="fixed inset-x-0 bottom-10 z-50 mx-auto w-fit px-2.5" style={{ bottom: '1.5rem' }}> + <div className="w-full overflow-x-auto"> + <div className="mx-auto flex w-fit items-center gap-2 rounded-md border bg-background p-2 text-foreground shadow"> + <div className="flex h-7 items-center rounded-md border border-dashed pl-2.5 pr-1"> + <span className="whitespace-nowrap text-xs"> + {rows.length} selected + </span> + <Separator orientation="vertical" className="ml-2 mr-1" /> + <Tooltip> + <TooltipTrigger asChild> + <Button + variant="ghost" + size="icon" + className="size-5 hover:border" + onClick={() => table.toggleAllRowsSelected(false)} + > + <X className="size-3.5 shrink-0" aria-hidden="true" /> + </Button> + </TooltipTrigger> + <TooltipContent className="flex items-center border bg-accent px-2 py-1 font-semibold text-foreground dark:bg-zinc-900"> + <p className="mr-2">Clear selection</p> + <Kbd abbrTitle="Escape" variant="outline"> + Esc + </Kbd> + </TooltipContent> + </Tooltip> + </div> + <Separator orientation="vertical" className="hidden h-5 sm:block" /> + <div className="flex items-center gap-1.5"> + + <Popover open={rolesPopoverOpen} onOpenChange={setRolesPopoverOpen}> + + <Tooltip> + <PopoverTrigger asChild> + <TooltipTrigger asChild> + <Button + variant="secondary" + size="icon" + className="size-7 border data-[state=open]:bg-accent data-[state=open]:text-accent-foreground" + disabled={isPending} + > + {isPending && action === "update-roles" ? ( + <Loader + className="size-3.5 animate-spin" + aria-hidden="true" + /> + ) : ( + <ArrowUp className="size-3.5" aria-hidden="true" /> + + )} + </Button> + </TooltipTrigger> + </PopoverTrigger> + <TooltipContent className="border bg-accent font-semibold text-foreground dark:bg-zinc-900"> + <p>Update roles</p> + </TooltipContent> + </Tooltip> + <PopoverContent> + <MultiSelect + defaultValue={["999999999"]} + options={[ + /* ... */ + { value: "999999999", label: "admin" } + ]} + onValueChange={(newRoles) => { + handleSelectRoles(newRoles) + }} + /> + </PopoverContent> + + </Popover> + + + <Tooltip> + <TooltipTrigger asChild> + <Button + variant="secondary" + size="icon" + className="size-7 border" + onClick={() => { + setAction("export") + + startTransition(() => { + exportTableToExcel(table, { + excludeColumns: ["select", "actions"], + onlySelected: true, + }) + }) + }} + disabled={isPending} + > + {isPending && action === "export" ? ( + <Loader + className="size-3.5 animate-spin" + aria-hidden="true" + /> + ) : ( + <Download className="size-3.5" aria-hidden="true" /> + )} + </Button> + </TooltipTrigger> + <TooltipContent className="border bg-accent font-semibold text-foreground dark:bg-zinc-900"> + <p>Export users</p> + </TooltipContent> + </Tooltip> + + <Tooltip> + <TooltipTrigger asChild> + <Button + variant="secondary" + size="icon" + className="size-7 border" + onClick={handleDeleteConfirm} + disabled={isPending} + > + {isPending && action === "delete" ? ( + <Loader + className="size-3.5 animate-spin" + aria-hidden="true" + /> + ) : ( + <Trash2 className="size-3.5" aria-hidden="true" /> + )} + </Button> + </TooltipTrigger> + <TooltipContent className="border bg-accent font-semibold text-foreground dark:bg-zinc-900"> + <p>Delete users</p> + </TooltipContent> + </Tooltip> + </div> + </div> + </div> + </div> + + {/* 공용 Confirm Dialog */} + <ActionConfirmDialog + open={confirmDialogOpen} + onOpenChange={setConfirmDialogOpen} + title={confirmProps.title} + description={confirmProps.description} + onConfirm={confirmProps.onConfirm} + isLoading={isPending && (action === "delete" || action === "update-roles")} + confirmLabel={ + action === "delete" + ? "Delete" + : action === "update-roles" + ? "Update" + : "Confirm" + } + confirmVariant={ + action === "delete" ? "destructive" : "default" + } + /> + </Portal> + ) +} diff --git a/lib/vendor-users/table/ausers-table-toolbar-actions.tsx b/lib/vendor-users/table/ausers-table-toolbar-actions.tsx new file mode 100644 index 00000000..5472c3ac --- /dev/null +++ b/lib/vendor-users/table/ausers-table-toolbar-actions.tsx @@ -0,0 +1,118 @@ +"use client" + +import * as React from "react" +import { type Task } from "@/db/schema/tasks" +import { type Table } from "@tanstack/react-table" +import { Download, Upload } from "lucide-react" +import { toast } from "sonner" + +import { exportTableToExcel } from "@/lib/export" +import { Button } from "@/components/ui/button" + +// 삭제, 추가 다이얼로그 +import { DeleteUsersDialog } from "./delete-ausers-dialog" +import { AddUserDialog } from "./add-ausers-dialog" + +// 만약 서버 액션이나 API 라우트를 이용해 업로드 처리한다면 import +import { importTasksExcel } from "@/lib/tasks/service" // 예시 +import { type UserView } from "@/db/schema/users" + +interface AdmUserTableToolbarActionsProps { + table: Table<UserView> +} + +export function AdmUserTableToolbarActions({ table }: AdmUserTableToolbarActionsProps) { + // 파일 input을 숨기고, 버튼 클릭 시 참조해 클릭하는 방식 + const fileInputRef = React.useRef<HTMLInputElement>(null) + + // 파일이 선택되었을 때 처리 + async function onFileChange(event: React.ChangeEvent<HTMLInputElement>) { + const file = event.target.files?.[0] + if (!file) return + + // 파일 초기화 (동일 파일 재업로드 시에도 onChange가 트리거되도록) + event.target.value = "" + + // 서버 액션 or API 호출 + try { + // 예: 서버 액션 호출 + const { errorFile, errorMessage } = await importTasksExcel(file) + + if (errorMessage) { + toast.error(errorMessage) + } + if (errorFile) { + // 에러 엑셀을 다운로드 + const url = URL.createObjectURL(errorFile) + const link = document.createElement("a") + link.href = url + link.download = "errors.xlsx" + link.click() + URL.revokeObjectURL(url) + } else { + // 성공 + toast.success("Import success") + // 필요 시 revalidateTag("tasks") 등 + } + + } catch (err) { + toast.error("파일 업로드 중 오류가 발생했습니다.") + + } + } + + function handleImportClick() { + // 숨겨진 <input type="file" /> 요소를 클릭 + fileInputRef.current?.click() + } + + return ( + <div className="flex items-center gap-2"> + {/** 1) 선택된 로우가 있으면 삭제 다이얼로그 */} + {table.getFilteredSelectedRowModel().rows.length > 0 ? ( + <DeleteUsersDialog + users={table + .getFilteredSelectedRowModel() + .rows.map((row) => row.original)} + onSuccess={() => table.toggleAllRowsSelected(false)} + /> + ) : null} + + {/** 2) 새 Task 추가 다이얼로그 */} + <AddUserDialog /> + + {/** 3) Import 버튼 (파일 업로드) */} + <Button variant="outline" size="sm" className="gap-2" onClick={handleImportClick}> + <Upload className="size-4" aria-hidden="true" /> + <span className="hidden sm:inline">Import</span> + </Button> + {/* + 실제로는 숨겨진 input과 연결: + - accept=".xlsx,.xls" 등으로 Excel 파일만 업로드 허용 + */} + <input + ref={fileInputRef} + type="file" + accept=".xlsx,.xls" + className="hidden" + onChange={onFileChange} + /> + + {/** 4) Export 버튼 */} + <Button + variant="outline" + size="sm" + onClick={() => + exportTableToExcel(table, { + filename: "tasks", + excludeColumns: ["select", "actions"], + }) + } + className="gap-2" + > + <Download className="size-4" aria-hidden="true" /> + <span className="hidden sm:inline">Export</span> + </Button> + </div> + ) +}
\ No newline at end of file diff --git a/lib/vendor-users/table/ausers-table.tsx b/lib/vendor-users/table/ausers-table.tsx new file mode 100644 index 00000000..06cb1e3f --- /dev/null +++ b/lib/vendor-users/table/ausers-table.tsx @@ -0,0 +1,163 @@ +"use client" + +import * as React from "react" +import { userRoles , type UserView} from "@/db/schema/users" +import type { + DataTableAdvancedFilterField, + DataTableFilterField, + DataTableRowAction, +} from "@/types/table" + +import { toSentenceCase } from "@/lib/utils" +import { useDataTable } from "@/hooks/use-data-table" +import { DataTable } from "@/components/data-table/data-table" +import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar" +import { DataTableToolbar } from "@/components/data-table/data-table-toolbar" + +import { getColumns } from "./ausers-table-columns" +import { AdmUserTableToolbarActions } from "./ausers-table-toolbar-actions" +import { DeleteUsersDialog } from "./delete-ausers-dialog" +import { AusersTableFloatingBar } from "./ausers-table-floating-bar" +import { UpdateAuserSheet } from "./update-auser-sheet" +import { getAllRolesbyVendor, getVendorUsers } from "../service" + +interface UsersTableProps { + promises: Promise< + [ + Awaited<ReturnType<typeof getVendorUsers>>, + Record<number, number>, + Awaited<ReturnType<typeof getAllRolesbyVendor>> + ] + > +} +type RoleCounts = Record<string, number> + +export function VendorUserTable({ promises }: UsersTableProps) { + + const [{ data, pageCount }, roleCountsRaw, roles] = + React.use(promises) + + + const [rowAction, setRowAction] = + React.useState<DataTableRowAction<UserView> | null>(null) + + const columns = React.useMemo( + () => getColumns({ setRowAction }), + [setRowAction] + ) + + const roleCounts = roleCountsRaw as RoleCounts + + + /** + * This component can render either a faceted filter or a search filter based on the `options` prop. + * + * @prop options - An array of objects, each representing a filter option. If provided, a faceted filter is rendered. If not, a search filter is rendered. + * + * Each `option` object has the following properties: + * @prop {string} label - The label for the filter option. + * @prop {string} value - The value for the filter option. + * @prop {React.ReactNode} [icon] - An optional icon to display next to the label. + * @prop {boolean} [withCount] - An optional boolean to display the count of the filter option. + */ + const filterFields: DataTableFilterField<UserView>[] = [ + { + id: "user_email", + label: "Email", + placeholder: "Filter email...", + }, + + ] + + /** + * Advanced filter fields for the data table. + * These fields provide more complex filtering options compared to the regular filterFields. + * + * Key differences from regular filterFields: + * 1. More field types: Includes 'text', 'multi-select', 'date', and 'boolean'. + * 2. Enhanced flexibility: Allows for more precise and varied filtering options. + * 3. Used with DataTableAdvancedToolbar: Enables a more sophisticated filtering UI. + * 4. Date and boolean types: Adds support for filtering by date ranges and boolean values. + */ + const advancedFilterFields: DataTableAdvancedFilterField<UserView>[] = [ + { + id: "user_name", + label: "User Name", + type: "text", + }, + { + id: "user_email", + label: "Email", + type: "text", + }, + + { + id: "roles", + label: "Roles", + type: "multi-select", + options: roles.map((role) => { + return { + label: toSentenceCase(role.name), + value: role.id, + count: roleCounts[role.id], // 이 값이 undefined인지 확인 + }; + }), + }, + { + id: "created_at", + label: "Created at", + type: "date", + }, + ] + + + const { table } = useDataTable({ + data, + columns, + pageCount, + filterFields, + enablePinning: true, + enableAdvancedFilter: true, + initialState: { + sorting: [{ id: "created_at", desc: true }], + columnPinning: { right: ["actions"] }, + }, + getRowId: (originalRow) => `${originalRow.user_id}`, + shallow: false, + clearOnDefault: true, + }) + + return ( + <> + <DataTable + table={table} + floatingBar={<AusersTableFloatingBar table={table}/>} + + > + <DataTableAdvancedToolbar + table={table} + filterFields={advancedFilterFields} + shallow={false} + > + <AdmUserTableToolbarActions table={table} /> + </DataTableAdvancedToolbar> + + </DataTable> + + <DeleteUsersDialog + open={rowAction?.type === "delete"} + onOpenChange={() => setRowAction(null)} + users={rowAction?.row.original ? [rowAction?.row.original] : []} + showTrigger={false} + onSuccess={() => rowAction?.row.toggleSelected(false)} + /> + + <UpdateAuserSheet + open={rowAction?.type === "update"} + onOpenChange={() => setRowAction(null)} + user={rowAction?.row.original ?? null} + /> + + </> + ) +} diff --git a/lib/vendor-users/table/delete-ausers-dialog.tsx b/lib/vendor-users/table/delete-ausers-dialog.tsx new file mode 100644 index 00000000..e3259211 --- /dev/null +++ b/lib/vendor-users/table/delete-ausers-dialog.tsx @@ -0,0 +1,149 @@ +"use client" + +import * as React from "react" +import { type Row } from "@tanstack/react-table" +import { Loader, Trash } from "lucide-react" +import { toast } from "sonner" + +import { useMediaQuery } from "@/hooks/use-media-query" +import { Button } from "@/components/ui/button" +import { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@/components/ui/dialog" +import { + Drawer, + DrawerClose, + DrawerContent, + DrawerDescription, + DrawerFooter, + DrawerHeader, + DrawerTitle, + DrawerTrigger, +} from "@/components/ui/drawer" + +import { type UserView } from "@/db/schema/users" +import { removeVendorUsers } from "../service" + +interface DeleteUsersDialogProps + extends React.ComponentPropsWithoutRef<typeof Dialog> { + users: Row<UserView>["original"][] + showTrigger?: boolean + onSuccess?: () => void +} + +export function DeleteUsersDialog({ + users, + showTrigger = true, + onSuccess, + ...props +}: DeleteUsersDialogProps) { + const [isDeletePending, startDeleteTransition] = React.useTransition() + const isDesktop = useMediaQuery("(min-width: 640px)") + + function onDelete() { + startDeleteTransition(async () => { + const { error } = await removeVendorUsers({ + ids: users.map((user) => Number(user.user_id)), + }) + + if (error) { + toast.error(error) + return + } + + props.onOpenChange?.(false) + toast.success("Users deleted") + onSuccess?.() + }) + } + + if (isDesktop) { + return ( + <Dialog {...props}> + {showTrigger ? ( + <DialogTrigger asChild> + <Button variant="outline" size="sm"> + <Trash className="mr-2 size-4" aria-hidden="true" /> + Delete ({users.length}) + </Button> + </DialogTrigger> + ) : null} + <DialogContent> + <DialogHeader> + <DialogTitle>Are you absolutely sure?</DialogTitle> + <DialogDescription> + This action cannot be undone. This will permanently delete your{" "} + <span className="font-medium">{users.length}</span> + {users.length === 1 ? " user" : " users"} from our servers. + </DialogDescription> + </DialogHeader> + <DialogFooter className="gap-2 sm:space-x-0"> + <DialogClose asChild> + <Button variant="outline">Cancel</Button> + </DialogClose> + <Button + aria-label="Delete selected rows" + variant="destructive" + onClick={onDelete} + disabled={isDeletePending} + > + {isDeletePending && ( + <Loader + className="mr-2 size-4 animate-spin" + aria-hidden="true" + /> + )} + Delete + </Button> + </DialogFooter> + </DialogContent> + </Dialog> + ) + } + + return ( + <Drawer {...props}> + {showTrigger ? ( + <DrawerTrigger asChild> + <Button variant="outline" size="sm"> + <Trash className="mr-2 size-4" aria-hidden="true" /> + Delete ({users.length}) + </Button> + </DrawerTrigger> + ) : null} + <DrawerContent> + <DrawerHeader> + <DrawerTitle>Are you absolutely sure?</DrawerTitle> + <DrawerDescription> + This action cannot be undone. This will permanently delete your{" "} + <span className="font-medium">{users.length}</span> + {users.length === 1 ? " user" : " users"} from our servers. + </DrawerDescription> + </DrawerHeader> + <DrawerFooter className="gap-2 sm:space-x-0"> + <DrawerClose asChild> + <Button variant="outline">Cancel</Button> + </DrawerClose> + <Button + aria-label="Delete selected rows" + variant="destructive" + onClick={onDelete} + disabled={isDeletePending} + > + {isDeletePending && ( + <Loader className="mr-2 size-4 animate-spin" aria-hidden="true" /> + )} + Delete + </Button> + </DrawerFooter> + </DrawerContent> + </Drawer> + ) +} diff --git a/lib/vendor-users/table/update-auser-sheet.tsx b/lib/vendor-users/table/update-auser-sheet.tsx new file mode 100644 index 00000000..2009e517 --- /dev/null +++ b/lib/vendor-users/table/update-auser-sheet.tsx @@ -0,0 +1,273 @@ +"use client" + +import * as React from "react" +import { zodResolver } from "@hookform/resolvers/zod" +import { Loader } from "lucide-react" +import { useForm } from "react-hook-form" +import { toast } from "sonner" + +import { + Sheet, + SheetClose, + SheetContent, + SheetDescription, + SheetFooter, + SheetHeader, + SheetTitle, +} from "@/components/ui/sheet" +import { Button } from "@/components/ui/button" +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, + FormDescription, +} from "@/components/ui/form" +import { Input } from "@/components/ui/input" +import { + Select, + SelectTrigger, + SelectContent, + SelectItem, + SelectValue, + SelectGroup, +} from "@/components/ui/select" +// import your MultiSelect or other role selection +import { MultiSelect } from "@/components/ui/multi-select" +import { cn } from "@/lib/utils" + +import { userRoles, type UserView } from "@/db/schema/users" +import { UpdateVendorUserSchema, updateVendorUserSchema } from "../validations" +import { modifiVendorUser } from "../service" + +export interface UpdateAuserSheetProps + extends React.ComponentPropsWithRef<typeof Sheet> { + user: UserView | null +} + +const languageOptions = [ + { value: "ko", label: "한국어" }, + { value: "en", label: "English" }, +] + +// Phone validation helper +const validatePhoneNumber = (phone: string): boolean => { + if (!phone) return true; // Optional field + // Basic international phone number validation + const cleanPhone = phone.replace(/[\s\-\(\)]/g, ''); + return /^\+\d{10,15}$/.test(cleanPhone); +}; + +// Get phone placeholder +const getPhonePlaceholder = (): string => { + return "+82 010-1234-5678"; +}; + +// Get phone description +const getPhoneDescription = (): string => { + return "국제 전화번호를 입력하세요. (예: +82 010-1234-5678)"; +}; + +export function UpdateAuserSheet({ user, ...props }: UpdateAuserSheetProps) { + const [isUpdatePending, startUpdateTransition] = React.useTransition() + + // 1) RHF 설정 + const form = useForm<UpdateVendorUserSchema & { language?: string; phone?: string }>({ + resolver: zodResolver(updateVendorUserSchema), + defaultValues: { + name: user?.user_name ?? "", + email: user?.user_email ?? "", + phone: user?.user_phone ?? "", // Add phone field + roles: user?.roles ?? [], + language: 'en', + }, + }) + + // 2) user prop 바뀔 때마다 form.reset + React.useEffect(() => { + if (user) { + form.reset({ + name: user.user_name, + email: user.user_email, + phone: user.user_phone || "", // Add phone field + roles: user.roles, + language: 'en', // You might want to get this from user object + }) + } + }, [user, form]) + + // 3) onSubmit + async function onSubmit(input: UpdateVendorUserSchema & { language?: string; phone?: string }) { + // Validate phone number if provided + if (input.phone && !validatePhoneNumber(input.phone)) { + toast.error("올바른 국제 전화번호 형식이 아닙니다.") + return + } + + startUpdateTransition(async () => { + if (!user) return + + const { error } = await modifiVendorUser({ + id: user.user_id, + ...input, + }) + + if (error) { + toast.error(error) + return + } + + // 성공 시 + form.reset() + props.onOpenChange?.(false) + toast.success("User updated successfully!") + }) + } + + return ( + <Sheet {...props}> + <SheetContent className="flex flex-col gap-6 sm:max-w-md"> + <SheetHeader className="text-left"> + <SheetTitle>Update user</SheetTitle> + <SheetDescription> + Update the user details and save the changes + </SheetDescription> + </SheetHeader> + + {/* 4) RHF Form */} + <Form {...form}> + <form + onSubmit={form.handleSubmit(onSubmit)} + className="flex flex-col gap-4" + > + {/* name */} + <FormField + control={form.control} + name="name" + render={({ field }) => ( + <FormItem> + <FormLabel>User Name</FormLabel> + <FormControl> + <Input placeholder="e.g. dujin" {...field} /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + {/* email */} + <FormField + control={form.control} + name="email" + render={({ field }) => ( + <FormItem> + <FormLabel>Email</FormLabel> + <FormControl> + <Input type="email" placeholder="user@example.com" {...field} /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + {/* 전화번호 - 새로 추가 */} + <FormField + control={form.control} + name="phone" + render={({ field }) => ( + <FormItem> + <FormLabel>Phone Number</FormLabel> + <FormControl> + <Input + placeholder={getPhonePlaceholder()} + {...field} + className={cn( + field.value && !validatePhoneNumber(field.value) && "border-red-500" + )} + /> + </FormControl> + <FormDescription className="text-xs text-muted-foreground"> + {getPhoneDescription()} + </FormDescription> + <FormMessage /> + </FormItem> + )} + /> + + {/* roles */} + <FormField + control={form.control} + name="roles" + render={({ field }) => ( + <FormItem> + <FormLabel>Roles</FormLabel> + <FormControl> + <MultiSelect + defaultValue={form?.getValues().roles} + options={[ + { value: "999999999", label: "admin" } + ]} + value={field.value} + onValueChange={(vals) => field.onChange(vals)} + /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + {/* language */} + <FormField + control={form.control} + name="language" + render={({ field }) => ( + <FormItem> + <FormLabel>Language</FormLabel> + <FormControl> + <Select + onValueChange={field.onChange} + value={field.value} + > + <SelectTrigger> + <SelectValue placeholder="Select language" /> + </SelectTrigger> + <SelectContent> + {languageOptions.map((v, index) => ( + <SelectItem key={index} value={v.value}> + {v.label} + </SelectItem> + ))} + </SelectContent> + </Select> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + {/* 5) Footer: Cancel, Save */} + <SheetFooter className="gap-2 pt-2 sm:space-x-0"> + <SheetClose asChild> + <Button type="button" variant="outline"> + Cancel + </Button> + </SheetClose> + + <Button type="submit" disabled={isUpdatePending}> + {isUpdatePending && ( + <Loader + className="mr-2 size-4 animate-spin" + aria-hidden="true" + /> + )} + Save + </Button> + </SheetFooter> + </form> + </Form> + </SheetContent> + </Sheet> + ) +}
\ No newline at end of file |
