summaryrefslogtreecommitdiff
path: root/components/permissions/role-selector.tsx
blob: 5f62ca517062a43dd4cb1ebdc4a424a9fc090f85 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
// components/permissions/role-selector.tsx

"use client"

import * as React from "react"
import { Check, ChevronsUpDown, Shield, Users } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"
import { Command, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem } from "@/components/ui/command"
import { Badge } from "@/components/ui/badge"
import { cn } from "@/lib/utils"
import { getRoles } from "@/lib/permissions/service"

export interface Role {
  id: number;
  name: string;
  domain: string;
  description?: string;
  userCount?: number;
}

interface RoleSelectorProps {
  selectedRoleId?: number | null;
  onRoleSelect: (role: Role) => void;
  placeholder?: string;
  domain?: string; // 특정 도메인의 역할만 필터링
  className?: string;
}

export function RoleSelector({ 
  selectedRoleId, 
  onRoleSelect, 
  placeholder = "역할 선택...",
  domain,
  className
}: RoleSelectorProps) {
  const [open, setOpen] = React.useState(false)
  const [searchTerm, setSearchTerm] = React.useState("")
  const [roles, setRoles] = React.useState<Role[]>([])
  const [isLoading, setIsLoading] = React.useState(false)
  const [selectedRole, setSelectedRole] = React.useState<Role | null>(null)

  // 역할 데이터 로드
  React.useEffect(() => {
    async function loadRoles() {
      setIsLoading(true);
      try {
        const allRoles = await getRoles();
        
        // domain이 지정된 경우 해당 도메인만 필터링
        const filteredByDomain = domain 
          ? allRoles.filter((r: Role) => r.domain === domain)
          : allRoles;
        
        console.log(`Loaded ${filteredByDomain.length} roles${domain ? ` for domain: ${domain}` : ''}`);
        setRoles(filteredByDomain);
        
        // 초기 선택된 역할이 있으면 설정
        if (selectedRoleId) {
          const selected = filteredByDomain.find((r: Role) => r.id === selectedRoleId);
          if (selected) {
            setSelectedRole(selected);
          }
        }
      } catch (error) {
        console.error("역할 목록 로드 오류:", error);
        setRoles([]);
      } finally {
        setIsLoading(false);
      }
    }
    
    loadRoles();
  }, [selectedRoleId, domain]);

  // 클라이언트 측에서 검색어로 필터링
  const filteredRoles = React.useMemo(() => {
    if (!searchTerm.trim()) return roles;
    
    const lowerSearch = searchTerm.toLowerCase();
    return roles.filter(
      role => 
        role.name.toLowerCase().includes(lowerSearch) || 
        role.domain.toLowerCase().includes(lowerSearch) ||
        (role.description && role.description.toLowerCase().includes(lowerSearch))
    );
  }, [roles, searchTerm]);

  // 역할 선택 처리
  const handleSelectRole = (role: Role) => {
    setSelectedRole(role);
    onRoleSelect(role);
    setOpen(false);
  };

  // 도메인별 색상 결정
  const getDomainColor = (domain: string) => {
    switch(domain?.toLowerCase()) {
      case 'evcp':
        return 'default';
      case 'partners':
        return 'secondary';
      case 'admin':
        return 'destructive';
      default:
        return 'outline';
    }
  };

  // 도메인별 그룹화
  const groupedRoles = React.useMemo(() => {
    return filteredRoles.reduce((acc, role) => {
      const key = role.domain || 'other';
      if (!acc[key]) acc[key] = [];
      acc[key].push(role);
      return acc;
    }, {} as Record<string, Role[]>);
  }, [filteredRoles]);

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          role="combobox"
          aria-expanded={open}
          className={cn("w-full justify-between", className)}
          disabled={isLoading}
        >
          {isLoading ? (
            <span className="text-muted-foreground">역할 로딩 중...</span>
          ) : selectedRole ? (
            <div className="flex items-center gap-2 w-full">
              <Shield className="h-4 w-4 text-muted-foreground" />
              <span className="truncate">{selectedRole.name}</span>
              <Badge 
                variant={getDomainColor(selectedRole.domain)} 
                className="ml-auto text-xs"
              >
                {selectedRole.domain}
              </Badge>
              {selectedRole.userCount !== undefined && (
                <Badge variant="outline" className="text-xs">
                  {selectedRole.userCount}명
                </Badge>
              )}
            </div>
          ) : (
            <span className="text-muted-foreground">{placeholder}</span>
          )}
          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-[400px] p-0">
        <Command>
          <CommandInput
            placeholder="역할명, 도메인으로 검색..."
            onValueChange={setSearchTerm}
          />
          <CommandList 
            className="max-h-[300px]" 
            onWheel={(e) => {
              e.stopPropagation();
              const target = e.currentTarget;
              target.scrollTop += e.deltaY;
            }}
          >
            {isLoading ? (
              <div className="py-6 text-center text-sm text-muted-foreground">
                역할 목록 로딩 중...
              </div>
            ) : Object.keys(groupedRoles).length === 0 ? (
              <CommandEmpty>
                {searchTerm 
                  ? "검색 결과가 없습니다" 
                  : domain 
                    ? `${domain} 도메인에 역할이 없습니다`
                    : "역할이 없습니다"}
              </CommandEmpty>
            ) : (
              Object.entries(groupedRoles).map(([groupDomain, groupRoles]) => (
                <CommandGroup key={groupDomain} heading={groupDomain.toUpperCase()}>
                  {groupRoles.map((role) => (
                    <CommandItem
                      key={role.id}
                      value={`${role.name} ${role.domain} ${role.description || ''}`}
                      onSelect={() => handleSelectRole(role)}
                      className="cursor-pointer"
                    >
                      <Check
                        className={cn(
                          "mr-2 h-4 w-4",
                          selectedRole?.id === role.id
                            ? "opacity-100"
                            : "opacity-0"
                        )}
                      />
                      <div className="flex items-center gap-2 flex-1">
                        <Shield className="h-4 w-4 text-muted-foreground" />
                        <div className="flex-1">
                          <div className="font-medium">{role.name}</div>
                          {role.description && (
                            <div className="text-xs text-muted-foreground truncate">
                              {role.description}
                            </div>
                          )}
                        </div>
                        <div className="flex items-center gap-1">
                          {role.userCount !== undefined && (
                            <Badge variant="outline" className="text-xs">
                              <Users className="h-3 w-3 mr-1" />
                              {role.userCount}
                            </Badge>
                          )}
                        </div>
                      </div>
                    </CommandItem>
                  ))}
                </CommandGroup>
              ))
            )}
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
}