summaryrefslogtreecommitdiff
path: root/components/common/user/user-selector.tsx
blob: 4a43fa5eb33d73d5d48152a8b104f27e091893a8 (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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
"use client"

import * as React from "react"
import { Search, X, Users, ChevronLeft, ChevronRight } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { useDebounce } from "@/hooks/use-debounce"
import { cn } from "@/lib/utils"
// import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Skeleton } from "@/components/ui/skeleton"
import { searchUsersForSelector } from "@/lib/users/service"

// User 타입 정의
export interface UserSelectItem {
  id: number
  name: string
  email: string
  epId?: string | null
  deptCode?: string | null
  deptName?: string | null
  imageUrl?: string | null
  domain?: string
  companyName?: string | null
}

// Domain 필터 타입
export type UserDomainFilter = 
  | { type: "exclude"; domains: string[] }  // partners가 아닌 경우
  | { type: "include"; domains: string[] }  // 특정 domain인 경우
  | null  // 필터 없음

// 페이지네이션 정보 타입
interface PaginationInfo {
  page: number
  perPage: number
  total: number
  pageCount: number
  hasNextPage: boolean
  hasPrevPage: boolean
}

export interface UserSelectorProps {
  /** 선택된 사용자들 */
  selectedUsers?: UserSelectItem[]
  /** 사용자 선택 변경 콜백 */
  onUsersChange?: (users: UserSelectItem[]) => void
  /** 단일 선택 모드 여부 */
  singleSelect?: boolean
  /** domain 필터 */
  domainFilter?: UserDomainFilter
  /** placeholder 텍스트 */
  placeholder?: string
  /** 입력 없이 focus 시 표시할 placeholder */
  noValuePlaceHolder?: string
  /** 비활성화 여부 */
  disabled?: boolean
  /** 최대 선택 가능 사용자 수 */
  maxSelections?: number
  /** 조직도 선택 다이얼로그 오픈 콜백 (추후 구현) */
  onOpenOrgChart?: () => void
  /** 컴포넌트 클래스명 */
  className?: string
  /** 사용자 선택 후 팝오버 닫기 여부 */
  closeOnSelect?: boolean
}

export function UserSelector({
  selectedUsers = [],
  onUsersChange,
  singleSelect = false,
  domainFilter,
  placeholder = "사용자를 검색하세요...",
  noValuePlaceHolder = "사용자를 검색하거나 조직도에서 찾아보세요",
  disabled = false,
  maxSelections,
  onOpenOrgChart,
  className,
  closeOnSelect = true // 기본값으로 선택 후 닫기
}: UserSelectorProps) {
  const [searchQuery, setSearchQuery] = React.useState("")
  const [isSearching, setIsSearching] = React.useState(false)
  const [searchResults, setSearchResults] = React.useState<UserSelectItem[]>([])
  const [isPopoverOpen, setIsPopoverOpen] = React.useState(false)
  const [currentPage, setCurrentPage] = React.useState(1)
  const [pagination, setPagination] = React.useState<PaginationInfo>({
    page: 1,
    perPage: 10,
    total: 0,
    pageCount: 0,
    hasNextPage: false,
    hasPrevPage: false,
  })
  const [searchError, setSearchError] = React.useState<string | null>(null)
  
  const inputRef = React.useRef<HTMLInputElement>(null)

  // Debounce 적용된 검색어
  const debouncedSearchQuery = useDebounce(searchQuery, 300)

  // 검색 실행 - useCallback으로 메모이제이션
  const performSearch = React.useCallback(async (query: string, page: number = 1) => {
    setIsSearching(true)
    setSearchError(null)
    
    try {
      const result = await searchUsersForSelector(query, page, 10, domainFilter)
      
      if (result.success) {
        setSearchResults(result.data)
        setPagination(result.pagination)
        setCurrentPage(page)
      } else {
        setSearchResults([])
        setSearchError("검색 중 오류가 발생했습니다.")
        setPagination({
          page: 1,
          perPage: 10,
          total: 0,
          pageCount: 0,
          hasNextPage: false,
          hasPrevPage: false,
        })
      }
    } catch (err) {
      console.error("사용자 검색 실패:", err)
      setSearchResults([])
      setSearchError("검색 중 오류가 발생했습니다.")
      setPagination({
        page: 1,
        perPage: 10,
        total: 0,
        pageCount: 0,
        hasNextPage: false,
        hasPrevPage: false,
      })
    } finally {
      setIsSearching(false)
    }
  }, [domainFilter])

  // Debounced 검색어 변경 시 검색 실행
  React.useEffect(() => {
    setCurrentPage(1)
    performSearch(debouncedSearchQuery, 1)
  }, [debouncedSearchQuery, performSearch])

  // 페이지 변경 처리 - useCallback으로 메모이제이션
  const handlePageChange = React.useCallback((newPage: number) => {
    if (newPage >= 1 && newPage <= pagination.pageCount) {
      performSearch(debouncedSearchQuery, newPage)
    }
  }, [pagination.pageCount, performSearch, debouncedSearchQuery])

  // 사용자 선택 처리 - useCallback으로 메모이제이션
  const handleUserSelect = React.useCallback((user: UserSelectItem) => {
    if (disabled) return

    const isSelected = selectedUsers.some(u => u.id === user.id)
    let newSelection: UserSelectItem[]

    if (singleSelect) {
      newSelection = isSelected ? [] : [user]
    } else {
      if (isSelected) {
        newSelection = selectedUsers.filter(u => u.id !== user.id)
      } else {
        if (maxSelections && selectedUsers.length >= maxSelections) {
          return // 최대 선택 수 도달
        }
        newSelection = [...selectedUsers, user]
      }
    }

    onUsersChange?.(newSelection)
    
    // 선택 후 팝오버 닫기 (closeOnSelect가 true이거나 단일 선택 모드일 때)
    if ((closeOnSelect || singleSelect) && !isSelected) {
      setIsPopoverOpen(false)
      setSearchQuery("")
    }
  }, [disabled, selectedUsers, singleSelect, maxSelections, onUsersChange, closeOnSelect])

  // 선택된 사용자 제거 - useCallback으로 메모이제이션
  const handleRemoveUser = React.useCallback((userId: number) => {
    if (disabled) return
    const newSelection = selectedUsers.filter(u => u.id !== userId)
    onUsersChange?.(newSelection)
  }, [disabled, selectedUsers, onUsersChange])

  // 사용자 이니셜 생성 - useMemo로 메모이제이션
  const getUserInitials = React.useCallback((name: string) => {
    const names = name.split(' ')
    return names.length > 1 
      ? `${names[0][0]}${names[1][0]}`
      : name.slice(0, 2)
  }, [])

  // Input 이벤트 핸들러들
  const handleInputFocus = React.useCallback(() => {
    setIsPopoverOpen(true)
  }, [])

  const handleInputChange = React.useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchQuery(e.target.value)
    if (!isPopoverOpen) {
      setIsPopoverOpen(true)
    }
  }, [isPopoverOpen])

  const handleClosePopover = React.useCallback(() => {
    setIsPopoverOpen(false)
  }, [])

  // 계산된 값들 - useMemo로 메모이제이션
  const shouldShowResults = React.useMemo(() => 
    searchQuery.trim() || isSearching, [searchQuery, isSearching])
  
  const hasResults = React.useMemo(() => 
    searchResults.length > 0, [searchResults.length])

  // 검색 결과 렌더링 - 컴포넌트 분리로 가독성 향상
  const renderSearchResults = React.useMemo(() => {
    if (!shouldShowResults) {
      return (
        <div className="p-4 text-sm text-muted-foreground text-center">
          {noValuePlaceHolder}
        </div>
      )
    }

    if (isSearching) {
      return (
        <div className="p-2 space-y-2">
          {Array.from({ length: 3 }).map((_, i) => (
            <div key={i} className="flex items-center space-x-2 p-2">
              <div className="h-6 w-6 rounded-full bg-muted flex items-center justify-center text-xs">
                ?
              </div>
              <div className="space-y-1 flex-1">
                <Skeleton className="h-3 w-full" />
              </div>
            </div>
          ))}
        </div>
      )
    }

    if (searchError) {
      return (
        <div className="p-4 text-sm text-destructive text-center">
          {searchError}
        </div>
      )
    }

    if (!hasResults) {
      return (
        <div className="p-4 text-sm text-muted-foreground text-center">
          검색 결과가 없습니다.
        </div>
      )
    }

    return (
      <>
        <div className="p-1">
          {searchResults.map((user) => {
            const isSelected = selectedUsers.some(u => u.id === user.id)
            const canSelect = !maxSelections || selectedUsers.length < maxSelections || isSelected
            
            return (
              <div
                key={user.id}
                onClick={() => handleUserSelect(user)}
                className={cn(
                  "flex items-center space-x-3 p-2 rounded-md cursor-pointer hover:bg-accent",
                  !canSelect && !isSelected && "opacity-50 cursor-not-allowed"
                )}
              >
                <div className="h-6 w-6 rounded-full bg-muted flex items-center justify-center text-xs">
                  {getUserInitials(user.name)}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 text-sm">
                    <span className="font-medium">{user.name}</span>
                    <span className="text-muted-foreground">·</span>
                    <span className="text-muted-foreground">{user.email}</span>
                    {user.deptName && (
                      <>
                        <span className="text-muted-foreground">·</span>
                        <span className="text-muted-foreground">{user.deptName}</span>
                      </>
                    )}
                    {isSelected && <div className="h-2 w-2 bg-primary rounded-full ml-auto" />}
                  </div>
                </div>
              </div>
            )
          })}
        </div>

        {/* 페이지네이션 */}
        {pagination.pageCount > 1 && (
          <div className="flex items-center justify-between p-3 border-t bg-muted/30">
            <div className="text-xs text-muted-foreground">
              {pagination.total}명 중 {((pagination.page - 1) * pagination.perPage) + 1}-{Math.min(pagination.page * pagination.perPage, pagination.total)}명
            </div>
            <div className="flex items-center gap-1">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handlePageChange(currentPage - 1)}
                disabled={!pagination.hasPrevPage}
                className="h-8 w-8 p-0"
              >
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <span className="text-xs text-muted-foreground px-2">
                {pagination.page} / {pagination.pageCount}
              </span>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handlePageChange(currentPage + 1)}
                disabled={!pagination.hasNextPage}
                className="h-8 w-8 p-0"
              >
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>
        )}
      </>
    )
  }, [
    shouldShowResults, 
    noValuePlaceHolder, 
    isSearching, 
    searchError, 
    hasResults, 
    searchResults, 
    selectedUsers, 
    maxSelections, 
    handleUserSelect, 
    getUserInitials, 
    pagination, 
    currentPage, 
    handlePageChange
  ])

  return (
    <div className={cn("space-y-2", className)}>
      {/* 검색 입력 영역 */}
      <div className="flex gap-2">
        <div className="flex-1 relative">
          <div className="relative">
            <Input
              ref={inputRef}
              placeholder={placeholder}
              value={searchQuery}
              onChange={handleInputChange}
              onFocus={handleInputFocus}
              disabled={disabled}
              className="pr-10"
            />
            <Search className="absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          </div>
          
          {/* 검색 결과 팝오버 */}
          {isPopoverOpen && (
            <div className="absolute top-full left-0 right-0 z-50 mt-1 rounded-md border bg-popover text-popover-foreground shadow-md outline-none">
              {/* 팝오버 헤더 */}
              <div className="flex items-center justify-between p-3 border-b">
                <span className="text-sm font-medium">사용자 선택</span>
                <Button 
                  variant="ghost" 
                  size="sm" 
                  onClick={handleClosePopover}
                  className="h-6 w-6 p-0"
                >
                  <X className="h-4 w-4" />
                </Button>
              </div>

              {/* 검색 결과 영역 */}
              <div className="max-h-[400px] overflow-y-auto">
                {renderSearchResults}
              </div>
            </div>
          )}
        </div>
        
        {/* 조직도 찾기 버튼 */}
        {onOpenOrgChart && (
          <Button
            variant="outline"
            onClick={onOpenOrgChart}
            disabled={disabled}
            className="px-3"
          >
            <Users className="h-4 w-4 mr-2" />
            찾기
          </Button>
        )}
      </div>

      {/* 선택된 사용자들 표시 */}
      {selectedUsers.length > 0 && (
        <div className="flex flex-wrap gap-2">
          {selectedUsers.map((user) => (
            <Badge
              key={user.id}
              variant="secondary"
              className="flex items-center gap-2 px-3 py-1"
            >
              <div className="h-5 w-5 rounded-full bg-muted flex items-center justify-center text-xs">
                {getUserInitials(user.name)}
              </div>
              <span className="text-sm">{user.name}</span>
              {user.deptName && (
                <span className="text-xs text-muted-foreground">({user.deptName})</span>
              )}
              {!disabled && (
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-4 w-4 p-0 hover:bg-transparent"
                  onClick={() => handleRemoveUser(user.id)}
                >
                  <X className="h-3 w-3" />
                </Button>
              )}
            </Badge>
          ))}
        </div>
      )}

      {/* 선택 제한 안내 */}
      {maxSelections && selectedUsers.length >= maxSelections && (
        <div className="text-xs text-muted-foreground">
          최대 {maxSelections}명까지 선택할 수 있습니다.
        </div>
      )}
    </div>
  )
}