summaryrefslogtreecommitdiff
path: root/lib/evaluation-target-list/table/evaluation-targets-toolbar-actions.tsx
blob: d1c7e5009bd6d3aa5ea8635c81e55fc92ac2a7bc (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
"use client"

import * as React from "react"
import { type Table } from "@tanstack/react-table"
import { 
  Plus, 
  Check, 
  MessageSquare, 
  X, 
  Download,
  Upload,
  RefreshCw,
  Settings
} from "lucide-react"
import { toast } from "sonner"
import { useRouter } from "next/navigation"
import { useSession } from "next-auth/react"

import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { ManualCreateEvaluationTargetDialog } from "./manual-create-evaluation-target-dialog"
import { 
  ConfirmTargetsDialog,
  ExcludeTargetsDialog,
  RequestReviewDialog
} from "./evaluation-target-action-dialogs"
import { EvaluationTargetWithDepartments } from "@/db/schema"
import { exportTableToExcel } from "@/lib/export"
import { autoGenerateEvaluationTargets } from "../service" // 서버 액션 import
import { useAuthRole } from "@/hooks/use-auth-role"

interface EvaluationTargetsTableToolbarActionsProps {
  table: Table<EvaluationTargetWithDepartments>
  onRefresh?: () => void
}

export function EvaluationTargetsTableToolbarActions({ 
  table, 
  onRefresh 
}: EvaluationTargetsTableToolbarActionsProps) {
  const [isLoading, setIsLoading] = React.useState(false)
  const [manualCreateDialogOpen, setManualCreateDialogOpen] = React.useState(false)
  const [confirmDialogOpen, setConfirmDialogOpen] = React.useState(false)
  const [excludeDialogOpen, setExcludeDialogOpen] = React.useState(false)
  const [reviewDialogOpen, setReviewDialogOpen] = React.useState(false)
  const router = useRouter()
  const { data: session } = useSession()

  // 권한 체크
  const { hasRole, isLoading: roleLoading } = useAuthRole()
  const canManageEvaluations = hasRole('정기평가') || hasRole('admin')

  // 사용자 ID 가져오기
  const userId = React.useMemo(() => {
    return session?.user?.id ? Number(session.user.id) : 1;
  }, [session]);

  // 선택된 행들
  const selectedRows = table.getFilteredSelectedRowModel().rows
  const hasSelection = selectedRows.length > 0

  // ✅ selectedTargets를 useMemo로 안정화 (VendorsTable 방식과 동일)
  const selectedTargets = React.useMemo(() => {
    return selectedRows.map(row => row.original)
  }, [selectedRows])

  // ✅ 각 상태별 타겟들을 개별적으로 메모이제이션 (VendorsTable 방식과 동일)
  const pendingTargets = React.useMemo(() => {
    return table
      .getFilteredSelectedRowModel()
      .rows
      .map(row => row.original)
      .filter(t => t.status === "PENDING");
  }, [table.getFilteredSelectedRowModel().rows]);

  const confirmedTargets = React.useMemo(() => {
    return table
      .getFilteredSelectedRowModel()
      .rows
      .map(row => row.original)
      .filter(t => t.status === "CONFIRMED");
  }, [table.getFilteredSelectedRowModel().rows]);

  const excludedTargets = React.useMemo(() => {
    return table
      .getFilteredSelectedRowModel()
      .rows
      .map(row => row.original)
      .filter(t => t.status === "EXCLUDED");
  }, [table.getFilteredSelectedRowModel().rows]);

  const consensusTrueTargets = React.useMemo(() => {
    return table
      .getFilteredSelectedRowModel()
      .rows
      .map(row => row.original)
      .filter(t => t.consensusStatus === true);
  }, [table.getFilteredSelectedRowModel().rows]);

  const consensusFalseTargets = React.useMemo(() => {
    return table
      .getFilteredSelectedRowModel()
      .rows
      .map(row => row.original)
      .filter(t => t.consensusStatus === false);
  }, [table.getFilteredSelectedRowModel().rows]);

  const consensusNullTargets = React.useMemo(() => {
    return table
      .getFilteredSelectedRowModel()
      .rows
      .map(row => row.original)
      .filter(t => t.consensusStatus === null);
  }, [table.getFilteredSelectedRowModel().rows]);

  // ✅ 선택된 항목들의 상태 분석 - 안정화된 개별 배열들 사용
  const selectedStats = React.useMemo(() => {
    const pending = pendingTargets.length
    const confirmed = confirmedTargets.length
    const excluded = excludedTargets.length
    const consensusTrue = consensusTrueTargets.length
    const consensusFalse = consensusFalseTargets.length
    const consensusNull = consensusNullTargets.length

    return {
      pending,
      confirmed,
      excluded,
      consensusTrue,
      consensusFalse,
      consensusNull,
      canConfirm: pending > 0 && consensusTrue > 0,
      canExclude: pending > 0,
      canRequestReview: pending > 0
    }
  }, [
    pendingTargets.length,
    confirmedTargets.length,
    excludedTargets.length,
    consensusTrueTargets.length,
    consensusFalseTargets.length,
    consensusNullTargets.length
  ])

  // ----------------------------------------------------------------
  // 신규 평가 대상 생성 (자동)
  // ----------------------------------------------------------------
  const handleAutoGenerate = React.useCallback(async () => {
    setIsLoading(true)
    try {
      // 현재 년도를 기준으로 평가 대상 자동 생성
      const currentYear = new Date().getFullYear()
      const result = await autoGenerateEvaluationTargets(currentYear, userId)
      
      if (result.success) {
        if (result.generatedCount === 0) {
          toast.info(result.message, {
            description: result.skippedCount 
              ? `이미 존재하는 평가 대상: ${result.skippedCount}개`
              : undefined
          })
        } else {
          toast.success(result.message, {
            description: result.details 
              ? `해양: ${result.details.shipTargets}개, 조선: ${result.details.plantTargets}개 생성${result.details.duplicateSkipped > 0 ? `, 중복 건너뜀: ${result.details.duplicateSkipped}개` : ''}`
              : undefined
          })
        }
        onRefresh?.()
        router.refresh()
      } else {
        toast.error(result.error || "자동 생성 중 오류가 발생했습니다.")
      }
    } catch (error) {
      console.error('Error auto generating targets:', error)
      toast.error("자동 생성 중 오류가 발생했습니다.")
    } finally {
      setIsLoading(false)
    }
  }, [router, onRefresh, userId])

  // ----------------------------------------------------------------
  // 신규 평가 대상 생성 (수동)
  // ----------------------------------------------------------------
  const handleManualCreate = React.useCallback(() => {
    setManualCreateDialogOpen(true)
  }, [])

  // ----------------------------------------------------------------
  // 다이얼로그 성공 핸들러
  // ----------------------------------------------------------------
  const handleActionSuccess = React.useCallback(() => {
    table.resetRowSelection()
    onRefresh?.()
    router.refresh()
  }, [table, onRefresh, router])

  // ----------------------------------------------------------------
  // 내보내기 핸들러
  // ----------------------------------------------------------------
  const handleExport = React.useCallback(() => {
    exportTableToExcel(table, {
      filename: "vendor-target-list",
      excludeColumns: ["select", "actions"],
    })
  }, [table])

  // 권한이 없거나 로딩 중인 경우 내보내기 버튼만 표시
  if (roleLoading) {
    return (
      <div className="flex items-center gap-2">
        <div className="flex items-center gap-1 border-l pl-2 ml-2">
          <Button
            variant="outline"
            size="sm"
            disabled
            className="gap-2"
          >
            <Download className="size-4 animate-spin" aria-hidden="true" />
            <span className="hidden sm:inline">로딩중...</span>
          </Button>
        </div>
      </div>
    )
  }

  return (
    <>
      <div className="flex items-center gap-2">
        {/* 신규 생성 드롭다운 - 정기평가 권한이 있는 경우만 표시 */}
        {canManageEvaluations && (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button
                variant="default"
                size="sm"
                className="gap-2"
                disabled={isLoading}
              >
                <Plus className="size-4" aria-hidden="true" />
                <span className="hidden sm:inline">신규 생성</span>
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="start">
              <DropdownMenuItem onClick={handleAutoGenerate} disabled={isLoading}>
                <RefreshCw className={`size-4 mr-2 ${isLoading ? 'animate-spin' : ''}`} />
                자동 생성 (발주실적 기반)
              </DropdownMenuItem>
              <DropdownMenuItem onClick={handleManualCreate}>
                <Plus className="size-4 mr-2" />
                수동 생성
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        )}

        {/* 유틸리티 버튼들 */}
        <div className="flex items-center gap-1 border-l pl-2 ml-2">
          <Button
            variant="outline"
            size="sm"
            onClick={handleExport}
            className="gap-2"
          >
            <Download className="size-4" aria-hidden="true" />
            <span className="hidden sm:inline">내보내기</span>
          </Button>
        </div>

        {/* 선택된 항목 액션 버튼들 - 정기평가 권한이 있는 경우만 표시 */}
        {canManageEvaluations && hasSelection && (
          <div className="flex items-center gap-1 border-l pl-2 ml-2">
            {/* 확정 버튼 */}
            {selectedStats.canConfirm && (
              <Button
                variant="success"
                size="sm"
                className="gap-2"
                onClick={() => setConfirmDialogOpen(true)}
                disabled={isLoading}
              >
                <Check className="size-4" aria-hidden="true" />
                <span className="hidden sm:inline">
                  확정 ({selectedStats.consensusTrue})
                </span>
              </Button>
            )}

            {/* 제외 버튼 */}
            {selectedStats.canExclude && (
              <Button
                variant="destructive"
                size="sm"
                className="gap-2"
                onClick={() => setExcludeDialogOpen(true)}
                disabled={isLoading}
              >
                <X className="size-4" aria-hidden="true" />
                <span className="hidden sm:inline">
                  제외 ({selectedStats.pending})
                </span>
              </Button>
            )}

            {/* 의견 요청 버튼 */}
            {selectedStats.canRequestReview && (
              <Button
                variant="outline"
                size="sm"
                className="gap-2"
                onClick={() => setReviewDialogOpen(true)}
                disabled={isLoading}
              >
                <MessageSquare className="size-4" aria-hidden="true" />
                <span className="hidden sm:inline">
                  의견 요청 ({selectedStats.pending})
                </span>
              </Button>
            )}
          </div>
        )}

        {/* 권한이 없는 경우 안내 메시지 (선택사항) */}
        {!canManageEvaluations && hasSelection && (
          <div className="flex items-center gap-1 border-l pl-2 ml-2">
            <div className="text-xs text-muted-foreground px-2 py-1">
              평가 관리 권한이 필요합니다
            </div>
          </div>
        )}
      </div>

      {/* 다이얼로그들 - 권한이 있는 경우만 렌더링 */}
      {canManageEvaluations && (
        <>
          {/* 수동 생성 다이얼로그 */}
          <ManualCreateEvaluationTargetDialog
            open={manualCreateDialogOpen}
            onOpenChange={setManualCreateDialogOpen}
            onSuccess={handleActionSuccess}
          />

          {/* 확정 컨펌 다이얼로그 */}
          <ConfirmTargetsDialog
            open={confirmDialogOpen}
            onOpenChange={setConfirmDialogOpen}
            targets={selectedTargets}
            onSuccess={handleActionSuccess}
          />

          {/* 제외 컨펌 다이얼로그 */}
          <ExcludeTargetsDialog
            open={excludeDialogOpen}
            onOpenChange={setExcludeDialogOpen}
            targets={selectedTargets}
            onSuccess={handleActionSuccess}
          />

          {/* 의견 요청 다이얼로그 */}
          <RequestReviewDialog
            open={reviewDialogOpen}
            onOpenChange={setReviewDialogOpen}
            targets={selectedTargets}
            onSuccess={handleActionSuccess}
          />
        </>
      )}
    </>
  )
}