summaryrefslogtreecommitdiff
path: root/lib/users/table
diff options
context:
space:
mode:
authordujinkim <dujin.kim@dtsolution.co.kr>2025-03-26 00:37:41 +0000
committerdujinkim <dujin.kim@dtsolution.co.kr>2025-03-26 00:37:41 +0000
commite0dfb55c5457aec489fc084c4567e791b4c65eb1 (patch)
tree68543a65d88f5afb3a0202925804103daa91bc6f /lib/users/table
3/25 까지의 대표님 작업사항
Diffstat (limited to 'lib/users/table')
-rw-r--r--lib/users/table/assign-roles-dialog.tsx194
-rw-r--r--lib/users/table/users-table-columns.tsx154
-rw-r--r--lib/users/table/users-table-toolbar-actions.tsx61
-rw-r--r--lib/users/table/users-table.tsx150
4 files changed, 559 insertions, 0 deletions
diff --git a/lib/users/table/assign-roles-dialog.tsx b/lib/users/table/assign-roles-dialog.tsx
new file mode 100644
index 00000000..003f6500
--- /dev/null
+++ b/lib/users/table/assign-roles-dialog.tsx
@@ -0,0 +1,194 @@
+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"
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form"
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select"
+import { Check, ChevronsUpDown, Loader, UserRoundPlus } from "lucide-react"
+import { cn } from "@/lib/utils"
+import { toast } from "sonner"
+
+import { Textarea } from "@/components/ui/textarea"
+import { Company } from "@/db/schema/companies"
+import { getAllCompanies } from "@/lib/admin-users/service"
+import {
+ Popover,
+ PopoverTrigger,
+ PopoverContent,
+} from "@/components/ui/popover"
+import {
+ Command,
+ CommandInput,
+ CommandList,
+ CommandGroup,
+ CommandItem,
+ CommandEmpty,
+} from "@/components/ui/command"
+import { assignRolesToUsers, getAllRoleView } from "@/lib/roles/services"
+import { RoleView } from "@/db/schema/users"
+import { type UserView } from "@/db/schema/users"
+import { type Row } from "@tanstack/react-table"
+import { createRoleAssignmentSchema, CreateRoleAssignmentSchema, createRoleSchema, CreateRoleSchema } from "@/lib/roles/validations"
+import { MultiSelect } from "@/components/ui/multi-select"
+
+interface AssignRoleDialogProps
+ extends React.ComponentPropsWithoutRef<typeof Dialog> {
+ users: Row<UserView>["original"][]
+
+}
+
+
+export function AssignRoleDialog({ users }: AssignRoleDialogProps) {
+ const [open, setOpen] = React.useState(false)
+ const [isAddPending, startAddTransition] = React.useTransition()
+ const [roles, setRoles] = React.useState<RoleView[]>([]) // 회사 목록
+ const [loading, setLoading] = React.useState(false)
+
+ const partnersRoles = roles.filter(v => v.domain === "partners")
+ const evcpRoles = roles.filter(v => v.domain === "evcp")
+
+
+ React.useEffect(() => {
+ getAllRoleView("evcp").then((res) => {
+ setRoles(res)
+ })
+ }, [])
+
+
+ const form = useForm<CreateRoleAssignmentSchema>({
+ resolver: zodResolver(createRoleAssignmentSchema),
+ defaultValues: {
+ evcpRoles: [],
+ },
+ })
+
+
+ function handleDialogOpenChange(nextOpen: boolean) {
+ if (!nextOpen) {
+ form.reset()
+ }
+ setOpen(nextOpen)
+ }
+
+ const evcpUsers = users.filter(v => v.user_domain === "evcp");
+
+
+ async function onSubmit(data: CreateRoleAssignmentSchema) {
+ console.log(data.evcpRoles.map((v)=>Number(v)))
+ startAddTransition(async () => {
+
+
+ // if(partnerUsers.length>0){
+ // const result = await assignRolesToUsers( partnerUsers.map(v=>v.user_id) ,data.partnersRoles)
+
+ // if (result.error) {
+ // toast.error(`에러: ${result.error}`)
+ // return
+ // }
+ // }
+
+ if (evcpUsers.length > 0) {
+ const result = await assignRolesToUsers( data.evcpRoles.map((v)=>Number(v)), evcpUsers.map(v => v.user_id))
+
+ if (result.error) {
+ toast.error(`에러: ${result.error}`)
+ return
+ }
+ }
+
+ form.reset()
+ setOpen(false)
+ toast.success("Role assgined")
+ })
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={handleDialogOpenChange}>
+ <DialogTrigger asChild>
+ <Button variant="default" size="sm">
+ <UserRoundPlus className="mr-2 size-4" aria-hidden="true" />
+ Assign Role ({users.length})
+ </Button>
+ </DialogTrigger>
+
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Assign Roles to {evcpUsers.length} Users</DialogTitle>
+ <DialogDescription>
+ Role을 Multi-select 하시기 바랍니다.
+ </DialogDescription>
+ </DialogHeader>
+
+
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)}>
+ <div className="space-y-4 py-4">
+ {/* evcp 롤 선택 */}
+ {evcpUsers.length > 0 &&
+ <FormField
+ control={form.control}
+ name="evcpRoles"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>eVCP Role</FormLabel>
+ <FormControl>
+ <MultiSelect
+ options={evcpRoles.map((role) => ({ value: String(role.id), label: role.name }))}
+ onValueChange={(values) => {
+ field.onChange(values);
+ }}
+
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ }
+ </div>
+
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setOpen(false)}
+ disabled={isAddPending}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ disabled={form.formState.isSubmitting || isAddPending}
+ >
+ {isAddPending && (
+ <Loader
+ className="mr-2 size-4 animate-spin"
+ aria-hidden="true"
+ />
+ )}
+ Assgin
+ </Button>
+ </DialogFooter>
+ </form>
+ </Form>
+ </DialogContent>
+ </Dialog>
+ )
+} \ No newline at end of file
diff --git a/lib/users/table/users-table-columns.tsx b/lib/users/table/users-table-columns.tsx
new file mode 100644
index 00000000..c0eb9520
--- /dev/null
+++ b/lib/users/table/users-table-columns.tsx
@@ -0,0 +1,154 @@
+"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 { euserColumnsConfig } from "@/config/euserColumnsConfig"
+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,
+ }
+
+
+
+ const groupMap: Record<string, ColumnDef<UserView>[]> = {}
+
+ euserColumnsConfig.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) => (
+ v === null?"":
+ <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,
+ ]
+} \ No newline at end of file
diff --git a/lib/users/table/users-table-toolbar-actions.tsx b/lib/users/table/users-table-toolbar-actions.tsx
new file mode 100644
index 00000000..106953a6
--- /dev/null
+++ b/lib/users/table/users-table-toolbar-actions.tsx
@@ -0,0 +1,61 @@
+"use client"
+
+import * as React from "react"
+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 { UserView } from "@/db/schema/users"
+import { DeleteUsersDialog } from "@/lib/admin-users/table/delete-ausers-dialog"
+import { AssignRoleDialog } from "./assign-roles-dialog"
+
+interface UsersTableToolbarActionsProps {
+ table: Table<UserView>
+}
+
+export function UsersTableToolbarActions({ table }: UsersTableToolbarActionsProps) {
+ // 파일 input을 숨기고, 버튼 클릭 시 참조해 클릭하는 방식
+ const fileInputRef = React.useRef<HTMLInputElement>(null)
+
+
+ function handleImportClick() {
+ // 숨겨진 <input type="file" /> 요소를 클릭
+ fileInputRef.current?.click()
+ }
+
+ return (
+ <div className="flex items-center gap-2">
+
+ {table.getFilteredSelectedRowModel().rows.length > 0 ? (
+ <AssignRoleDialog
+ users={table
+ .getFilteredSelectedRowModel()
+ .rows.map((row) => row.original)}
+ />
+ ) : null}
+
+
+
+ {/** 4) Export 버튼 */}
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ exportTableToExcel(table, {
+ filename: "roles",
+ 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/users/table/users-table.tsx b/lib/users/table/users-table.tsx
new file mode 100644
index 00000000..53cb961e
--- /dev/null
+++ b/lib/users/table/users-table.tsx
@@ -0,0 +1,150 @@
+"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 type {
+ getAllRoles, getUsersEVCP
+} from "@/lib//users/service"
+import { getColumns } from "./users-table-columns"
+import { UsersTableToolbarActions } from "./users-table-toolbar-actions"
+
+
+
+interface UsersTableProps {
+ promises: Promise<
+ [
+ Awaited<ReturnType<typeof getUsersEVCP>>,
+ Record<number, number>,
+ Awaited<ReturnType<typeof getAllRoles>>
+ ]
+ >
+}
+type RoleCounts = Record<string, number>
+
+export function UserTable({ 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}
+
+ >
+ <DataTableAdvancedToolbar
+ table={table}
+ filterFields={advancedFilterFields}
+ shallow={false}
+ >
+ <UsersTableToolbarActions table={table}/>
+ </DataTableAdvancedToolbar>
+
+ </DataTable>
+
+
+ </>
+ )
+}