From 4eb7532f822c821fb6b69bf103bd075fefba769b Mon Sep 17 00:00:00 2001
From: dujinkim <dujin.kim@dtsolution.co.kr>
Date: Tue, 15 Jul 2025 10:07:09 +0000
Subject: (대표님) 20250715 협력사 정기평가, spreadJS, roles 서비스에 함수 추가
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 lib/roles/userTable/assignedUsers-table.tsx | 127 ++++++++++++++++++++++++----
 1 file changed, 109 insertions(+), 18 deletions(-)

(limited to 'lib/roles/userTable/assignedUsers-table.tsx')

diff --git a/lib/roles/userTable/assignedUsers-table.tsx b/lib/roles/userTable/assignedUsers-table.tsx
index 5ac52f13..565ddda2 100644
--- a/lib/roles/userTable/assignedUsers-table.tsx
+++ b/lib/roles/userTable/assignedUsers-table.tsx
@@ -1,7 +1,7 @@
 "use client"
 
 import * as React from "react"
-import { userRoles ,  type UserView} from "@/db/schema/users"
+import { userRoles, type UserView } from "@/db/schema/users"
 import type {
   DataTableAdvancedFilterField,
   DataTableFilterField,
@@ -19,23 +19,98 @@ import type {
 } from "@/lib//users/service"
 import { getColumns } from "./assginedUsers-table-columns"
 
-
+type TableMode = "assign" | "remove"
 
 interface UsersTableProps {
   promises: Promise<
     [
       Awaited<ReturnType<typeof getUsersAll>>
-
     ]
   >
-  onSelectedChange:any
+  onSelectedChange: any
+  mode?: TableMode // 새로 추가: assign | remove
+  currentRoleName?: string // 새로 추가: 현재 선택된 롤 ID (필터링용)
+  showAllUsers?: boolean // 디버깅용: 모든 사용자 표시
 }
 
-export function AssginedUserTable({ promises ,onSelectedChange}: UsersTableProps) {
+export function AssginedUserTable({ 
+  promises, 
+  onSelectedChange, 
+  mode = "assign",
+  currentRoleName,
+  showAllUsers = false 
+}: UsersTableProps) {
+
+  const [{ data: rawData, pageCount }] = React.use(promises)
+
+  // 모드에 따라 데이터 필터링
+  const filteredData = React.useMemo(() => {
+    console.log('🔍 Filtering Debug Info:', {
+      mode,
+      currentRoleName,
+      rawDataLength: rawData?.length,
+      sampleUser: rawData?.[0],
+      showAllUsers
+    })
+
+    // 디버깅용: 모든 사용자 표시
+    if (showAllUsers) {
+      console.log('🔧 Debug mode: showing all users')
+      return rawData
+    }
 
-  const [{ data, pageCount }] =
-    React.use(promises)
+    if (!currentRoleName || !rawData) {
+      console.log('❌ No currentRoleId or rawData, returning rawData')
+      return rawData
+    }
 
+    if (mode === "assign") {
+      // assign 모드: 현재 롤에 할당되지 않은 사용자들만 표시
+      const filtered = rawData.filter(user => {
+        if (!user.roles || !Array.isArray(user.roles)) {
+          console.log('✅ User has no roles, including in assign:', user.user_name)
+          return true
+        }
+        
+        // 다양한 roles 구조 지원
+        const hasRole = user.roles.some(role => {
+          if (typeof role === 'string') return role === currentRoleName.toString()
+          return false
+        })
+        
+        if (!hasRole) {
+          console.log('✅ User does not have role, including in assign:', user.user_name)
+        }
+        return !hasRole
+      })
+      
+      console.log(`📊 Assign mode: ${filtered.length} users available`)
+      return filtered
+    } else {
+      // remove 모드: 현재 롤에 할당된 사용자들만 표시  
+      const filtered = rawData.filter(user => {
+        if (!user.roles || !Array.isArray(user.roles)) {
+          console.log('❌ User has no roles, excluding from remove:', user.user_name)
+          return false
+        }
+        
+        // 다양한 roles 구조 지원
+        const hasRole = user.roles.some(role => {
+          if (typeof role === 'string') return role === currentRoleName.toString()
+
+          return false
+        })
+        
+        if (hasRole) {
+          console.log('✅ User has role, including in remove:', user.user_name, 'roles:', user.roles)
+        }
+        return hasRole
+      })
+      
+      console.log(`📊 Remove mode: ${filtered.length} users with role`)
+      return filtered
+    }
+  }, [rawData, mode, currentRoleName, showAllUsers])
 
   const [rowAction, setRowAction] =
     React.useState<DataTableRowAction<UserView> | null>(null)
@@ -45,8 +120,6 @@ export function AssginedUserTable({ promises ,onSelectedChange}: UsersTableProps
     [setRowAction]
   )
 
-
-
   /**
    * This component can render either a faceted filter or a search filter based on the `options` prop.
    *
@@ -64,7 +137,6 @@ export function AssginedUserTable({ promises ,onSelectedChange}: UsersTableProps
       label: "Email",
       placeholder: "Filter email...",
     },
-
   ]
 
   /**
@@ -88,8 +160,6 @@ export function AssginedUserTable({ promises ,onSelectedChange}: UsersTableProps
       label: "Email",
       type: "text",
     },
-
-
     {
       id: "created_at",
       label: "Created at",
@@ -98,7 +168,7 @@ export function AssginedUserTable({ promises ,onSelectedChange}: UsersTableProps
   ]
 
   const { table } = useDataTable({
-    data,
+    data: filteredData, // 필터링된 데이터 사용
     columns,
     pageCount,
     filterFields,
@@ -122,6 +192,7 @@ export function AssginedUserTable({ promises ,onSelectedChange}: UsersTableProps
     }
     return true
   }
+  
   const previousUserIdsRef = React.useRef<number[]>([])
 
   React.useEffect(() => {
@@ -138,11 +209,34 @@ export function AssginedUserTable({ promises ,onSelectedChange}: UsersTableProps
     }
   }, [rowSelection, onSelectedChange])
 
+  // 모드 변경시 선택 초기화
+  React.useEffect(() => {
+    table.toggleAllPageRowsSelected(false)
+    setRowAction(null)
+  }, [mode, table])
+
   return (
     <>
+      {/* 빈 데이터 상태 메시지 */}
+      {filteredData && filteredData.length === 0 && (
+        <div className="flex flex-col items-center justify-center py-8 text-center border-2 border-dashed border-gray-200 rounded-lg">
+          <div className="text-gray-500 mb-2">
+            {mode === "assign" 
+              ? "🎯 모든 사용자가 이미 이 롤에 할당되어 있습니다"
+              : "👥 이 롤에 할당된 사용자가 없습니다"
+            }
+          </div>
+          <div className="text-sm text-gray-400">
+            {mode === "assign" 
+              ? "할당 가능한 사용자가 없습니다"
+              : "제거할 사용자가 없습니다"
+            }
+          </div>
+        </div>
+      )}
+
       <DataTable
         table={table}
-
       >
         <DataTableAdvancedToolbar
           table={table}
@@ -150,10 +244,7 @@ export function AssginedUserTable({ promises ,onSelectedChange}: UsersTableProps
           shallow={false}
         >
         </DataTableAdvancedToolbar>
-
       </DataTable>
-
-   
     </>
   )
-}
+}
\ No newline at end of file
-- 
cgit v1.2.3

